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"
15#include "clang/AST/ASTLambda.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/Type.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Overload.h"
36#include "clang/Sema/SemaCUDA.h"
38#include "clang/Sema/SemaObjC.h"
39#include "clang/Sema/Template.h"
41#include "llvm/ADT/DenseSet.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/STLForwardCompat.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallString.h"
47#include "llvm/ADT/SmallVector.h"
48#include "llvm/Support/Casting.h"
49#include <algorithm>
50#include <cassert>
51#include <cstddef>
52#include <cstdlib>
53#include <optional>
54
55using namespace clang;
56using namespace sema;
57
59
61 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
62 return P->hasAttr<PassObjectSizeAttr>();
63 });
64}
65
66/// A convenience routine for creating a decayed reference to a function.
68 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
69 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
70 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
71 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
72 return ExprError();
73 // If FoundDecl is different from Fn (such as if one is a template
74 // and the other a specialization), make sure DiagnoseUseOfDecl is
75 // called on both.
76 // FIXME: This would be more comprehensively addressed by modifying
77 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
78 // being used.
79 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
80 return ExprError();
81 DeclRefExpr *DRE = new (S.Context)
82 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
83 if (HadMultipleCandidates)
84 DRE->setHadMultipleCandidates(true);
85
87 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
88 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
90 DRE->setType(Fn->getType());
91 }
92 }
93 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
94 CK_FunctionToPointerDecay);
95}
96
97static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
98 bool InOverloadResolution,
100 bool CStyle,
101 bool AllowObjCWritebackConversion);
102
104 QualType &ToType,
105 bool InOverloadResolution,
107 bool CStyle);
109IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
111 OverloadCandidateSet& Conversions,
112 AllowedExplicit AllowExplicit,
113 bool AllowObjCConversionOnExplicit);
114
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
122 const StandardConversionSequence& SCS1,
123 const StandardConversionSequence& SCS2);
124
127 const StandardConversionSequence& SCS1,
128 const StandardConversionSequence& SCS2);
129
130/// GetConversionRank - Retrieve the implicit conversion rank
131/// corresponding to the given implicit conversion kind.
133 static const ImplicitConversionRank Rank[] = {
160 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
161 // it was omitted by the patch that added
162 // ICK_Zero_Event_Conversion
163 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
164 // it was omitted by the patch that added
165 // ICK_Zero_Queue_Conversion
172 };
173 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
174 return Rank[(int)Kind];
175}
176
179 ImplicitConversionKind Dimension) {
181 if (Rank == ICR_HLSL_Scalar_Widening) {
182 if (Base == ICR_Promotion)
184 if (Base == ICR_Conversion)
186 }
187 if (Rank == ICR_HLSL_Dimension_Reduction) {
188 if (Base == ICR_Promotion)
190 if (Base == ICR_Conversion)
192 }
193 return Rank;
194}
195
196/// GetImplicitConversionName - Return the name of this kind of
197/// implicit conversion.
199 static const char *const Name[] = {
200 "No conversion",
201 "Lvalue-to-rvalue",
202 "Array-to-pointer",
203 "Function-to-pointer",
204 "Function pointer conversion",
205 "Qualification",
206 "Integral promotion",
207 "Floating point promotion",
208 "Complex promotion",
209 "Integral conversion",
210 "Floating conversion",
211 "Complex conversion",
212 "Floating-integral conversion",
213 "Pointer conversion",
214 "Pointer-to-member conversion",
215 "Boolean conversion",
216 "Compatible-types conversion",
217 "Derived-to-base conversion",
218 "Vector conversion",
219 "SVE Vector conversion",
220 "RVV Vector conversion",
221 "Vector splat",
222 "Complex-real conversion",
223 "Block Pointer conversion",
224 "Transparent Union Conversion",
225 "Writeback conversion",
226 "OpenCL Zero Event Conversion",
227 "OpenCL Zero Queue Conversion",
228 "C specific type conversion",
229 "Incompatible pointer conversion",
230 "Fixed point conversion",
231 "HLSL vector truncation",
232 "Non-decaying array conversion",
233 "HLSL vector splat",
234 };
235 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
236 return Name[Kind];
237}
238
239/// StandardConversionSequence - Set the standard conversion
240/// sequence to the identity conversion.
248 ReferenceBinding = false;
249 DirectBinding = false;
250 IsLvalueReference = true;
251 BindsToFunctionLvalue = false;
252 BindsToRvalue = false;
255 CopyConstructor = nullptr;
256}
257
258/// getRank - Retrieve the rank of this standard conversion sequence
259/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
260/// implicit conversions.
263 if (GetConversionRank(First) > Rank)
264 Rank = GetConversionRank(First);
265 if (GetConversionRank(Second) > Rank)
267 if (GetDimensionConversionRank(Rank, Dimension) > Rank)
269 if (GetConversionRank(Third) > Rank)
270 Rank = GetConversionRank(Third);
271 return Rank;
272}
273
274/// isPointerConversionToBool - Determines whether this conversion is
275/// a conversion of a pointer or pointer-to-member to bool. This is
276/// used as part of the ranking of standard conversion sequences
277/// (C++ 13.3.3.2p4).
279 // Note that FromType has not necessarily been transformed by the
280 // array-to-pointer or function-to-pointer implicit conversions, so
281 // check for their presence as well as checking whether FromType is
282 // a pointer.
283 if (getToType(1)->isBooleanType() &&
284 (getFromType()->isPointerType() ||
285 getFromType()->isMemberPointerType() ||
286 getFromType()->isObjCObjectPointerType() ||
287 getFromType()->isBlockPointerType() ||
289 return true;
290
291 return false;
292}
293
294/// isPointerConversionToVoidPointer - Determines whether this
295/// conversion is a conversion of a pointer to a void pointer. This is
296/// used as part of the ranking of standard conversion sequences (C++
297/// 13.3.3.2p4).
298bool
301 QualType FromType = getFromType();
302 QualType ToType = getToType(1);
303
304 // Note that FromType has not necessarily been transformed by the
305 // array-to-pointer implicit conversion, so check for its presence
306 // and redo the conversion to get a pointer.
308 FromType = Context.getArrayDecayedType(FromType);
309
310 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
311 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
312 return ToPtrType->getPointeeType()->isVoidType();
313
314 return false;
315}
316
317/// Skip any implicit casts which could be either part of a narrowing conversion
318/// or after one in an implicit conversion.
320 const Expr *Converted) {
321 // We can have cleanups wrapping the converted expression; these need to be
322 // preserved so that destructors run if necessary.
323 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
324 Expr *Inner =
325 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
326 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
327 EWC->getObjects());
328 }
329
330 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
331 switch (ICE->getCastKind()) {
332 case CK_NoOp:
333 case CK_IntegralCast:
334 case CK_IntegralToBoolean:
335 case CK_IntegralToFloating:
336 case CK_BooleanToSignedIntegral:
337 case CK_FloatingToIntegral:
338 case CK_FloatingToBoolean:
339 case CK_FloatingCast:
340 Converted = ICE->getSubExpr();
341 continue;
342
343 default:
344 return Converted;
345 }
346 }
347
348 return Converted;
349}
350
351/// Check if this standard conversion sequence represents a narrowing
352/// conversion, according to C++11 [dcl.init.list]p7.
353///
354/// \param Ctx The AST context.
355/// \param Converted The result of applying this standard conversion sequence.
356/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
357/// value of the expression prior to the narrowing conversion.
358/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
359/// type of the expression prior to the narrowing conversion.
360/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
361/// from floating point types to integral types should be ignored.
363 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
364 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
365 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
366 "narrowing check outside C++");
367
368 // C++11 [dcl.init.list]p7:
369 // A narrowing conversion is an implicit conversion ...
370 QualType FromType = getToType(0);
371 QualType ToType = getToType(1);
372
373 // A conversion to an enumeration type is narrowing if the conversion to
374 // the underlying type is narrowing. This only arises for expressions of
375 // the form 'Enum{init}'.
376 if (auto *ET = ToType->getAs<EnumType>())
377 ToType = ET->getDecl()->getIntegerType();
378
379 switch (Second) {
380 // 'bool' is an integral type; dispatch to the right place to handle it.
382 if (FromType->isRealFloatingType())
383 goto FloatingIntegralConversion;
385 goto IntegralConversion;
386 // -- from a pointer type or pointer-to-member type to bool, or
387 return NK_Type_Narrowing;
388
389 // -- from a floating-point type to an integer type, or
390 //
391 // -- from an integer type or unscoped enumeration type to a floating-point
392 // type, except where the source is a constant expression and the actual
393 // value after conversion will fit into the target type and will produce
394 // the original value when converted back to the original type, or
396 FloatingIntegralConversion:
397 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
398 return NK_Type_Narrowing;
399 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
400 ToType->isRealFloatingType()) {
401 if (IgnoreFloatToIntegralConversion)
402 return NK_Not_Narrowing;
403 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
404 assert(Initializer && "Unknown conversion expression");
405
406 // If it's value-dependent, we can't tell whether it's narrowing.
407 if (Initializer->isValueDependent())
409
410 if (std::optional<llvm::APSInt> IntConstantValue =
411 Initializer->getIntegerConstantExpr(Ctx)) {
412 // Convert the integer to the floating type.
413 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
414 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
415 llvm::APFloat::rmNearestTiesToEven);
416 // And back.
417 llvm::APSInt ConvertedValue = *IntConstantValue;
418 bool ignored;
419 Result.convertToInteger(ConvertedValue,
420 llvm::APFloat::rmTowardZero, &ignored);
421 // If the resulting value is different, this was a narrowing conversion.
422 if (*IntConstantValue != ConvertedValue) {
423 ConstantValue = APValue(*IntConstantValue);
424 ConstantType = Initializer->getType();
426 }
427 } else {
428 // Variables are always narrowings.
430 }
431 }
432 return NK_Not_Narrowing;
433
434 // -- from long double to double or float, or from double to float, except
435 // where the source is a constant expression and the actual value after
436 // conversion is within the range of values that can be represented (even
437 // if it cannot be represented exactly), or
439 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
440 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
441 // FromType is larger than ToType.
442 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
443
444 // If it's value-dependent, we can't tell whether it's narrowing.
445 if (Initializer->isValueDependent())
447
449 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
450 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
451 // Constant!
452 if (Ctx.getLangOpts().C23)
453 ConstantValue = R.Val;
454 assert(ConstantValue.isFloat());
455 llvm::APFloat FloatVal = ConstantValue.getFloat();
456 // Convert the source value into the target type.
457 bool ignored;
458 llvm::APFloat Converted = FloatVal;
459 llvm::APFloat::opStatus ConvertStatus =
460 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
461 llvm::APFloat::rmNearestTiesToEven, &ignored);
462 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
463 llvm::APFloat::rmNearestTiesToEven, &ignored);
464 if (Ctx.getLangOpts().C23) {
465 if (FloatVal.isNaN() && Converted.isNaN() &&
466 !FloatVal.isSignaling() && !Converted.isSignaling()) {
467 // Quiet NaNs are considered the same value, regardless of
468 // payloads.
469 return NK_Not_Narrowing;
470 }
471 // For normal values, check exact equality.
472 if (!Converted.bitwiseIsEqual(FloatVal)) {
473 ConstantType = Initializer->getType();
475 }
476 } else {
477 // If there was no overflow, the source value is within the range of
478 // values that can be represented.
479 if (ConvertStatus & llvm::APFloat::opOverflow) {
480 ConstantType = Initializer->getType();
482 }
483 }
484 } else {
486 }
487 }
488 return NK_Not_Narrowing;
489
490 // -- from an integer type or unscoped enumeration type to an integer type
491 // that cannot represent all the values of the original type, except where
492 // (CWG2627) -- the source is a bit-field whose width w is less than that
493 // of its type (or, for an enumeration type, its underlying type) and the
494 // target type can represent all the values of a hypothetical extended
495 // integer type with width w and with the same signedness as the original
496 // type or
497 // -- the source is a constant expression and the actual value after
498 // conversion will fit into the target type and will produce the original
499 // value when converted back to the original type.
501 IntegralConversion: {
502 assert(FromType->isIntegralOrUnscopedEnumerationType());
503 assert(ToType->isIntegralOrUnscopedEnumerationType());
504 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
505 unsigned FromWidth = Ctx.getIntWidth(FromType);
506 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
507 const unsigned ToWidth = Ctx.getIntWidth(ToType);
508
509 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
510 bool ToSigned, unsigned ToWidth) {
511 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
512 (FromSigned <= ToSigned);
513 };
514
515 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
516 return NK_Not_Narrowing;
517
518 // Not all values of FromType can be represented in ToType.
519 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
520
521 bool DependentBitField = false;
522 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
523 if (BitField->getBitWidth()->isValueDependent())
524 DependentBitField = true;
525 else if (unsigned BitFieldWidth = BitField->getBitWidthValue(Ctx);
526 BitFieldWidth < FromWidth) {
527 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
528 return NK_Not_Narrowing;
529
530 // The initializer will be truncated to the bit-field width
531 FromWidth = BitFieldWidth;
532 }
533 }
534
535 // If it's value-dependent, we can't tell whether it's narrowing.
536 if (Initializer->isValueDependent())
538
539 std::optional<llvm::APSInt> OptInitializerValue =
540 Initializer->getIntegerConstantExpr(Ctx);
541 if (!OptInitializerValue) {
542 // If the bit-field width was dependent, it might end up being small
543 // enough to fit in the target type (unless the target type is unsigned
544 // and the source type is signed, in which case it will never fit)
545 if (DependentBitField && (FromSigned <= ToSigned))
547
548 // Otherwise, such a conversion is always narrowing
550 }
551 llvm::APSInt &InitializerValue = *OptInitializerValue;
552 bool Narrowing = false;
553 if (FromWidth < ToWidth) {
554 // Negative -> unsigned is narrowing. Otherwise, more bits is never
555 // narrowing.
556 if (InitializerValue.isSigned() && InitializerValue.isNegative())
557 Narrowing = true;
558 } else {
559 // Add a bit to the InitializerValue so we don't have to worry about
560 // signed vs. unsigned comparisons.
561 InitializerValue =
562 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
563 // Convert the initializer to and from the target width and signed-ness.
564 llvm::APSInt ConvertedValue = InitializerValue;
565 ConvertedValue = ConvertedValue.trunc(ToWidth);
566 ConvertedValue.setIsSigned(ToSigned);
567 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
568 ConvertedValue.setIsSigned(InitializerValue.isSigned());
569 // If the result is different, this was a narrowing conversion.
570 if (ConvertedValue != InitializerValue)
571 Narrowing = true;
572 }
573 if (Narrowing) {
574 ConstantType = Initializer->getType();
575 ConstantValue = APValue(InitializerValue);
577 }
578
579 return NK_Not_Narrowing;
580 }
581 case ICK_Complex_Real:
582 if (FromType->isComplexType() && !ToType->isComplexType())
583 return NK_Type_Narrowing;
584 return NK_Not_Narrowing;
585
587 if (Ctx.getLangOpts().C23) {
588 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
590 if (Initializer->EvaluateAsRValue(R, Ctx)) {
591 ConstantValue = R.Val;
592 assert(ConstantValue.isFloat());
593 llvm::APFloat FloatVal = ConstantValue.getFloat();
594 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
595 // value, the unqualified versions of the type of the initializer and
596 // the corresponding real type of the object declared shall be
597 // compatible.
598 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
599 ConstantType = Initializer->getType();
601 }
602 }
603 }
604 return NK_Not_Narrowing;
605 default:
606 // Other kinds of conversions are not narrowings.
607 return NK_Not_Narrowing;
608 }
609}
610
611/// dump - Print this standard conversion sequence to standard
612/// error. Useful for debugging overloading issues.
613LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
614 raw_ostream &OS = llvm::errs();
615 bool PrintedSomething = false;
616 if (First != ICK_Identity) {
618 PrintedSomething = true;
619 }
620
621 if (Second != ICK_Identity) {
622 if (PrintedSomething) {
623 OS << " -> ";
624 }
626
627 if (CopyConstructor) {
628 OS << " (by copy constructor)";
629 } else if (DirectBinding) {
630 OS << " (direct reference binding)";
631 } else if (ReferenceBinding) {
632 OS << " (reference binding)";
633 }
634 PrintedSomething = true;
635 }
636
637 if (Third != ICK_Identity) {
638 if (PrintedSomething) {
639 OS << " -> ";
640 }
642 PrintedSomething = true;
643 }
644
645 if (!PrintedSomething) {
646 OS << "No conversions required";
647 }
648}
649
650/// dump - Print this user-defined conversion sequence to standard
651/// error. Useful for debugging overloading issues.
653 raw_ostream &OS = llvm::errs();
654 if (Before.First || Before.Second || Before.Third) {
655 Before.dump();
656 OS << " -> ";
657 }
659 OS << '\'' << *ConversionFunction << '\'';
660 else
661 OS << "aggregate initialization";
662 if (After.First || After.Second || After.Third) {
663 OS << " -> ";
664 After.dump();
665 }
666}
667
668/// dump - Print this implicit conversion sequence to standard
669/// error. Useful for debugging overloading issues.
671 raw_ostream &OS = llvm::errs();
673 OS << "Worst list element conversion: ";
674 switch (ConversionKind) {
676 OS << "Standard conversion: ";
677 Standard.dump();
678 break;
680 OS << "User-defined conversion: ";
682 break;
684 OS << "Ellipsis conversion";
685 break;
687 OS << "Ambiguous conversion";
688 break;
689 case BadConversion:
690 OS << "Bad conversion";
691 break;
692 }
693
694 OS << "\n";
695}
696
698 new (&conversions()) ConversionSet();
699}
700
702 conversions().~ConversionSet();
703}
704
705void
710}
711
712namespace {
713 // Structure used by DeductionFailureInfo to store
714 // template argument information.
715 struct DFIArguments {
716 TemplateArgument FirstArg;
717 TemplateArgument SecondArg;
718 };
719 // Structure used by DeductionFailureInfo to store
720 // template parameter and template argument information.
721 struct DFIParamWithArguments : DFIArguments {
722 TemplateParameter Param;
723 };
724 // Structure used by DeductionFailureInfo to store template argument
725 // information and the index of the problematic call argument.
726 struct DFIDeducedMismatchArgs : DFIArguments {
727 TemplateArgumentList *TemplateArgs;
728 unsigned CallArgIndex;
729 };
730 // Structure used by DeductionFailureInfo to store information about
731 // unsatisfied constraints.
732 struct CNSInfo {
733 TemplateArgumentList *TemplateArgs;
734 ConstraintSatisfaction Satisfaction;
735 };
736}
737
738/// Convert from Sema's representation of template deduction information
739/// to the form used in overload-candidate information.
743 TemplateDeductionInfo &Info) {
745 Result.Result = static_cast<unsigned>(TDK);
746 Result.HasDiagnostic = false;
747 switch (TDK) {
754 Result.Data = nullptr;
755 break;
756
759 Result.Data = Info.Param.getOpaqueValue();
760 break;
761
764 // FIXME: Should allocate from normal heap so that we can free this later.
765 auto *Saved = new (Context) DFIDeducedMismatchArgs;
766 Saved->FirstArg = Info.FirstArg;
767 Saved->SecondArg = Info.SecondArg;
768 Saved->TemplateArgs = Info.takeSugared();
769 Saved->CallArgIndex = Info.CallArgIndex;
770 Result.Data = Saved;
771 break;
772 }
773
775 // FIXME: Should allocate from normal heap so that we can free this later.
776 DFIArguments *Saved = new (Context) DFIArguments;
777 Saved->FirstArg = Info.FirstArg;
778 Saved->SecondArg = Info.SecondArg;
779 Result.Data = Saved;
780 break;
781 }
782
784 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
787 // FIXME: Should allocate from normal heap so that we can free this later.
788 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
789 Saved->Param = Info.Param;
790 Saved->FirstArg = Info.FirstArg;
791 Saved->SecondArg = Info.SecondArg;
792 Result.Data = Saved;
793 break;
794 }
795
797 Result.Data = Info.takeSugared();
798 if (Info.hasSFINAEDiagnostic()) {
802 Result.HasDiagnostic = true;
803 }
804 break;
805
807 CNSInfo *Saved = new (Context) CNSInfo;
808 Saved->TemplateArgs = Info.takeSugared();
809 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
810 Result.Data = Saved;
811 break;
812 }
813
817 llvm_unreachable("not a deduction failure");
818 }
819
820 return Result;
821}
822
824 switch (static_cast<TemplateDeductionResult>(Result)) {
834 break;
835
842 // FIXME: Destroy the data?
843 Data = nullptr;
844 break;
845
847 // FIXME: Destroy the template argument list?
848 Data = nullptr;
850 Diag->~PartialDiagnosticAt();
851 HasDiagnostic = false;
852 }
853 break;
854
856 // FIXME: Destroy the template argument list?
857 Data = nullptr;
859 Diag->~PartialDiagnosticAt();
860 HasDiagnostic = false;
861 }
862 break;
863
864 // Unhandled
867 break;
868 }
869}
870
872 if (HasDiagnostic)
873 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
874 return nullptr;
875}
876
878 switch (static_cast<TemplateDeductionResult>(Result)) {
891 return TemplateParameter();
892
895 return TemplateParameter::getFromOpaqueValue(Data);
896
900 return static_cast<DFIParamWithArguments*>(Data)->Param;
901
902 // Unhandled
905 break;
906 }
907
908 return TemplateParameter();
909}
910
912 switch (static_cast<TemplateDeductionResult>(Result)) {
926 return nullptr;
927
930 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
931
933 return static_cast<TemplateArgumentList*>(Data);
934
936 return static_cast<CNSInfo*>(Data)->TemplateArgs;
937
938 // Unhandled
941 break;
942 }
943
944 return nullptr;
945}
946
948 switch (static_cast<TemplateDeductionResult>(Result)) {
960 return nullptr;
961
968 return &static_cast<DFIArguments*>(Data)->FirstArg;
969
970 // Unhandled
973 break;
974 }
975
976 return nullptr;
977}
978
980 switch (static_cast<TemplateDeductionResult>(Result)) {
993 return nullptr;
994
1000 return &static_cast<DFIArguments*>(Data)->SecondArg;
1001
1002 // Unhandled
1005 break;
1006 }
1007
1008 return nullptr;
1009}
1010
1011std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
1012 switch (static_cast<TemplateDeductionResult>(Result)) {
1015 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1016
1017 default:
1018 return std::nullopt;
1019 }
1020}
1021
1023 const FunctionDecl *Y) {
1024 if (!X || !Y)
1025 return false;
1026 if (X->getNumParams() != Y->getNumParams())
1027 return false;
1028 // FIXME: when do rewritten comparison operators
1029 // with explicit object parameters correspond?
1030 // https://cplusplus.github.io/CWG/issues/2797.html
1031 for (unsigned I = 0; I < X->getNumParams(); ++I)
1032 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1033 Y->getParamDecl(I)->getType()))
1034 return false;
1035 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1036 auto *FTY = Y->getDescribedFunctionTemplate();
1037 if (!FTY)
1038 return false;
1039 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1040 FTY->getTemplateParameters()))
1041 return false;
1042 }
1043 return true;
1044}
1045
1047 Expr *FirstOperand, FunctionDecl *EqFD) {
1048 assert(EqFD->getOverloadedOperator() ==
1049 OverloadedOperatorKind::OO_EqualEqual);
1050 // C++2a [over.match.oper]p4:
1051 // A non-template function or function template F named operator== is a
1052 // rewrite target with first operand o unless a search for the name operator!=
1053 // in the scope S from the instantiation context of the operator expression
1054 // finds a function or function template that would correspond
1055 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1056 // scope of the class type of o if F is a class member, and the namespace
1057 // scope of which F is a member otherwise. A function template specialization
1058 // named operator== is a rewrite target if its function template is a rewrite
1059 // target.
1061 OverloadedOperatorKind::OO_ExclaimEqual);
1062 if (isa<CXXMethodDecl>(EqFD)) {
1063 // If F is a class member, search scope is class type of first operand.
1064 QualType RHS = FirstOperand->getType();
1065 auto *RHSRec = RHS->getAs<RecordType>();
1066 if (!RHSRec)
1067 return true;
1068 LookupResult Members(S, NotEqOp, OpLoc,
1070 S.LookupQualifiedName(Members, RHSRec->getDecl());
1071 Members.suppressAccessDiagnostics();
1072 for (NamedDecl *Op : Members)
1073 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1074 return false;
1075 return true;
1076 }
1077 // Otherwise the search scope is the namespace scope of which F is a member.
1078 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1079 auto *NotEqFD = Op->getAsFunction();
1080 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1081 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1082 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1084 cast<Decl>(Op->getLexicalDeclContext())))
1085 return false;
1086 }
1087 return true;
1088}
1089
1093 return false;
1094 return Op == OO_EqualEqual || Op == OO_Spaceship;
1095}
1096
1098 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1099 auto Op = FD->getOverloadedOperator();
1100 if (!allowsReversed(Op))
1101 return false;
1102 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1103 assert(OriginalArgs.size() == 2);
1105 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1106 return false;
1107 }
1108 // Don't bother adding a reversed candidate that can never be a better
1109 // match than the non-reversed version.
1110 return FD->getNumNonObjectParams() != 2 ||
1112 FD->getParamDecl(1)->getType()) ||
1113 FD->hasAttr<EnableIfAttr>();
1114}
1115
1116void OverloadCandidateSet::destroyCandidates() {
1117 for (iterator i = begin(), e = end(); i != e; ++i) {
1118 for (auto &C : i->Conversions)
1119 C.~ImplicitConversionSequence();
1120 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1121 i->DeductionFailure.Destroy();
1122 }
1123}
1124
1126 destroyCandidates();
1127 SlabAllocator.Reset();
1128 NumInlineBytesUsed = 0;
1129 Candidates.clear();
1130 Functions.clear();
1131 Kind = CSK;
1132}
1133
1134namespace {
1135 class UnbridgedCastsSet {
1136 struct Entry {
1137 Expr **Addr;
1138 Expr *Saved;
1139 };
1140 SmallVector<Entry, 2> Entries;
1141
1142 public:
1143 void save(Sema &S, Expr *&E) {
1144 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1145 Entry entry = { &E, E };
1146 Entries.push_back(entry);
1148 }
1149
1150 void restore() {
1152 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1153 *i->Addr = i->Saved;
1154 }
1155 };
1156}
1157
1158/// checkPlaceholderForOverload - Do any interesting placeholder-like
1159/// preprocessing on the given expression.
1160///
1161/// \param unbridgedCasts a collection to which to add unbridged casts;
1162/// without this, they will be immediately diagnosed as errors
1163///
1164/// Return true on unrecoverable error.
1165static bool
1167 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1168 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1169 // We can't handle overloaded expressions here because overload
1170 // resolution might reasonably tweak them.
1171 if (placeholder->getKind() == BuiltinType::Overload) return false;
1172
1173 // If the context potentially accepts unbridged ARC casts, strip
1174 // the unbridged cast and add it to the collection for later restoration.
1175 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1176 unbridgedCasts) {
1177 unbridgedCasts->save(S, E);
1178 return false;
1179 }
1180
1181 // Go ahead and check everything else.
1182 ExprResult result = S.CheckPlaceholderExpr(E);
1183 if (result.isInvalid())
1184 return true;
1185
1186 E = result.get();
1187 return false;
1188 }
1189
1190 // Nothing to do.
1191 return false;
1192}
1193
1194/// checkArgPlaceholdersForOverload - Check a set of call operands for
1195/// placeholders.
1197 UnbridgedCastsSet &unbridged) {
1198 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1199 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1200 return true;
1201
1202 return false;
1203}
1204
1207 NamedDecl *&Match, bool NewIsUsingDecl) {
1208 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1209 I != E; ++I) {
1210 NamedDecl *OldD = *I;
1211
1212 bool OldIsUsingDecl = false;
1213 if (isa<UsingShadowDecl>(OldD)) {
1214 OldIsUsingDecl = true;
1215
1216 // We can always introduce two using declarations into the same
1217 // context, even if they have identical signatures.
1218 if (NewIsUsingDecl) continue;
1219
1220 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1221 }
1222
1223 // A using-declaration does not conflict with another declaration
1224 // if one of them is hidden.
1225 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1226 continue;
1227
1228 // If either declaration was introduced by a using declaration,
1229 // we'll need to use slightly different rules for matching.
1230 // Essentially, these rules are the normal rules, except that
1231 // function templates hide function templates with different
1232 // return types or template parameter lists.
1233 bool UseMemberUsingDeclRules =
1234 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1235 !New->getFriendObjectKind();
1236
1237 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1238 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1239 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1240 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1241 continue;
1242 }
1243
1244 if (!isa<FunctionTemplateDecl>(OldD) &&
1245 !shouldLinkPossiblyHiddenDecl(*I, New))
1246 continue;
1247
1248 Match = *I;
1249 return Ovl_Match;
1250 }
1251
1252 // Builtins that have custom typechecking or have a reference should
1253 // not be overloadable or redeclarable.
1254 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1255 Match = *I;
1256 return Ovl_NonFunction;
1257 }
1258 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1259 // We can overload with these, which can show up when doing
1260 // redeclaration checks for UsingDecls.
1261 assert(Old.getLookupKind() == LookupUsingDeclName);
1262 } else if (isa<TagDecl>(OldD)) {
1263 // We can always overload with tags by hiding them.
1264 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1265 // Optimistically assume that an unresolved using decl will
1266 // overload; if it doesn't, we'll have to diagnose during
1267 // template instantiation.
1268 //
1269 // Exception: if the scope is dependent and this is not a class
1270 // member, the using declaration can only introduce an enumerator.
1271 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1272 Match = *I;
1273 return Ovl_NonFunction;
1274 }
1275 } else {
1276 // (C++ 13p1):
1277 // Only function declarations can be overloaded; object and type
1278 // declarations cannot be overloaded.
1279 Match = *I;
1280 return Ovl_NonFunction;
1281 }
1282 }
1283
1284 // C++ [temp.friend]p1:
1285 // For a friend function declaration that is not a template declaration:
1286 // -- if the name of the friend is a qualified or unqualified template-id,
1287 // [...], otherwise
1288 // -- if the name of the friend is a qualified-id and a matching
1289 // non-template function is found in the specified class or namespace,
1290 // the friend declaration refers to that function, otherwise,
1291 // -- if the name of the friend is a qualified-id and a matching function
1292 // template is found in the specified class or namespace, the friend
1293 // declaration refers to the deduced specialization of that function
1294 // template, otherwise
1295 // -- the name shall be an unqualified-id [...]
1296 // If we get here for a qualified friend declaration, we've just reached the
1297 // third bullet. If the type of the friend is dependent, skip this lookup
1298 // until instantiation.
1299 if (New->getFriendObjectKind() && New->getQualifier() &&
1302 !New->getType()->isDependentType()) {
1303 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1304 TemplateSpecResult.addAllDecls(Old);
1305 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1306 /*QualifiedFriend*/true)) {
1307 New->setInvalidDecl();
1308 return Ovl_Overload;
1309 }
1310
1311 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1312 return Ovl_Match;
1313 }
1314
1315 return Ovl_Overload;
1316}
1317
1318static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1319 FunctionDecl *Old,
1320 bool UseMemberUsingDeclRules,
1321 bool ConsiderCudaAttrs,
1322 bool UseOverrideRules = false) {
1323 // C++ [basic.start.main]p2: This function shall not be overloaded.
1324 if (New->isMain())
1325 return false;
1326
1327 // MSVCRT user defined entry points cannot be overloaded.
1328 if (New->isMSVCRTEntryPoint())
1329 return false;
1330
1331 NamedDecl *OldDecl = Old;
1332 NamedDecl *NewDecl = New;
1335
1336 // C++ [temp.fct]p2:
1337 // A function template can be overloaded with other function templates
1338 // and with normal (non-template) functions.
1339 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1340 return true;
1341
1342 // Is the function New an overload of the function Old?
1343 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1344 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1345
1346 // Compare the signatures (C++ 1.3.10) of the two functions to
1347 // determine whether they are overloads. If we find any mismatch
1348 // in the signature, they are overloads.
1349
1350 // If either of these functions is a K&R-style function (no
1351 // prototype), then we consider them to have matching signatures.
1352 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1353 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1354 return false;
1355
1356 const auto *OldType = cast<FunctionProtoType>(OldQType);
1357 const auto *NewType = cast<FunctionProtoType>(NewQType);
1358
1359 // The signature of a function includes the types of its
1360 // parameters (C++ 1.3.10), which includes the presence or absence
1361 // of the ellipsis; see C++ DR 357).
1362 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1363 return true;
1364
1365 // For member-like friends, the enclosing class is part of the signature.
1366 if ((New->isMemberLikeConstrainedFriend() ||
1369 return true;
1370
1371 // Compare the parameter lists.
1372 // This can only be done once we have establish that friend functions
1373 // inhabit the same context, otherwise we might tried to instantiate
1374 // references to non-instantiated entities during constraint substitution.
1375 // GH78101.
1376 if (NewTemplate) {
1377 OldDecl = OldTemplate;
1378 NewDecl = NewTemplate;
1379 // C++ [temp.over.link]p4:
1380 // The signature of a function template consists of its function
1381 // signature, its return type and its template parameter list. The names
1382 // of the template parameters are significant only for establishing the
1383 // relationship between the template parameters and the rest of the
1384 // signature.
1385 //
1386 // We check the return type and template parameter lists for function
1387 // templates first; the remaining checks follow.
1388 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1389 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1390 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1391 bool SameReturnType = SemaRef.Context.hasSameType(
1393 // FIXME(GH58571): Match template parameter list even for non-constrained
1394 // template heads. This currently ensures that the code prior to C++20 is
1395 // not newly broken.
1396 bool ConstraintsInTemplateHead =
1399 // C++ [namespace.udecl]p11:
1400 // The set of declarations named by a using-declarator that inhabits a
1401 // class C does not include member functions and member function
1402 // templates of a base class that "correspond" to (and thus would
1403 // conflict with) a declaration of a function or function template in
1404 // C.
1405 // Comparing return types is not required for the "correspond" check to
1406 // decide whether a member introduced by a shadow declaration is hidden.
1407 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1408 !SameTemplateParameterList)
1409 return true;
1410 if (!UseMemberUsingDeclRules &&
1411 (!SameTemplateParameterList || !SameReturnType))
1412 return true;
1413 }
1414
1415 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1416 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1417
1418 int OldParamsOffset = 0;
1419 int NewParamsOffset = 0;
1420
1421 // When determining if a method is an overload from a base class, act as if
1422 // the implicit object parameter are of the same type.
1423
1424 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1426 return Q;
1427
1428 // We do not allow overloading based off of '__restrict'.
1429 Q.removeRestrict();
1430
1431 // We may not have applied the implicit const for a constexpr member
1432 // function yet (because we haven't yet resolved whether this is a static
1433 // or non-static member function). Add it now, on the assumption that this
1434 // is a redeclaration of OldMethod.
1435 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1436 (M->isConstexpr() || M->isConsteval()) &&
1437 !isa<CXXConstructorDecl>(NewMethod))
1438 Q.addConst();
1439 return Q;
1440 };
1441
1442 auto CompareType = [&](QualType Base, QualType D) {
1443 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1444 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1445
1446 auto DS = D.getNonReferenceType().getCanonicalType().split();
1447 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1448
1449 if (BS.Quals != DS.Quals)
1450 return false;
1451
1452 if (OldMethod->isImplicitObjectMemberFunction() &&
1453 OldMethod->getParent() != NewMethod->getParent()) {
1454 QualType ParentType =
1455 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1457 if (ParentType.getTypePtr() != BS.Ty)
1458 return false;
1459 BS.Ty = DS.Ty;
1460 }
1461
1462 // FIXME: should we ignore some type attributes here?
1463 if (BS.Ty != DS.Ty)
1464 return false;
1465
1466 if (Base->isLValueReferenceType())
1467 return D->isLValueReferenceType();
1468 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1469 };
1470
1471 // If the function is a class member, its signature includes the
1472 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1473 auto DiagnoseInconsistentRefQualifiers = [&]() {
1474 if (SemaRef.LangOpts.CPlusPlus23)
1475 return false;
1476 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1477 return false;
1478 if (OldMethod->isExplicitObjectMemberFunction() ||
1479 NewMethod->isExplicitObjectMemberFunction())
1480 return false;
1481 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1482 NewMethod->getRefQualifier() == RQ_None)) {
1483 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1484 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1485 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1486 return true;
1487 }
1488 return false;
1489 };
1490
1491 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1492 OldParamsOffset++;
1493 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1494 NewParamsOffset++;
1495
1496 if (OldType->getNumParams() - OldParamsOffset !=
1497 NewType->getNumParams() - NewParamsOffset ||
1499 {OldType->param_type_begin() + OldParamsOffset,
1500 OldType->param_type_end()},
1501 {NewType->param_type_begin() + NewParamsOffset,
1502 NewType->param_type_end()},
1503 nullptr)) {
1504 return true;
1505 }
1506
1507 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1508 !NewMethod->isStatic()) {
1509 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1510 const CXXMethodDecl *New) {
1511 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1512 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1513
1514 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1515 return F->getRefQualifier() == RQ_None &&
1516 !F->isExplicitObjectMemberFunction();
1517 };
1518
1519 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1520 CompareType(OldObjectType.getNonReferenceType(),
1521 NewObjectType.getNonReferenceType()))
1522 return true;
1523 return CompareType(OldObjectType, NewObjectType);
1524 }(OldMethod, NewMethod);
1525
1526 if (!HaveCorrespondingObjectParameters) {
1527 if (DiagnoseInconsistentRefQualifiers())
1528 return true;
1529 // CWG2554
1530 // and, if at least one is an explicit object member function, ignoring
1531 // object parameters
1532 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1533 !OldMethod->isExplicitObjectMemberFunction()))
1534 return true;
1535 }
1536 }
1537
1538 if (!UseOverrideRules &&
1540 Expr *NewRC = New->getTrailingRequiresClause(),
1541 *OldRC = Old->getTrailingRequiresClause();
1542 if ((NewRC != nullptr) != (OldRC != nullptr))
1543 return true;
1544 if (NewRC &&
1545 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC, NewDecl, NewRC))
1546 return true;
1547 }
1548
1549 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1550 NewMethod->isImplicitObjectMemberFunction()) {
1551 if (DiagnoseInconsistentRefQualifiers())
1552 return true;
1553 }
1554
1555 // Though pass_object_size is placed on parameters and takes an argument, we
1556 // consider it to be a function-level modifier for the sake of function
1557 // identity. Either the function has one or more parameters with
1558 // pass_object_size or it doesn't.
1561 return true;
1562
1563 // enable_if attributes are an order-sensitive part of the signature.
1565 NewI = New->specific_attr_begin<EnableIfAttr>(),
1566 NewE = New->specific_attr_end<EnableIfAttr>(),
1567 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1568 OldE = Old->specific_attr_end<EnableIfAttr>();
1569 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1570 if (NewI == NewE || OldI == OldE)
1571 return true;
1572 llvm::FoldingSetNodeID NewID, OldID;
1573 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1574 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1575 if (NewID != OldID)
1576 return true;
1577 }
1578
1579 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1580 // Don't allow overloading of destructors. (In theory we could, but it
1581 // would be a giant change to clang.)
1582 if (!isa<CXXDestructorDecl>(New)) {
1583 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1584 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1585 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1586 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1587 "Unexpected invalid target.");
1588
1589 // Allow overloading of functions with same signature and different CUDA
1590 // target attributes.
1591 if (NewTarget != OldTarget)
1592 return true;
1593 }
1594 }
1595 }
1596
1597 // The signatures match; this is not an overload.
1598 return false;
1599}
1600
1602 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1603 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1604 ConsiderCudaAttrs);
1605}
1606
1608 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1609 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1610 /*UseMemberUsingDeclRules=*/false,
1611 /*ConsiderCudaAttrs=*/true,
1612 /*UseOverrideRules=*/true);
1613}
1614
1615/// Tries a user-defined conversion from From to ToType.
1616///
1617/// Produces an implicit conversion sequence for when a standard conversion
1618/// is not an option. See TryImplicitConversion for more information.
1621 bool SuppressUserConversions,
1622 AllowedExplicit AllowExplicit,
1623 bool InOverloadResolution,
1624 bool CStyle,
1625 bool AllowObjCWritebackConversion,
1626 bool AllowObjCConversionOnExplicit) {
1628
1629 if (SuppressUserConversions) {
1630 // We're not in the case above, so there is no conversion that
1631 // we can perform.
1633 return ICS;
1634 }
1635
1636 // Attempt user-defined conversion.
1637 OverloadCandidateSet Conversions(From->getExprLoc(),
1639 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1640 Conversions, AllowExplicit,
1641 AllowObjCConversionOnExplicit)) {
1642 case OR_Success:
1643 case OR_Deleted:
1644 ICS.setUserDefined();
1645 // C++ [over.ics.user]p4:
1646 // A conversion of an expression of class type to the same class
1647 // type is given Exact Match rank, and a conversion of an
1648 // expression of class type to a base class of that type is
1649 // given Conversion rank, in spite of the fact that a copy
1650 // constructor (i.e., a user-defined conversion function) is
1651 // called for those cases.
1652 if (CXXConstructorDecl *Constructor
1653 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1654 QualType FromType;
1655 SourceLocation FromLoc;
1656 // C++11 [over.ics.list]p6, per DR2137:
1657 // C++17 [over.ics.list]p6:
1658 // If C is not an initializer-list constructor and the initializer list
1659 // has a single element of type cv U, where U is X or a class derived
1660 // from X, the implicit conversion sequence has Exact Match rank if U is
1661 // X, or Conversion rank if U is derived from X.
1662 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1663 InitList && InitList->getNumInits() == 1 &&
1664 !S.isInitListConstructor(Constructor)) {
1665 const Expr *SingleInit = InitList->getInit(0);
1666 FromType = SingleInit->getType();
1667 FromLoc = SingleInit->getBeginLoc();
1668 } else {
1669 FromType = From->getType();
1670 FromLoc = From->getBeginLoc();
1671 }
1672 QualType FromCanon =
1674 QualType ToCanon
1676 if ((FromCanon == ToCanon ||
1677 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1678 // Turn this into a "standard" conversion sequence, so that it
1679 // gets ranked with standard conversion sequences.
1681 ICS.setStandard();
1683 ICS.Standard.setFromType(FromType);
1684 ICS.Standard.setAllToTypes(ToType);
1685 ICS.Standard.CopyConstructor = Constructor;
1687 if (ToCanon != FromCanon)
1689 }
1690 }
1691 break;
1692
1693 case OR_Ambiguous:
1694 ICS.setAmbiguous();
1695 ICS.Ambiguous.setFromType(From->getType());
1696 ICS.Ambiguous.setToType(ToType);
1697 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1698 Cand != Conversions.end(); ++Cand)
1699 if (Cand->Best)
1700 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1701 break;
1702
1703 // Fall through.
1706 break;
1707 }
1708
1709 return ICS;
1710}
1711
1712/// TryImplicitConversion - Attempt to perform an implicit conversion
1713/// from the given expression (Expr) to the given type (ToType). This
1714/// function returns an implicit conversion sequence that can be used
1715/// to perform the initialization. Given
1716///
1717/// void f(float f);
1718/// void g(int i) { f(i); }
1719///
1720/// this routine would produce an implicit conversion sequence to
1721/// describe the initialization of f from i, which will be a standard
1722/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1723/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1724//
1725/// Note that this routine only determines how the conversion can be
1726/// performed; it does not actually perform the conversion. As such,
1727/// it will not produce any diagnostics if no conversion is available,
1728/// but will instead return an implicit conversion sequence of kind
1729/// "BadConversion".
1730///
1731/// If @p SuppressUserConversions, then user-defined conversions are
1732/// not permitted.
1733/// If @p AllowExplicit, then explicit user-defined conversions are
1734/// permitted.
1735///
1736/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1737/// writeback conversion, which allows __autoreleasing id* parameters to
1738/// be initialized with __strong id* or __weak id* arguments.
1741 bool SuppressUserConversions,
1742 AllowedExplicit AllowExplicit,
1743 bool InOverloadResolution,
1744 bool CStyle,
1745 bool AllowObjCWritebackConversion,
1746 bool AllowObjCConversionOnExplicit) {
1748 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1749 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1750 ICS.setStandard();
1751 return ICS;
1752 }
1753
1754 if (!S.getLangOpts().CPlusPlus) {
1756 return ICS;
1757 }
1758
1759 // C++ [over.ics.user]p4:
1760 // A conversion of an expression of class type to the same class
1761 // type is given Exact Match rank, and a conversion of an
1762 // expression of class type to a base class of that type is
1763 // given Conversion rank, in spite of the fact that a copy/move
1764 // constructor (i.e., a user-defined conversion function) is
1765 // called for those cases.
1766 QualType FromType = From->getType();
1767 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1768 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1769 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1770 ICS.setStandard();
1772 ICS.Standard.setFromType(FromType);
1773 ICS.Standard.setAllToTypes(ToType);
1774
1775 // We don't actually check at this point whether there is a valid
1776 // copy/move constructor, since overloading just assumes that it
1777 // exists. When we actually perform initialization, we'll find the
1778 // appropriate constructor to copy the returned object, if needed.
1779 ICS.Standard.CopyConstructor = nullptr;
1780
1781 // Determine whether this is considered a derived-to-base conversion.
1782 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1784
1785 return ICS;
1786 }
1787
1788 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1789 AllowExplicit, InOverloadResolution, CStyle,
1790 AllowObjCWritebackConversion,
1791 AllowObjCConversionOnExplicit);
1792}
1793
1796 bool SuppressUserConversions,
1797 AllowedExplicit AllowExplicit,
1798 bool InOverloadResolution,
1799 bool CStyle,
1800 bool AllowObjCWritebackConversion) {
1801 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1802 AllowExplicit, InOverloadResolution, CStyle,
1803 AllowObjCWritebackConversion,
1804 /*AllowObjCConversionOnExplicit=*/false);
1805}
1806
1808 AssignmentAction Action,
1809 bool AllowExplicit) {
1810 if (checkPlaceholderForOverload(*this, From))
1811 return ExprError();
1812
1813 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1814 bool AllowObjCWritebackConversion
1815 = getLangOpts().ObjCAutoRefCount &&
1816 (Action == AA_Passing || Action == AA_Sending);
1817 if (getLangOpts().ObjC)
1818 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1819 From->getType(), From);
1821 *this, From, ToType,
1822 /*SuppressUserConversions=*/false,
1823 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1824 /*InOverloadResolution=*/false,
1825 /*CStyle=*/false, AllowObjCWritebackConversion,
1826 /*AllowObjCConversionOnExplicit=*/false);
1827 return PerformImplicitConversion(From, ToType, ICS, Action);
1828}
1829
1831 QualType &ResultTy) {
1832 if (Context.hasSameUnqualifiedType(FromType, ToType))
1833 return false;
1834
1835 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1836 // or F(t noexcept) -> F(t)
1837 // where F adds one of the following at most once:
1838 // - a pointer
1839 // - a member pointer
1840 // - a block pointer
1841 // Changes here need matching changes in FindCompositePointerType.
1842 CanQualType CanTo = Context.getCanonicalType(ToType);
1843 CanQualType CanFrom = Context.getCanonicalType(FromType);
1844 Type::TypeClass TyClass = CanTo->getTypeClass();
1845 if (TyClass != CanFrom->getTypeClass()) return false;
1846 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1847 if (TyClass == Type::Pointer) {
1848 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1849 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1850 } else if (TyClass == Type::BlockPointer) {
1851 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1852 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1853 } else if (TyClass == Type::MemberPointer) {
1854 auto ToMPT = CanTo.castAs<MemberPointerType>();
1855 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1856 // A function pointer conversion cannot change the class of the function.
1857 if (ToMPT->getClass() != FromMPT->getClass())
1858 return false;
1859 CanTo = ToMPT->getPointeeType();
1860 CanFrom = FromMPT->getPointeeType();
1861 } else {
1862 return false;
1863 }
1864
1865 TyClass = CanTo->getTypeClass();
1866 if (TyClass != CanFrom->getTypeClass()) return false;
1867 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1868 return false;
1869 }
1870
1871 const auto *FromFn = cast<FunctionType>(CanFrom);
1872 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1873
1874 const auto *ToFn = cast<FunctionType>(CanTo);
1875 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1876
1877 bool Changed = false;
1878
1879 // Drop 'noreturn' if not present in target type.
1880 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1881 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1882 Changed = true;
1883 }
1884
1885 // Drop 'noexcept' if not present in target type.
1886 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1887 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1888 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1889 FromFn = cast<FunctionType>(
1890 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1891 EST_None)
1892 .getTypePtr());
1893 Changed = true;
1894 }
1895
1896 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1897 // only if the ExtParameterInfo lists of the two function prototypes can be
1898 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1900 bool CanUseToFPT, CanUseFromFPT;
1901 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1902 CanUseFromFPT, NewParamInfos) &&
1903 CanUseToFPT && !CanUseFromFPT) {
1904 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1905 ExtInfo.ExtParameterInfos =
1906 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1907 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1908 FromFPT->getParamTypes(), ExtInfo);
1909 FromFn = QT->getAs<FunctionType>();
1910 Changed = true;
1911 }
1912
1913 // For C, when called from checkPointerTypesForAssignment,
1914 // we need to not alter FromFn, or else even an innocuous cast
1915 // like dropping effects will fail. In C++ however we do want to
1916 // alter FromFn (because of the way PerformImplicitConversion works).
1917 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
1918 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
1919
1920 // Transparently add/drop effects; here we are concerned with
1921 // language rules/canonicalization. Adding/dropping effects is a warning.
1922 const auto FromFX = FromFPT->getFunctionEffects();
1923 const auto ToFX = ToFPT->getFunctionEffects();
1924 if (FromFX != ToFX) {
1925 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1926 ExtInfo.FunctionEffects = ToFX;
1927 QualType QT = Context.getFunctionType(
1928 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
1929 FromFn = QT->getAs<FunctionType>();
1930 Changed = true;
1931 }
1932 }
1933 }
1934
1935 if (!Changed)
1936 return false;
1937
1938 assert(QualType(FromFn, 0).isCanonical());
1939 if (QualType(FromFn, 0) != CanTo) return false;
1940
1941 ResultTy = ToType;
1942 return true;
1943}
1944
1945/// Determine whether the conversion from FromType to ToType is a valid
1946/// floating point conversion.
1947///
1948static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1949 QualType ToType) {
1950 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1951 return false;
1952 // FIXME: disable conversions between long double, __ibm128 and __float128
1953 // if their representation is different until there is back end support
1954 // We of course allow this conversion if long double is really double.
1955
1956 // Conversions between bfloat16 and float16 are currently not supported.
1957 if ((FromType->isBFloat16Type() &&
1958 (ToType->isFloat16Type() || ToType->isHalfType())) ||
1959 (ToType->isBFloat16Type() &&
1960 (FromType->isFloat16Type() || FromType->isHalfType())))
1961 return false;
1962
1963 // Conversions between IEEE-quad and IBM-extended semantics are not
1964 // permitted.
1965 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
1966 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1967 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1968 &ToSem == &llvm::APFloat::IEEEquad()) ||
1969 (&FromSem == &llvm::APFloat::IEEEquad() &&
1970 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1971 return false;
1972 return true;
1973}
1974
1975static bool IsVectorElementConversion(Sema &S, QualType FromType,
1976 QualType ToType,
1977 ImplicitConversionKind &ICK, Expr *From) {
1978 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1979 return true;
1980
1981 if (S.IsFloatingPointPromotion(FromType, ToType)) {
1983 return true;
1984 }
1985
1986 if (IsFloatingPointConversion(S, FromType, ToType)) {
1988 return true;
1989 }
1990
1991 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
1993 return true;
1994 }
1995
1996 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
1998 ToType->isRealFloatingType())) {
2000 return true;
2001 }
2002
2003 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2005 return true;
2006 }
2007
2008 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2009 ToType->isIntegralType(S.Context)) {
2011 return true;
2012 }
2013
2014 return false;
2015}
2016
2017/// Determine whether the conversion from FromType to ToType is a valid
2018/// vector conversion.
2019///
2020/// \param ICK Will be set to the vector conversion kind, if this is a vector
2021/// conversion.
2022static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2024 ImplicitConversionKind &ElConv, Expr *From,
2025 bool InOverloadResolution, bool CStyle) {
2026 // We need at least one of these types to be a vector type to have a vector
2027 // conversion.
2028 if (!ToType->isVectorType() && !FromType->isVectorType())
2029 return false;
2030
2031 // Identical types require no conversions.
2032 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2033 return false;
2034
2035 // There are no conversions between extended vector types, only identity.
2036 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2037 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2038 // HLSL allows implicit truncation of vector types.
2039 if (S.getLangOpts().HLSL) {
2040 unsigned FromElts = FromExtType->getNumElements();
2041 unsigned ToElts = ToExtType->getNumElements();
2042 if (FromElts < ToElts)
2043 return false;
2044 if (FromElts == ToElts)
2045 ElConv = ICK_Identity;
2046 else
2048
2049 QualType FromElTy = FromExtType->getElementType();
2050 QualType ToElTy = ToExtType->getElementType();
2051 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2052 return true;
2053 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2054 }
2055 // There are no conversions between extended vector types other than the
2056 // identity conversion.
2057 return false;
2058 }
2059
2060 // Vector splat from any arithmetic type to a vector.
2061 if (FromType->isArithmeticType()) {
2062 if (S.getLangOpts().HLSL) {
2063 ElConv = ICK_HLSL_Vector_Splat;
2064 QualType ToElTy = ToExtType->getElementType();
2065 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2066 }
2067 ICK = ICK_Vector_Splat;
2068 return true;
2069 }
2070 }
2071
2072 if (ToType->isSVESizelessBuiltinType() ||
2073 FromType->isSVESizelessBuiltinType())
2074 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
2075 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
2077 return true;
2078 }
2079
2080 if (ToType->isRVVSizelessBuiltinType() ||
2081 FromType->isRVVSizelessBuiltinType())
2082 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2083 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2085 return true;
2086 }
2087
2088 // We can perform the conversion between vector types in the following cases:
2089 // 1)vector types are equivalent AltiVec and GCC vector types
2090 // 2)lax vector conversions are permitted and the vector types are of the
2091 // same size
2092 // 3)the destination type does not have the ARM MVE strict-polymorphism
2093 // attribute, which inhibits lax vector conversion for overload resolution
2094 // only
2095 if (ToType->isVectorType() && FromType->isVectorType()) {
2096 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2097 (S.isLaxVectorConversion(FromType, ToType) &&
2098 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2099 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2100 S.isLaxVectorConversion(FromType, ToType) &&
2101 S.anyAltivecTypes(FromType, ToType) &&
2102 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2103 !InOverloadResolution && !CStyle) {
2104 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2105 << FromType << ToType;
2106 }
2108 return true;
2109 }
2110 }
2111
2112 return false;
2113}
2114
2115static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2116 bool InOverloadResolution,
2118 bool CStyle);
2119
2120/// IsStandardConversion - Determines whether there is a standard
2121/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2122/// expression From to the type ToType. Standard conversion sequences
2123/// only consider non-class types; for conversions that involve class
2124/// types, use TryImplicitConversion. If a conversion exists, SCS will
2125/// contain the standard conversion sequence required to perform this
2126/// conversion and this routine will return true. Otherwise, this
2127/// routine will return false and the value of SCS is unspecified.
2128static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2129 bool InOverloadResolution,
2131 bool CStyle,
2132 bool AllowObjCWritebackConversion) {
2133 QualType FromType = From->getType();
2134
2135 // Standard conversions (C++ [conv])
2137 SCS.IncompatibleObjC = false;
2138 SCS.setFromType(FromType);
2139 SCS.CopyConstructor = nullptr;
2140
2141 // There are no standard conversions for class types in C++, so
2142 // abort early. When overloading in C, however, we do permit them.
2143 if (S.getLangOpts().CPlusPlus &&
2144 (FromType->isRecordType() || ToType->isRecordType()))
2145 return false;
2146
2147 // The first conversion can be an lvalue-to-rvalue conversion,
2148 // array-to-pointer conversion, or function-to-pointer conversion
2149 // (C++ 4p1).
2150
2151 if (FromType == S.Context.OverloadTy) {
2152 DeclAccessPair AccessPair;
2153 if (FunctionDecl *Fn
2154 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2155 AccessPair)) {
2156 // We were able to resolve the address of the overloaded function,
2157 // so we can convert to the type of that function.
2158 FromType = Fn->getType();
2159 SCS.setFromType(FromType);
2160
2161 // we can sometimes resolve &foo<int> regardless of ToType, so check
2162 // if the type matches (identity) or we are converting to bool
2164 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2165 QualType resultTy;
2166 // if the function type matches except for [[noreturn]], it's ok
2167 if (!S.IsFunctionConversion(FromType,
2168 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
2169 // otherwise, only a boolean conversion is standard
2170 if (!ToType->isBooleanType())
2171 return false;
2172 }
2173
2174 // Check if the "from" expression is taking the address of an overloaded
2175 // function and recompute the FromType accordingly. Take advantage of the
2176 // fact that non-static member functions *must* have such an address-of
2177 // expression.
2178 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2179 if (Method && !Method->isStatic() &&
2180 !Method->isExplicitObjectMemberFunction()) {
2181 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2182 "Non-unary operator on non-static member address");
2183 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2184 == UO_AddrOf &&
2185 "Non-address-of operator on non-static member address");
2186 const Type *ClassType
2188 FromType = S.Context.getMemberPointerType(FromType, ClassType);
2189 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2190 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2191 UO_AddrOf &&
2192 "Non-address-of operator for overloaded function expression");
2193 FromType = S.Context.getPointerType(FromType);
2194 }
2195 } else {
2196 return false;
2197 }
2198 }
2199 // Lvalue-to-rvalue conversion (C++11 4.1):
2200 // A glvalue (3.10) of a non-function, non-array type T can
2201 // be converted to a prvalue.
2202 bool argIsLValue = From->isGLValue();
2203 if (argIsLValue && !FromType->canDecayToPointerType() &&
2204 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2206
2207 // C11 6.3.2.1p2:
2208 // ... if the lvalue has atomic type, the value has the non-atomic version
2209 // of the type of the lvalue ...
2210 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2211 FromType = Atomic->getValueType();
2212
2213 // If T is a non-class type, the type of the rvalue is the
2214 // cv-unqualified version of T. Otherwise, the type of the rvalue
2215 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2216 // just strip the qualifiers because they don't matter.
2217 FromType = FromType.getUnqualifiedType();
2218 } else if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2219 ToType->isArrayParameterType()) {
2220 // HLSL constant array parameters do not decay, so if the argument is a
2221 // constant array and the parameter is an ArrayParameterType we have special
2222 // handling here.
2223 FromType = S.Context.getArrayParameterType(FromType);
2224 if (S.Context.getCanonicalType(FromType) !=
2225 S.Context.getCanonicalType(ToType))
2226 return false;
2227
2229 SCS.setAllToTypes(ToType);
2230 return true;
2231 } else if (FromType->isArrayType()) {
2232 // Array-to-pointer conversion (C++ 4.2)
2234
2235 // An lvalue or rvalue of type "array of N T" or "array of unknown
2236 // bound of T" can be converted to an rvalue of type "pointer to
2237 // T" (C++ 4.2p1).
2238 FromType = S.Context.getArrayDecayedType(FromType);
2239
2240 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2241 // This conversion is deprecated in C++03 (D.4)
2243
2244 // For the purpose of ranking in overload resolution
2245 // (13.3.3.1.1), this conversion is considered an
2246 // array-to-pointer conversion followed by a qualification
2247 // conversion (4.4). (C++ 4.2p2)
2248 SCS.Second = ICK_Identity;
2251 SCS.setAllToTypes(FromType);
2252 return true;
2253 }
2254 } else if (FromType->isFunctionType() && argIsLValue) {
2255 // Function-to-pointer conversion (C++ 4.3).
2257
2258 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2259 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2261 return false;
2262
2263 // An lvalue of function type T can be converted to an rvalue of
2264 // type "pointer to T." The result is a pointer to the
2265 // function. (C++ 4.3p1).
2266 FromType = S.Context.getPointerType(FromType);
2267 } else {
2268 // We don't require any conversions for the first step.
2269 SCS.First = ICK_Identity;
2270 }
2271 SCS.setToType(0, FromType);
2272
2273 // The second conversion can be an integral promotion, floating
2274 // point promotion, integral conversion, floating point conversion,
2275 // floating-integral conversion, pointer conversion,
2276 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2277 // For overloading in C, this can also be a "compatible-type"
2278 // conversion.
2279 bool IncompatibleObjC = false;
2281 ImplicitConversionKind DimensionICK = ICK_Identity;
2282 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2283 // The unqualified versions of the types are the same: there's no
2284 // conversion to do.
2285 SCS.Second = ICK_Identity;
2286 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2287 // Integral promotion (C++ 4.5).
2289 FromType = ToType.getUnqualifiedType();
2290 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2291 // Floating point promotion (C++ 4.6).
2293 FromType = ToType.getUnqualifiedType();
2294 } else if (S.IsComplexPromotion(FromType, ToType)) {
2295 // Complex promotion (Clang extension)
2297 FromType = ToType.getUnqualifiedType();
2298 } else if (ToType->isBooleanType() &&
2299 (FromType->isArithmeticType() ||
2300 FromType->isAnyPointerType() ||
2301 FromType->isBlockPointerType() ||
2302 FromType->isMemberPointerType())) {
2303 // Boolean conversions (C++ 4.12).
2305 FromType = S.Context.BoolTy;
2306 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2307 ToType->isIntegralType(S.Context)) {
2308 // Integral conversions (C++ 4.7).
2310 FromType = ToType.getUnqualifiedType();
2311 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2312 // Complex conversions (C99 6.3.1.6)
2314 FromType = ToType.getUnqualifiedType();
2315 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2316 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2317 // Complex-real conversions (C99 6.3.1.7)
2319 FromType = ToType.getUnqualifiedType();
2320 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2321 // Floating point conversions (C++ 4.8).
2323 FromType = ToType.getUnqualifiedType();
2324 } else if ((FromType->isRealFloatingType() &&
2325 ToType->isIntegralType(S.Context)) ||
2327 ToType->isRealFloatingType())) {
2328
2329 // Floating-integral conversions (C++ 4.9).
2331 FromType = ToType.getUnqualifiedType();
2332 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2334 } else if (AllowObjCWritebackConversion &&
2335 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2337 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2338 FromType, IncompatibleObjC)) {
2339 // Pointer conversions (C++ 4.10).
2341 SCS.IncompatibleObjC = IncompatibleObjC;
2342 FromType = FromType.getUnqualifiedType();
2343 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2344 InOverloadResolution, FromType)) {
2345 // Pointer to member conversions (4.11).
2347 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2348 From, InOverloadResolution, CStyle)) {
2349 SCS.Second = SecondICK;
2350 SCS.Dimension = DimensionICK;
2351 FromType = ToType.getUnqualifiedType();
2352 } else if (!S.getLangOpts().CPlusPlus &&
2353 S.Context.typesAreCompatible(ToType, FromType)) {
2354 // Compatible conversions (Clang extension for C function overloading)
2356 FromType = ToType.getUnqualifiedType();
2358 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2360 FromType = ToType;
2361 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2362 CStyle)) {
2363 // tryAtomicConversion has updated the standard conversion sequence
2364 // appropriately.
2365 return true;
2366 } else if (ToType->isEventT() &&
2368 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2370 FromType = ToType;
2371 } else if (ToType->isQueueT() &&
2373 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2375 FromType = ToType;
2376 } else if (ToType->isSamplerT() &&
2379 FromType = ToType;
2380 } else if ((ToType->isFixedPointType() &&
2381 FromType->isConvertibleToFixedPointType()) ||
2382 (FromType->isFixedPointType() &&
2383 ToType->isConvertibleToFixedPointType())) {
2385 FromType = ToType;
2386 } else {
2387 // No second conversion required.
2388 SCS.Second = ICK_Identity;
2389 }
2390 SCS.setToType(1, FromType);
2391
2392 // The third conversion can be a function pointer conversion or a
2393 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2394 bool ObjCLifetimeConversion;
2395 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2396 // Function pointer conversions (removing 'noexcept') including removal of
2397 // 'noreturn' (Clang extension).
2399 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2400 ObjCLifetimeConversion)) {
2402 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2403 FromType = ToType;
2404 } else {
2405 // No conversion required
2406 SCS.Third = ICK_Identity;
2407 }
2408
2409 // C++ [over.best.ics]p6:
2410 // [...] Any difference in top-level cv-qualification is
2411 // subsumed by the initialization itself and does not constitute
2412 // a conversion. [...]
2413 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2414 QualType CanonTo = S.Context.getCanonicalType(ToType);
2415 if (CanonFrom.getLocalUnqualifiedType()
2416 == CanonTo.getLocalUnqualifiedType() &&
2417 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2418 FromType = ToType;
2419 CanonFrom = CanonTo;
2420 }
2421
2422 SCS.setToType(2, FromType);
2423
2424 if (CanonFrom == CanonTo)
2425 return true;
2426
2427 // If we have not converted the argument type to the parameter type,
2428 // this is a bad conversion sequence, unless we're resolving an overload in C.
2429 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2430 return false;
2431
2432 ExprResult ER = ExprResult{From};
2435 /*Diagnose=*/false,
2436 /*DiagnoseCFAudited=*/false,
2437 /*ConvertRHS=*/false);
2438 ImplicitConversionKind SecondConv;
2439 switch (Conv) {
2440 case Sema::Compatible:
2441 SecondConv = ICK_C_Only_Conversion;
2442 break;
2443 // For our purposes, discarding qualifiers is just as bad as using an
2444 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2445 // qualifiers, as well.
2450 break;
2451 default:
2452 return false;
2453 }
2454
2455 // First can only be an lvalue conversion, so we pretend that this was the
2456 // second conversion. First should already be valid from earlier in the
2457 // function.
2458 SCS.Second = SecondConv;
2459 SCS.setToType(1, ToType);
2460
2461 // Third is Identity, because Second should rank us worse than any other
2462 // conversion. This could also be ICK_Qualification, but it's simpler to just
2463 // lump everything in with the second conversion, and we don't gain anything
2464 // from making this ICK_Qualification.
2465 SCS.Third = ICK_Identity;
2466 SCS.setToType(2, ToType);
2467 return true;
2468}
2469
2470static bool
2472 QualType &ToType,
2473 bool InOverloadResolution,
2475 bool CStyle) {
2476
2477 const RecordType *UT = ToType->getAsUnionType();
2478 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2479 return false;
2480 // The field to initialize within the transparent union.
2481 RecordDecl *UD = UT->getDecl();
2482 // It's compatible if the expression matches any of the fields.
2483 for (const auto *it : UD->fields()) {
2484 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2485 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2486 ToType = it->getType();
2487 return true;
2488 }
2489 }
2490 return false;
2491}
2492
2493bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2494 const BuiltinType *To = ToType->getAs<BuiltinType>();
2495 // All integers are built-in.
2496 if (!To) {
2497 return false;
2498 }
2499
2500 // An rvalue of type char, signed char, unsigned char, short int, or
2501 // unsigned short int can be converted to an rvalue of type int if
2502 // int can represent all the values of the source type; otherwise,
2503 // the source rvalue can be converted to an rvalue of type unsigned
2504 // int (C++ 4.5p1).
2505 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2506 !FromType->isEnumeralType()) {
2507 if ( // We can promote any signed, promotable integer type to an int
2508 (FromType->isSignedIntegerType() ||
2509 // We can promote any unsigned integer type whose size is
2510 // less than int to an int.
2511 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2512 return To->getKind() == BuiltinType::Int;
2513 }
2514
2515 return To->getKind() == BuiltinType::UInt;
2516 }
2517
2518 // C++11 [conv.prom]p3:
2519 // A prvalue of an unscoped enumeration type whose underlying type is not
2520 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2521 // following types that can represent all the values of the enumeration
2522 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2523 // unsigned int, long int, unsigned long int, long long int, or unsigned
2524 // long long int. If none of the types in that list can represent all the
2525 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2526 // type can be converted to an rvalue a prvalue of the extended integer type
2527 // with lowest integer conversion rank (4.13) greater than the rank of long
2528 // long in which all the values of the enumeration can be represented. If
2529 // there are two such extended types, the signed one is chosen.
2530 // C++11 [conv.prom]p4:
2531 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2532 // can be converted to a prvalue of its underlying type. Moreover, if
2533 // integral promotion can be applied to its underlying type, a prvalue of an
2534 // unscoped enumeration type whose underlying type is fixed can also be
2535 // converted to a prvalue of the promoted underlying type.
2536 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2537 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2538 // provided for a scoped enumeration.
2539 if (FromEnumType->getDecl()->isScoped())
2540 return false;
2541
2542 // We can perform an integral promotion to the underlying type of the enum,
2543 // even if that's not the promoted type. Note that the check for promoting
2544 // the underlying type is based on the type alone, and does not consider
2545 // the bitfield-ness of the actual source expression.
2546 if (FromEnumType->getDecl()->isFixed()) {
2547 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2548 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2549 IsIntegralPromotion(nullptr, Underlying, ToType);
2550 }
2551
2552 // We have already pre-calculated the promotion type, so this is trivial.
2553 if (ToType->isIntegerType() &&
2554 isCompleteType(From->getBeginLoc(), FromType))
2555 return Context.hasSameUnqualifiedType(
2556 ToType, FromEnumType->getDecl()->getPromotionType());
2557
2558 // C++ [conv.prom]p5:
2559 // If the bit-field has an enumerated type, it is treated as any other
2560 // value of that type for promotion purposes.
2561 //
2562 // ... so do not fall through into the bit-field checks below in C++.
2563 if (getLangOpts().CPlusPlus)
2564 return false;
2565 }
2566
2567 // C++0x [conv.prom]p2:
2568 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2569 // to an rvalue a prvalue of the first of the following types that can
2570 // represent all the values of its underlying type: int, unsigned int,
2571 // long int, unsigned long int, long long int, or unsigned long long int.
2572 // If none of the types in that list can represent all the values of its
2573 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2574 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2575 // type.
2576 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2577 ToType->isIntegerType()) {
2578 // Determine whether the type we're converting from is signed or
2579 // unsigned.
2580 bool FromIsSigned = FromType->isSignedIntegerType();
2581 uint64_t FromSize = Context.getTypeSize(FromType);
2582
2583 // The types we'll try to promote to, in the appropriate
2584 // order. Try each of these types.
2585 QualType PromoteTypes[6] = {
2586 Context.IntTy, Context.UnsignedIntTy,
2587 Context.LongTy, Context.UnsignedLongTy ,
2588 Context.LongLongTy, Context.UnsignedLongLongTy
2589 };
2590 for (int Idx = 0; Idx < 6; ++Idx) {
2591 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2592 if (FromSize < ToSize ||
2593 (FromSize == ToSize &&
2594 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2595 // We found the type that we can promote to. If this is the
2596 // type we wanted, we have a promotion. Otherwise, no
2597 // promotion.
2598 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2599 }
2600 }
2601 }
2602
2603 // An rvalue for an integral bit-field (9.6) can be converted to an
2604 // rvalue of type int if int can represent all the values of the
2605 // bit-field; otherwise, it can be converted to unsigned int if
2606 // unsigned int can represent all the values of the bit-field. If
2607 // the bit-field is larger yet, no integral promotion applies to
2608 // it. If the bit-field has an enumerated type, it is treated as any
2609 // other value of that type for promotion purposes (C++ 4.5p3).
2610 // FIXME: We should delay checking of bit-fields until we actually perform the
2611 // conversion.
2612 //
2613 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2614 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2615 // bit-fields and those whose underlying type is larger than int) for GCC
2616 // compatibility.
2617 if (From) {
2618 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2619 std::optional<llvm::APSInt> BitWidth;
2620 if (FromType->isIntegralType(Context) &&
2621 (BitWidth =
2622 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2623 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2624 ToSize = Context.getTypeSize(ToType);
2625
2626 // Are we promoting to an int from a bitfield that fits in an int?
2627 if (*BitWidth < ToSize ||
2628 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2629 return To->getKind() == BuiltinType::Int;
2630 }
2631
2632 // Are we promoting to an unsigned int from an unsigned bitfield
2633 // that fits into an unsigned int?
2634 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2635 return To->getKind() == BuiltinType::UInt;
2636 }
2637
2638 return false;
2639 }
2640 }
2641 }
2642
2643 // An rvalue of type bool can be converted to an rvalue of type int,
2644 // with false becoming zero and true becoming one (C++ 4.5p4).
2645 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2646 return true;
2647 }
2648
2649 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2650 // integral type.
2651 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2652 ToType->isIntegerType())
2653 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2654
2655 return false;
2656}
2657
2659 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2660 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2661 /// An rvalue of type float can be converted to an rvalue of type
2662 /// double. (C++ 4.6p1).
2663 if (FromBuiltin->getKind() == BuiltinType::Float &&
2664 ToBuiltin->getKind() == BuiltinType::Double)
2665 return true;
2666
2667 // C99 6.3.1.5p1:
2668 // When a float is promoted to double or long double, or a
2669 // double is promoted to long double [...].
2670 if (!getLangOpts().CPlusPlus &&
2671 (FromBuiltin->getKind() == BuiltinType::Float ||
2672 FromBuiltin->getKind() == BuiltinType::Double) &&
2673 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2674 ToBuiltin->getKind() == BuiltinType::Float128 ||
2675 ToBuiltin->getKind() == BuiltinType::Ibm128))
2676 return true;
2677
2678 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2679 // or not native half types are enabled.
2680 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2681 (ToBuiltin->getKind() == BuiltinType::Float ||
2682 ToBuiltin->getKind() == BuiltinType::Double))
2683 return true;
2684
2685 // Half can be promoted to float.
2686 if (!getLangOpts().NativeHalfType &&
2687 FromBuiltin->getKind() == BuiltinType::Half &&
2688 ToBuiltin->getKind() == BuiltinType::Float)
2689 return true;
2690 }
2691
2692 return false;
2693}
2694
2696 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2697 if (!FromComplex)
2698 return false;
2699
2700 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2701 if (!ToComplex)
2702 return false;
2703
2704 return IsFloatingPointPromotion(FromComplex->getElementType(),
2705 ToComplex->getElementType()) ||
2706 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2707 ToComplex->getElementType());
2708}
2709
2710/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2711/// the pointer type FromPtr to a pointer to type ToPointee, with the
2712/// same type qualifiers as FromPtr has on its pointee type. ToType,
2713/// if non-empty, will be a pointer to ToType that may or may not have
2714/// the right set of qualifiers on its pointee.
2715///
2716static QualType
2718 QualType ToPointee, QualType ToType,
2719 ASTContext &Context,
2720 bool StripObjCLifetime = false) {
2721 assert((FromPtr->getTypeClass() == Type::Pointer ||
2722 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2723 "Invalid similarly-qualified pointer type");
2724
2725 /// Conversions to 'id' subsume cv-qualifier conversions.
2726 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2727 return ToType.getUnqualifiedType();
2728
2729 QualType CanonFromPointee
2730 = Context.getCanonicalType(FromPtr->getPointeeType());
2731 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2732 Qualifiers Quals = CanonFromPointee.getQualifiers();
2733
2734 if (StripObjCLifetime)
2735 Quals.removeObjCLifetime();
2736
2737 // Exact qualifier match -> return the pointer type we're converting to.
2738 if (CanonToPointee.getLocalQualifiers() == Quals) {
2739 // ToType is exactly what we need. Return it.
2740 if (!ToType.isNull())
2741 return ToType.getUnqualifiedType();
2742
2743 // Build a pointer to ToPointee. It has the right qualifiers
2744 // already.
2745 if (isa<ObjCObjectPointerType>(ToType))
2746 return Context.getObjCObjectPointerType(ToPointee);
2747 return Context.getPointerType(ToPointee);
2748 }
2749
2750 // Just build a canonical type that has the right qualifiers.
2751 QualType QualifiedCanonToPointee
2752 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2753
2754 if (isa<ObjCObjectPointerType>(ToType))
2755 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2756 return Context.getPointerType(QualifiedCanonToPointee);
2757}
2758
2760 bool InOverloadResolution,
2761 ASTContext &Context) {
2762 // Handle value-dependent integral null pointer constants correctly.
2763 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2764 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2766 return !InOverloadResolution;
2767
2768 return Expr->isNullPointerConstant(Context,
2769 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2771}
2772
2774 bool InOverloadResolution,
2775 QualType& ConvertedType,
2776 bool &IncompatibleObjC) {
2777 IncompatibleObjC = false;
2778 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2779 IncompatibleObjC))
2780 return true;
2781
2782 // Conversion from a null pointer constant to any Objective-C pointer type.
2783 if (ToType->isObjCObjectPointerType() &&
2784 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2785 ConvertedType = ToType;
2786 return true;
2787 }
2788
2789 // Blocks: Block pointers can be converted to void*.
2790 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2791 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2792 ConvertedType = ToType;
2793 return true;
2794 }
2795 // Blocks: A null pointer constant can be converted to a block
2796 // pointer type.
2797 if (ToType->isBlockPointerType() &&
2798 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2799 ConvertedType = ToType;
2800 return true;
2801 }
2802
2803 // If the left-hand-side is nullptr_t, the right side can be a null
2804 // pointer constant.
2805 if (ToType->isNullPtrType() &&
2806 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2807 ConvertedType = ToType;
2808 return true;
2809 }
2810
2811 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2812 if (!ToTypePtr)
2813 return false;
2814
2815 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2816 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2817 ConvertedType = ToType;
2818 return true;
2819 }
2820
2821 // Beyond this point, both types need to be pointers
2822 // , including objective-c pointers.
2823 QualType ToPointeeType = ToTypePtr->getPointeeType();
2824 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2825 !getLangOpts().ObjCAutoRefCount) {
2826 ConvertedType = BuildSimilarlyQualifiedPointerType(
2827 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2828 Context);
2829 return true;
2830 }
2831 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2832 if (!FromTypePtr)
2833 return false;
2834
2835 QualType FromPointeeType = FromTypePtr->getPointeeType();
2836
2837 // If the unqualified pointee types are the same, this can't be a
2838 // pointer conversion, so don't do all of the work below.
2839 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2840 return false;
2841
2842 // An rvalue of type "pointer to cv T," where T is an object type,
2843 // can be converted to an rvalue of type "pointer to cv void" (C++
2844 // 4.10p2).
2845 if (FromPointeeType->isIncompleteOrObjectType() &&
2846 ToPointeeType->isVoidType()) {
2847 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2848 ToPointeeType,
2849 ToType, Context,
2850 /*StripObjCLifetime=*/true);
2851 return true;
2852 }
2853
2854 // MSVC allows implicit function to void* type conversion.
2855 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2856 ToPointeeType->isVoidType()) {
2857 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2858 ToPointeeType,
2859 ToType, Context);
2860 return true;
2861 }
2862
2863 // When we're overloading in C, we allow a special kind of pointer
2864 // conversion for compatible-but-not-identical pointee types.
2865 if (!getLangOpts().CPlusPlus &&
2866 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2867 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2868 ToPointeeType,
2869 ToType, Context);
2870 return true;
2871 }
2872
2873 // C++ [conv.ptr]p3:
2874 //
2875 // An rvalue of type "pointer to cv D," where D is a class type,
2876 // can be converted to an rvalue of type "pointer to cv B," where
2877 // B is a base class (clause 10) of D. If B is an inaccessible
2878 // (clause 11) or ambiguous (10.2) base class of D, a program that
2879 // necessitates this conversion is ill-formed. The result of the
2880 // conversion is a pointer to the base class sub-object of the
2881 // derived class object. The null pointer value is converted to
2882 // the null pointer value of the destination type.
2883 //
2884 // Note that we do not check for ambiguity or inaccessibility
2885 // here. That is handled by CheckPointerConversion.
2886 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2887 ToPointeeType->isRecordType() &&
2888 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2889 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2890 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2891 ToPointeeType,
2892 ToType, Context);
2893 return true;
2894 }
2895
2896 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2897 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2898 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2899 ToPointeeType,
2900 ToType, Context);
2901 return true;
2902 }
2903
2904 return false;
2905}
2906
2907/// Adopt the given qualifiers for the given type.
2909 Qualifiers TQs = T.getQualifiers();
2910
2911 // Check whether qualifiers already match.
2912 if (TQs == Qs)
2913 return T;
2914
2915 if (Qs.compatiblyIncludes(TQs))
2916 return Context.getQualifiedType(T, Qs);
2917
2918 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2919}
2920
2922 QualType& ConvertedType,
2923 bool &IncompatibleObjC) {
2924 if (!getLangOpts().ObjC)
2925 return false;
2926
2927 // The set of qualifiers on the type we're converting from.
2928 Qualifiers FromQualifiers = FromType.getQualifiers();
2929
2930 // First, we handle all conversions on ObjC object pointer types.
2931 const ObjCObjectPointerType* ToObjCPtr =
2932 ToType->getAs<ObjCObjectPointerType>();
2933 const ObjCObjectPointerType *FromObjCPtr =
2934 FromType->getAs<ObjCObjectPointerType>();
2935
2936 if (ToObjCPtr && FromObjCPtr) {
2937 // If the pointee types are the same (ignoring qualifications),
2938 // then this is not a pointer conversion.
2939 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2940 FromObjCPtr->getPointeeType()))
2941 return false;
2942
2943 // Conversion between Objective-C pointers.
2944 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2945 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2946 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2947 if (getLangOpts().CPlusPlus && LHS && RHS &&
2949 FromObjCPtr->getPointeeType()))
2950 return false;
2951 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2952 ToObjCPtr->getPointeeType(),
2953 ToType, Context);
2954 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2955 return true;
2956 }
2957
2958 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2959 // Okay: this is some kind of implicit downcast of Objective-C
2960 // interfaces, which is permitted. However, we're going to
2961 // complain about it.
2962 IncompatibleObjC = true;
2963 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2964 ToObjCPtr->getPointeeType(),
2965 ToType, Context);
2966 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2967 return true;
2968 }
2969 }
2970 // Beyond this point, both types need to be C pointers or block pointers.
2971 QualType ToPointeeType;
2972 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2973 ToPointeeType = ToCPtr->getPointeeType();
2974 else if (const BlockPointerType *ToBlockPtr =
2975 ToType->getAs<BlockPointerType>()) {
2976 // Objective C++: We're able to convert from a pointer to any object
2977 // to a block pointer type.
2978 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2979 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2980 return true;
2981 }
2982 ToPointeeType = ToBlockPtr->getPointeeType();
2983 }
2984 else if (FromType->getAs<BlockPointerType>() &&
2985 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2986 // Objective C++: We're able to convert from a block pointer type to a
2987 // pointer to any object.
2988 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2989 return true;
2990 }
2991 else
2992 return false;
2993
2994 QualType FromPointeeType;
2995 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2996 FromPointeeType = FromCPtr->getPointeeType();
2997 else if (const BlockPointerType *FromBlockPtr =
2998 FromType->getAs<BlockPointerType>())
2999 FromPointeeType = FromBlockPtr->getPointeeType();
3000 else
3001 return false;
3002
3003 // If we have pointers to pointers, recursively check whether this
3004 // is an Objective-C conversion.
3005 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3006 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3007 IncompatibleObjC)) {
3008 // We always complain about this conversion.
3009 IncompatibleObjC = true;
3010 ConvertedType = Context.getPointerType(ConvertedType);
3011 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3012 return true;
3013 }
3014 // Allow conversion of pointee being objective-c pointer to another one;
3015 // as in I* to id.
3016 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3017 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3018 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3019 IncompatibleObjC)) {
3020
3021 ConvertedType = Context.getPointerType(ConvertedType);
3022 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3023 return true;
3024 }
3025
3026 // If we have pointers to functions or blocks, check whether the only
3027 // differences in the argument and result types are in Objective-C
3028 // pointer conversions. If so, we permit the conversion (but
3029 // complain about it).
3030 const FunctionProtoType *FromFunctionType
3031 = FromPointeeType->getAs<FunctionProtoType>();
3032 const FunctionProtoType *ToFunctionType
3033 = ToPointeeType->getAs<FunctionProtoType>();
3034 if (FromFunctionType && ToFunctionType) {
3035 // If the function types are exactly the same, this isn't an
3036 // Objective-C pointer conversion.
3037 if (Context.getCanonicalType(FromPointeeType)
3038 == Context.getCanonicalType(ToPointeeType))
3039 return false;
3040
3041 // Perform the quick checks that will tell us whether these
3042 // function types are obviously different.
3043 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3044 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3045 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3046 return false;
3047
3048 bool HasObjCConversion = false;
3049 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3050 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3051 // Okay, the types match exactly. Nothing to do.
3052 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3053 ToFunctionType->getReturnType(),
3054 ConvertedType, IncompatibleObjC)) {
3055 // Okay, we have an Objective-C pointer conversion.
3056 HasObjCConversion = true;
3057 } else {
3058 // Function types are too different. Abort.
3059 return false;
3060 }
3061
3062 // Check argument types.
3063 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3064 ArgIdx != NumArgs; ++ArgIdx) {
3065 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3066 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3067 if (Context.getCanonicalType(FromArgType)
3068 == Context.getCanonicalType(ToArgType)) {
3069 // Okay, the types match exactly. Nothing to do.
3070 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3071 ConvertedType, IncompatibleObjC)) {
3072 // Okay, we have an Objective-C pointer conversion.
3073 HasObjCConversion = true;
3074 } else {
3075 // Argument types are too different. Abort.
3076 return false;
3077 }
3078 }
3079
3080 if (HasObjCConversion) {
3081 // We had an Objective-C conversion. Allow this pointer
3082 // conversion, but complain about it.
3083 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3084 IncompatibleObjC = true;
3085 return true;
3086 }
3087 }
3088
3089 return false;
3090}
3091
3093 QualType& ConvertedType) {
3094 QualType ToPointeeType;
3095 if (const BlockPointerType *ToBlockPtr =
3096 ToType->getAs<BlockPointerType>())
3097 ToPointeeType = ToBlockPtr->getPointeeType();
3098 else
3099 return false;
3100
3101 QualType FromPointeeType;
3102 if (const BlockPointerType *FromBlockPtr =
3103 FromType->getAs<BlockPointerType>())
3104 FromPointeeType = FromBlockPtr->getPointeeType();
3105 else
3106 return false;
3107 // We have pointer to blocks, check whether the only
3108 // differences in the argument and result types are in Objective-C
3109 // pointer conversions. If so, we permit the conversion.
3110
3111 const FunctionProtoType *FromFunctionType
3112 = FromPointeeType->getAs<FunctionProtoType>();
3113 const FunctionProtoType *ToFunctionType
3114 = ToPointeeType->getAs<FunctionProtoType>();
3115
3116 if (!FromFunctionType || !ToFunctionType)
3117 return false;
3118
3119 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3120 return true;
3121
3122 // Perform the quick checks that will tell us whether these
3123 // function types are obviously different.
3124 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3125 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3126 return false;
3127
3128 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3129 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3130 if (FromEInfo != ToEInfo)
3131 return false;
3132
3133 bool IncompatibleObjC = false;
3134 if (Context.hasSameType(FromFunctionType->getReturnType(),
3135 ToFunctionType->getReturnType())) {
3136 // Okay, the types match exactly. Nothing to do.
3137 } else {
3138 QualType RHS = FromFunctionType->getReturnType();
3139 QualType LHS = ToFunctionType->getReturnType();
3140 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3141 !RHS.hasQualifiers() && LHS.hasQualifiers())
3142 LHS = LHS.getUnqualifiedType();
3143
3144 if (Context.hasSameType(RHS,LHS)) {
3145 // OK exact match.
3146 } else if (isObjCPointerConversion(RHS, LHS,
3147 ConvertedType, IncompatibleObjC)) {
3148 if (IncompatibleObjC)
3149 return false;
3150 // Okay, we have an Objective-C pointer conversion.
3151 }
3152 else
3153 return false;
3154 }
3155
3156 // Check argument types.
3157 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3158 ArgIdx != NumArgs; ++ArgIdx) {
3159 IncompatibleObjC = false;
3160 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3161 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3162 if (Context.hasSameType(FromArgType, ToArgType)) {
3163 // Okay, the types match exactly. Nothing to do.
3164 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3165 ConvertedType, IncompatibleObjC)) {
3166 if (IncompatibleObjC)
3167 return false;
3168 // Okay, we have an Objective-C pointer conversion.
3169 } else
3170 // Argument types are too different. Abort.
3171 return false;
3172 }
3173
3175 bool CanUseToFPT, CanUseFromFPT;
3176 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3177 CanUseToFPT, CanUseFromFPT,
3178 NewParamInfos))
3179 return false;
3180
3181 ConvertedType = ToType;
3182 return true;
3183}
3184
3185enum {
3194
3195/// Attempts to get the FunctionProtoType from a Type. Handles
3196/// MemberFunctionPointers properly.
3198 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3199 return FPT;
3200
3201 if (auto *MPT = FromType->getAs<MemberPointerType>())
3202 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3203
3204 return nullptr;
3205}
3206
3208 QualType FromType, QualType ToType) {
3209 // If either type is not valid, include no extra info.
3210 if (FromType.isNull() || ToType.isNull()) {
3211 PDiag << ft_default;
3212 return;
3213 }
3214
3215 // Get the function type from the pointers.
3216 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3217 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3218 *ToMember = ToType->castAs<MemberPointerType>();
3219 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3220 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3221 << QualType(FromMember->getClass(), 0);
3222 return;
3223 }
3224 FromType = FromMember->getPointeeType();
3225 ToType = ToMember->getPointeeType();
3226 }
3227
3228 if (FromType->isPointerType())
3229 FromType = FromType->getPointeeType();
3230 if (ToType->isPointerType())
3231 ToType = ToType->getPointeeType();
3232
3233 // Remove references.
3234 FromType = FromType.getNonReferenceType();
3235 ToType = ToType.getNonReferenceType();
3236
3237 // Don't print extra info for non-specialized template functions.
3238 if (FromType->isInstantiationDependentType() &&
3239 !FromType->getAs<TemplateSpecializationType>()) {
3240 PDiag << ft_default;
3241 return;
3242 }
3243
3244 // No extra info for same types.
3245 if (Context.hasSameType(FromType, ToType)) {
3246 PDiag << ft_default;
3247 return;
3248 }
3249
3250 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3251 *ToFunction = tryGetFunctionProtoType(ToType);
3252
3253 // Both types need to be function types.
3254 if (!FromFunction || !ToFunction) {
3255 PDiag << ft_default;
3256 return;
3257 }
3258
3259 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3260 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3261 << FromFunction->getNumParams();
3262 return;
3263 }
3264
3265 // Handle different parameter types.
3266 unsigned ArgPos;
3267 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3268 PDiag << ft_parameter_mismatch << ArgPos + 1
3269 << ToFunction->getParamType(ArgPos)
3270 << FromFunction->getParamType(ArgPos);
3271 return;
3272 }
3273
3274 // Handle different return type.
3275 if (!Context.hasSameType(FromFunction->getReturnType(),
3276 ToFunction->getReturnType())) {
3277 PDiag << ft_return_type << ToFunction->getReturnType()
3278 << FromFunction->getReturnType();
3279 return;
3280 }
3281
3282 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3283 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3284 << FromFunction->getMethodQuals();
3285 return;
3286 }
3287
3288 // Handle exception specification differences on canonical type (in C++17
3289 // onwards).
3290 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3291 ->isNothrow() !=
3292 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3293 ->isNothrow()) {
3294 PDiag << ft_noexcept;
3295 return;
3296 }
3297
3298 // Unable to find a difference, so add no extra info.
3299 PDiag << ft_default;
3300}
3301
3303 ArrayRef<QualType> New, unsigned *ArgPos,
3304 bool Reversed) {
3305 assert(llvm::size(Old) == llvm::size(New) &&
3306 "Can't compare parameters of functions with different number of "
3307 "parameters!");
3308
3309 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3310 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3311 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3312
3313 // Ignore address spaces in pointee type. This is to disallow overloading
3314 // on __ptr32/__ptr64 address spaces.
3315 QualType OldType =
3316 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3317 QualType NewType =
3318 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3319
3320 if (!Context.hasSameType(OldType, NewType)) {
3321 if (ArgPos)
3322 *ArgPos = Idx;
3323 return false;
3324 }
3325 }
3326 return true;
3327}
3328
3330 const FunctionProtoType *NewType,
3331 unsigned *ArgPos, bool Reversed) {
3332 return FunctionParamTypesAreEqual(OldType->param_types(),
3333 NewType->param_types(), ArgPos, Reversed);
3334}
3335
3337 const FunctionDecl *NewFunction,
3338 unsigned *ArgPos,
3339 bool Reversed) {
3340
3341 if (OldFunction->getNumNonObjectParams() !=
3342 NewFunction->getNumNonObjectParams())
3343 return false;
3344
3345 unsigned OldIgnore =
3347 unsigned NewIgnore =
3349
3350 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3351 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3352
3353 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3354 NewPT->param_types().slice(NewIgnore),
3355 ArgPos, Reversed);
3356}
3357
3359 CastKind &Kind,
3360 CXXCastPath& BasePath,
3361 bool IgnoreBaseAccess,
3362 bool Diagnose) {
3363 QualType FromType = From->getType();
3364 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3365
3366 Kind = CK_BitCast;
3367
3368 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3371 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3372 DiagRuntimeBehavior(From->getExprLoc(), From,
3373 PDiag(diag::warn_impcast_bool_to_null_pointer)
3374 << ToType << From->getSourceRange());
3375 else if (!isUnevaluatedContext())
3376 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3377 << ToType << From->getSourceRange();
3378 }
3379 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3380 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3381 QualType FromPointeeType = FromPtrType->getPointeeType(),
3382 ToPointeeType = ToPtrType->getPointeeType();
3383
3384 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3385 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3386 // We must have a derived-to-base conversion. Check an
3387 // ambiguous or inaccessible conversion.
3388 unsigned InaccessibleID = 0;
3389 unsigned AmbiguousID = 0;
3390 if (Diagnose) {
3391 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3392 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3393 }
3394 if (CheckDerivedToBaseConversion(
3395 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3396 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3397 &BasePath, IgnoreBaseAccess))
3398 return true;
3399
3400 // The conversion was successful.
3401 Kind = CK_DerivedToBase;
3402 }
3403
3404 if (Diagnose && !IsCStyleOrFunctionalCast &&
3405 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3406 assert(getLangOpts().MSVCCompat &&
3407 "this should only be possible with MSVCCompat!");
3408 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3409 << From->getSourceRange();
3410 }
3411 }
3412 } else if (const ObjCObjectPointerType *ToPtrType =
3413 ToType->getAs<ObjCObjectPointerType>()) {
3414 if (const ObjCObjectPointerType *FromPtrType =
3415 FromType->getAs<ObjCObjectPointerType>()) {
3416 // Objective-C++ conversions are always okay.
3417 // FIXME: We should have a different class of conversions for the
3418 // Objective-C++ implicit conversions.
3419 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3420 return false;
3421 } else if (FromType->isBlockPointerType()) {
3422 Kind = CK_BlockPointerToObjCPointerCast;
3423 } else {
3424 Kind = CK_CPointerToObjCPointerCast;
3425 }
3426 } else if (ToType->isBlockPointerType()) {
3427 if (!FromType->isBlockPointerType())
3428 Kind = CK_AnyPointerToBlockPointerCast;
3429 }
3430
3431 // We shouldn't fall into this case unless it's valid for other
3432 // reasons.
3434 Kind = CK_NullToPointer;
3435
3436 return false;
3437}
3438
3440 QualType ToType,
3441 bool InOverloadResolution,
3442 QualType &ConvertedType) {
3443 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3444 if (!ToTypePtr)
3445 return false;
3446
3447 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3448 if (From->isNullPointerConstant(Context,
3449 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3451 ConvertedType = ToType;
3452 return true;
3453 }
3454
3455 // Otherwise, both types have to be member pointers.
3456 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3457 if (!FromTypePtr)
3458 return false;
3459
3460 // A pointer to member of B can be converted to a pointer to member of D,
3461 // where D is derived from B (C++ 4.11p2).
3462 QualType FromClass(FromTypePtr->getClass(), 0);
3463 QualType ToClass(ToTypePtr->getClass(), 0);
3464
3465 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3466 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3467 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3468 ToClass.getTypePtr());
3469 return true;
3470 }
3471
3472 return false;
3473}
3474
3476 CastKind &Kind,
3477 CXXCastPath &BasePath,
3478 bool IgnoreBaseAccess) {
3479 QualType FromType = From->getType();
3480 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3481 if (!FromPtrType) {
3482 // This must be a null pointer to member pointer conversion
3483 assert(From->isNullPointerConstant(Context,
3485 "Expr must be null pointer constant!");
3486 Kind = CK_NullToMemberPointer;
3487 return false;
3488 }
3489
3490 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3491 assert(ToPtrType && "No member pointer cast has a target type "
3492 "that is not a member pointer.");
3493
3494 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3495 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3496
3497 // FIXME: What about dependent types?
3498 assert(FromClass->isRecordType() && "Pointer into non-class.");
3499 assert(ToClass->isRecordType() && "Pointer into non-class.");
3500
3501 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3502 /*DetectVirtual=*/true);
3503 bool DerivationOkay =
3504 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3505 assert(DerivationOkay &&
3506 "Should not have been called if derivation isn't OK.");
3507 (void)DerivationOkay;
3508
3509 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3510 getUnqualifiedType())) {
3511 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3512 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3513 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3514 return true;
3515 }
3516
3517 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3518 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3519 << FromClass << ToClass << QualType(VBase, 0)
3520 << From->getSourceRange();
3521 return true;
3522 }
3523
3524 if (!IgnoreBaseAccess)
3525 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3526 Paths.front(),
3527 diag::err_downcast_from_inaccessible_base);
3528
3529 // Must be a base to derived member conversion.
3530 BuildBasePathArray(Paths, BasePath);
3531 Kind = CK_BaseToDerivedMemberPointer;
3532 return false;
3533}
3534
3535/// Determine whether the lifetime conversion between the two given
3536/// qualifiers sets is nontrivial.
3538 Qualifiers ToQuals) {
3539 // Converting anything to const __unsafe_unretained is trivial.
3540 if (ToQuals.hasConst() &&
3542 return false;
3543
3544 return true;
3545}
3546
3547/// Perform a single iteration of the loop for checking if a qualification
3548/// conversion is valid.
3549///
3550/// Specifically, check whether any change between the qualifiers of \p
3551/// FromType and \p ToType is permissible, given knowledge about whether every
3552/// outer layer is const-qualified.
3554 bool CStyle, bool IsTopLevel,
3555 bool &PreviousToQualsIncludeConst,
3556 bool &ObjCLifetimeConversion) {
3557 Qualifiers FromQuals = FromType.getQualifiers();
3558 Qualifiers ToQuals = ToType.getQualifiers();
3559
3560 // Ignore __unaligned qualifier.
3561 FromQuals.removeUnaligned();
3562
3563 // Objective-C ARC:
3564 // Check Objective-C lifetime conversions.
3565 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3566 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3567 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3568 ObjCLifetimeConversion = true;
3569 FromQuals.removeObjCLifetime();
3570 ToQuals.removeObjCLifetime();
3571 } else {
3572 // Qualification conversions cannot cast between different
3573 // Objective-C lifetime qualifiers.
3574 return false;
3575 }
3576 }
3577
3578 // Allow addition/removal of GC attributes but not changing GC attributes.
3579 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3580 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3581 FromQuals.removeObjCGCAttr();
3582 ToQuals.removeObjCGCAttr();
3583 }
3584
3585 // -- for every j > 0, if const is in cv 1,j then const is in cv
3586 // 2,j, and similarly for volatile.
3587 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3588 return false;
3589
3590 // If address spaces mismatch:
3591 // - in top level it is only valid to convert to addr space that is a
3592 // superset in all cases apart from C-style casts where we allow
3593 // conversions between overlapping address spaces.
3594 // - in non-top levels it is not a valid conversion.
3595 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3596 (!IsTopLevel ||
3597 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3598 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3599 return false;
3600
3601 // -- if the cv 1,j and cv 2,j are different, then const is in
3602 // every cv for 0 < k < j.
3603 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3604 !PreviousToQualsIncludeConst)
3605 return false;
3606
3607 // The following wording is from C++20, where the result of the conversion
3608 // is T3, not T2.
3609 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3610 // "array of unknown bound of"
3611 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3612 return false;
3613
3614 // -- if the resulting P3,i is different from P1,i [...], then const is
3615 // added to every cv 3_k for 0 < k < i.
3616 if (!CStyle && FromType->isConstantArrayType() &&
3617 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3618 return false;
3619
3620 // Keep track of whether all prior cv-qualifiers in the "to" type
3621 // include const.
3622 PreviousToQualsIncludeConst =
3623 PreviousToQualsIncludeConst && ToQuals.hasConst();
3624 return true;
3625}
3626
3627bool
3629 bool CStyle, bool &ObjCLifetimeConversion) {
3630 FromType = Context.getCanonicalType(FromType);
3631 ToType = Context.getCanonicalType(ToType);
3632 ObjCLifetimeConversion = false;
3633
3634 // If FromType and ToType are the same type, this is not a
3635 // qualification conversion.
3636 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3637 return false;
3638
3639 // (C++ 4.4p4):
3640 // A conversion can add cv-qualifiers at levels other than the first
3641 // in multi-level pointers, subject to the following rules: [...]
3642 bool PreviousToQualsIncludeConst = true;
3643 bool UnwrappedAnyPointer = false;
3644 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3646 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3647 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3648 return false;
3649 UnwrappedAnyPointer = true;
3650 }
3651
3652 // We are left with FromType and ToType being the pointee types
3653 // after unwrapping the original FromType and ToType the same number
3654 // of times. If we unwrapped any pointers, and if FromType and
3655 // ToType have the same unqualified type (since we checked
3656 // qualifiers above), then this is a qualification conversion.
3657 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3658}
3659
3660/// - Determine whether this is a conversion from a scalar type to an
3661/// atomic type.
3662///
3663/// If successful, updates \c SCS's second and third steps in the conversion
3664/// sequence to finish the conversion.
3665static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3666 bool InOverloadResolution,
3668 bool CStyle) {
3669 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3670 if (!ToAtomic)
3671 return false;
3672
3674 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3675 InOverloadResolution, InnerSCS,
3676 CStyle, /*AllowObjCWritebackConversion=*/false))
3677 return false;
3678
3679 SCS.Second = InnerSCS.Second;
3680 SCS.setToType(1, InnerSCS.getToType(1));
3681 SCS.Third = InnerSCS.Third;
3684 SCS.setToType(2, InnerSCS.getToType(2));
3685 return true;
3686}
3687
3689 CXXConstructorDecl *Constructor,
3690 QualType Type) {
3691 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3692 if (CtorType->getNumParams() > 0) {
3693 QualType FirstArg = CtorType->getParamType(0);
3694 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3695 return true;
3696 }
3697 return false;
3698}
3699
3700static OverloadingResult
3702 CXXRecordDecl *To,
3704 OverloadCandidateSet &CandidateSet,
3705 bool AllowExplicit) {
3707 for (auto *D : S.LookupConstructors(To)) {
3708 auto Info = getConstructorInfo(D);
3709 if (!Info)
3710 continue;
3711
3712 bool Usable = !Info.Constructor->isInvalidDecl() &&
3713 S.isInitListConstructor(Info.Constructor);
3714 if (Usable) {
3715 bool SuppressUserConversions = false;
3716 if (Info.ConstructorTmpl)
3717 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3718 /*ExplicitArgs*/ nullptr, From,
3719 CandidateSet, SuppressUserConversions,
3720 /*PartialOverloading*/ false,
3721 AllowExplicit);
3722 else
3723 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3724 CandidateSet, SuppressUserConversions,
3725 /*PartialOverloading*/ false, AllowExplicit);
3726 }
3727 }
3728
3729 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3730
3732 switch (auto Result =
3733 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3734 case OR_Deleted:
3735 case OR_Success: {
3736 // Record the standard conversion we used and the conversion function.
3737 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3738 QualType ThisType = Constructor->getFunctionObjectParameterType();
3739 // Initializer lists don't have conversions as such.
3741 User.HadMultipleCandidates = HadMultipleCandidates;
3742 User.ConversionFunction = Constructor;
3743 User.FoundConversionFunction = Best->FoundDecl;
3745 User.After.setFromType(ThisType);
3746 User.After.setAllToTypes(ToType);
3747 return Result;
3748 }
3749
3751 return OR_No_Viable_Function;
3752 case OR_Ambiguous:
3753 return OR_Ambiguous;
3754 }
3755
3756 llvm_unreachable("Invalid OverloadResult!");
3757}
3758
3759/// Determines whether there is a user-defined conversion sequence
3760/// (C++ [over.ics.user]) that converts expression From to the type
3761/// ToType. If such a conversion exists, User will contain the
3762/// user-defined conversion sequence that performs such a conversion
3763/// and this routine will return true. Otherwise, this routine returns
3764/// false and User is unspecified.
3765///
3766/// \param AllowExplicit true if the conversion should consider C++0x
3767/// "explicit" conversion functions as well as non-explicit conversion
3768/// functions (C++0x [class.conv.fct]p2).
3769///
3770/// \param AllowObjCConversionOnExplicit true if the conversion should
3771/// allow an extra Objective-C pointer conversion on uses of explicit
3772/// constructors. Requires \c AllowExplicit to also be set.
3773static OverloadingResult
3776 OverloadCandidateSet &CandidateSet,
3777 AllowedExplicit AllowExplicit,
3778 bool AllowObjCConversionOnExplicit) {
3779 assert(AllowExplicit != AllowedExplicit::None ||
3780 !AllowObjCConversionOnExplicit);
3782
3783 // Whether we will only visit constructors.
3784 bool ConstructorsOnly = false;
3785
3786 // If the type we are conversion to is a class type, enumerate its
3787 // constructors.
3788 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3789 // C++ [over.match.ctor]p1:
3790 // When objects of class type are direct-initialized (8.5), or
3791 // copy-initialized from an expression of the same or a
3792 // derived class type (8.5), overload resolution selects the
3793 // constructor. [...] For copy-initialization, the candidate
3794 // functions are all the converting constructors (12.3.1) of
3795 // that class. The argument list is the expression-list within
3796 // the parentheses of the initializer.
3797 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3798 (From->getType()->getAs<RecordType>() &&
3799 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3800 ConstructorsOnly = true;
3801
3802 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3803 // We're not going to find any constructors.
3804 } else if (CXXRecordDecl *ToRecordDecl
3805 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3806
3807 Expr **Args = &From;
3808 unsigned NumArgs = 1;
3809 bool ListInitializing = false;
3810 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3811 // But first, see if there is an init-list-constructor that will work.
3813 S, From, ToType, ToRecordDecl, User, CandidateSet,
3814 AllowExplicit == AllowedExplicit::All);
3816 return Result;
3817 // Never mind.
3818 CandidateSet.clear(
3820
3821 // If we're list-initializing, we pass the individual elements as
3822 // arguments, not the entire list.
3823 Args = InitList->getInits();
3824 NumArgs = InitList->getNumInits();
3825 ListInitializing = true;
3826 }
3827
3828 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3829 auto Info = getConstructorInfo(D);
3830 if (!Info)
3831 continue;
3832
3833 bool Usable = !Info.Constructor->isInvalidDecl();
3834 if (!ListInitializing)
3835 Usable = Usable && Info.Constructor->isConvertingConstructor(
3836 /*AllowExplicit*/ true);
3837 if (Usable) {
3838 bool SuppressUserConversions = !ConstructorsOnly;
3839 // C++20 [over.best.ics.general]/4.5:
3840 // if the target is the first parameter of a constructor [of class
3841 // X] and the constructor [...] is a candidate by [...] the second
3842 // phase of [over.match.list] when the initializer list has exactly
3843 // one element that is itself an initializer list, [...] and the
3844 // conversion is to X or reference to cv X, user-defined conversion
3845 // sequences are not cnosidered.
3846 if (SuppressUserConversions && ListInitializing) {
3847 SuppressUserConversions =
3848 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3849 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3850 ToType);
3851 }
3852 if (Info.ConstructorTmpl)
3854 Info.ConstructorTmpl, Info.FoundDecl,
3855 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3856 CandidateSet, SuppressUserConversions,
3857 /*PartialOverloading*/ false,
3858 AllowExplicit == AllowedExplicit::All);
3859 else
3860 // Allow one user-defined conversion when user specifies a
3861 // From->ToType conversion via an static cast (c-style, etc).
3862 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3863 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3864 SuppressUserConversions,
3865 /*PartialOverloading*/ false,
3866 AllowExplicit == AllowedExplicit::All);
3867 }
3868 }
3869 }
3870 }
3871
3872 // Enumerate conversion functions, if we're allowed to.
3873 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3874 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3875 // No conversion functions from incomplete types.
3876 } else if (const RecordType *FromRecordType =
3877 From->getType()->getAs<RecordType>()) {
3878 if (CXXRecordDecl *FromRecordDecl
3879 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3880 // Add all of the conversion functions as candidates.
3881 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3882 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3883 DeclAccessPair FoundDecl = I.getPair();
3884 NamedDecl *D = FoundDecl.getDecl();
3885 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3886 if (isa<UsingShadowDecl>(D))
3887 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3888
3889 CXXConversionDecl *Conv;
3890 FunctionTemplateDecl *ConvTemplate;
3891 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3892 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3893 else
3894 Conv = cast<CXXConversionDecl>(D);
3895
3896 if (ConvTemplate)
3898 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3899 CandidateSet, AllowObjCConversionOnExplicit,
3900 AllowExplicit != AllowedExplicit::None);
3901 else
3902 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3903 CandidateSet, AllowObjCConversionOnExplicit,
3904 AllowExplicit != AllowedExplicit::None);
3905 }
3906 }
3907 }
3908
3909 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3910
3912 switch (auto Result =
3913 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3914 case OR_Success:
3915 case OR_Deleted:
3916 // Record the standard conversion we used and the conversion function.
3917 if (CXXConstructorDecl *Constructor
3918 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3919 // C++ [over.ics.user]p1:
3920 // If the user-defined conversion is specified by a
3921 // constructor (12.3.1), the initial standard conversion
3922 // sequence converts the source type to the type required by
3923 // the argument of the constructor.
3924 //
3925 if (isa<InitListExpr>(From)) {
3926 // Initializer lists don't have conversions as such.
3928 } else {
3929 if (Best->Conversions[0].isEllipsis())
3930 User.EllipsisConversion = true;
3931 else {
3932 User.Before = Best->Conversions[0].Standard;
3933 User.EllipsisConversion = false;
3934 }
3935 }
3936 User.HadMultipleCandidates = HadMultipleCandidates;
3937 User.ConversionFunction = Constructor;
3938 User.FoundConversionFunction = Best->FoundDecl;
3940 User.After.setFromType(Constructor->getFunctionObjectParameterType());
3941 User.After.setAllToTypes(ToType);
3942 return Result;
3943 }
3944 if (CXXConversionDecl *Conversion
3945 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3946 // C++ [over.ics.user]p1:
3947 //
3948 // [...] If the user-defined conversion is specified by a
3949 // conversion function (12.3.2), the initial standard
3950 // conversion sequence converts the source type to the
3951 // implicit object parameter of the conversion function.
3952 User.Before = Best->Conversions[0].Standard;
3953 User.HadMultipleCandidates = HadMultipleCandidates;
3954 User.ConversionFunction = Conversion;
3955 User.FoundConversionFunction = Best->FoundDecl;
3956 User.EllipsisConversion = false;
3957
3958 // C++ [over.ics.user]p2:
3959 // The second standard conversion sequence converts the
3960 // result of the user-defined conversion to the target type
3961 // for the sequence. Since an implicit conversion sequence
3962 // is an initialization, the special rules for
3963 // initialization by user-defined conversion apply when
3964 // selecting the best user-defined conversion for a
3965 // user-defined conversion sequence (see 13.3.3 and
3966 // 13.3.3.1).
3967 User.After = Best->FinalConversion;
3968 return Result;
3969 }
3970 llvm_unreachable("Not a constructor or conversion function?");
3971
3973 return OR_No_Viable_Function;
3974
3975 case OR_Ambiguous:
3976 return OR_Ambiguous;
3977 }
3978
3979 llvm_unreachable("Invalid OverloadResult!");
3980}
3981
3982bool
3985 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3987 OverloadingResult OvResult =
3988 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3989 CandidateSet, AllowedExplicit::None, false);
3990
3991 if (!(OvResult == OR_Ambiguous ||
3992 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3993 return false;
3994
3995 auto Cands = CandidateSet.CompleteCandidates(
3996 *this,
3998 From);
3999 if (OvResult == OR_Ambiguous)
4000 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4001 << From->getType() << ToType << From->getSourceRange();
4002 else { // OR_No_Viable_Function && !CandidateSet.empty()
4003 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4004 diag::err_typecheck_nonviable_condition_incomplete,
4005 From->getType(), From->getSourceRange()))
4006 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4007 << false << From->getType() << From->getSourceRange() << ToType;
4008 }
4009
4010 CandidateSet.NoteCandidates(
4011 *this, From, Cands);
4012 return true;
4013}
4014
4015// Helper for compareConversionFunctions that gets the FunctionType that the
4016// conversion-operator return value 'points' to, or nullptr.
4017static const FunctionType *
4019 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4020 const PointerType *RetPtrTy =
4021 ConvFuncTy->getReturnType()->getAs<PointerType>();
4022
4023 if (!RetPtrTy)
4024 return nullptr;
4025
4026 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4027}
4028
4029/// Compare the user-defined conversion functions or constructors
4030/// of two user-defined conversion sequences to determine whether any ordering
4031/// is possible.
4034 FunctionDecl *Function2) {
4035 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4036 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4037 if (!Conv1 || !Conv2)
4039
4040 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4042
4043 // Objective-C++:
4044 // If both conversion functions are implicitly-declared conversions from
4045 // a lambda closure type to a function pointer and a block pointer,
4046 // respectively, always prefer the conversion to a function pointer,
4047 // because the function pointer is more lightweight and is more likely
4048 // to keep code working.
4049 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4050 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4051 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4052 if (Block1 != Block2)
4053 return Block1 ? ImplicitConversionSequence::Worse
4055 }
4056
4057 // In order to support multiple calling conventions for the lambda conversion
4058 // operator (such as when the free and member function calling convention is
4059 // different), prefer the 'free' mechanism, followed by the calling-convention
4060 // of operator(). The latter is in place to support the MSVC-like solution of
4061 // defining ALL of the possible conversions in regards to calling-convention.
4062 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4063 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4064
4065 if (Conv1FuncRet && Conv2FuncRet &&
4066 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4067 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4068 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4069
4070 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4071 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4072
4073 CallingConv CallOpCC =
4074 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4076 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4078 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4079
4080 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4081 for (CallingConv CC : PrefOrder) {
4082 if (Conv1CC == CC)
4084 if (Conv2CC == CC)
4086 }
4087 }
4088
4090}
4091
4093 const ImplicitConversionSequence &ICS) {
4095 (ICS.isUserDefined() &&
4097}
4098
4099/// CompareImplicitConversionSequences - Compare two implicit
4100/// conversion sequences to determine whether one is better than the
4101/// other or if they are indistinguishable (C++ 13.3.3.2).
4104 const ImplicitConversionSequence& ICS1,
4105 const ImplicitConversionSequence& ICS2)
4106{
4107 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4108 // conversion sequences (as defined in 13.3.3.1)
4109 // -- a standard conversion sequence (13.3.3.1.1) is a better
4110 // conversion sequence than a user-defined conversion sequence or
4111 // an ellipsis conversion sequence, and
4112 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4113 // conversion sequence than an ellipsis conversion sequence
4114 // (13.3.3.1.3).
4115 //
4116 // C++0x [over.best.ics]p10:
4117 // For the purpose of ranking implicit conversion sequences as
4118 // described in 13.3.3.2, the ambiguous conversion sequence is
4119 // treated as a user-defined sequence that is indistinguishable
4120 // from any other user-defined conversion sequence.
4121
4122 // String literal to 'char *' conversion has been deprecated in C++03. It has
4123 // been removed from C++11. We still accept this conversion, if it happens at
4124 // the best viable function. Otherwise, this conversion is considered worse
4125 // than ellipsis conversion. Consider this as an extension; this is not in the
4126 // standard. For example:
4127 //
4128 // int &f(...); // #1
4129 // void f(char*); // #2
4130 // void g() { int &r = f("foo"); }
4131 //
4132 // In C++03, we pick #2 as the best viable function.
4133 // In C++11, we pick #1 as the best viable function, because ellipsis
4134 // conversion is better than string-literal to char* conversion (since there
4135 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4136 // convert arguments, #2 would be the best viable function in C++11.
4137 // If the best viable function has this conversion, a warning will be issued
4138 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4139
4140 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4143 // Ill-formedness must not differ
4144 ICS1.isBad() == ICS2.isBad())
4148
4149 if (ICS1.getKindRank() < ICS2.getKindRank())
4151 if (ICS2.getKindRank() < ICS1.getKindRank())
4153
4154 // The following checks require both conversion sequences to be of
4155 // the same kind.
4156 if (ICS1.getKind() != ICS2.getKind())
4158
4161
4162 // Two implicit conversion sequences of the same form are
4163 // indistinguishable conversion sequences unless one of the
4164 // following rules apply: (C++ 13.3.3.2p3):
4165
4166 // List-initialization sequence L1 is a better conversion sequence than
4167 // list-initialization sequence L2 if:
4168 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4169 // if not that,
4170 // — L1 and L2 convert to arrays of the same element type, and either the
4171 // number of elements n_1 initialized by L1 is less than the number of
4172 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4173 // an array of unknown bound and L1 does not,
4174 // even if one of the other rules in this paragraph would otherwise apply.
4175 if (!ICS1.isBad()) {
4176 bool StdInit1 = false, StdInit2 = false;
4179 nullptr);
4182 nullptr);
4183 if (StdInit1 != StdInit2)
4184 return StdInit1 ? ImplicitConversionSequence::Better
4186
4189 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4191 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4193 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4194 CAT2->getElementType())) {
4195 // Both to arrays of the same element type
4196 if (CAT1->getSize() != CAT2->getSize())
4197 // Different sized, the smaller wins
4198 return CAT1->getSize().ult(CAT2->getSize())
4203 // One is incomplete, it loses
4207 }
4208 }
4209 }
4210
4211 if (ICS1.isStandard())
4212 // Standard conversion sequence S1 is a better conversion sequence than
4213 // standard conversion sequence S2 if [...]
4215 ICS1.Standard, ICS2.Standard);
4216 else if (ICS1.isUserDefined()) {
4217 // User-defined conversion sequence U1 is a better conversion
4218 // sequence than another user-defined conversion sequence U2 if
4219 // they contain the same user-defined conversion function or
4220 // constructor and if the second standard conversion sequence of
4221 // U1 is better than the second standard conversion sequence of
4222 // U2 (C++ 13.3.3.2p3).
4226 ICS1.UserDefined.After,
4227 ICS2.UserDefined.After);
4228 else
4232 }
4233
4234 return Result;
4235}
4236
4237// Per 13.3.3.2p3, compare the given standard conversion sequences to
4238// determine if one is a proper subset of the other.
4241 const StandardConversionSequence& SCS1,
4242 const StandardConversionSequence& SCS2) {
4245
4246 // the identity conversion sequence is considered to be a subsequence of
4247 // any non-identity conversion sequence
4248 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4250 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4252
4253 if (SCS1.Second != SCS2.Second) {
4254 if (SCS1.Second == ICK_Identity)
4256 else if (SCS2.Second == ICK_Identity)
4258 else
4260 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4262
4263 if (SCS1.Third == SCS2.Third) {
4264 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4266 }
4267
4268 if (SCS1.Third == ICK_Identity)
4272
4273 if (SCS2.Third == ICK_Identity)
4277
4279}
4280
4281/// Determine whether one of the given reference bindings is better
4282/// than the other based on what kind of bindings they are.
4283static bool
4285 const StandardConversionSequence &SCS2) {
4286 // C++0x [over.ics.rank]p3b4:
4287 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4288 // implicit object parameter of a non-static member function declared
4289 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4290 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4291 // lvalue reference to a function lvalue and S2 binds an rvalue
4292 // reference*.
4293 //
4294 // FIXME: Rvalue references. We're going rogue with the above edits,
4295 // because the semantics in the current C++0x working paper (N3225 at the
4296 // time of this writing) break the standard definition of std::forward
4297 // and std::reference_wrapper when dealing with references to functions.
4298 // Proposed wording changes submitted to CWG for consideration.
4301 return false;
4302
4303 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4304 SCS2.IsLvalueReference) ||
4307}
4308
4310 None,
4313};
4314
4315/// Returns kind of fixed enum promotion the \a SCS uses.
4316static FixedEnumPromotion
4318
4319 if (SCS.Second != ICK_Integral_Promotion)
4320 return FixedEnumPromotion::None;
4321
4322 QualType FromType = SCS.getFromType();
4323 if (!FromType->isEnumeralType())
4324 return FixedEnumPromotion::None;
4325
4326 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4327 if (!Enum->isFixed())
4328 return FixedEnumPromotion::None;
4329
4330 QualType UnderlyingType = Enum->getIntegerType();
4331 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4332 return FixedEnumPromotion::ToUnderlyingType;
4333
4334 return FixedEnumPromotion::ToPromotedUnderlyingType;
4335}
4336
4337/// CompareStandardConversionSequences - Compare two standard
4338/// conversion sequences to determine whether one is better than the
4339/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4342 const StandardConversionSequence& SCS1,
4343 const StandardConversionSequence& SCS2)
4344{
4345 // Standard conversion sequence S1 is a better conversion sequence
4346 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4347
4348 // -- S1 is a proper subsequence of S2 (comparing the conversion
4349 // sequences in the canonical form defined by 13.3.3.1.1,
4350 // excluding any Lvalue Transformation; the identity conversion
4351 // sequence is considered to be a subsequence of any
4352 // non-identity conversion sequence) or, if not that,
4355 return CK;
4356
4357 // -- the rank of S1 is better than the rank of S2 (by the rules
4358 // defined below), or, if not that,
4359 ImplicitConversionRank Rank1 = SCS1.getRank();
4360 ImplicitConversionRank Rank2 = SCS2.getRank();
4361 if (Rank1 < Rank2)
4363 else if (Rank2 < Rank1)
4365
4366 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4367 // are indistinguishable unless one of the following rules
4368 // applies:
4369
4370 // A conversion that is not a conversion of a pointer, or
4371 // pointer to member, to bool is better than another conversion
4372 // that is such a conversion.
4374 return SCS2.isPointerConversionToBool()
4377
4378 // C++14 [over.ics.rank]p4b2:
4379 // This is retroactively applied to C++11 by CWG 1601.
4380 //
4381 // A conversion that promotes an enumeration whose underlying type is fixed
4382 // to its underlying type is better than one that promotes to the promoted
4383 // underlying type, if the two are different.
4386 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4387 FEP1 != FEP2)
4388 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4391
4392 // C++ [over.ics.rank]p4b2:
4393 //
4394 // If class B is derived directly or indirectly from class A,
4395 // conversion of B* to A* is better than conversion of B* to
4396 // void*, and conversion of A* to void* is better than conversion
4397 // of B* to void*.
4398 bool SCS1ConvertsToVoid
4400 bool SCS2ConvertsToVoid
4402 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4403 // Exactly one of the conversion sequences is a conversion to
4404 // a void pointer; it's the worse conversion.
4405 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4407 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4408 // Neither conversion sequence converts to a void pointer; compare
4409 // their derived-to-base conversions.
4411 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4412 return DerivedCK;
4413 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4414 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4415 // Both conversion sequences are conversions to void
4416 // pointers. Compare the source types to determine if there's an
4417 // inheritance relationship in their sources.
4418 QualType FromType1 = SCS1.getFromType();
4419 QualType FromType2 = SCS2.getFromType();
4420
4421 // Adjust the types we're converting from via the array-to-pointer
4422 // conversion, if we need to.
4423 if (SCS1.First == ICK_Array_To_Pointer)
4424 FromType1 = S.Context.getArrayDecayedType(FromType1);
4425 if (SCS2.First == ICK_Array_To_Pointer)
4426 FromType2 = S.Context.getArrayDecayedType(FromType2);
4427
4428 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4429 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4430
4431 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4433 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4435
4436 // Objective-C++: If one interface is more specific than the
4437 // other, it is the better one.
4438 const ObjCObjectPointerType* FromObjCPtr1
4439 = FromType1->getAs<ObjCObjectPointerType>();
4440 const ObjCObjectPointerType* FromObjCPtr2
4441 = FromType2->getAs<ObjCObjectPointerType>();
4442 if (FromObjCPtr1 && FromObjCPtr2) {
4443 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4444 FromObjCPtr2);
4445 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4446 FromObjCPtr1);
4447 if (AssignLeft != AssignRight) {
4448 return AssignLeft? ImplicitConversionSequence::Better
4450 }
4451 }
4452 }
4453
4454 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4455 // Check for a better reference binding based on the kind of bindings.
4456 if (isBetterReferenceBindingKind(SCS1, SCS2))
4458 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4460 }
4461
4462 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4463 // bullet 3).
4465 = CompareQualificationConversions(S, SCS1, SCS2))
4466 return QualCK;
4467
4468 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4469 // C++ [over.ics.rank]p3b4:
4470 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4471 // which the references refer are the same type except for
4472 // top-level cv-qualifiers, and the type to which the reference
4473 // initialized by S2 refers is more cv-qualified than the type
4474 // to which the reference initialized by S1 refers.
4475 QualType T1 = SCS1.getToType(2);
4476 QualType T2 = SCS2.getToType(2);
4477 T1 = S.Context.getCanonicalType(T1);
4478 T2 = S.Context.getCanonicalType(T2);
4479 Qualifiers T1Quals, T2Quals;
4480 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4481 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4482 if (UnqualT1 == UnqualT2) {
4483 // Objective-C++ ARC: If the references refer to objects with different
4484 // lifetimes, prefer bindings that don't change lifetime.
4490 }
4491
4492 // If the type is an array type, promote the element qualifiers to the
4493 // type for comparison.
4494 if (isa<ArrayType>(T1) && T1Quals)
4495 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4496 if (isa<ArrayType>(T2) && T2Quals)
4497 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4498 if (T2.isMoreQualifiedThan(T1))
4500 if (T1.isMoreQualifiedThan(T2))
4502 }
4503 }
4504
4505 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4506 // floating-to-integral conversion if the integral conversion
4507 // is between types of the same size.
4508 // For example:
4509 // void f(float);
4510 // void f(int);
4511 // int main {
4512 // long a;
4513 // f(a);
4514 // }
4515 // Here, MSVC will call f(int) instead of generating a compile error
4516 // as clang will do in standard mode.
4517 if (S.getLangOpts().MSVCCompat &&
4520 SCS2.Second == ICK_Floating_Integral &&
4521 S.Context.getTypeSize(SCS1.getFromType()) ==
4522 S.Context.getTypeSize(SCS1.getToType(2)))
4524
4525 // Prefer a compatible vector conversion over a lax vector conversion
4526 // For example:
4527 //
4528 // typedef float __v4sf __attribute__((__vector_size__(16)));
4529 // void f(vector float);
4530 // void f(vector signed int);
4531 // int main() {
4532 // __v4sf a;
4533 // f(a);
4534 // }
4535 // Here, we'd like to choose f(vector float) and not
4536 // report an ambiguous call error
4537 if (SCS1.Second == ICK_Vector_Conversion &&
4538 SCS2.Second == ICK_Vector_Conversion) {
4539 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4540 SCS1.getFromType(), SCS1.getToType(2));
4541 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4542 SCS2.getFromType(), SCS2.getToType(2));
4543
4544 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4545 return SCS1IsCompatibleVectorConversion
4548 }
4549
4550 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4552 bool SCS1IsCompatibleSVEVectorConversion =
4554 bool SCS2IsCompatibleSVEVectorConversion =
4556
4557 if (SCS1IsCompatibleSVEVectorConversion !=
4558 SCS2IsCompatibleSVEVectorConversion)
4559 return SCS1IsCompatibleSVEVectorConversion
4562 }
4563
4564 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4566 bool SCS1IsCompatibleRVVVectorConversion =
4568 bool SCS2IsCompatibleRVVVectorConversion =
4570
4571 if (SCS1IsCompatibleRVVVectorConversion !=
4572 SCS2IsCompatibleRVVVectorConversion)
4573 return SCS1IsCompatibleRVVVectorConversion
4576 }
4578}
4579
4580/// CompareQualificationConversions - Compares two standard conversion
4581/// sequences to determine whether they can be ranked based on their
4582/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4585 const StandardConversionSequence& SCS1,
4586 const StandardConversionSequence& SCS2) {
4587 // C++ [over.ics.rank]p3:
4588 // -- S1 and S2 differ only in their qualification conversion and
4589 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4590 // [C++98]
4591 // [...] and the cv-qualification signature of type T1 is a proper subset
4592 // of the cv-qualification signature of type T2, and S1 is not the
4593 // deprecated string literal array-to-pointer conversion (4.2).
4594 // [C++2a]
4595 // [...] where T1 can be converted to T2 by a qualification conversion.
4596 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4597 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4599
4600 // FIXME: the example in the standard doesn't use a qualification
4601 // conversion (!)
4602 QualType T1 = SCS1.getToType(2);
4603 QualType T2 = SCS2.getToType(2);
4604 T1 = S.Context.getCanonicalType(T1);
4605 T2 = S.Context.getCanonicalType(T2);
4606 assert(!T1->isReferenceType() && !T2->isReferenceType());
4607 Qualifiers T1Quals, T2Quals;
4608 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4609 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4610
4611 // If the types are the same, we won't learn anything by unwrapping
4612 // them.
4613 if (UnqualT1 == UnqualT2)
4615
4616 // Don't ever prefer a standard conversion sequence that uses the deprecated
4617 // string literal array to pointer conversion.
4618 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4619 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4620
4621 // Objective-C++ ARC:
4622 // Prefer qualification conversions not involving a change in lifetime
4623 // to qualification conversions that do change lifetime.
4626 CanPick1 = false;
4629 CanPick2 = false;
4630
4631 bool ObjCLifetimeConversion;
4632 if (CanPick1 &&
4633 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4634 CanPick1 = false;
4635 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4636 // directions, so we can't short-cut this second check in general.
4637 if (CanPick2 &&
4638 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4639 CanPick2 = false;
4640
4641 if (CanPick1 != CanPick2)
4642 return CanPick1 ? ImplicitConversionSequence::Better
4645}
4646
4647/// CompareDerivedToBaseConversions - Compares two standard conversion
4648/// sequences to determine whether they can be ranked based on their
4649/// various kinds of derived-to-base conversions (C++
4650/// [over.ics.rank]p4b3). As part of these checks, we also look at
4651/// conversions between Objective-C interface types.
4654 const StandardConversionSequence& SCS1,
4655 const StandardConversionSequence& SCS2) {
4656 QualType FromType1 = SCS1.getFromType();
4657 QualType ToType1 = SCS1.getToType(1);
4658 QualType FromType2 = SCS2.getFromType();
4659 QualType ToType2 = SCS2.getToType(1);
4660
4661 // Adjust the types we're converting from via the array-to-pointer
4662 // conversion, if we need to.
4663 if (SCS1.First == ICK_Array_To_Pointer)
4664 FromType1 = S.Context.getArrayDecayedType(FromType1);
4665 if (SCS2.First == ICK_Array_To_Pointer)
4666 FromType2 = S.Context.getArrayDecayedType(FromType2);
4667
4668 // Canonicalize all of the types.
4669 FromType1 = S.Context.getCanonicalType(FromType1);
4670 ToType1 = S.Context.getCanonicalType(ToType1);
4671 FromType2 = S.Context.getCanonicalType(FromType2);
4672 ToType2 = S.Context.getCanonicalType(ToType2);
4673
4674 // C++ [over.ics.rank]p4b3:
4675 //
4676 // If class B is derived directly or indirectly from class A and
4677 // class C is derived directly or indirectly from B,
4678 //
4679 // Compare based on pointer conversions.
4680 if (SCS1.Second == ICK_Pointer_Conversion &&
4682 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4683 FromType1->isPointerType() && FromType2->isPointerType() &&
4684 ToType1->isPointerType() && ToType2->isPointerType()) {
4685 QualType FromPointee1 =
4687 QualType ToPointee1 =
4689 QualType FromPointee2 =
4691 QualType ToPointee2 =
4693
4694 // -- conversion of C* to B* is better than conversion of C* to A*,
4695 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4696 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4698 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4700 }
4701
4702 // -- conversion of B* to A* is better than conversion of C* to A*,
4703 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4704 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4706 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4708 }
4709 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4711 const ObjCObjectPointerType *FromPtr1
4712 = FromType1->getAs<ObjCObjectPointerType>();
4713 const ObjCObjectPointerType *FromPtr2
4714 = FromType2->getAs<ObjCObjectPointerType>();
4715 const ObjCObjectPointerType *ToPtr1
4716 = ToType1->getAs<ObjCObjectPointerType>();
4717 const ObjCObjectPointerType *ToPtr2
4718 = ToType2->getAs<ObjCObjectPointerType>();
4719
4720 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4721 // Apply the same conversion ranking rules for Objective-C pointer types
4722 // that we do for C++ pointers to class types. However, we employ the
4723 // Objective-C pseudo-subtyping relationship used for assignment of
4724 // Objective-C pointer types.
4725 bool FromAssignLeft
4726 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4727 bool FromAssignRight
4728 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4729 bool ToAssignLeft
4730 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4731 bool ToAssignRight
4732 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4733
4734 // A conversion to an a non-id object pointer type or qualified 'id'
4735 // type is better than a conversion to 'id'.
4736 if (ToPtr1->isObjCIdType() &&
4737 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4739 if (ToPtr2->isObjCIdType() &&
4740 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4742
4743 // A conversion to a non-id object pointer type is better than a
4744 // conversion to a qualified 'id' type
4745 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4747 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4749
4750 // A conversion to an a non-Class object pointer type or qualified 'Class'
4751 // type is better than a conversion to 'Class'.
4752 if (ToPtr1->isObjCClassType() &&
4753 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4755 if (ToPtr2->isObjCClassType() &&
4756 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4758
4759 // A conversion to a non-Class object pointer type is better than a
4760 // conversion to a qualified 'Class' type.
4761 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4763 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4765
4766 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4767 if (S.Context.hasSameType(FromType1, FromType2) &&
4768 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4769 (ToAssignLeft != ToAssignRight)) {
4770 if (FromPtr1->isSpecialized()) {
4771 // "conversion of B<A> * to B * is better than conversion of B * to
4772 // C *.
4773 bool IsFirstSame =
4774 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4775 bool IsSecondSame =
4776 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4777 if (IsFirstSame) {
4778 if (!IsSecondSame)
4780 } else if (IsSecondSame)
4782 }
4783 return ToAssignLeft? ImplicitConversionSequence::Worse
4785 }
4786
4787 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4788 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4789 (FromAssignLeft != FromAssignRight))
4790 return FromAssignLeft? ImplicitConversionSequence::Better
4792 }
4793 }
4794
4795 // Ranking of member-pointer types.
4796 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4797 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4798 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4799 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4800 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4801 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4802 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4803 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4804 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4805 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4806 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4807 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4808 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4809 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4810 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4811 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4812 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4813 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4815 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4817 }
4818 // conversion of B::* to C::* is better than conversion of A::* to C::*
4819 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4820 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4822 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4824 }
4825 }
4826
4827 if (SCS1.Second == ICK_Derived_To_Base) {
4828 // -- conversion of C to B is better than conversion of C to A,
4829 // -- binding of an expression of type C to a reference of type
4830 // B& is better than binding an expression of type C to a
4831 // reference of type A&,
4832 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4833 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4834 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4836 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4838 }
4839
4840 // -- conversion of B to A is better than conversion of C to A.
4841 // -- binding of an expression of type B to a reference of type
4842 // A& is better than binding an expression of type C to a
4843 // reference of type A&,
4844 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4845 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4846 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4848 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4850 }
4851 }
4852
4854}
4855
4857 if (!T.getQualifiers().hasUnaligned())
4858 return T;
4859
4860 Qualifiers Q;
4861 T = Ctx.getUnqualifiedArrayType(T, Q);
4862 Q.removeUnaligned();
4863 return Ctx.getQualifiedType(T, Q);
4864}
4865
4868 QualType OrigT1, QualType OrigT2,
4869 ReferenceConversions *ConvOut) {
4870 assert(!OrigT1->isReferenceType() &&
4871 "T1 must be the pointee type of the reference type");
4872 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4873
4874 QualType T1 = Context.getCanonicalType(OrigT1);
4875 QualType T2 = Context.getCanonicalType(OrigT2);
4876 Qualifiers T1Quals, T2Quals;
4877 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4878 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4879
4880 ReferenceConversions ConvTmp;
4881 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4882 Conv = ReferenceConversions();
4883
4884 // C++2a [dcl.init.ref]p4:
4885 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4886 // reference-related to "cv2 T2" if T1 is similar to T2, or
4887 // T1 is a base class of T2.
4888 // "cv1 T1" is reference-compatible with "cv2 T2" if
4889 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4890 // "pointer to cv1 T1" via a standard conversion sequence.
4891
4892 // Check for standard conversions we can apply to pointers: derived-to-base
4893 // conversions, ObjC pointer conversions, and function pointer conversions.
4894 // (Qualification conversions are checked last.)
4895 QualType ConvertedT2;
4896 if (UnqualT1 == UnqualT2) {
4897 // Nothing to do.
4898 } else if (isCompleteType(Loc, OrigT2) &&
4899 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4900 Conv |= ReferenceConversions::DerivedToBase;
4901 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4902 UnqualT2->isObjCObjectOrInterfaceType() &&
4903 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4904 Conv |= ReferenceConversions::ObjC;
4905 else if (UnqualT2->isFunctionType() &&
4906 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4907 Conv |= ReferenceConversions::Function;
4908 // No need to check qualifiers; function types don't have them.
4909 return Ref_Compatible;
4910 }
4911 bool ConvertedReferent = Conv != 0;
4912
4913 // We can have a qualification conversion. Compute whether the types are
4914 // similar at the same time.
4915 bool PreviousToQualsIncludeConst = true;
4916 bool TopLevel = true;
4917 do {
4918 if (T1 == T2)
4919 break;
4920
4921 // We will need a qualification conversion.
4922 Conv |= ReferenceConversions::Qualification;
4923
4924 // Track whether we performed a qualification conversion anywhere other
4925 // than the top level. This matters for ranking reference bindings in
4926 // overload resolution.
4927 if (!TopLevel)
4928 Conv |= ReferenceConversions::NestedQualification;
4929
4930 // MS compiler ignores __unaligned qualifier for references; do the same.
4931 T1 = withoutUnaligned(Context, T1);
4932 T2 = withoutUnaligned(Context, T2);
4933
4934 // If we find a qualifier mismatch, the types are not reference-compatible,
4935 // but are still be reference-related if they're similar.
4936 bool ObjCLifetimeConversion = false;
4937 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4938 PreviousToQualsIncludeConst,
4939 ObjCLifetimeConversion))
4940 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4941 ? Ref_Related
4942 : Ref_Incompatible;
4943
4944 // FIXME: Should we track this for any level other than the first?
4945 if (ObjCLifetimeConversion)
4946 Conv |= ReferenceConversions::ObjCLifetime;
4947
4948 TopLevel = false;
4949 } while (Context.UnwrapSimilarTypes(T1, T2));
4950
4951 // At this point, if the types are reference-related, we must either have the
4952 // same inner type (ignoring qualifiers), or must have already worked out how
4953 // to convert the referent.
4954 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4955 ? Ref_Compatible
4956 : Ref_Incompatible;
4957}
4958
4959/// Look for a user-defined conversion to a value reference-compatible
4960/// with DeclType. Return true if something definite is found.
4961static bool
4963 QualType DeclType, SourceLocation DeclLoc,
4964 Expr *Init, QualType T2, bool AllowRvalues,
4965 bool AllowExplicit) {
4966 assert(T2->isRecordType() && "Can only find conversions of record types.");
4967 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4968
4969 OverloadCandidateSet CandidateSet(
4971 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4972 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4973 NamedDecl *D = *I;
4974 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4975 if (isa<UsingShadowDecl>(D))
4976 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4977
4978 FunctionTemplateDecl *ConvTemplate
4979 = dyn_cast<FunctionTemplateDecl>(D);
4980 CXXConversionDecl *Conv;
4981 if (ConvTemplate)
4982 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4983 else
4984 Conv = cast<CXXConversionDecl>(D);
4985
4986 if (AllowRvalues) {
4987 // If we are initializing an rvalue reference, don't permit conversion
4988 // functions that return lvalues.
4989 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4990 const ReferenceType *RefType
4992 if (RefType && !RefType->getPointeeType()->isFunctionType())
4993 continue;
4994 }
4995
4996 if (!ConvTemplate &&
4998 DeclLoc,
4999 Conv->getConversionType()
5004 continue;
5005 } else {
5006 // If the conversion function doesn't return a reference type,
5007 // it can't be considered for this conversion. An rvalue reference
5008 // is only acceptable if its referencee is a function type.
5009
5010 const ReferenceType *RefType =
5012 if (!RefType ||
5013 (!RefType->isLValueReferenceType() &&
5014 !RefType->getPointeeType()->isFunctionType()))
5015 continue;
5016 }
5017
5018 if (ConvTemplate)
5020 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5021 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5022 else
5024 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5025 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5026 }
5027
5028 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5029
5031 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5032 case OR_Success:
5033 // C++ [over.ics.ref]p1:
5034 //
5035 // [...] If the parameter binds directly to the result of
5036 // applying a conversion function to the argument
5037 // expression, the implicit conversion sequence is a
5038 // user-defined conversion sequence (13.3.3.1.2), with the
5039 // second standard conversion sequence either an identity
5040 // conversion or, if the conversion function returns an
5041 // entity of a type that is a derived class of the parameter
5042 // type, a derived-to-base Conversion.
5043 if (!Best->FinalConversion.DirectBinding)
5044 return false;
5045
5046 ICS.setUserDefined();
5047 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5048 ICS.UserDefined.After = Best->FinalConversion;
5049 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5050 ICS.UserDefined.ConversionFunction = Best->Function;
5051 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5052 ICS.UserDefined.EllipsisConversion = false;
5053 assert(ICS.UserDefined.After.ReferenceBinding &&
5055 "Expected a direct reference binding!");
5056 return true;
5057
5058 case OR_Ambiguous:
5059 ICS.setAmbiguous();
5060 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5061 Cand != CandidateSet.end(); ++Cand)
5062 if (Cand->Best)
5063 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5064 return true;
5065
5067 case OR_Deleted:
5068 // There was no suitable conversion, or we found a deleted
5069 // conversion; continue with other checks.
5070 return false;
5071 }
5072
5073 llvm_unreachable("Invalid OverloadResult!");
5074}
5075
5076/// Compute an implicit conversion sequence for reference
5077/// initialization.
5080 SourceLocation DeclLoc,
5081 bool SuppressUserConversions,
5082 bool AllowExplicit) {
5083 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5084
5085 // Most paths end in a failed conversion.
5088
5089 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5090 QualType T2 = Init->getType();
5091
5092 // If the initializer is the address of an overloaded function, try
5093 // to resolve the overloaded function. If all goes well, T2 is the
5094 // type of the resulting function.
5095 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5098 false, Found))
5099 T2 = Fn->getType();
5100 }
5101
5102 // Compute some basic properties of the types and the initializer.
5103 bool isRValRef = DeclType->isRValueReferenceType();
5104 Expr::Classification InitCategory = Init->Classify(S.Context);
5105
5107 Sema::ReferenceCompareResult RefRelationship =
5108 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5109
5110 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5111 ICS.setStandard();
5113 // FIXME: A reference binding can be a function conversion too. We should
5114 // consider that when ordering reference-to-function bindings.
5115 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5117 : (RefConv & Sema::ReferenceConversions::ObjC)
5119 : ICK_Identity;
5121 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5122 // a reference binding that performs a non-top-level qualification
5123 // conversion as a qualification conversion, not as an identity conversion.
5124 ICS.Standard.Third = (RefConv &
5125 Sema::ReferenceConversions::NestedQualification)
5127 : ICK_Identity;
5128 ICS.Standard.setFromType(T2);
5129 ICS.Standard.setToType(0, T2);
5130 ICS.Standard.setToType(1, T1);
5131 ICS.Standard.setToType(2, T1);
5132 ICS.Standard.ReferenceBinding = true;
5133 ICS.Standard.DirectBinding = BindsDirectly;
5134 ICS.Standard.IsLvalueReference = !isRValRef;
5136 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5139 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5140 ICS.Standard.CopyConstructor = nullptr;
5142 };
5143
5144 // C++0x [dcl.init.ref]p5:
5145 // A reference to type "cv1 T1" is initialized by an expression
5146 // of type "cv2 T2" as follows:
5147
5148 // -- If reference is an lvalue reference and the initializer expression
5149 if (!isRValRef) {
5150 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5151 // reference-compatible with "cv2 T2," or
5152 //
5153 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5154 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5155 // C++ [over.ics.ref]p1:
5156 // When a parameter of reference type binds directly (8.5.3)
5157 // to an argument expression, the implicit conversion sequence
5158 // is the identity conversion, unless the argument expression
5159 // has a type that is a derived class of the parameter type,
5160 // in which case the implicit conversion sequence is a
5161 // derived-to-base Conversion (13.3.3.1).
5162 SetAsReferenceBinding(/*BindsDirectly=*/true);
5163
5164 // Nothing more to do: the inaccessibility/ambiguity check for
5165 // derived-to-base conversions is suppressed when we're
5166 // computing the implicit conversion sequence (C++
5167 // [over.best.ics]p2).
5168 return ICS;
5169 }
5170
5171 // -- has a class type (i.e., T2 is a class type), where T1 is
5172 // not reference-related to T2, and can be implicitly
5173 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5174 // is reference-compatible with "cv3 T3" 92) (this
5175 // conversion is selected by enumerating the applicable
5176 // conversion functions (13.3.1.6) and choosing the best
5177 // one through overload resolution (13.3)),
5178 if (!SuppressUserConversions && T2->isRecordType() &&
5179 S.isCompleteType(DeclLoc, T2) &&
5180 RefRelationship == Sema::Ref_Incompatible) {
5181 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5182 Init, T2, /*AllowRvalues=*/false,
5183 AllowExplicit))
5184 return ICS;
5185 }
5186 }
5187
5188 // -- Otherwise, the reference shall be an lvalue reference to a
5189 // non-volatile const type (i.e., cv1 shall be const), or the reference
5190 // shall be an rvalue reference.
5191 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5192 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5194 return ICS;
5195 }
5196
5197 // -- If the initializer expression
5198 //
5199 // -- is an xvalue, class prvalue, array prvalue or function
5200 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5201 if (RefRelationship == Sema::Ref_Compatible &&
5202 (InitCategory.isXValue() ||
5203 (InitCategory.isPRValue() &&
5204 (T2->isRecordType() || T2->isArrayType())) ||
5205 (InitCategory.isLValue() && T2->isFunctionType()))) {
5206 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5207 // binding unless we're binding to a class prvalue.
5208 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5209 // allow the use of rvalue references in C++98/03 for the benefit of
5210 // standard library implementors; therefore, we need the xvalue check here.
5211 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5212 !(InitCategory.isPRValue() || T2->isRecordType()));
5213 return ICS;
5214 }
5215
5216 // -- has a class type (i.e., T2 is a class type), where T1 is not
5217 // reference-related to T2, and can be implicitly converted to
5218 // an xvalue, class prvalue, or function lvalue of type
5219 // "cv3 T3", where "cv1 T1" is reference-compatible with
5220 // "cv3 T3",
5221 //
5222 // then the reference is bound to the value of the initializer
5223 // expression in the first case and to the result of the conversion
5224 // in the second case (or, in either case, to an appropriate base
5225 // class subobject).
5226 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5227 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5228 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5229 Init, T2, /*AllowRvalues=*/true,
5230 AllowExplicit)) {
5231 // In the second case, if the reference is an rvalue reference
5232 // and the second standard conversion sequence of the
5233 // user-defined conversion sequence includes an lvalue-to-rvalue
5234 // conversion, the program is ill-formed.
5235 if (ICS.isUserDefined() && isRValRef &&
5238
5239 return ICS;
5240 }
5241
5242 // A temporary of function type cannot be created; don't even try.
5243 if (T1->isFunctionType())
5244 return ICS;
5245
5246 // -- Otherwise, a temporary of type "cv1 T1" is created and
5247 // initialized from the initializer expression using the
5248 // rules for a non-reference copy initialization (8.5). The
5249 // reference is then bound to the temporary. If T1 is
5250 // reference-related to T2, cv1 must be the same
5251 // cv-qualification as, or greater cv-qualification than,
5252 // cv2; otherwise, the program is ill-formed.
5253 if (RefRelationship == Sema::Ref_Related) {
5254 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5255 // we would be reference-compatible or reference-compatible with
5256 // added qualification. But that wasn't the case, so the reference
5257 // initialization fails.
5258 //
5259 // Note that we only want to check address spaces and cvr-qualifiers here.
5260 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5261 Qualifiers T1Quals = T1.getQualifiers();
5262 Qualifiers T2Quals = T2.getQualifiers();
5263 T1Quals.removeObjCGCAttr();
5264 T1Quals.removeObjCLifetime();
5265 T2Quals.removeObjCGCAttr();
5266 T2Quals.removeObjCLifetime();
5267 // MS compiler ignores __unaligned qualifier for references; do the same.
5268 T1Quals.removeUnaligned();
5269 T2Quals.removeUnaligned();
5270 if (!T1Quals.compatiblyIncludes(T2Quals))
5271 return ICS;
5272 }
5273
5274 // If at least one of the types is a class type, the types are not
5275 // related, and we aren't allowed any user conversions, the
5276 // reference binding fails. This case is important for breaking
5277 // recursion, since TryImplicitConversion below will attempt to
5278 // create a temporary through the use of a copy constructor.
5279 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5280 (T1->isRecordType() || T2->isRecordType()))
5281 return ICS;
5282
5283 // If T1 is reference-related to T2 and the reference is an rvalue
5284 // reference, the initializer expression shall not be an lvalue.
5285 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5286 Init->Classify(S.Context).isLValue()) {
5288 return ICS;
5289 }
5290
5291 // C++ [over.ics.ref]p2:
5292 // When a parameter of reference type is not bound directly to
5293 // an argument expression, the conversion sequence is the one
5294 // required to convert the argument expression to the
5295 // underlying type of the reference according to
5296 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5297 // to copy-initializing a temporary of the underlying type with
5298 // the argument expression. Any difference in top-level
5299 // cv-qualification is subsumed by the initialization itself
5300 // and does not constitute a conversion.
5301 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5302 AllowedExplicit::None,
5303 /*InOverloadResolution=*/false,
5304 /*CStyle=*/false,
5305 /*AllowObjCWritebackConversion=*/false,
5306 /*AllowObjCConversionOnExplicit=*/false);
5307
5308 // Of course, that's still a reference binding.
5309 if (ICS.isStandard()) {
5310 ICS.Standard.ReferenceBinding = true;
5311 ICS.Standard.IsLvalueReference = !isRValRef;
5312 ICS.Standard.BindsToFunctionLvalue = false;
5313 ICS.Standard.BindsToRvalue = true;
5316 } else if (ICS.isUserDefined()) {
5317 const ReferenceType *LValRefType =
5320
5321 // C++ [over.ics.ref]p3:
5322 // Except for an implicit object parameter, for which see 13.3.1, a
5323 // standard conversion sequence cannot be formed if it requires [...]
5324 // binding an rvalue reference to an lvalue other than a function
5325 // lvalue.
5326 // Note that the function case is not possible here.
5327 if (isRValRef && LValRefType) {
5329 return ICS;
5330 }
5331
5333 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5335 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5338 }
5339
5340 return ICS;
5341}
5342
5344TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5345 bool SuppressUserConversions,
5346 bool InOverloadResolution,
5347 bool AllowObjCWritebackConversion,
5348 bool AllowExplicit = false);
5349
5350/// TryListConversion - Try to copy-initialize a value of type ToType from the
5351/// initializer list From.
5354 bool SuppressUserConversions,
5355 bool InOverloadResolution,
5356 bool AllowObjCWritebackConversion) {
5357 // C++11 [over.ics.list]p1:
5358 // When an argument is an initializer list, it is not an expression and
5359 // special rules apply for converting it to a parameter type.
5360
5362 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5363
5364 // We need a complete type for what follows. With one C++20 exception,
5365 // incomplete types can never be initialized from init lists.
5366 QualType InitTy = ToType;
5367 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5368 if (AT && S.getLangOpts().CPlusPlus20)
5369 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5370 // C++20 allows list initialization of an incomplete array type.
5371 InitTy = IAT->getElementType();
5372 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5373 return Result;
5374
5375 // C++20 [over.ics.list]/2:
5376 // If the initializer list is a designated-initializer-list, a conversion
5377 // is only possible if the parameter has an aggregate type
5378 //
5379 // FIXME: The exception for reference initialization here is not part of the
5380 // language rules, but follow other compilers in adding it as a tentative DR
5381 // resolution.
5382 bool IsDesignatedInit = From->hasDesignatedInit();
5383 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5384 IsDesignatedInit)
5385 return Result;
5386
5387 // Per DR1467 and DR2137:
5388 // If the parameter type is an aggregate class X and the initializer list
5389 // has a single element of type cv U, where U is X or a class derived from
5390 // X, the implicit conversion sequence is the one required to convert the
5391 // element to the parameter type.
5392 //
5393 // Otherwise, if the parameter type is a character array [... ]
5394 // and the initializer list has a single element that is an
5395 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5396 // implicit conversion sequence is the identity conversion.
5397 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5398 if (ToType->isRecordType() && ToType->isAggregateType()) {
5399 QualType InitType = From->getInit(0)->getType();
5400 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5401 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5402 return TryCopyInitialization(S, From->getInit(0), ToType,
5403 SuppressUserConversions,
5404 InOverloadResolution,
5405 AllowObjCWritebackConversion);
5406 }
5407
5408 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5409 InitializedEntity Entity =
5411 /*Consumed=*/false);
5412 if (S.CanPerformCopyInitialization(Entity, From)) {
5413 Result.setStandard();
5414 Result.Standard.setAsIdentityConversion();
5415 Result.Standard.setFromType(ToType);
5416 Result.Standard.setAllToTypes(ToType);
5417 return Result;
5418 }
5419 }
5420 }
5421
5422 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5423 // C++11 [over.ics.list]p2:
5424 // If the parameter type is std::initializer_list<X> or "array of X" and
5425 // all the elements can be implicitly converted to X, the implicit
5426 // conversion sequence is the worst conversion necessary to convert an
5427 // element of the list to X.
5428 //
5429 // C++14 [over.ics.list]p3:
5430 // Otherwise, if the parameter type is "array of N X", if the initializer
5431 // list has exactly N elements or if it has fewer than N elements and X is
5432 // default-constructible, and if all the elements of the initializer list
5433 // can be implicitly converted to X, the implicit conversion sequence is
5434 // the worst conversion necessary to convert an element of the list to X.
5435 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5436 unsigned e = From->getNumInits();
5439 QualType());
5440 QualType ContTy = ToType;
5441 bool IsUnbounded = false;
5442 if (AT) {
5443 InitTy = AT->getElementType();
5444 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5445 if (CT->getSize().ult(e)) {
5446 // Too many inits, fatally bad
5448 ToType);
5449 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5450 return Result;
5451 }
5452 if (CT->getSize().ugt(e)) {
5453 // Need an init from empty {}, is there one?
5454 InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5455 From->getEndLoc());
5456 EmptyList.setType(S.Context.VoidTy);
5457 DfltElt = TryListConversion(
5458 S, &EmptyList, InitTy, SuppressUserConversions,
5459 InOverloadResolution, AllowObjCWritebackConversion);
5460 if (DfltElt.isBad()) {
5461 // No {} init, fatally bad
5463 ToType);
5464 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5465 return Result;
5466 }
5467 }
5468 } else {
5469 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5470 IsUnbounded = true;
5471 if (!e) {
5472 // Cannot convert to zero-sized.
5474 ToType);
5475 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5476 return Result;
5477 }
5478 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5479 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5481 }
5482 }
5483
5484 Result.setStandard();
5485 Result.Standard.setAsIdentityConversion();
5486 Result.Standard.setFromType(InitTy);
5487 Result.Standard.setAllToTypes(InitTy);
5488 for (unsigned i = 0; i < e; ++i) {
5489 Expr *Init = From->getInit(i);
5491 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5492 AllowObjCWritebackConversion);
5493
5494 // Keep the worse conversion seen so far.
5495 // FIXME: Sequences are not totally ordered, so 'worse' can be
5496 // ambiguous. CWG has been informed.
5498 Result) ==
5500 Result = ICS;
5501 // Bail as soon as we find something unconvertible.
5502 if (Result.isBad()) {
5503 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5504 return Result;
5505 }
5506 }
5507 }
5508
5509 // If we needed any implicit {} initialization, compare that now.
5510 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5511 // has been informed that this might not be the best thing.
5512 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5513 S, From->getEndLoc(), DfltElt, Result) ==
5515 Result = DfltElt;
5516 // Record the type being initialized so that we may compare sequences
5517 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5518 return Result;
5519 }
5520
5521 // C++14 [over.ics.list]p4:
5522 // C++11 [over.ics.list]p3:
5523 // Otherwise, if the parameter is a non-aggregate class X and overload
5524 // resolution chooses a single best constructor [...] the implicit
5525 // conversion sequence is a user-defined conversion sequence. If multiple
5526 // constructors are viable but none is better than the others, the
5527 // implicit conversion sequence is a user-defined conversion sequence.
5528 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5529 // This function can deal with initializer lists.
5530 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5531 AllowedExplicit::None,
5532 InOverloadResolution, /*CStyle=*/false,
5533 AllowObjCWritebackConversion,
5534 /*AllowObjCConversionOnExplicit=*/false);
5535 }
5536
5537 // C++14 [over.ics.list]p5:
5538 // C++11 [over.ics.list]p4:
5539 // Otherwise, if the parameter has an aggregate type which can be
5540 // initialized from the initializer list [...] the implicit conversion
5541 // sequence is a user-defined conversion sequence.
5542 if (ToType->isAggregateType()) {
5543 // Type is an aggregate, argument is an init list. At this point it comes
5544 // down to checking whether the initialization works.
5545 // FIXME: Find out whether this parameter is consumed or not.
5546 InitializedEntity Entity =
5548 /*Consumed=*/false);
5550 From)) {
5551 Result.setUserDefined();
5552 Result.UserDefined.Before.setAsIdentityConversion();
5553 // Initializer lists don't have a type.
5554 Result.UserDefined.Before.setFromType(QualType());
5555 Result.UserDefined.Before.setAllToTypes(QualType());
5556
5557 Result.UserDefined.After.setAsIdentityConversion();
5558 Result.UserDefined.After.setFromType(ToType);
5559 Result.UserDefined.After.setAllToTypes(ToType);
5560 Result.UserDefined.ConversionFunction = nullptr;
5561 }
5562 return Result;
5563 }
5564
5565 // C++14 [over.ics.list]p6:
5566 // C++11 [over.ics.list]p5:
5567 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5568 if (ToType->isReferenceType()) {
5569 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5570 // mention initializer lists in any way. So we go by what list-
5571 // initialization would do and try to extrapolate from that.
5572
5573 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5574
5575 // If the initializer list has a single element that is reference-related
5576 // to the parameter type, we initialize the reference from that.
5577 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5578 Expr *Init = From->getInit(0);
5579
5580 QualType T2 = Init->getType();
5581
5582 // If the initializer is the address of an overloaded function, try
5583 // to resolve the overloaded function. If all goes well, T2 is the
5584 // type of the resulting function.
5585 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5588 Init, ToType, false, Found))
5589 T2 = Fn->getType();
5590 }
5591
5592 // Compute some basic properties of the types and the initializer.
5593 Sema::ReferenceCompareResult RefRelationship =
5594 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5595
5596 if (RefRelationship >= Sema::Ref_Related) {
5597 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5598 SuppressUserConversions,
5599 /*AllowExplicit=*/false);
5600 }
5601 }
5602
5603 // Otherwise, we bind the reference to a temporary created from the
5604 // initializer list.
5605 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5606 InOverloadResolution,
5607 AllowObjCWritebackConversion);
5608 if (Result.isFailure())
5609 return Result;
5610 assert(!Result.isEllipsis() &&
5611 "Sub-initialization cannot result in ellipsis conversion.");
5612
5613 // Can we even bind to a temporary?
5614 if (ToType->isRValueReferenceType() ||
5615 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5616 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5617 Result.UserDefined.After;
5618 SCS.ReferenceBinding = true;
5620 SCS.BindsToRvalue = true;
5621 SCS.BindsToFunctionLvalue = false;
5624 } else
5626 From, ToType);
5627 return Result;
5628 }
5629
5630 // C++14 [over.ics.list]p7:
5631 // C++11 [over.ics.list]p6:
5632 // Otherwise, if the parameter type is not a class:
5633 if (!ToType->isRecordType()) {
5634 // - if the initializer list has one element that is not itself an
5635 // initializer list, the implicit conversion sequence is the one
5636 // required to convert the element to the parameter type.
5637 unsigned NumInits = From->getNumInits();
5638 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5639 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5640 SuppressUserConversions,
5641 InOverloadResolution,
5642 AllowObjCWritebackConversion);
5643 // - if the initializer list has no elements, the implicit conversion
5644 // sequence is the identity conversion.
5645 else if (NumInits == 0) {
5646 Result.setStandard();
5647 Result.Standard.setAsIdentityConversion();
5648 Result.Standard.setFromType(ToType);
5649 Result.Standard.setAllToTypes(ToType);
5650 }
5651 return Result;
5652 }
5653
5654 // C++14 [over.ics.list]p8:
5655 // C++11 [over.ics.list]p7:
5656 // In all cases other than those enumerated above, no conversion is possible
5657 return Result;
5658}
5659
5660/// TryCopyInitialization - Try to copy-initialize a value of type
5661/// ToType from the expression From. Return the implicit conversion
5662/// sequence required to pass this argument, which may be a bad
5663/// conversion sequence (meaning that the argument cannot be passed to
5664/// a parameter of this type). If @p SuppressUserConversions, then we
5665/// do not permit any user-defined conversion sequences.
5668 bool SuppressUserConversions,
5669 bool InOverloadResolution,
5670 bool AllowObjCWritebackConversion,
5671 bool AllowExplicit) {
5672 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5673 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5674 InOverloadResolution,AllowObjCWritebackConversion);
5675
5676 if (ToType->isReferenceType())
5677 return TryReferenceInit(S, From, ToType,
5678 /*FIXME:*/ From->getBeginLoc(),
5679 SuppressUserConversions, AllowExplicit);
5680
5681 return TryImplicitConversion(S, From, ToType,
5682 SuppressUserConversions,
5683 AllowedExplicit::None,
5684 InOverloadResolution,
5685 /*CStyle=*/false,
5686 AllowObjCWritebackConversion,
5687 /*AllowObjCConversionOnExplicit=*/false);
5688}
5689
5690static bool TryCopyInitialization(const CanQualType FromQTy,
5691 const CanQualType ToQTy,
5692 Sema &S,
5693 SourceLocation Loc,
5694 ExprValueKind FromVK) {
5695 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5697 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5698
5699 return !ICS.isBad();
5700}
5701
5702/// TryObjectArgumentInitialization - Try to initialize the object
5703/// parameter of the given member function (@c Method) from the
5704/// expression @p From.
5706 Sema &S, SourceLocation Loc, QualType FromType,
5707 Expr::Classification FromClassification, CXXMethodDecl *Method,
5708 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5709 QualType ExplicitParameterType = QualType(),
5710 bool SuppressUserConversion = false) {
5711
5712 // We need to have an object of class type.
5713 if (const auto *PT = FromType->getAs<PointerType>()) {
5714 FromType = PT->getPointeeType();
5715
5716 // When we had a pointer, it's implicitly dereferenced, so we
5717 // better have an lvalue.
5718 assert(FromClassification.isLValue());
5719 }
5720
5721 auto ValueKindFromClassification = [](Expr::Classification C) {
5722 if (C.isPRValue())
5723 return clang::VK_PRValue;
5724 if (C.isXValue())
5725 return VK_XValue;
5726 return clang::VK_LValue;
5727 };
5728
5729 if (Method->isExplicitObjectMemberFunction()) {
5730 if (ExplicitParameterType.isNull())
5731 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5732 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5733 ValueKindFromClassification(FromClassification));
5735 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5736 /*InOverloadResolution=*/true, false);
5737 if (ICS.isBad())
5738 ICS.Bad.FromExpr = nullptr;
5739 return ICS;
5740 }
5741
5742 assert(FromType->isRecordType());
5743
5744 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5745 // C++98 [class.dtor]p2:
5746 // A destructor can be invoked for a const, volatile or const volatile
5747 // object.
5748 // C++98 [over.match.funcs]p4:
5749 // For static member functions, the implicit object parameter is considered
5750 // to match any object (since if the function is selected, the object is
5751 // discarded).
5752 Qualifiers Quals = Method->getMethodQualifiers();
5753 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5754 Quals.addConst();
5755 Quals.addVolatile();
5756 }
5757
5758 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5759
5760 // Set up the conversion sequence as a "bad" conversion, to allow us
5761 // to exit early.
5763
5764 // C++0x [over.match.funcs]p4:
5765 // For non-static member functions, the type of the implicit object
5766 // parameter is
5767 //
5768 // - "lvalue reference to cv X" for functions declared without a
5769 // ref-qualifier or with the & ref-qualifier
5770 // - "rvalue reference to cv X" for functions declared with the &&
5771 // ref-qualifier
5772 //
5773 // where X is the class of which the function is a member and cv is the
5774 // cv-qualification on the member function declaration.
5775 //
5776 // However, when finding an implicit conversion sequence for the argument, we
5777 // are not allowed to perform user-defined conversions
5778 // (C++ [over.match.funcs]p5). We perform a simplified version of
5779 // reference binding here, that allows class rvalues to bind to
5780 // non-constant references.
5781
5782 // First check the qualifiers.
5783 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5784 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5785 if (ImplicitParamType.getCVRQualifiers() !=
5786 FromTypeCanon.getLocalCVRQualifiers() &&
5787 !ImplicitParamType.isAtLeastAsQualifiedAs(
5788 withoutUnaligned(S.Context, FromTypeCanon))) {
5790 FromType, ImplicitParamType);
5791 return ICS;
5792 }
5793
5794 if (FromTypeCanon.hasAddressSpace()) {
5795 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5796 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5797 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5799 FromType, ImplicitParamType);
5800 return ICS;
5801 }
5802 }
5803
5804 // Check that we have either the same type or a derived type. It
5805 // affects the conversion rank.
5806 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5807 ImplicitConversionKind SecondKind;
5808 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5809 SecondKind = ICK_Identity;
5810 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
5811 SecondKind = ICK_Derived_To_Base;
5812 } else if (!Method->isExplicitObjectMemberFunction()) {
5814 FromType, ImplicitParamType);
5815 return ICS;
5816 }
5817
5818 // Check the ref-qualifier.
5819 switch (Method->getRefQualifier()) {
5820 case RQ_None:
5821 // Do nothing; we don't care about lvalueness or rvalueness.
5822 break;
5823
5824 case RQ_LValue:
5825 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5826 // non-const lvalue reference cannot bind to an rvalue
5828 ImplicitParamType);
5829 return ICS;
5830 }
5831 break;
5832
5833 case RQ_RValue:
5834 if (!FromClassification.isRValue()) {
5835 // rvalue reference cannot bind to an lvalue
5837 ImplicitParamType);
5838 return ICS;
5839 }
5840 break;
5841 }
5842
5843 // Success. Mark this as a reference binding.
5844 ICS.setStandard();
5846 ICS.Standard.Second = SecondKind;
5847 ICS.Standard.setFromType(FromType);
5848 ICS.Standard.setAllToTypes(ImplicitParamType);
5849 ICS.Standard.ReferenceBinding = true;
5850 ICS.Standard.DirectBinding = true;
5852 ICS.Standard.BindsToFunctionLvalue = false;
5853 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5855 = (Method->getRefQualifier() == RQ_None);
5856 return ICS;
5857}
5858
5859/// PerformObjectArgumentInitialization - Perform initialization of
5860/// the implicit object parameter for the given Method with the given
5861/// expression.
5863 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5864 CXXMethodDecl *Method) {
5865 QualType FromRecordType, DestType;
5866 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5867
5868 Expr::Classification FromClassification;
5869 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5870 FromRecordType = PT->getPointeeType();
5871 DestType = Method->getThisType();
5872 FromClassification = Expr::Classification::makeSimpleLValue();
5873 } else {
5874 FromRecordType = From->getType();
5875 DestType = ImplicitParamRecordType;
5876 FromClassification = From->Classify(Context);
5877
5878 // When performing member access on a prvalue, materialize a temporary.
5879 if (From->isPRValue()) {
5880 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5881 Method->getRefQualifier() !=
5883 }
5884 }
5885
5886 // Note that we always use the true parent context when performing
5887 // the actual argument initialization.
5889 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5890 Method->getParent());
5891 if (ICS.isBad()) {
5892 switch (ICS.Bad.Kind) {
5894 Qualifiers FromQs = FromRecordType.getQualifiers();
5895 Qualifiers ToQs = DestType.getQualifiers();
5896 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5897 if (CVR) {
5898 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5899 << Method->getDeclName() << FromRecordType << (CVR - 1)
5900 << From->getSourceRange();
5901 Diag(Method->getLocation(), diag::note_previous_decl)
5902 << Method->getDeclName();
5903 return ExprError();
5904 }
5905 break;
5906 }
5907
5910 bool IsRValueQualified =
5912 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5913 << Method->getDeclName() << FromClassification.isRValue()
5914 << IsRValueQualified;
5915 Diag(Method->getLocation(), diag::note_previous_decl)
5916 << Method->getDeclName();
5917 return ExprError();
5918 }
5919
5922 break;
5923
5926 llvm_unreachable("Lists are not objects");
5927 }
5928
5929 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5930 << ImplicitParamRecordType << FromRecordType
5931 << From->getSourceRange();
5932 }
5933
5934 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5935 ExprResult FromRes =
5936 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5937 if (FromRes.isInvalid())
5938 return ExprError();
5939 From = FromRes.get();
5940 }
5941
5942 if (!Context.hasSameType(From->getType(), DestType)) {
5943 CastKind CK;
5944 QualType PteeTy = DestType->getPointeeType();
5945 LangAS DestAS =
5946 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5947 if (FromRecordType.getAddressSpace() != DestAS)
5948 CK = CK_AddressSpaceConversion;
5949 else
5950 CK = CK_NoOp;
5951 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5952 }
5953 return From;
5954}
5955
5956/// TryContextuallyConvertToBool - Attempt to contextually convert the
5957/// expression From to bool (C++0x [conv]p3).
5960 // C++ [dcl.init]/17.8:
5961 // - Otherwise, if the initialization is direct-initialization, the source
5962 // type is std::nullptr_t, and the destination type is bool, the initial
5963 // value of the object being initialized is false.
5964 if (From->getType()->isNullPtrType())
5966 S.Context.BoolTy,
5967 From->isGLValue());
5968
5969 // All other direct-initialization of bool is equivalent to an implicit
5970 // conversion to bool in which explicit conversions are permitted.
5971 return TryImplicitConversion(S, From, S.Context.BoolTy,
5972 /*SuppressUserConversions=*/false,
5973 AllowedExplicit::Conversions,
5974 /*InOverloadResolution=*/false,
5975 /*CStyle=*/false,
5976 /*AllowObjCWritebackConversion=*/false,
5977 /*AllowObjCConversionOnExplicit=*/false);
5978}
5979
5981 if (checkPlaceholderForOverload(*this, From))
5982 return ExprError();
5983
5985 if (!ICS.isBad())
5986 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5987
5988 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5989 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5990 << From->getType() << From->getSourceRange();
5991 return ExprError();
5992}
5993
5994/// Check that the specified conversion is permitted in a converted constant
5995/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5996/// is acceptable.
5999 // Since we know that the target type is an integral or unscoped enumeration
6000 // type, most conversion kinds are impossible. All possible First and Third
6001 // conversions are fine.
6002 switch (SCS.Second) {
6003 case ICK_Identity:
6005 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6007 return true;
6008
6010 // Conversion from an integral or unscoped enumeration type to bool is
6011 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6012 // conversion, so we allow it in a converted constant expression.
6013 //
6014 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6015 // a lot of popular code. We should at least add a warning for this
6016 // (non-conforming) extension.
6018 SCS.getToType(2)->isBooleanType();
6019
6021 case ICK_Pointer_Member:
6022 // C++1z: null pointer conversions and null member pointer conversions are
6023 // only permitted if the source type is std::nullptr_t.
6024 return SCS.getFromType()->isNullPtrType();
6025
6037 case ICK_Vector_Splat:
6038 case ICK_Complex_Real:
6047 return false;
6048
6053 llvm_unreachable("found a first conversion kind in Second");
6054
6056 case ICK_Qualification:
6057 llvm_unreachable("found a third conversion kind in Second");
6058
6060 break;
6061 }
6062
6063 llvm_unreachable("unknown conversion kind");
6064}
6065
6066/// BuildConvertedConstantExpression - Check that the expression From is a
6067/// converted constant expression of type T, perform the conversion but
6068/// does not evaluate the expression
6070 QualType T,
6071 Sema::CCEKind CCE,
6072 NamedDecl *Dest,
6073 APValue &PreNarrowingValue) {
6074 assert(S.getLangOpts().CPlusPlus11 &&
6075 "converted constant expression outside C++11");
6076
6077 if (checkPlaceholderForOverload(S, From))
6078 return ExprError();
6079
6080 // C++1z [expr.const]p3:
6081 // A converted constant expression of type T is an expression,
6082 // implicitly converted to type T, where the converted
6083 // expression is a constant expression and the implicit conversion
6084 // sequence contains only [... list of conversions ...].
6088 : TryCopyInitialization(S, From, T,
6089 /*SuppressUserConversions=*/false,
6090 /*InOverloadResolution=*/false,
6091 /*AllowObjCWritebackConversion=*/false,
6092 /*AllowExplicit=*/false);
6093 StandardConversionSequence *SCS = nullptr;
6094 switch (ICS.getKind()) {
6096 SCS = &ICS.Standard;
6097 break;
6099 if (T->isRecordType())
6100 SCS = &ICS.UserDefined.Before;
6101 else
6102 SCS = &ICS.UserDefined.After;
6103 break;
6107 return S.Diag(From->getBeginLoc(),
6108 diag::err_typecheck_converted_constant_expression)
6109 << From->getType() << From->getSourceRange() << T;
6110 return ExprError();
6111
6114 llvm_unreachable("bad conversion in converted constant expression");
6115 }
6116
6117 // Check that we would only use permitted conversions.
6118 if (!CheckConvertedConstantConversions(S, *SCS)) {
6119 return S.Diag(From->getBeginLoc(),
6120 diag::err_typecheck_converted_constant_expression_disallowed)
6121 << From->getType() << From->getSourceRange() << T;
6122 }
6123 // [...] and where the reference binding (if any) binds directly.
6124 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6125 return S.Diag(From->getBeginLoc(),
6126 diag::err_typecheck_converted_constant_expression_indirect)
6127 << From->getType() << From->getSourceRange() << T;
6128 }
6129 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6130 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6131 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6132 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6133 // case explicitly.
6134 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6135 return S.Diag(From->getBeginLoc(),
6136 diag::err_reference_bind_to_bitfield_in_cce)
6137 << From->getSourceRange();
6138 }
6139
6140 // Usually we can simply apply the ImplicitConversionSequence we formed
6141 // earlier, but that's not guaranteed to work when initializing an object of
6142 // class type.
6144 if (T->isRecordType()) {
6145 assert(CCE == Sema::CCEK_TemplateArg &&
6146 "unexpected class type converted constant expr");
6149 T, cast<NonTypeTemplateParmDecl>(Dest)),
6150 SourceLocation(), From);
6151 } else {
6153 }
6154 if (Result.isInvalid())
6155 return Result;
6156
6157 // C++2a [intro.execution]p5:
6158 // A full-expression is [...] a constant-expression [...]
6159 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6160 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6162 if (Result.isInvalid())
6163 return Result;
6164
6165 // Check for a narrowing implicit conversion.
6166 bool ReturnPreNarrowingValue = false;
6167 QualType PreNarrowingType;
6168 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6169 PreNarrowingType)) {
6171 // Implicit conversion to a narrower type, but the expression is
6172 // value-dependent so we can't tell whether it's actually narrowing.
6174 // Implicit conversion to a narrower type, and the value is not a constant
6175 // expression. We'll diagnose this in a moment.
6176 case NK_Not_Narrowing:
6177 break;
6178
6180 if (CCE == Sema::CCEK_ArrayBound &&
6181 PreNarrowingType->isIntegralOrEnumerationType() &&
6182 PreNarrowingValue.isInt()) {
6183 // Don't diagnose array bound narrowing here; we produce more precise
6184 // errors by allowing the un-narrowed value through.
6185 ReturnPreNarrowingValue = true;
6186 break;
6187 }
6188 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6189 << CCE << /*Constant*/ 1
6190 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6191 break;
6192
6193 case NK_Type_Narrowing:
6194 // FIXME: It would be better to diagnose that the expression is not a
6195 // constant expression.
6196 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6197 << CCE << /*Constant*/ 0 << From->getType() << T;
6198 break;
6199 }
6200 if (!ReturnPreNarrowingValue)
6201 PreNarrowingValue = {};
6202
6203 return Result;
6204}
6205
6206/// CheckConvertedConstantExpression - Check that the expression From is a
6207/// converted constant expression of type T, perform the conversion and produce
6208/// the converted expression, per C++11 [expr.const]p3.
6211 Sema::CCEKind CCE,
6212 bool RequireInt,
6213 NamedDecl *Dest) {
6214
6215 APValue PreNarrowingValue;
6217 PreNarrowingValue);
6218 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6219 Value = APValue();
6220 return Result;
6221 }
6222 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6223 RequireInt, PreNarrowingValue);
6224}
6225
6227 CCEKind CCE,
6228 NamedDecl *Dest) {
6229 APValue PreNarrowingValue;
6230 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6231 PreNarrowingValue);
6232}
6233
6235 APValue &Value, CCEKind CCE,
6236 NamedDecl *Dest) {
6237 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6238 Dest);
6239}
6240
6242 llvm::APSInt &Value,
6243 CCEKind CCE) {
6244 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6245
6246 APValue V;
6247 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6248 /*Dest=*/nullptr);
6249 if (!R.isInvalid() && !R.get()->isValueDependent())
6250 Value = V.getInt();
6251 return R;
6252}
6253
6256 Sema::CCEKind CCE, bool RequireInt,
6257 const APValue &PreNarrowingValue) {
6258
6260 // Check the expression is a constant expression.
6262 Expr::EvalResult Eval;
6263 Eval.Diag = &Notes;
6264
6265 ConstantExprKind Kind;
6266 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6267 Kind = ConstantExprKind::ClassTemplateArgument;
6268 else if (CCE == Sema::CCEK_TemplateArg)
6269 Kind = ConstantExprKind::NonClassTemplateArgument;
6270 else
6271 Kind = ConstantExprKind::Normal;
6272
6273 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6274 (RequireInt && !Eval.Val.isInt())) {
6275 // The expression can't be folded, so we can't keep it at this position in
6276 // the AST.
6277 Result = ExprError();
6278 } else {
6279 Value = Eval.Val;
6280
6281 if (Notes.empty()) {
6282 // It's a constant expression.
6283 Expr *E = Result.get();
6284 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6285 // We expect a ConstantExpr to have a value associated with it
6286 // by this point.
6287 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6288 "ConstantExpr has no value associated with it");
6289 (void)CE;
6290 } else {
6291 E = ConstantExpr::Create(Context, Result.get(), Value);
6292 }
6293 if (!PreNarrowingValue.isAbsent())
6294 Value = std::move(PreNarrowingValue);
6295 return E;
6296 }
6297 }
6298
6299 // It's not a constant expression. Produce an appropriate diagnostic.
6300 if (Notes.size() == 1 &&
6301 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6302 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6303 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6304 diag::note_constexpr_invalid_template_arg) {
6305 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6306 for (unsigned I = 0; I < Notes.size(); ++I)
6307 Diag(Notes[I].first, Notes[I].second);
6308 } else {
6309 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6310 << CCE << E->getSourceRange();
6311 for (unsigned I = 0; I < Notes.size(); ++I)
6312 Diag(Notes[I].first, Notes[I].second);
6313 }
6314 return ExprError();
6315}
6316
6317/// dropPointerConversions - If the given standard conversion sequence
6318/// involves any pointer conversions, remove them. This may change
6319/// the result type of the conversion sequence.
6321 if (SCS.Second == ICK_Pointer_Conversion) {
6322 SCS.Second = ICK_Identity;
6323 SCS.Dimension = ICK_Identity;
6324 SCS.Third = ICK_Identity;
6325 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6326 }
6327}
6328
6329/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6330/// convert the expression From to an Objective-C pointer type.
6333 // Do an implicit conversion to 'id'.
6336 = TryImplicitConversion(S, From, Ty,
6337 // FIXME: Are these flags correct?
6338 /*SuppressUserConversions=*/false,
6339 AllowedExplicit::Conversions,
6340 /*InOverloadResolution=*/false,
6341 /*CStyle=*/false,
6342 /*AllowObjCWritebackConversion=*/false,
6343 /*AllowObjCConversionOnExplicit=*/true);
6344
6345 // Strip off any final conversions to 'id'.
6346 switch (ICS.getKind()) {
6351 break;
6352
6355 break;
6356
6359 break;
6360 }
6361
6362 return ICS;
6363}
6364
6366 if (checkPlaceholderForOverload(*this, From))
6367 return ExprError();
6368
6369 QualType Ty = Context.getObjCIdType();
6372 if (!ICS.isBad())
6373 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
6374 return ExprResult();
6375}
6376
6377static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6378 const Expr *Base = nullptr;
6379 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6380 "expected a member expression");
6381
6382 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6383 M && !M->isImplicitAccess())
6384 Base = M->getBase();
6385 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6386 M && !M->isImplicitAccess())
6387 Base = M->getBase();
6388
6389 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6390
6391 if (T->isPointerType())
6392 T = T->getPointeeType();
6393
6394 return T;
6395}
6396
6398 const FunctionDecl *Fun) {
6399 QualType ObjType = Obj->getType();
6400 if (ObjType->isPointerType()) {
6401 ObjType = ObjType->getPointeeType();
6402 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6404 /*CanOverflow=*/false, FPOptionsOverride());
6405 }
6406 if (Obj->Classify(S.getASTContext()).isPRValue()) {
6408 ObjType, Obj,
6410 }
6411 return Obj;
6412}
6413
6415 FunctionDecl *Fun) {
6416 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6419 Obj->getExprLoc(), Obj);
6420}
6421
6423 Expr *Object, MultiExprArg &Args,
6424 SmallVectorImpl<Expr *> &NewArgs) {
6425 assert(Method->isExplicitObjectMemberFunction() &&
6426 "Method is not an explicit member function");
6427 assert(NewArgs.empty() && "NewArgs should be empty");
6428
6429 NewArgs.reserve(Args.size() + 1);
6430 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6431 NewArgs.push_back(This);
6432 NewArgs.append(Args.begin(), Args.end());
6433 Args = NewArgs;
6435 Method, Object->getBeginLoc());
6436}
6437
6438/// Determine whether the provided type is an integral type, or an enumeration
6439/// type of a permitted flavor.
6441 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6443}
6444
6445static ExprResult
6448 QualType T, UnresolvedSetImpl &ViableConversions) {
6449
6450 if (Converter.Suppress)
6451 return ExprError();
6452
6453 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6454 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6455 CXXConversionDecl *Conv =
6456 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6458 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6459 }
6460 return From;
6461}
6462
6463static bool
6466 QualType T, bool HadMultipleCandidates,
6467 UnresolvedSetImpl &ExplicitConversions) {
6468 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6469 DeclAccessPair Found = ExplicitConversions[0];
6470 CXXConversionDecl *Conversion =
6471 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6472
6473 // The user probably meant to invoke the given explicit
6474 // conversion; use it.
6475 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6476 std::string TypeStr;
6477 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6478
6479 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6481 "static_cast<" + TypeStr + ">(")
6483 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6484 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6485
6486 // If we aren't in a SFINAE context, build a call to the
6487 // explicit conversion function.
6488 if (SemaRef.isSFINAEContext())
6489 return true;
6490
6491 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6492 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6493 HadMultipleCandidates);
6494 if (Result.isInvalid())
6495 return true;
6496
6497 // Replace the conversion with a RecoveryExpr, so we don't try to
6498 // instantiate it later, but can further diagnose here.
6499 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6500 From, Result.get()->getType());
6501 if (Result.isInvalid())
6502 return true;
6503 From = Result.get();
6504 }
6505 return false;
6506}
6507
6508static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6510 QualType T, bool HadMultipleCandidates,
6512 CXXConversionDecl *Conversion =
6513 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6514 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6515
6516 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6517 if (!Converter.SuppressConversion) {
6518 if (SemaRef.isSFINAEContext())
6519 return true;
6520
6521 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6522 << From->getSourceRange();
6523 }
6524
6525 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6526 HadMultipleCandidates);
6527 if (Result.isInvalid())
6528 return true;
6529 // Record usage of conversion in an implicit cast.
6530 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6531 CK_UserDefinedConversion, Result.get(),
6532 nullptr, Result.get()->getValueKind(),
6533 SemaRef.CurFPFeatureOverrides());
6534 return false;
6535}
6536
6538 Sema &SemaRef, SourceLocation Loc, Expr *From,
6540 if (!Converter.match(From->getType()) && !Converter.Suppress)
6541 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6542 << From->getSourceRange();
6543
6544 return SemaRef.DefaultLvalueConversion(From);
6545}
6546
6547static void
6549 UnresolvedSetImpl &ViableConversions,
6550 OverloadCandidateSet &CandidateSet) {
6551 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6552 DeclAccessPair FoundDecl = ViableConversions[I];
6553 NamedDecl *D = FoundDecl.getDecl();
6554 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6555 if (isa<UsingShadowDecl>(D))
6556 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6557
6558 CXXConversionDecl *Conv;
6559 FunctionTemplateDecl *ConvTemplate;
6560 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6561 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6562 else
6563 Conv = cast<CXXConversionDecl>(D);
6564
6565 if (ConvTemplate)
6567 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6568 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6569 else
6570 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6571 ToType, CandidateSet,
6572 /*AllowObjCConversionOnExplicit=*/false,
6573 /*AllowExplicit*/ true);
6574 }
6575}
6576
6577/// Attempt to convert the given expression to a type which is accepted
6578/// by the given converter.
6579///
6580/// This routine will attempt to convert an expression of class type to a
6581/// type accepted by the specified converter. In C++11 and before, the class
6582/// must have a single non-explicit conversion function converting to a matching
6583/// type. In C++1y, there can be multiple such conversion functions, but only
6584/// one target type.
6585///
6586/// \param Loc The source location of the construct that requires the
6587/// conversion.
6588///
6589/// \param From The expression we're converting from.
6590///
6591/// \param Converter Used to control and diagnose the conversion process.
6592///
6593/// \returns The expression, converted to an integral or enumeration type if
6594/// successful.
6596 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6597 // We can't perform any more checking for type-dependent expressions.
6598 if (From->isTypeDependent())
6599 return From;
6600
6601 // Process placeholders immediately.
6602 if (From->hasPlaceholderType()) {
6603 ExprResult result = CheckPlaceholderExpr(From);
6604 if (result.isInvalid())
6605 return result;
6606 From = result.get();
6607 }
6608
6609 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6610 ExprResult Converted = DefaultLvalueConversion(From);
6611 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6612 // If the expression already has a matching type, we're golden.
6613 if (Converter.match(T))
6614 return Converted;
6615
6616 // FIXME: Check for missing '()' if T is a function type?
6617
6618 // We can only perform contextual implicit conversions on objects of class
6619 // type.
6620 const RecordType *RecordTy = T->getAs<RecordType>();
6621 if (!RecordTy || !getLangOpts().CPlusPlus) {
6622 if (!Converter.Suppress)
6623 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6624 return From;
6625 }
6626
6627 // We must have a complete class type.
6628 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6629 ContextualImplicitConverter &Converter;
6630 Expr *From;
6631
6632 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6633 : Converter(Converter), From(From) {}
6634
6635 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6636 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6637 }
6638 } IncompleteDiagnoser(Converter, From);
6639
6640 if (Converter.Suppress ? !isCompleteType(Loc, T)
6641 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6642 return From;
6643
6644 // Look for a conversion to an integral or enumeration type.
6646 ViableConversions; // These are *potentially* viable in C++1y.
6647 UnresolvedSet<4> ExplicitConversions;
6648 const auto &Conversions =
6649 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6650
6651 bool HadMultipleCandidates =
6652 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6653
6654 // To check that there is only one target type, in C++1y:
6655 QualType ToType;
6656 bool HasUniqueTargetType = true;
6657
6658 // Collect explicit or viable (potentially in C++1y) conversions.
6659 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6660 NamedDecl *D = (*I)->getUnderlyingDecl();
6661 CXXConversionDecl *Conversion;
6662 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6663 if (ConvTemplate) {
6664 if (getLangOpts().CPlusPlus14)
6665 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6666 else
6667 continue; // C++11 does not consider conversion operator templates(?).
6668 } else
6669 Conversion = cast<CXXConversionDecl>(D);
6670
6671 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6672 "Conversion operator templates are considered potentially "
6673 "viable in C++1y");
6674
6675 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6676 if (Converter.match(CurToType) || ConvTemplate) {
6677
6678 if (Conversion->isExplicit()) {
6679 // FIXME: For C++1y, do we need this restriction?
6680 // cf. diagnoseNoViableConversion()
6681 if (!ConvTemplate)
6682 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6683 } else {
6684 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6685 if (ToType.isNull())
6686 ToType = CurToType.getUnqualifiedType();
6687 else if (HasUniqueTargetType &&
6688 (CurToType.getUnqualifiedType() != ToType))
6689 HasUniqueTargetType = false;
6690 }
6691 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6692 }
6693 }
6694 }
6695
6696 if (getLangOpts().CPlusPlus14) {
6697 // C++1y [conv]p6:
6698 // ... An expression e of class type E appearing in such a context
6699 // is said to be contextually implicitly converted to a specified
6700 // type T and is well-formed if and only if e can be implicitly
6701 // converted to a type T that is determined as follows: E is searched
6702 // for conversion functions whose return type is cv T or reference to
6703 // cv T such that T is allowed by the context. There shall be
6704 // exactly one such T.
6705
6706 // If no unique T is found:
6707 if (ToType.isNull()) {
6708 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6709 HadMultipleCandidates,
6710 ExplicitConversions))
6711 return ExprError();
6712 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6713 }
6714
6715 // If more than one unique Ts are found:
6716 if (!HasUniqueTargetType)
6717 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6718 ViableConversions);
6719
6720 // If one unique T is found:
6721 // First, build a candidate set from the previously recorded
6722 // potentially viable conversions.
6724 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6725 CandidateSet);
6726
6727 // Then, perform overload resolution over the candidate set.
6729 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6730 case OR_Success: {
6731 // Apply this conversion.
6733 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6734 if (recordConversion(*this, Loc, From, Converter, T,
6735 HadMultipleCandidates, Found))
6736 return ExprError();
6737 break;
6738 }
6739 case OR_Ambiguous:
6740 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6741 ViableConversions);
6743 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6744 HadMultipleCandidates,
6745 ExplicitConversions))
6746 return ExprError();
6747 [[fallthrough]];
6748 case OR_Deleted:
6749 // We'll complain below about a non-integral condition type.
6750 break;
6751 }
6752 } else {
6753 switch (ViableConversions.size()) {
6754 case 0: {
6755 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6756 HadMultipleCandidates,
6757 ExplicitConversions))
6758 return ExprError();
6759
6760 // We'll complain below about a non-integral condition type.
6761 break;
6762 }
6763 case 1: {
6764 // Apply this conversion.
6765 DeclAccessPair Found = ViableConversions[0];
6766 if (recordConversion(*this, Loc, From, Converter, T,
6767 HadMultipleCandidates, Found))
6768 return ExprError();
6769 break;
6770 }
6771 default:
6772 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6773 ViableConversions);
6774 }
6775 }
6776
6777 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6778}
6779
6780/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6781/// an acceptable non-member overloaded operator for a call whose
6782/// arguments have types T1 (and, if non-empty, T2). This routine
6783/// implements the check in C++ [over.match.oper]p3b2 concerning
6784/// enumeration types.
6786 FunctionDecl *Fn,
6787 ArrayRef<Expr *> Args) {
6788 QualType T1 = Args[0]->getType();
6789 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6790
6791 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6792 return true;
6793
6794 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6795 return true;
6796
6797 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6798 if (Proto->getNumParams() < 1)
6799 return false;
6800
6801 if (T1->isEnumeralType()) {
6802 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6803 if (Context.hasSameUnqualifiedType(T1, ArgType))
6804 return true;
6805 }
6806
6807 if (Proto->getNumParams() < 2)
6808 return false;
6809
6810 if (!T2.isNull() && T2->isEnumeralType()) {
6811 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6812 if (Context.hasSameUnqualifiedType(T2, ArgType))
6813 return true;
6814 }
6815
6816 return false;
6817}
6818
6821 return false;
6822
6823 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
6824 return FD->isTargetMultiVersion();
6825
6826 if (!FD->isMultiVersion())
6827 return false;
6828
6829 // Among multiple target versions consider either the default,
6830 // or the first non-default in the absence of default version.
6831 unsigned SeenAt = 0;
6832 unsigned I = 0;
6833 bool HasDefault = false;
6835 FD, [&](const FunctionDecl *CurFD) {
6836 if (FD == CurFD)
6837 SeenAt = I;
6838 else if (CurFD->isTargetMultiVersionDefault())
6839 HasDefault = true;
6840 ++I;
6841 });
6842 return HasDefault || SeenAt != 0;
6843}
6844
6847 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6848 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6849 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6850 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6851 const FunctionProtoType *Proto
6852 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6853 assert(Proto && "Functions without a prototype cannot be overloaded");
6854 assert(!Function->getDescribedFunctionTemplate() &&
6855 "Use AddTemplateOverloadCandidate for function templates");
6856
6857 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6858 if (!isa<CXXConstructorDecl>(Method)) {
6859 // If we get here, it's because we're calling a member function
6860 // that is named without a member access expression (e.g.,
6861 // "this->f") that was either written explicitly or created
6862 // implicitly. This can happen with a qualified call to a member
6863 // function, e.g., X::f(). We use an empty type for the implied
6864 // object argument (C++ [over.call.func]p3), and the acting context
6865 // is irrelevant.
6866 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6868 CandidateSet, SuppressUserConversions,
6869 PartialOverloading, EarlyConversions, PO);
6870 return;
6871 }
6872 // We treat a constructor like a non-member function, since its object
6873 // argument doesn't participate in overload resolution.
6874 }
6875
6876 if (!CandidateSet.isNewCandidate(Function, PO))
6877 return;
6878
6879 // C++11 [class.copy]p11: [DR1402]
6880 // A defaulted move constructor that is defined as deleted is ignored by
6881 // overload resolution.
6882 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6883 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6884 Constructor->isMoveConstructor())
6885 return;
6886
6887 // Overload resolution is always an unevaluated context.
6890
6891 // C++ [over.match.oper]p3:
6892 // if no operand has a class type, only those non-member functions in the
6893 // lookup set that have a first parameter of type T1 or "reference to
6894 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6895 // is a right operand) a second parameter of type T2 or "reference to
6896 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6897 // candidate functions.
6898 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6900 return;
6901
6902 // Add this candidate
6903 OverloadCandidate &Candidate =
6904 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6905 Candidate.FoundDecl = FoundDecl;
6906 Candidate.Function = Function;
6907 Candidate.Viable = true;
6908 Candidate.RewriteKind =
6909 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6910 Candidate.IsADLCandidate = IsADLCandidate;
6911 Candidate.ExplicitCallArguments = Args.size();
6912
6913 // Explicit functions are not actually candidates at all if we're not
6914 // allowing them in this context, but keep them around so we can point
6915 // to them in diagnostics.
6916 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6917 Candidate.Viable = false;
6918 Candidate.FailureKind = ovl_fail_explicit;
6919 return;
6920 }
6921
6922 // Functions with internal linkage are only viable in the same module unit.
6923 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
6924 /// FIXME: Currently, the semantics of linkage in clang is slightly
6925 /// different from the semantics in C++ spec. In C++ spec, only names
6926 /// have linkage. So that all entities of the same should share one
6927 /// linkage. But in clang, different entities of the same could have
6928 /// different linkage.
6929 NamedDecl *ND = Function;
6930 if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6931 ND = SpecInfo->getTemplate();
6932
6933 if (ND->getFormalLinkage() == Linkage::Internal) {
6934 Candidate.Viable = false;
6936 return;
6937 }
6938 }
6939
6941 Candidate.Viable = false;
6943 return;
6944 }
6945
6946 if (Constructor) {
6947 // C++ [class.copy]p3:
6948 // A member function template is never instantiated to perform the copy
6949 // of a class object to an object of its class type.
6950 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6951 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6952 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6953 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6954 ClassType))) {
6955 Candidate.Viable = false;
6957 return;
6958 }
6959
6960 // C++ [over.match.funcs]p8: (proposed DR resolution)
6961 // A constructor inherited from class type C that has a first parameter
6962 // of type "reference to P" (including such a constructor instantiated
6963 // from a template) is excluded from the set of candidate functions when
6964 // constructing an object of type cv D if the argument list has exactly
6965 // one argument and D is reference-related to P and P is reference-related
6966 // to C.
6967 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6968 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6969 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6970 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6971 QualType C = Context.getRecordType(Constructor->getParent());
6972 QualType D = Context.getRecordType(Shadow->getParent());
6973 SourceLocation Loc = Args.front()->getExprLoc();
6974 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6975 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6976 Candidate.Viable = false;
6978 return;
6979 }
6980 }
6981
6982 // Check that the constructor is capable of constructing an object in the
6983 // destination address space.
6985 Constructor->getMethodQualifiers().getAddressSpace(),
6986 CandidateSet.getDestAS())) {
6987 Candidate.Viable = false;
6989 }
6990 }
6991
6992 unsigned NumParams = Proto->getNumParams();
6993
6994 // (C++ 13.3.2p2): A candidate function having fewer than m
6995 // parameters is viable only if it has an ellipsis in its parameter
6996 // list (8.3.5).
6997 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6998 !Proto->isVariadic() &&
6999 shouldEnforceArgLimit(PartialOverloading, Function)) {
7000 Candidate.Viable = false;
7002 return;
7003 }
7004
7005 // (C++ 13.3.2p2): A candidate function having more than m parameters
7006 // is viable only if the (m+1)st parameter has a default argument
7007 // (8.3.6). For the purposes of overload resolution, the
7008 // parameter list is truncated on the right, so that there are
7009 // exactly m parameters.
7010 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7011 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7012 !PartialOverloading) {
7013 // Not enough arguments.
7014 Candidate.Viable = false;
7016 return;
7017 }
7018
7019 // (CUDA B.1): Check for invalid calls between targets.
7020 if (getLangOpts().CUDA) {
7021 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7022 // Skip the check for callers that are implicit members, because in this
7023 // case we may not yet know what the member's target is; the target is
7024 // inferred for the member automatically, based on the bases and fields of
7025 // the class.
7026 if (!(Caller && Caller->isImplicit()) &&
7027 !CUDA().IsAllowedCall(Caller, Function)) {
7028 Candidate.Viable = false;
7029 Candidate.FailureKind = ovl_fail_bad_target;
7030 return;
7031 }
7032 }
7033
7034 if (Function->getTrailingRequiresClause()) {
7035 ConstraintSatisfaction Satisfaction;
7036 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7037 /*ForOverloadResolution*/ true) ||
7038 !Satisfaction.IsSatisfied) {
7039 Candidate.Viable = false;
7041 return;
7042 }
7043 }
7044
7045 // Determine the implicit conversion sequences for each of the
7046 // arguments.
7047 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7048 unsigned ConvIdx =
7049 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7050 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7051 // We already formed a conversion sequence for this parameter during
7052 // template argument deduction.
7053 } else if (ArgIdx < NumParams) {
7054 // (C++ 13.3.2p3): for F to be a viable function, there shall
7055 // exist for each argument an implicit conversion sequence
7056 // (13.3.3.1) that converts that argument to the corresponding
7057 // parameter of F.
7058 QualType ParamType = Proto->getParamType(ArgIdx);
7059 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7060 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7061 /*InOverloadResolution=*/true,
7062 /*AllowObjCWritebackConversion=*/
7063 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7064 if (Candidate.Conversions[ConvIdx].isBad()) {
7065 Candidate.Viable = false;
7067 return;
7068 }
7069 } else {
7070 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7071 // argument for which there is no corresponding parameter is
7072 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7073 Candidate.Conversions[ConvIdx].setEllipsis();
7074 }
7075 }
7076
7077 if (EnableIfAttr *FailedAttr =
7078 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7079 Candidate.Viable = false;
7080 Candidate.FailureKind = ovl_fail_enable_if;
7081 Candidate.DeductionFailure.Data = FailedAttr;
7082 return;
7083 }
7084}
7085
7089 if (Methods.size() <= 1)
7090 return nullptr;
7091
7092 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7093 bool Match = true;
7094 ObjCMethodDecl *Method = Methods[b];
7095 unsigned NumNamedArgs = Sel.getNumArgs();
7096 // Method might have more arguments than selector indicates. This is due
7097 // to addition of c-style arguments in method.
7098 if (Method->param_size() > NumNamedArgs)
7099 NumNamedArgs = Method->param_size();
7100 if (Args.size() < NumNamedArgs)
7101 continue;
7102
7103 for (unsigned i = 0; i < NumNamedArgs; i++) {
7104 // We can't do any type-checking on a type-dependent argument.
7105 if (Args[i]->isTypeDependent()) {
7106 Match = false;
7107 break;
7108 }
7109
7110 ParmVarDecl *param = Method->parameters()[i];
7111 Expr *argExpr = Args[i];
7112 assert(argExpr && "SelectBestMethod(): missing expression");
7113
7114 // Strip the unbridged-cast placeholder expression off unless it's
7115 // a consumed argument.
7116 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7117 !param->hasAttr<CFConsumedAttr>())
7118 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7119
7120 // If the parameter is __unknown_anytype, move on to the next method.
7121 if (param->getType() == Context.UnknownAnyTy) {
7122 Match = false;
7123 break;
7124 }
7125
7126 ImplicitConversionSequence ConversionState
7127 = TryCopyInitialization(*this, argExpr, param->getType(),
7128 /*SuppressUserConversions*/false,
7129 /*InOverloadResolution=*/true,
7130 /*AllowObjCWritebackConversion=*/
7131 getLangOpts().ObjCAutoRefCount,
7132 /*AllowExplicit*/false);
7133 // This function looks for a reasonably-exact match, so we consider
7134 // incompatible pointer conversions to be a failure here.
7135 if (ConversionState.isBad() ||
7136 (ConversionState.isStandard() &&
7137 ConversionState.Standard.Second ==
7139 Match = false;
7140 break;
7141 }
7142 }
7143 // Promote additional arguments to variadic methods.
7144 if (Match && Method->isVariadic()) {
7145 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7146 if (Args[i]->isTypeDependent()) {
7147 Match = false;
7148 break;
7149 }
7150 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
7151 nullptr);
7152 if (Arg.isInvalid()) {
7153 Match = false;
7154 break;
7155 }
7156 }
7157 } else {
7158 // Check for extra arguments to non-variadic methods.
7159 if (Args.size() != NumNamedArgs)
7160 Match = false;
7161 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7162 // Special case when selectors have no argument. In this case, select
7163 // one with the most general result type of 'id'.
7164 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7165 QualType ReturnT = Methods[b]->getReturnType();
7166 if (ReturnT->isObjCIdType())
7167 return Methods[b];
7168 }
7169 }
7170 }
7171
7172 if (Match)
7173 return Method;
7174 }
7175 return nullptr;
7176}
7177
7179 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7180 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7181 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7182 if (ThisArg) {
7183 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7184 assert(!isa<CXXConstructorDecl>(Method) &&
7185 "Shouldn't have `this` for ctors!");
7186 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7188 ThisArg, /*Qualifier=*/nullptr, Method, Method);
7189 if (R.isInvalid())
7190 return false;
7191 ConvertedThis = R.get();
7192 } else {
7193 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7194 (void)MD;
7195 assert((MissingImplicitThis || MD->isStatic() ||
7196 isa<CXXConstructorDecl>(MD)) &&
7197 "Expected `this` for non-ctor instance methods");
7198 }
7199 ConvertedThis = nullptr;
7200 }
7201
7202 // Ignore any variadic arguments. Converting them is pointless, since the
7203 // user can't refer to them in the function condition.
7204 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7205
7206 // Convert the arguments.
7207 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7208 ExprResult R;
7210 S.Context, Function->getParamDecl(I)),
7211 SourceLocation(), Args[I]);
7212
7213 if (R.isInvalid())
7214 return false;
7215
7216 ConvertedArgs.push_back(R.get());
7217 }
7218
7219 if (Trap.hasErrorOccurred())
7220 return false;
7221
7222 // Push default arguments if needed.
7223 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7224 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7225 ParmVarDecl *P = Function->getParamDecl(i);
7226 if (!P->hasDefaultArg())
7227 return false;
7229 if (R.isInvalid())
7230 return false;
7231 ConvertedArgs.push_back(R.get());
7232 }
7233
7234 if (Trap.hasErrorOccurred())
7235 return false;
7236 }
7237 return true;
7238}
7239
7241 SourceLocation CallLoc,
7242 ArrayRef<Expr *> Args,
7243 bool MissingImplicitThis) {
7244 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7245 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7246 return nullptr;
7247
7248 SFINAETrap Trap(*this);
7249 SmallVector<Expr *, 16> ConvertedArgs;
7250 // FIXME: We should look into making enable_if late-parsed.
7251 Expr *DiscardedThis;
7253 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7254 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7255 return *EnableIfAttrs.begin();
7256
7257 for (auto *EIA : EnableIfAttrs) {
7259 // FIXME: This doesn't consider value-dependent cases, because doing so is
7260 // very difficult. Ideally, we should handle them more gracefully.
7261 if (EIA->getCond()->isValueDependent() ||
7262 !EIA->getCond()->EvaluateWithSubstitution(
7263 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7264 return EIA;
7265
7266 if (!Result.isInt() || !Result.getInt().getBoolValue())
7267 return EIA;
7268 }
7269 return nullptr;
7270}
7271
7272template <typename CheckFn>
7274 bool ArgDependent, SourceLocation Loc,
7275 CheckFn &&IsSuccessful) {
7277 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7278 if (ArgDependent == DIA->getArgDependent())
7279 Attrs.push_back(DIA);
7280 }
7281
7282 // Common case: No diagnose_if attributes, so we can quit early.
7283 if (Attrs.empty())
7284 return false;
7285
7286 auto WarningBegin = std::stable_partition(
7287 Attrs.begin(), Attrs.end(),
7288 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7289
7290 // Note that diagnose_if attributes are late-parsed, so they appear in the
7291 // correct order (unlike enable_if attributes).
7292 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7293 IsSuccessful);
7294 if (ErrAttr != WarningBegin) {
7295 const DiagnoseIfAttr *DIA = *ErrAttr;
7296 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7297 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7298 << DIA->getParent() << DIA->getCond()->getSourceRange();
7299 return true;
7300 }
7301
7302 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7303 if (IsSuccessful(DIA)) {
7304 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7305 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7306 << DIA->getParent() << DIA->getCond()->getSourceRange();
7307 }
7308
7309 return false;
7310}
7311
7313 const Expr *ThisArg,
7315 SourceLocation Loc) {
7317 *this, Function, /*ArgDependent=*/true, Loc,
7318 [&](const DiagnoseIfAttr *DIA) {
7320 // It's sane to use the same Args for any redecl of this function, since
7321 // EvaluateWithSubstitution only cares about the position of each
7322 // argument in the arg list, not the ParmVarDecl* it maps to.
7323 if (!DIA->getCond()->EvaluateWithSubstitution(
7324 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7325 return false;
7326 return Result.isInt() && Result.getInt().getBoolValue();
7327 });
7328}
7329
7331 SourceLocation Loc) {
7333 *this, ND, /*ArgDependent=*/false, Loc,
7334 [&](const DiagnoseIfAttr *DIA) {
7335 bool Result;
7336 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7337 Result;
7338 });
7339}
7340
7342 ArrayRef<Expr *> Args,
7343 OverloadCandidateSet &CandidateSet,
7344 TemplateArgumentListInfo *ExplicitTemplateArgs,
7345 bool SuppressUserConversions,
7346 bool PartialOverloading,
7347 bool FirstArgumentIsBase) {
7348 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7349 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7350 ArrayRef<Expr *> FunctionArgs = Args;
7351
7352 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7353 FunctionDecl *FD =
7354 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7355
7356 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7357 QualType ObjectType;
7358 Expr::Classification ObjectClassification;
7359 if (Args.size() > 0) {
7360 if (Expr *E = Args[0]) {
7361 // Use the explicit base to restrict the lookup:
7362 ObjectType = E->getType();
7363 // Pointers in the object arguments are implicitly dereferenced, so we
7364 // always classify them as l-values.
7365 if (!ObjectType.isNull() && ObjectType->isPointerType())
7366 ObjectClassification = Expr::Classification::makeSimpleLValue();
7367 else
7368 ObjectClassification = E->Classify(Context);
7369 } // .. else there is an implicit base.
7370 FunctionArgs = Args.slice(1);
7371 }
7372 if (FunTmpl) {
7373 AddMethodTemplateCandidate(
7374 FunTmpl, F.getPair(),
7375 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7376 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7377 FunctionArgs, CandidateSet, SuppressUserConversions,
7378 PartialOverloading);
7379 } else {
7380 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7381 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7382 ObjectClassification, FunctionArgs, CandidateSet,
7383 SuppressUserConversions, PartialOverloading);
7384 }
7385 } else {
7386 // This branch handles both standalone functions and static methods.
7387
7388 // Slice the first argument (which is the base) when we access
7389 // static method as non-static.
7390 if (Args.size() > 0 &&
7391 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7392 !isa<CXXConstructorDecl>(FD)))) {
7393 assert(cast<CXXMethodDecl>(FD)->isStatic());
7394 FunctionArgs = Args.slice(1);
7395 }
7396 if (FunTmpl) {
7397 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7398 ExplicitTemplateArgs, FunctionArgs,
7399 CandidateSet, SuppressUserConversions,
7400 PartialOverloading);
7401 } else {
7402 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7403 SuppressUserConversions, PartialOverloading);
7404 }
7405 }
7406 }
7407}
7408
7410 Expr::Classification ObjectClassification,
7411 ArrayRef<Expr *> Args,
7412 OverloadCandidateSet &CandidateSet,
7413 bool SuppressUserConversions,
7415 NamedDecl *Decl = FoundDecl.getDecl();
7416 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7417
7418 if (isa<UsingShadowDecl>(Decl))
7419 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7420
7421 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7422 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7423 "Expected a member function template");
7424 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7425 /*ExplicitArgs*/ nullptr, ObjectType,
7426 ObjectClassification, Args, CandidateSet,
7427 SuppressUserConversions, false, PO);
7428 } else {
7429 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7430 ObjectType, ObjectClassification, Args, CandidateSet,
7431 SuppressUserConversions, false, std::nullopt, PO);
7432 }
7433}
7434
7435void
7437 CXXRecordDecl *ActingContext, QualType ObjectType,
7438 Expr::Classification ObjectClassification,
7439 ArrayRef<Expr *> Args,
7440 OverloadCandidateSet &CandidateSet,
7441 bool SuppressUserConversions,
7442 bool PartialOverloading,
7443 ConversionSequenceList EarlyConversions,
7445 const FunctionProtoType *Proto
7446 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7447 assert(Proto && "Methods without a prototype cannot be overloaded");
7448 assert(!isa<CXXConstructorDecl>(Method) &&
7449 "Use AddOverloadCandidate for constructors");
7450
7451 if (!CandidateSet.isNewCandidate(Method, PO))
7452 return;
7453
7454 // C++11 [class.copy]p23: [DR1402]
7455 // A defaulted move assignment operator that is defined as deleted is
7456 // ignored by overload resolution.
7457 if (Method->isDefaulted() && Method->isDeleted() &&
7458 Method->isMoveAssignmentOperator())
7459 return;
7460
7461 // Overload resolution is always an unevaluated context.
7464
7465 // Add this candidate
7466 OverloadCandidate &Candidate =
7467 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7468 Candidate.FoundDecl = FoundDecl;
7469 Candidate.Function = Method;
7470 Candidate.RewriteKind =
7471 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7472 Candidate.TookAddressOfOverload =
7474 Candidate.ExplicitCallArguments = Args.size();
7475
7476 bool IgnoreExplicitObject =
7477 (Method->isExplicitObjectMemberFunction() &&
7478 CandidateSet.getKind() ==
7480 bool ImplicitObjectMethodTreatedAsStatic =
7481 CandidateSet.getKind() ==
7484
7485 unsigned ExplicitOffset =
7486 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7487
7488 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7489 int(ImplicitObjectMethodTreatedAsStatic);
7490
7491 // (C++ 13.3.2p2): A candidate function having fewer than m
7492 // parameters is viable only if it has an ellipsis in its parameter
7493 // list (8.3.5).
7494 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7495 !Proto->isVariadic() &&
7496 shouldEnforceArgLimit(PartialOverloading, Method)) {
7497 Candidate.Viable = false;
7499 return;
7500 }
7501
7502 // (C++ 13.3.2p2): A candidate function having more than m parameters
7503 // is viable only if the (m+1)st parameter has a default argument
7504 // (8.3.6). For the purposes of overload resolution, the
7505 // parameter list is truncated on the right, so that there are
7506 // exactly m parameters.
7507 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7508 ExplicitOffset +
7509 int(ImplicitObjectMethodTreatedAsStatic);
7510
7511 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7512 // Not enough arguments.
7513 Candidate.Viable = false;
7515 return;
7516 }
7517
7518 Candidate.Viable = true;
7519
7520 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7521 if (ObjectType.isNull())
7522 Candidate.IgnoreObjectArgument = true;
7523 else if (Method->isStatic()) {
7524 // [over.best.ics.general]p8
7525 // When the parameter is the implicit object parameter of a static member
7526 // function, the implicit conversion sequence is a standard conversion
7527 // sequence that is neither better nor worse than any other standard
7528 // conversion sequence.
7529 //
7530 // This is a rule that was introduced in C++23 to support static lambdas. We
7531 // apply it retroactively because we want to support static lambdas as an
7532 // extension and it doesn't hurt previous code.
7533 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7534 } else {
7535 // Determine the implicit conversion sequence for the object
7536 // parameter.
7537 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7538 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7539 Method, ActingContext, /*InOverloadResolution=*/true);
7540 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7541 Candidate.Viable = false;
7543 return;
7544 }
7545 }
7546
7547 // (CUDA B.1): Check for invalid calls between targets.
7548 if (getLangOpts().CUDA)
7549 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7550 Method)) {
7551 Candidate.Viable = false;
7552 Candidate.FailureKind = ovl_fail_bad_target;
7553 return;
7554 }
7555
7556 if (Method->getTrailingRequiresClause()) {
7557 ConstraintSatisfaction Satisfaction;
7558 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7559 /*ForOverloadResolution*/ true) ||
7560 !Satisfaction.IsSatisfied) {
7561 Candidate.Viable = false;
7563 return;
7564 }
7565 }
7566
7567 // Determine the implicit conversion sequences for each of the
7568 // arguments.
7569 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7570 unsigned ConvIdx =
7571 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7572 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7573 // We already formed a conversion sequence for this parameter during
7574 // template argument deduction.
7575 } else if (ArgIdx < NumParams) {
7576 // (C++ 13.3.2p3): for F to be a viable function, there shall
7577 // exist for each argument an implicit conversion sequence
7578 // (13.3.3.1) that converts that argument to the corresponding
7579 // parameter of F.
7580 QualType ParamType;
7581 if (ImplicitObjectMethodTreatedAsStatic) {
7582 ParamType = ArgIdx == 0
7584 : Proto->getParamType(ArgIdx - 1);
7585 } else {
7586 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7587 }
7588 Candidate.Conversions[ConvIdx]
7589 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7590 SuppressUserConversions,
7591 /*InOverloadResolution=*/true,
7592 /*AllowObjCWritebackConversion=*/
7593 getLangOpts().ObjCAutoRefCount);
7594 if (Candidate.Conversions[ConvIdx].isBad()) {
7595 Candidate.Viable = false;
7597 return;
7598 }
7599 } else {
7600 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7601 // argument for which there is no corresponding parameter is
7602 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7603 Candidate.Conversions[ConvIdx].setEllipsis();
7604 }
7605 }
7606
7607 if (EnableIfAttr *FailedAttr =
7608 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7609 Candidate.Viable = false;
7610 Candidate.FailureKind = ovl_fail_enable_if;
7611 Candidate.DeductionFailure.Data = FailedAttr;
7612 return;
7613 }
7614
7615 if (isNonViableMultiVersionOverload(Method)) {
7616 Candidate.Viable = false;
7618 }
7619}
7620
7622 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7623 CXXRecordDecl *ActingContext,
7624 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7625 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7626 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7627 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7628 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7629 return;
7630
7631 // C++ [over.match.funcs]p7:
7632 // In each case where a candidate is a function template, candidate
7633 // function template specializations are generated using template argument
7634 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7635 // candidate functions in the usual way.113) A given name can refer to one
7636 // or more function templates and also to a set of overloaded non-template
7637 // functions. In such a case, the candidate functions generated from each
7638 // function template are combined with the set of non-template candidate
7639 // functions.
7640 TemplateDeductionInfo Info(CandidateSet.getLocation());
7641 FunctionDecl *Specialization = nullptr;
7642 ConversionSequenceList Conversions;
7644 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7645 PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7646 ObjectClassification,
7647 [&](ArrayRef<QualType> ParamTypes) {
7648 return CheckNonDependentConversions(
7649 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7650 SuppressUserConversions, ActingContext, ObjectType,
7651 ObjectClassification, PO);
7652 });
7654 OverloadCandidate &Candidate =
7655 CandidateSet.addCandidate(Conversions.size(), Conversions);
7656 Candidate.FoundDecl = FoundDecl;
7657 Candidate.Function = MethodTmpl->getTemplatedDecl();
7658 Candidate.Viable = false;
7659 Candidate.RewriteKind =
7660 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7661 Candidate.IsSurrogate = false;
7662 Candidate.IgnoreObjectArgument =
7663 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7664 ObjectType.isNull();
7665 Candidate.ExplicitCallArguments = Args.size();
7668 else {
7671 Info);
7672 }
7673 return;
7674 }
7675
7676 // Add the function template specialization produced by template argument
7677 // deduction as a candidate.
7678 assert(Specialization && "Missing member function template specialization?");
7679 assert(isa<CXXMethodDecl>(Specialization) &&
7680 "Specialization is not a member function?");
7681 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7682 ActingContext, ObjectType, ObjectClassification, Args,
7683 CandidateSet, SuppressUserConversions, PartialOverloading,
7684 Conversions, PO);
7685}
7686
7687/// Determine whether a given function template has a simple explicit specifier
7688/// or a non-value-dependent explicit-specification that evaluates to true.
7691}
7692
7694 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7695 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7696 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7697 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7698 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7699 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7700 return;
7701
7702 // If the function template has a non-dependent explicit specification,
7703 // exclude it now if appropriate; we are not permitted to perform deduction
7704 // and substitution in this case.
7705 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7706 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7707 Candidate.FoundDecl = FoundDecl;
7708 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7709 Candidate.Viable = false;
7710 Candidate.FailureKind = ovl_fail_explicit;
7711 return;
7712 }
7713
7714 // C++ [over.match.funcs]p7:
7715 // In each case where a candidate is a function template, candidate
7716 // function template specializations are generated using template argument
7717 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7718 // candidate functions in the usual way.113) A given name can refer to one
7719 // or more function templates and also to a set of overloaded non-template
7720 // functions. In such a case, the candidate functions generated from each
7721 // function template are combined with the set of non-template candidate
7722 // functions.
7723 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7724 FunctionTemplate->getTemplateDepth());
7725 FunctionDecl *Specialization = nullptr;
7726 ConversionSequenceList Conversions;
7728 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7729 PartialOverloading, AggregateCandidateDeduction,
7730 /*ObjectType=*/QualType(),
7731 /*ObjectClassification=*/Expr::Classification(),
7732 [&](ArrayRef<QualType> ParamTypes) {
7733 return CheckNonDependentConversions(
7734 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7735 SuppressUserConversions, nullptr, QualType(), {}, PO);
7736 });
7738 OverloadCandidate &Candidate =
7739 CandidateSet.addCandidate(Conversions.size(), Conversions);
7740 Candidate.FoundDecl = FoundDecl;
7741 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7742 Candidate.Viable = false;
7743 Candidate.RewriteKind =
7744 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7745 Candidate.IsSurrogate = false;
7746 Candidate.IsADLCandidate = IsADLCandidate;
7747 // Ignore the object argument if there is one, since we don't have an object
7748 // type.
7749 Candidate.IgnoreObjectArgument =
7750 isa<CXXMethodDecl>(Candidate.Function) &&
7751 !isa<CXXConstructorDecl>(Candidate.Function);
7752 Candidate.ExplicitCallArguments = Args.size();
7755 else {
7758 Info);
7759 }
7760 return;
7761 }
7762
7763 // Add the function template specialization produced by template argument
7764 // deduction as a candidate.
7765 assert(Specialization && "Missing function template specialization?");
7766 AddOverloadCandidate(
7767 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7768 PartialOverloading, AllowExplicit,
7769 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7771}
7772
7774 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7775 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7776 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7777 CXXRecordDecl *ActingContext, QualType ObjectType,
7778 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7779 // FIXME: The cases in which we allow explicit conversions for constructor
7780 // arguments never consider calling a constructor template. It's not clear
7781 // that is correct.
7782 const bool AllowExplicit = false;
7783
7784 auto *FD = FunctionTemplate->getTemplatedDecl();
7785 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7786 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7787 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7788
7789 Conversions =
7790 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7791
7792 // Overload resolution is always an unevaluated context.
7795
7796 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7797 // require that, but this check should never result in a hard error, and
7798 // overload resolution is permitted to sidestep instantiations.
7799 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7800 !ObjectType.isNull()) {
7801 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7802 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7803 !ParamTypes[0]->isDependentType()) {
7804 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7805 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7806 Method, ActingContext, /*InOverloadResolution=*/true,
7807 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7808 : QualType());
7809 if (Conversions[ConvIdx].isBad())
7810 return true;
7811 }
7812 }
7813
7814 unsigned Offset =
7815 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7816
7817 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
7818 I != N; ++I) {
7819 QualType ParamType = ParamTypes[I + Offset];
7820 if (!ParamType->isDependentType()) {
7821 unsigned ConvIdx;
7823 ConvIdx = Args.size() - 1 - I;
7824 assert(Args.size() + ThisConversions == 2 &&
7825 "number of args (including 'this') must be exactly 2 for "
7826 "reversed order");
7827 // For members, there would be only one arg 'Args[0]' whose ConvIdx
7828 // would also be 0. 'this' got ConvIdx = 1 previously.
7829 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7830 } else {
7831 // For members, 'this' got ConvIdx = 0 previously.
7832 ConvIdx = ThisConversions + I;
7833 }
7834 Conversions[ConvIdx]
7835 = TryCopyInitialization(*this, Args[I], ParamType,
7836 SuppressUserConversions,
7837 /*InOverloadResolution=*/true,
7838 /*AllowObjCWritebackConversion=*/
7839 getLangOpts().ObjCAutoRefCount,
7840 AllowExplicit);
7841 if (Conversions[ConvIdx].isBad())
7842 return true;
7843 }
7844 }
7845
7846 return false;
7847}
7848
7849/// Determine whether this is an allowable conversion from the result
7850/// of an explicit conversion operator to the expected type, per C++
7851/// [over.match.conv]p1 and [over.match.ref]p1.
7852///
7853/// \param ConvType The return type of the conversion function.
7854///
7855/// \param ToType The type we are converting to.
7856///
7857/// \param AllowObjCPointerConversion Allow a conversion from one
7858/// Objective-C pointer to another.
7859///
7860/// \returns true if the conversion is allowable, false otherwise.
7862 QualType ConvType, QualType ToType,
7863 bool AllowObjCPointerConversion) {
7864 QualType ToNonRefType = ToType.getNonReferenceType();
7865
7866 // Easy case: the types are the same.
7867 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7868 return true;
7869
7870 // Allow qualification conversions.
7871 bool ObjCLifetimeConversion;
7872 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7873 ObjCLifetimeConversion))
7874 return true;
7875
7876 // If we're not allowed to consider Objective-C pointer conversions,
7877 // we're done.
7878 if (!AllowObjCPointerConversion)
7879 return false;
7880
7881 // Is this an Objective-C pointer conversion?
7882 bool IncompatibleObjC = false;
7883 QualType ConvertedType;
7884 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7885 IncompatibleObjC);
7886}
7887
7889 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7890 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7891 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7892 bool AllowExplicit, bool AllowResultConversion) {
7893 assert(!Conversion->getDescribedFunctionTemplate() &&
7894 "Conversion function templates use AddTemplateConversionCandidate");
7895 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7896 if (!CandidateSet.isNewCandidate(Conversion))
7897 return;
7898
7899 // If the conversion function has an undeduced return type, trigger its
7900 // deduction now.
7901 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7902 if (DeduceReturnType(Conversion, From->getExprLoc()))
7903 return;
7904 ConvType = Conversion->getConversionType().getNonReferenceType();
7905 }
7906
7907 // If we don't allow any conversion of the result type, ignore conversion
7908 // functions that don't convert to exactly (possibly cv-qualified) T.
7909 if (!AllowResultConversion &&
7910 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7911 return;
7912
7913 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7914 // operator is only a candidate if its return type is the target type or
7915 // can be converted to the target type with a qualification conversion.
7916 //
7917 // FIXME: Include such functions in the candidate list and explain why we
7918 // can't select them.
7919 if (Conversion->isExplicit() &&
7920 !isAllowableExplicitConversion(*this, ConvType, ToType,
7921 AllowObjCConversionOnExplicit))
7922 return;
7923
7924 // Overload resolution is always an unevaluated context.
7927
7928 // Add this candidate
7929 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7930 Candidate.FoundDecl = FoundDecl;
7931 Candidate.Function = Conversion;
7933 Candidate.FinalConversion.setFromType(ConvType);
7934 Candidate.FinalConversion.setAllToTypes(ToType);
7935 Candidate.Viable = true;
7936 Candidate.ExplicitCallArguments = 1;
7937
7938 // Explicit functions are not actually candidates at all if we're not
7939 // allowing them in this context, but keep them around so we can point
7940 // to them in diagnostics.
7941 if (!AllowExplicit && Conversion->isExplicit()) {
7942 Candidate.Viable = false;
7943 Candidate.FailureKind = ovl_fail_explicit;
7944 return;
7945 }
7946
7947 // C++ [over.match.funcs]p4:
7948 // For conversion functions, the function is considered to be a member of
7949 // the class of the implicit implied object argument for the purpose of
7950 // defining the type of the implicit object parameter.
7951 //
7952 // Determine the implicit conversion sequence for the implicit
7953 // object parameter.
7954 QualType ObjectType = From->getType();
7955 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
7956 ObjectType = FromPtrType->getPointeeType();
7957 const auto *ConversionContext =
7958 cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
7959
7960 // C++23 [over.best.ics.general]
7961 // However, if the target is [...]
7962 // - the object parameter of a user-defined conversion function
7963 // [...] user-defined conversion sequences are not considered.
7965 *this, CandidateSet.getLocation(), From->getType(),
7966 From->Classify(Context), Conversion, ConversionContext,
7967 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
7968 /*SuppressUserConversion*/ true);
7969
7970 if (Candidate.Conversions[0].isBad()) {
7971 Candidate.Viable = false;
7973 return;
7974 }
7975
7976 if (Conversion->getTrailingRequiresClause()) {
7977 ConstraintSatisfaction Satisfaction;
7978 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7979 !Satisfaction.IsSatisfied) {
7980 Candidate.Viable = false;
7982 return;
7983 }
7984 }
7985
7986 // We won't go through a user-defined type conversion function to convert a
7987 // derived to base as such conversions are given Conversion Rank. They only
7988 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7989 QualType FromCanon
7990 = Context.getCanonicalType(From->getType().getUnqualifiedType());
7991 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7992 if (FromCanon == ToCanon ||
7993 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7994 Candidate.Viable = false;
7996 return;
7997 }
7998
7999 // To determine what the conversion from the result of calling the
8000 // conversion function to the type we're eventually trying to
8001 // convert to (ToType), we need to synthesize a call to the
8002 // conversion function and attempt copy initialization from it. This
8003 // makes sure that we get the right semantics with respect to
8004 // lvalues/rvalues and the type. Fortunately, we can allocate this
8005 // call on the stack and we don't need its arguments to be
8006 // well-formed.
8007 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8008 VK_LValue, From->getBeginLoc());
8010 Context.getPointerType(Conversion->getType()),
8011 CK_FunctionToPointerDecay, &ConversionRef,
8013
8014 QualType ConversionType = Conversion->getConversionType();
8015 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8016 Candidate.Viable = false;
8018 return;
8019 }
8020
8021 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8022
8023 // Note that it is safe to allocate CallExpr on the stack here because
8024 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
8025 // allocator).
8026 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8027
8028 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
8029 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
8030 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
8031
8033 TryCopyInitialization(*this, TheTemporaryCall, ToType,
8034 /*SuppressUserConversions=*/true,
8035 /*InOverloadResolution=*/false,
8036 /*AllowObjCWritebackConversion=*/false);
8037
8038 switch (ICS.getKind()) {
8040 Candidate.FinalConversion = ICS.Standard;
8041
8042 // C++ [over.ics.user]p3:
8043 // If the user-defined conversion is specified by a specialization of a
8044 // conversion function template, the second standard conversion sequence
8045 // shall have exact match rank.
8046 if (Conversion->getPrimaryTemplate() &&
8048 Candidate.Viable = false;
8050 return;
8051 }
8052
8053 // C++0x [dcl.init.ref]p5:
8054 // In the second case, if the reference is an rvalue reference and
8055 // the second standard conversion sequence of the user-defined
8056 // conversion sequence includes an lvalue-to-rvalue conversion, the
8057 // program is ill-formed.
8058 if (ToType->isRValueReferenceType() &&
8060 Candidate.Viable = false;
8062 return;
8063 }
8064 break;
8065
8067 Candidate.Viable = false;
8069 return;
8070
8071 default:
8072 llvm_unreachable(
8073 "Can only end up with a standard conversion sequence or failure");
8074 }
8075
8076 if (EnableIfAttr *FailedAttr =
8077 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8078 Candidate.Viable = false;
8079 Candidate.FailureKind = ovl_fail_enable_if;
8080 Candidate.DeductionFailure.Data = FailedAttr;
8081 return;
8082 }
8083
8084 if (isNonViableMultiVersionOverload(Conversion)) {
8085 Candidate.Viable = false;
8087 }
8088}
8089
8091 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8092 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8093 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8094 bool AllowExplicit, bool AllowResultConversion) {
8095 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8096 "Only conversion function templates permitted here");
8097
8098 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8099 return;
8100
8101 // If the function template has a non-dependent explicit specification,
8102 // exclude it now if appropriate; we are not permitted to perform deduction
8103 // and substitution in this case.
8104 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8105 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8106 Candidate.FoundDecl = FoundDecl;
8107 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8108 Candidate.Viable = false;
8109 Candidate.FailureKind = ovl_fail_explicit;
8110 return;
8111 }
8112
8113 QualType ObjectType = From->getType();
8114 Expr::Classification ObjectClassification = From->Classify(getASTContext());
8115
8116 TemplateDeductionInfo Info(CandidateSet.getLocation());
8119 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8120 Specialization, Info);
8122 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8123 Candidate.FoundDecl = FoundDecl;
8124 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8125 Candidate.Viable = false;
8127 Candidate.ExplicitCallArguments = 1;
8129 Info);
8130 return;
8131 }
8132
8133 // Add the conversion function template specialization produced by
8134 // template argument deduction as a candidate.
8135 assert(Specialization && "Missing function template specialization?");
8136 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
8137 CandidateSet, AllowObjCConversionOnExplicit,
8138 AllowExplicit, AllowResultConversion);
8139}
8140
8142 DeclAccessPair FoundDecl,
8143 CXXRecordDecl *ActingContext,
8144 const FunctionProtoType *Proto,
8145 Expr *Object,
8146 ArrayRef<Expr *> Args,
8147 OverloadCandidateSet& CandidateSet) {
8148 if (!CandidateSet.isNewCandidate(Conversion))
8149 return;
8150
8151 // Overload resolution is always an unevaluated context.
8154
8155 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8156 Candidate.FoundDecl = FoundDecl;
8157 Candidate.Function = nullptr;
8158 Candidate.Surrogate = Conversion;
8159 Candidate.IsSurrogate = true;
8160 Candidate.Viable = true;
8161 Candidate.ExplicitCallArguments = Args.size();
8162
8163 // Determine the implicit conversion sequence for the implicit
8164 // object parameter.
8165 ImplicitConversionSequence ObjectInit;
8166 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8167 ObjectInit = TryCopyInitialization(*this, Object,
8168 Conversion->getParamDecl(0)->getType(),
8169 /*SuppressUserConversions=*/false,
8170 /*InOverloadResolution=*/true, false);
8171 } else {
8173 *this, CandidateSet.getLocation(), Object->getType(),
8174 Object->Classify(Context), Conversion, ActingContext);
8175 }
8176
8177 if (ObjectInit.isBad()) {
8178 Candidate.Viable = false;
8180 Candidate.Conversions[0] = ObjectInit;
8181 return;
8182 }
8183
8184 // The first conversion is actually a user-defined conversion whose
8185 // first conversion is ObjectInit's standard conversion (which is
8186 // effectively a reference binding). Record it as such.
8187 Candidate.Conversions[0].setUserDefined();
8188 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8189 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8190 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8191 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8192 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8193 Candidate.Conversions[0].UserDefined.After
8194 = Candidate.Conversions[0].UserDefined.Before;
8195 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8196
8197 // Find the
8198 unsigned NumParams = Proto->getNumParams();
8199
8200 // (C++ 13.3.2p2): A candidate function having fewer than m
8201 // parameters is viable only if it has an ellipsis in its parameter
8202 // list (8.3.5).
8203 if (Args.size() > NumParams && !Proto->isVariadic()) {
8204 Candidate.Viable = false;
8206 return;
8207 }
8208
8209 // Function types don't have any default arguments, so just check if
8210 // we have enough arguments.
8211 if (Args.size() < NumParams) {
8212 // Not enough arguments.
8213 Candidate.Viable = false;
8215 return;
8216 }
8217
8218 // Determine the implicit conversion sequences for each of the
8219 // arguments.
8220 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8221 if (ArgIdx < NumParams) {
8222 // (C++ 13.3.2p3): for F to be a viable function, there shall
8223 // exist for each argument an implicit conversion sequence
8224 // (13.3.3.1) that converts that argument to the corresponding
8225 // parameter of F.
8226 QualType ParamType = Proto->getParamType(ArgIdx);
8227 Candidate.Conversions[ArgIdx + 1]
8228 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8229 /*SuppressUserConversions=*/false,
8230 /*InOverloadResolution=*/false,
8231 /*AllowObjCWritebackConversion=*/
8232 getLangOpts().ObjCAutoRefCount);
8233 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8234 Candidate.Viable = false;
8236 return;
8237 }
8238 } else {
8239 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8240 // argument for which there is no corresponding parameter is
8241 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8242 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8243 }
8244 }
8245
8246 if (Conversion->getTrailingRequiresClause()) {
8247 ConstraintSatisfaction Satisfaction;
8248 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8249 /*ForOverloadResolution*/ true) ||
8250 !Satisfaction.IsSatisfied) {
8251 Candidate.Viable = false;
8253 return;
8254 }
8255 }
8256
8257 if (EnableIfAttr *FailedAttr =
8258 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8259 Candidate.Viable = false;
8260 Candidate.FailureKind = ovl_fail_enable_if;
8261 Candidate.DeductionFailure.Data = FailedAttr;
8262 return;
8263 }
8264}
8265
8267 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8268 OverloadCandidateSet &CandidateSet,
8269 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8270 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8271 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8272 ArrayRef<Expr *> FunctionArgs = Args;
8273
8274 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8275 FunctionDecl *FD =
8276 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8277
8278 // Don't consider rewritten functions if we're not rewriting.
8279 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8280 continue;
8281
8282 assert(!isa<CXXMethodDecl>(FD) &&
8283 "unqualified operator lookup found a member function");
8284
8285 if (FunTmpl) {
8286 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8287 FunctionArgs, CandidateSet);
8288 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8289 AddTemplateOverloadCandidate(
8290 FunTmpl, F.getPair(), ExplicitTemplateArgs,
8291 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
8292 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
8293 } else {
8294 if (ExplicitTemplateArgs)
8295 continue;
8296 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8297 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8298 AddOverloadCandidate(
8299 FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8300 false, false, true, false, ADLCallKind::NotADL, std::nullopt,
8302 }
8303 }
8304}
8305
8307 SourceLocation OpLoc,
8308 ArrayRef<Expr *> Args,
8309 OverloadCandidateSet &CandidateSet,
8312
8313 // C++ [over.match.oper]p3:
8314 // For a unary operator @ with an operand of a type whose
8315 // cv-unqualified version is T1, and for a binary operator @ with
8316 // a left operand of a type whose cv-unqualified version is T1 and
8317 // a right operand of a type whose cv-unqualified version is T2,
8318 // three sets of candidate functions, designated member
8319 // candidates, non-member candidates and built-in candidates, are
8320 // constructed as follows:
8321 QualType T1 = Args[0]->getType();
8322
8323 // -- If T1 is a complete class type or a class currently being
8324 // defined, the set of member candidates is the result of the
8325 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8326 // the set of member candidates is empty.
8327 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8328 // Complete the type if it can be completed.
8329 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8330 return;
8331 // If the type is neither complete nor being defined, bail out now.
8332 if (!T1Rec->getDecl()->getDefinition())
8333 return;
8334
8335 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8336 LookupQualifiedName(Operators, T1Rec->getDecl());
8337 Operators.suppressAccessDiagnostics();
8338
8339 for (LookupResult::iterator Oper = Operators.begin(),
8340 OperEnd = Operators.end();
8341 Oper != OperEnd; ++Oper) {
8342 if (Oper->getAsFunction() &&
8344 !CandidateSet.getRewriteInfo().shouldAddReversed(
8345 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8346 continue;
8347 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8348 Args[0]->Classify(Context), Args.slice(1),
8349 CandidateSet, /*SuppressUserConversion=*/false, PO);
8350 }
8351 }
8352}
8353
8355 OverloadCandidateSet& CandidateSet,
8356 bool IsAssignmentOperator,
8357 unsigned NumContextualBoolArguments) {
8358 // Overload resolution is always an unevaluated context.
8361
8362 // Add this candidate
8363 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8364 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8365 Candidate.Function = nullptr;
8366 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8367
8368 // Determine the implicit conversion sequences for each of the
8369 // arguments.
8370 Candidate.Viable = true;
8371 Candidate.ExplicitCallArguments = Args.size();
8372 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8373 // C++ [over.match.oper]p4:
8374 // For the built-in assignment operators, conversions of the
8375 // left operand are restricted as follows:
8376 // -- no temporaries are introduced to hold the left operand, and
8377 // -- no user-defined conversions are applied to the left
8378 // operand to achieve a type match with the left-most
8379 // parameter of a built-in candidate.
8380 //
8381 // We block these conversions by turning off user-defined
8382 // conversions, since that is the only way that initialization of
8383 // a reference to a non-class type can occur from something that
8384 // is not of the same type.
8385 if (ArgIdx < NumContextualBoolArguments) {
8386 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8387 "Contextual conversion to bool requires bool type");
8388 Candidate.Conversions[ArgIdx]
8389 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8390 } else {
8391 Candidate.Conversions[ArgIdx]
8392 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8393 ArgIdx == 0 && IsAssignmentOperator,
8394 /*InOverloadResolution=*/false,
8395 /*AllowObjCWritebackConversion=*/
8396 getLangOpts().ObjCAutoRefCount);
8397 }
8398 if (Candidate.Conversions[ArgIdx].isBad()) {
8399 Candidate.Viable = false;
8401 break;
8402 }
8403 }
8404}
8405
8406namespace {
8407
8408/// BuiltinCandidateTypeSet - A set of types that will be used for the
8409/// candidate operator functions for built-in operators (C++
8410/// [over.built]). The types are separated into pointer types and
8411/// enumeration types.
8412class BuiltinCandidateTypeSet {
8413 /// TypeSet - A set of types.
8414 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8415
8416 /// PointerTypes - The set of pointer types that will be used in the
8417 /// built-in candidates.
8418 TypeSet PointerTypes;
8419
8420 /// MemberPointerTypes - The set of member pointer types that will be
8421 /// used in the built-in candidates.
8422 TypeSet MemberPointerTypes;
8423
8424 /// EnumerationTypes - The set of enumeration types that will be
8425 /// used in the built-in candidates.
8426 TypeSet EnumerationTypes;
8427
8428 /// The set of vector types that will be used in the built-in
8429 /// candidates.
8430 TypeSet VectorTypes;
8431
8432 /// The set of matrix types that will be used in the built-in
8433 /// candidates.
8434 TypeSet MatrixTypes;
8435
8436 /// The set of _BitInt types that will be used in the built-in candidates.
8437 TypeSet BitIntTypes;
8438
8439 /// A flag indicating non-record types are viable candidates
8440 bool HasNonRecordTypes;
8441
8442 /// A flag indicating whether either arithmetic or enumeration types
8443 /// were present in the candidate set.
8444 bool HasArithmeticOrEnumeralTypes;
8445
8446 /// A flag indicating whether the nullptr type was present in the
8447 /// candidate set.
8448 bool HasNullPtrType;
8449
8450 /// Sema - The semantic analysis instance where we are building the
8451 /// candidate type set.
8452 Sema &SemaRef;
8453
8454 /// Context - The AST context in which we will build the type sets.
8455 ASTContext &Context;
8456
8457 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8458 const Qualifiers &VisibleQuals);
8459 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8460
8461public:
8462 /// iterator - Iterates through the types that are part of the set.
8463 typedef TypeSet::iterator iterator;
8464
8465 BuiltinCandidateTypeSet(Sema &SemaRef)
8466 : HasNonRecordTypes(false),
8467 HasArithmeticOrEnumeralTypes(false),
8468 HasNullPtrType(false),
8469 SemaRef(SemaRef),
8470 Context(SemaRef.Context) { }
8471
8472 void AddTypesConvertedFrom(QualType Ty,
8474 bool AllowUserConversions,
8475 bool AllowExplicitConversions,
8476 const Qualifiers &VisibleTypeConversionsQuals);
8477
8478 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8479 llvm::iterator_range<iterator> member_pointer_types() {
8480 return MemberPointerTypes;
8481 }
8482 llvm::iterator_range<iterator> enumeration_types() {
8483 return EnumerationTypes;
8484 }
8485 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8486 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8487 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8488
8489 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8490 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8491 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8492 bool hasNullPtrType() const { return HasNullPtrType; }
8493};
8494
8495} // end anonymous namespace
8496
8497/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8498/// the set of pointer types along with any more-qualified variants of
8499/// that type. For example, if @p Ty is "int const *", this routine
8500/// will add "int const *", "int const volatile *", "int const
8501/// restrict *", and "int const volatile restrict *" to the set of
8502/// pointer types. Returns true if the add of @p Ty itself succeeded,
8503/// false otherwise.
8504///
8505/// FIXME: what to do about extended qualifiers?
8506bool
8507BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8508 const Qualifiers &VisibleQuals) {
8509
8510 // Insert this type.
8511 if (!PointerTypes.insert(Ty))
8512 return false;
8513
8514 QualType PointeeTy;
8515 const PointerType *PointerTy = Ty->getAs<PointerType>();
8516 bool buildObjCPtr = false;
8517 if (!PointerTy) {
8519 PointeeTy = PTy->getPointeeType();
8520 buildObjCPtr = true;
8521 } else {
8522 PointeeTy = PointerTy->getPointeeType();
8523 }
8524
8525 // Don't add qualified variants of arrays. For one, they're not allowed
8526 // (the qualifier would sink to the element type), and for another, the
8527 // only overload situation where it matters is subscript or pointer +- int,
8528 // and those shouldn't have qualifier variants anyway.
8529 if (PointeeTy->isArrayType())
8530 return true;
8531
8532 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8533 bool hasVolatile = VisibleQuals.hasVolatile();
8534 bool hasRestrict = VisibleQuals.hasRestrict();
8535
8536 // Iterate through all strict supersets of BaseCVR.
8537 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8538 if ((CVR | BaseCVR) != CVR) continue;
8539 // Skip over volatile if no volatile found anywhere in the types.
8540 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8541
8542 // Skip over restrict if no restrict found anywhere in the types, or if
8543 // the type cannot be restrict-qualified.
8544 if ((CVR & Qualifiers::Restrict) &&
8545 (!hasRestrict ||
8546 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8547 continue;
8548
8549 // Build qualified pointee type.
8550 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8551
8552 // Build qualified pointer type.
8553 QualType QPointerTy;
8554 if (!buildObjCPtr)
8555 QPointerTy = Context.getPointerType(QPointeeTy);
8556 else
8557 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8558
8559 // Insert qualified pointer type.
8560 PointerTypes.insert(QPointerTy);
8561 }
8562
8563 return true;
8564}
8565
8566/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8567/// to the set of pointer types along with any more-qualified variants of
8568/// that type. For example, if @p Ty is "int const *", this routine
8569/// will add "int const *", "int const volatile *", "int const
8570/// restrict *", and "int const volatile restrict *" to the set of
8571/// pointer types. Returns true if the add of @p Ty itself succeeded,
8572/// false otherwise.
8573///
8574/// FIXME: what to do about extended qualifiers?
8575bool
8576BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8577 QualType Ty) {
8578 // Insert this type.
8579 if (!MemberPointerTypes.insert(Ty))
8580 return false;
8581
8582 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8583 assert(PointerTy && "type was not a member pointer type!");
8584
8585 QualType PointeeTy = PointerTy->getPointeeType();
8586 // Don't add qualified variants of arrays. For one, they're not allowed
8587 // (the qualifier would sink to the element type), and for another, the
8588 // only overload situation where it matters is subscript or pointer +- int,
8589 // and those shouldn't have qualifier variants anyway.
8590 if (PointeeTy->isArrayType())
8591 return true;
8592 const Type *ClassTy = PointerTy->getClass();
8593
8594 // Iterate through all strict supersets of the pointee type's CVR
8595 // qualifiers.
8596 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8597 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8598 if ((CVR | BaseCVR) != CVR) continue;
8599
8600 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8601 MemberPointerTypes.insert(
8602 Context.getMemberPointerType(QPointeeTy, ClassTy));
8603 }
8604
8605 return true;
8606}
8607
8608/// AddTypesConvertedFrom - Add each of the types to which the type @p
8609/// Ty can be implicit converted to the given set of @p Types. We're
8610/// primarily interested in pointer types and enumeration types. We also
8611/// take member pointer types, for the conditional operator.
8612/// AllowUserConversions is true if we should look at the conversion
8613/// functions of a class type, and AllowExplicitConversions if we
8614/// should also include the explicit conversion functions of a class
8615/// type.
8616void
8617BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8618 SourceLocation Loc,
8619 bool AllowUserConversions,
8620 bool AllowExplicitConversions,
8621 const Qualifiers &VisibleQuals) {
8622 // Only deal with canonical types.
8623 Ty = Context.getCanonicalType(Ty);
8624
8625 // Look through reference types; they aren't part of the type of an
8626 // expression for the purposes of conversions.
8627 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8628 Ty = RefTy->getPointeeType();
8629
8630 // If we're dealing with an array type, decay to the pointer.
8631 if (Ty->isArrayType())
8632 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8633
8634 // Otherwise, we don't care about qualifiers on the type.
8635 Ty = Ty.getLocalUnqualifiedType();
8636
8637 // Flag if we ever add a non-record type.
8638 const RecordType *TyRec = Ty->getAs<RecordType>();
8639 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8640
8641 // Flag if we encounter an arithmetic type.
8642 HasArithmeticOrEnumeralTypes =
8643 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8644
8645 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8646 PointerTypes.insert(Ty);
8647 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8648 // Insert our type, and its more-qualified variants, into the set
8649 // of types.
8650 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8651 return;
8652 } else if (Ty->isMemberPointerType()) {
8653 // Member pointers are far easier, since the pointee can't be converted.
8654 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8655 return;
8656 } else if (Ty->isEnumeralType()) {
8657 HasArithmeticOrEnumeralTypes = true;
8658 EnumerationTypes.insert(Ty);
8659 } else if (Ty->isBitIntType()) {
8660 HasArithmeticOrEnumeralTypes = true;
8661 BitIntTypes.insert(Ty);
8662 } else if (Ty->isVectorType()) {
8663 // We treat vector types as arithmetic types in many contexts as an
8664 // extension.
8665 HasArithmeticOrEnumeralTypes = true;
8666 VectorTypes.insert(Ty);
8667 } else if (Ty->isMatrixType()) {
8668 // Similar to vector types, we treat vector types as arithmetic types in
8669 // many contexts as an extension.
8670 HasArithmeticOrEnumeralTypes = true;
8671 MatrixTypes.insert(Ty);
8672 } else if (Ty->isNullPtrType()) {
8673 HasNullPtrType = true;
8674 } else if (AllowUserConversions && TyRec) {
8675 // No conversion functions in incomplete types.
8676 if (!SemaRef.isCompleteType(Loc, Ty))
8677 return;
8678
8679 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8680 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8681 if (isa<UsingShadowDecl>(D))
8682 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8683
8684 // Skip conversion function templates; they don't tell us anything
8685 // about which builtin types we can convert to.
8686 if (isa<FunctionTemplateDecl>(D))
8687 continue;
8688
8689 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8690 if (AllowExplicitConversions || !Conv->isExplicit()) {
8691 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8692 VisibleQuals);
8693 }
8694 }
8695 }
8696}
8697/// Helper function for adjusting address spaces for the pointer or reference
8698/// operands of builtin operators depending on the argument.
8700 Expr *Arg) {
8702}
8703
8704/// Helper function for AddBuiltinOperatorCandidates() that adds
8705/// the volatile- and non-volatile-qualified assignment operators for the
8706/// given type to the candidate set.
8708 QualType T,
8709 ArrayRef<Expr *> Args,
8710 OverloadCandidateSet &CandidateSet) {
8711 QualType ParamTypes[2];
8712
8713 // T& operator=(T&, T)
8714 ParamTypes[0] = S.Context.getLValueReferenceType(
8716 ParamTypes[1] = T;
8717 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8718 /*IsAssignmentOperator=*/true);
8719
8721 // volatile T& operator=(volatile T&, T)
8722 ParamTypes[0] = S.Context.getLValueReferenceType(
8724 Args[0]));
8725 ParamTypes[1] = T;
8726 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8727 /*IsAssignmentOperator=*/true);
8728 }
8729}
8730
8731/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8732/// if any, found in visible type conversion functions found in ArgExpr's type.
8733static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8734 Qualifiers VRQuals;
8735 const RecordType *TyRec;
8736 if (const MemberPointerType *RHSMPType =
8737 ArgExpr->getType()->getAs<MemberPointerType>())
8738 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8739 else
8740 TyRec = ArgExpr->getType()->getAs<RecordType>();
8741 if (!TyRec) {
8742 // Just to be safe, assume the worst case.
8743 VRQuals.addVolatile();
8744 VRQuals.addRestrict();
8745 return VRQuals;
8746 }
8747
8748 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8749 if (!ClassDecl->hasDefinition())
8750 return VRQuals;
8751
8752 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8753 if (isa<UsingShadowDecl>(D))
8754 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8755 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8756 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8757 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8758 CanTy = ResTypeRef->getPointeeType();
8759 // Need to go down the pointer/mempointer chain and add qualifiers
8760 // as see them.
8761 bool done = false;
8762 while (!done) {
8763 if (CanTy.isRestrictQualified())
8764 VRQuals.addRestrict();
8765 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8766 CanTy = ResTypePtr->getPointeeType();
8767 else if (const MemberPointerType *ResTypeMPtr =
8768 CanTy->getAs<MemberPointerType>())
8769 CanTy = ResTypeMPtr->getPointeeType();
8770 else
8771 done = true;
8772 if (CanTy.isVolatileQualified())
8773 VRQuals.addVolatile();
8774 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8775 return VRQuals;
8776 }
8777 }
8778 }
8779 return VRQuals;
8780}
8781
8782// Note: We're currently only handling qualifiers that are meaningful for the
8783// LHS of compound assignment overloading.
8785 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8786 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8787 // _Atomic
8788 if (Available.hasAtomic()) {
8789 Available.removeAtomic();
8790 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8791 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8792 return;
8793 }
8794
8795 // volatile
8796 if (Available.hasVolatile()) {
8797 Available.removeVolatile();
8798 assert(!Applied.hasVolatile());
8799 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8800 Callback);
8801 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8802 return;
8803 }
8804
8805 Callback(Applied);
8806}
8807
8809 QualifiersAndAtomic Quals,
8810 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8812 Callback);
8813}
8814
8816 QualifiersAndAtomic Quals,
8817 Sema &S) {
8818 if (Quals.hasAtomic())
8820 if (Quals.hasVolatile())
8823}
8824
8825namespace {
8826
8827/// Helper class to manage the addition of builtin operator overload
8828/// candidates. It provides shared state and utility methods used throughout
8829/// the process, as well as a helper method to add each group of builtin
8830/// operator overloads from the standard to a candidate set.
8831class BuiltinOperatorOverloadBuilder {
8832 // Common instance state available to all overload candidate addition methods.
8833 Sema &S;
8834 ArrayRef<Expr *> Args;
8835 QualifiersAndAtomic VisibleTypeConversionsQuals;
8836 bool HasArithmeticOrEnumeralCandidateType;
8838 OverloadCandidateSet &CandidateSet;
8839
8840 static constexpr int ArithmeticTypesCap = 26;
8842
8843 // Define some indices used to iterate over the arithmetic types in
8844 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8845 // types are that preserved by promotion (C++ [over.built]p2).
8846 unsigned FirstIntegralType,
8847 LastIntegralType;
8848 unsigned FirstPromotedIntegralType,
8849 LastPromotedIntegralType;
8850 unsigned FirstPromotedArithmeticType,
8851 LastPromotedArithmeticType;
8852 unsigned NumArithmeticTypes;
8853
8854 void InitArithmeticTypes() {
8855 // Start of promoted types.
8856 FirstPromotedArithmeticType = 0;
8857 ArithmeticTypes.push_back(S.Context.FloatTy);
8858 ArithmeticTypes.push_back(S.Context.DoubleTy);
8859 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8861 ArithmeticTypes.push_back(S.Context.Float128Ty);
8863 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8864
8865 // Start of integral types.
8866 FirstIntegralType = ArithmeticTypes.size();
8867 FirstPromotedIntegralType = ArithmeticTypes.size();
8868 ArithmeticTypes.push_back(S.Context.IntTy);
8869 ArithmeticTypes.push_back(S.Context.LongTy);
8870 ArithmeticTypes.push_back(S.Context.LongLongTy);
8874 ArithmeticTypes.push_back(S.Context.Int128Ty);
8875 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8876 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8877 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8881 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8882
8883 /// We add candidates for the unique, unqualified _BitInt types present in
8884 /// the candidate type set. The candidate set already handled ensuring the
8885 /// type is unqualified and canonical, but because we're adding from N
8886 /// different sets, we need to do some extra work to unique things. Insert
8887 /// the candidates into a unique set, then move from that set into the list
8888 /// of arithmetic types.
8889 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
8890 llvm::for_each(CandidateTypes, [&BitIntCandidates](
8891 BuiltinCandidateTypeSet &Candidate) {
8892 for (QualType BitTy : Candidate.bitint_types())
8893 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
8894 });
8895 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
8896 LastPromotedIntegralType = ArithmeticTypes.size();
8897 LastPromotedArithmeticType = ArithmeticTypes.size();
8898 // End of promoted types.
8899
8900 ArithmeticTypes.push_back(S.Context.BoolTy);
8901 ArithmeticTypes.push_back(S.Context.CharTy);
8902 ArithmeticTypes.push_back(S.Context.WCharTy);
8903 if (S.Context.getLangOpts().Char8)
8904 ArithmeticTypes.push_back(S.Context.Char8Ty);
8905 ArithmeticTypes.push_back(S.Context.Char16Ty);
8906 ArithmeticTypes.push_back(S.Context.Char32Ty);
8907 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8908 ArithmeticTypes.push_back(S.Context.ShortTy);
8909 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8910 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8911 LastIntegralType = ArithmeticTypes.size();
8912 NumArithmeticTypes = ArithmeticTypes.size();
8913 // End of integral types.
8914 // FIXME: What about complex? What about half?
8915
8916 // We don't know for sure how many bit-precise candidates were involved, so
8917 // we subtract those from the total when testing whether we're under the
8918 // cap or not.
8919 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
8920 ArithmeticTypesCap &&
8921 "Enough inline storage for all arithmetic types.");
8922 }
8923
8924 /// Helper method to factor out the common pattern of adding overloads
8925 /// for '++' and '--' builtin operators.
8926 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8927 bool HasVolatile,
8928 bool HasRestrict) {
8929 QualType ParamTypes[2] = {
8930 S.Context.getLValueReferenceType(CandidateTy),
8931 S.Context.IntTy
8932 };
8933
8934 // Non-volatile version.
8935 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8936
8937 // Use a heuristic to reduce number of builtin candidates in the set:
8938 // add volatile version only if there are conversions to a volatile type.
8939 if (HasVolatile) {
8940 ParamTypes[0] =
8942 S.Context.getVolatileType(CandidateTy));
8943 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8944 }
8945
8946 // Add restrict version only if there are conversions to a restrict type
8947 // and our candidate type is a non-restrict-qualified pointer.
8948 if (HasRestrict && CandidateTy->isAnyPointerType() &&
8949 !CandidateTy.isRestrictQualified()) {
8950 ParamTypes[0]
8953 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8954
8955 if (HasVolatile) {
8956 ParamTypes[0]
8958 S.Context.getCVRQualifiedType(CandidateTy,
8961 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8962 }
8963 }
8964
8965 }
8966
8967 /// Helper to add an overload candidate for a binary builtin with types \p L
8968 /// and \p R.
8969 void AddCandidate(QualType L, QualType R) {
8970 QualType LandR[2] = {L, R};
8971 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8972 }
8973
8974public:
8975 BuiltinOperatorOverloadBuilder(
8976 Sema &S, ArrayRef<Expr *> Args,
8977 QualifiersAndAtomic VisibleTypeConversionsQuals,
8978 bool HasArithmeticOrEnumeralCandidateType,
8980 OverloadCandidateSet &CandidateSet)
8981 : S(S), Args(Args),
8982 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8983 HasArithmeticOrEnumeralCandidateType(
8984 HasArithmeticOrEnumeralCandidateType),
8985 CandidateTypes(CandidateTypes),
8986 CandidateSet(CandidateSet) {
8987
8988 InitArithmeticTypes();
8989 }
8990
8991 // Increment is deprecated for bool since C++17.
8992 //
8993 // C++ [over.built]p3:
8994 //
8995 // For every pair (T, VQ), where T is an arithmetic type other
8996 // than bool, and VQ is either volatile or empty, there exist
8997 // candidate operator functions of the form
8998 //
8999 // VQ T& operator++(VQ T&);
9000 // T operator++(VQ T&, int);
9001 //
9002 // C++ [over.built]p4:
9003 //
9004 // For every pair (T, VQ), where T is an arithmetic type other
9005 // than bool, and VQ is either volatile or empty, there exist
9006 // candidate operator functions of the form
9007 //
9008 // VQ T& operator--(VQ T&);
9009 // T operator--(VQ T&, int);
9010 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9011 if (!HasArithmeticOrEnumeralCandidateType)
9012 return;
9013
9014 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9015 const auto TypeOfT = ArithmeticTypes[Arith];
9016 if (TypeOfT == S.Context.BoolTy) {
9017 if (Op == OO_MinusMinus)
9018 continue;
9019 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9020 continue;
9021 }
9022 addPlusPlusMinusMinusStyleOverloads(
9023 TypeOfT,
9024 VisibleTypeConversionsQuals.hasVolatile(),
9025 VisibleTypeConversionsQuals.hasRestrict());
9026 }
9027 }
9028
9029 // C++ [over.built]p5:
9030 //
9031 // For every pair (T, VQ), where T is a cv-qualified or
9032 // cv-unqualified object type, and VQ is either volatile or
9033 // empty, there exist candidate operator functions of the form
9034 //
9035 // T*VQ& operator++(T*VQ&);
9036 // T*VQ& operator--(T*VQ&);
9037 // T* operator++(T*VQ&, int);
9038 // T* operator--(T*VQ&, int);
9039 void addPlusPlusMinusMinusPointerOverloads() {
9040 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9041 // Skip pointer types that aren't pointers to object types.
9042 if (!PtrTy->getPointeeType()->isObjectType())
9043 continue;
9044
9045 addPlusPlusMinusMinusStyleOverloads(
9046 PtrTy,
9047 (!PtrTy.isVolatileQualified() &&
9048 VisibleTypeConversionsQuals.hasVolatile()),
9049 (!PtrTy.isRestrictQualified() &&
9050 VisibleTypeConversionsQuals.hasRestrict()));
9051 }
9052 }
9053
9054 // C++ [over.built]p6:
9055 // For every cv-qualified or cv-unqualified object type T, there
9056 // exist candidate operator functions of the form
9057 //
9058 // T& operator*(T*);
9059 //
9060 // C++ [over.built]p7:
9061 // For every function type T that does not have cv-qualifiers or a
9062 // ref-qualifier, there exist candidate operator functions of the form
9063 // T& operator*(T*);
9064 void addUnaryStarPointerOverloads() {
9065 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9066 QualType PointeeTy = ParamTy->getPointeeType();
9067 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9068 continue;
9069
9070 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9071 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9072 continue;
9073
9074 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9075 }
9076 }
9077
9078 // C++ [over.built]p9:
9079 // For every promoted arithmetic type T, there exist candidate
9080 // operator functions of the form
9081 //
9082 // T operator+(T);
9083 // T operator-(T);
9084 void addUnaryPlusOrMinusArithmeticOverloads() {
9085 if (!HasArithmeticOrEnumeralCandidateType)
9086 return;
9087
9088 for (unsigned Arith = FirstPromotedArithmeticType;
9089 Arith < LastPromotedArithmeticType; ++Arith) {
9090 QualType ArithTy = ArithmeticTypes[Arith];
9091 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9092 }
9093
9094 // Extension: We also add these operators for vector types.
9095 for (QualType VecTy : CandidateTypes[0].vector_types())
9096 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9097 }
9098
9099 // C++ [over.built]p8:
9100 // For every type T, there exist candidate operator functions of
9101 // the form
9102 //
9103 // T* operator+(T*);
9104 void addUnaryPlusPointerOverloads() {
9105 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9106 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9107 }
9108
9109 // C++ [over.built]p10:
9110 // For every promoted integral type T, there exist candidate
9111 // operator functions of the form
9112 //
9113 // T operator~(T);
9114 void addUnaryTildePromotedIntegralOverloads() {
9115 if (!HasArithmeticOrEnumeralCandidateType)
9116 return;
9117
9118 for (unsigned Int = FirstPromotedIntegralType;
9119 Int < LastPromotedIntegralType; ++Int) {
9120 QualType IntTy = ArithmeticTypes[Int];
9121 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9122 }
9123
9124 // Extension: We also add this operator for vector types.
9125 for (QualType VecTy : CandidateTypes[0].vector_types())
9126 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9127 }
9128
9129 // C++ [over.match.oper]p16:
9130 // For every pointer to member type T or type std::nullptr_t, there
9131 // exist candidate operator functions of the form
9132 //
9133 // bool operator==(T,T);
9134 // bool operator!=(T,T);
9135 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9136 /// Set of (canonical) types that we've already handled.
9138
9139 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9140 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9141 // Don't add the same builtin candidate twice.
9142 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9143 continue;
9144
9145 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9146 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9147 }
9148
9149 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9151 if (AddedTypes.insert(NullPtrTy).second) {
9152 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9153 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9154 }
9155 }
9156 }
9157 }
9158
9159 // C++ [over.built]p15:
9160 //
9161 // For every T, where T is an enumeration type or a pointer type,
9162 // there exist candidate operator functions of the form
9163 //
9164 // bool operator<(T, T);
9165 // bool operator>(T, T);
9166 // bool operator<=(T, T);
9167 // bool operator>=(T, T);
9168 // bool operator==(T, T);
9169 // bool operator!=(T, T);
9170 // R operator<=>(T, T)
9171 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9172 // C++ [over.match.oper]p3:
9173 // [...]the built-in candidates include all of the candidate operator
9174 // functions defined in 13.6 that, compared to the given operator, [...]
9175 // do not have the same parameter-type-list as any non-template non-member
9176 // candidate.
9177 //
9178 // Note that in practice, this only affects enumeration types because there
9179 // aren't any built-in candidates of record type, and a user-defined operator
9180 // must have an operand of record or enumeration type. Also, the only other
9181 // overloaded operator with enumeration arguments, operator=,
9182 // cannot be overloaded for enumeration types, so this is the only place
9183 // where we must suppress candidates like this.
9184 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9185 UserDefinedBinaryOperators;
9186
9187 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9188 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9189 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9190 CEnd = CandidateSet.end();
9191 C != CEnd; ++C) {
9192 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9193 continue;
9194
9195 if (C->Function->isFunctionTemplateSpecialization())
9196 continue;
9197
9198 // We interpret "same parameter-type-list" as applying to the
9199 // "synthesized candidate, with the order of the two parameters
9200 // reversed", not to the original function.
9201 bool Reversed = C->isReversed();
9202 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9203 ->getType()
9204 .getUnqualifiedType();
9205 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9206 ->getType()
9207 .getUnqualifiedType();
9208
9209 // Skip if either parameter isn't of enumeral type.
9210 if (!FirstParamType->isEnumeralType() ||
9211 !SecondParamType->isEnumeralType())
9212 continue;
9213
9214 // Add this operator to the set of known user-defined operators.
9215 UserDefinedBinaryOperators.insert(
9216 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9217 S.Context.getCanonicalType(SecondParamType)));
9218 }
9219 }
9220 }
9221
9222 /// Set of (canonical) types that we've already handled.
9224
9225 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9226 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9227 // Don't add the same builtin candidate twice.
9228 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9229 continue;
9230 if (IsSpaceship && PtrTy->isFunctionPointerType())
9231 continue;
9232
9233 QualType ParamTypes[2] = {PtrTy, PtrTy};
9234 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9235 }
9236 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9237 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9238
9239 // Don't add the same builtin candidate twice, or if a user defined
9240 // candidate exists.
9241 if (!AddedTypes.insert(CanonType).second ||
9242 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9243 CanonType)))
9244 continue;
9245 QualType ParamTypes[2] = {EnumTy, EnumTy};
9246 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9247 }
9248 }
9249 }
9250
9251 // C++ [over.built]p13:
9252 //
9253 // For every cv-qualified or cv-unqualified object type T
9254 // there exist candidate operator functions of the form
9255 //
9256 // T* operator+(T*, ptrdiff_t);
9257 // T& operator[](T*, ptrdiff_t); [BELOW]
9258 // T* operator-(T*, ptrdiff_t);
9259 // T* operator+(ptrdiff_t, T*);
9260 // T& operator[](ptrdiff_t, T*); [BELOW]
9261 //
9262 // C++ [over.built]p14:
9263 //
9264 // For every T, where T is a pointer to object type, there
9265 // exist candidate operator functions of the form
9266 //
9267 // ptrdiff_t operator-(T, T);
9268 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9269 /// Set of (canonical) types that we've already handled.
9271
9272 for (int Arg = 0; Arg < 2; ++Arg) {
9273 QualType AsymmetricParamTypes[2] = {
9276 };
9277 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9278 QualType PointeeTy = PtrTy->getPointeeType();
9279 if (!PointeeTy->isObjectType())
9280 continue;
9281
9282 AsymmetricParamTypes[Arg] = PtrTy;
9283 if (Arg == 0 || Op == OO_Plus) {
9284 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9285 // T* operator+(ptrdiff_t, T*);
9286 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9287 }
9288 if (Op == OO_Minus) {
9289 // ptrdiff_t operator-(T, T);
9290 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9291 continue;
9292
9293 QualType ParamTypes[2] = {PtrTy, PtrTy};
9294 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9295 }
9296 }
9297 }
9298 }
9299
9300 // C++ [over.built]p12:
9301 //
9302 // For every pair of promoted arithmetic types L and R, there
9303 // exist candidate operator functions of the form
9304 //
9305 // LR operator*(L, R);
9306 // LR operator/(L, R);
9307 // LR operator+(L, R);
9308 // LR operator-(L, R);
9309 // bool operator<(L, R);
9310 // bool operator>(L, R);
9311 // bool operator<=(L, R);
9312 // bool operator>=(L, R);
9313 // bool operator==(L, R);
9314 // bool operator!=(L, R);
9315 //
9316 // where LR is the result of the usual arithmetic conversions
9317 // between types L and R.
9318 //
9319 // C++ [over.built]p24:
9320 //
9321 // For every pair of promoted arithmetic types L and R, there exist
9322 // candidate operator functions of the form
9323 //
9324 // LR operator?(bool, L, R);
9325 //
9326 // where LR is the result of the usual arithmetic conversions
9327 // between types L and R.
9328 // Our candidates ignore the first parameter.
9329 void addGenericBinaryArithmeticOverloads() {
9330 if (!HasArithmeticOrEnumeralCandidateType)
9331 return;
9332
9333 for (unsigned Left = FirstPromotedArithmeticType;
9334 Left < LastPromotedArithmeticType; ++Left) {
9335 for (unsigned Right = FirstPromotedArithmeticType;
9336 Right < LastPromotedArithmeticType; ++Right) {
9337 QualType LandR[2] = { ArithmeticTypes[Left],
9338 ArithmeticTypes[Right] };
9339 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9340 }
9341 }
9342
9343 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9344 // conditional operator for vector types.
9345 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9346 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9347 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9348 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9349 }
9350 }
9351
9352 /// Add binary operator overloads for each candidate matrix type M1, M2:
9353 /// * (M1, M1) -> M1
9354 /// * (M1, M1.getElementType()) -> M1
9355 /// * (M2.getElementType(), M2) -> M2
9356 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9357 void addMatrixBinaryArithmeticOverloads() {
9358 if (!HasArithmeticOrEnumeralCandidateType)
9359 return;
9360
9361 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9362 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9363 AddCandidate(M1, M1);
9364 }
9365
9366 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9367 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9368 if (!CandidateTypes[0].containsMatrixType(M2))
9369 AddCandidate(M2, M2);
9370 }
9371 }
9372
9373 // C++2a [over.built]p14:
9374 //
9375 // For every integral type T there exists a candidate operator function
9376 // of the form
9377 //
9378 // std::strong_ordering operator<=>(T, T)
9379 //
9380 // C++2a [over.built]p15:
9381 //
9382 // For every pair of floating-point types L and R, there exists a candidate
9383 // operator function of the form
9384 //
9385 // std::partial_ordering operator<=>(L, R);
9386 //
9387 // FIXME: The current specification for integral types doesn't play nice with
9388 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9389 // comparisons. Under the current spec this can lead to ambiguity during
9390 // overload resolution. For example:
9391 //
9392 // enum A : int {a};
9393 // auto x = (a <=> (long)42);
9394 //
9395 // error: call is ambiguous for arguments 'A' and 'long'.
9396 // note: candidate operator<=>(int, int)
9397 // note: candidate operator<=>(long, long)
9398 //
9399 // To avoid this error, this function deviates from the specification and adds
9400 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9401 // arithmetic types (the same as the generic relational overloads).
9402 //
9403 // For now this function acts as a placeholder.
9404 void addThreeWayArithmeticOverloads() {
9405 addGenericBinaryArithmeticOverloads();
9406 }
9407
9408 // C++ [over.built]p17:
9409 //
9410 // For every pair of promoted integral types L and R, there
9411 // exist candidate operator functions of the form
9412 //
9413 // LR operator%(L, R);
9414 // LR operator&(L, R);
9415 // LR operator^(L, R);
9416 // LR operator|(L, R);
9417 // L operator<<(L, R);
9418 // L operator>>(L, R);
9419 //
9420 // where LR is the result of the usual arithmetic conversions
9421 // between types L and R.
9422 void addBinaryBitwiseArithmeticOverloads() {
9423 if (!HasArithmeticOrEnumeralCandidateType)
9424 return;
9425
9426 for (unsigned Left = FirstPromotedIntegralType;
9427 Left < LastPromotedIntegralType; ++Left) {
9428 for (unsigned Right = FirstPromotedIntegralType;
9429 Right < LastPromotedIntegralType; ++Right) {
9430 QualType LandR[2] = { ArithmeticTypes[Left],
9431 ArithmeticTypes[Right] };
9432 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9433 }
9434 }
9435 }
9436
9437 // C++ [over.built]p20:
9438 //
9439 // For every pair (T, VQ), where T is an enumeration or
9440 // pointer to member type and VQ is either volatile or
9441 // empty, there exist candidate operator functions of the form
9442 //
9443 // VQ T& operator=(VQ T&, T);
9444 void addAssignmentMemberPointerOrEnumeralOverloads() {
9445 /// Set of (canonical) types that we've already handled.
9447
9448 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9449 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9450 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9451 continue;
9452
9453 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9454 }
9455
9456 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9457 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9458 continue;
9459
9460 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9461 }
9462 }
9463 }
9464
9465 // C++ [over.built]p19:
9466 //
9467 // For every pair (T, VQ), where T is any type and VQ is either
9468 // volatile or empty, there exist candidate operator functions
9469 // of the form
9470 //
9471 // T*VQ& operator=(T*VQ&, T*);
9472 //
9473 // C++ [over.built]p21:
9474 //
9475 // For every pair (T, VQ), where T is a cv-qualified or
9476 // cv-unqualified object type and VQ is either volatile or
9477 // empty, there exist candidate operator functions of the form
9478 //
9479 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9480 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9481 void addAssignmentPointerOverloads(bool isEqualOp) {
9482 /// Set of (canonical) types that we've already handled.
9484
9485 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9486 // If this is operator=, keep track of the builtin candidates we added.
9487 if (isEqualOp)
9488 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9489 else if (!PtrTy->getPointeeType()->isObjectType())
9490 continue;
9491
9492 // non-volatile version
9493 QualType ParamTypes[2] = {
9495 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9496 };
9497 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9498 /*IsAssignmentOperator=*/ isEqualOp);
9499
9500 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9501 VisibleTypeConversionsQuals.hasVolatile();
9502 if (NeedVolatile) {
9503 // volatile version
9504 ParamTypes[0] =
9506 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9507 /*IsAssignmentOperator=*/isEqualOp);
9508 }
9509
9510 if (!PtrTy.isRestrictQualified() &&
9511 VisibleTypeConversionsQuals.hasRestrict()) {
9512 // restrict version
9513 ParamTypes[0] =
9515 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9516 /*IsAssignmentOperator=*/isEqualOp);
9517
9518 if (NeedVolatile) {
9519 // volatile restrict version
9520 ParamTypes[0] =
9523 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9524 /*IsAssignmentOperator=*/isEqualOp);
9525 }
9526 }
9527 }
9528
9529 if (isEqualOp) {
9530 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9531 // Make sure we don't add the same candidate twice.
9532 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9533 continue;
9534
9535 QualType ParamTypes[2] = {
9537 PtrTy,
9538 };
9539
9540 // non-volatile version
9541 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9542 /*IsAssignmentOperator=*/true);
9543
9544 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9545 VisibleTypeConversionsQuals.hasVolatile();
9546 if (NeedVolatile) {
9547 // volatile version
9548 ParamTypes[0] = S.Context.getLValueReferenceType(
9549 S.Context.getVolatileType(PtrTy));
9550 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9551 /*IsAssignmentOperator=*/true);
9552 }
9553
9554 if (!PtrTy.isRestrictQualified() &&
9555 VisibleTypeConversionsQuals.hasRestrict()) {
9556 // restrict version
9557 ParamTypes[0] = S.Context.getLValueReferenceType(
9558 S.Context.getRestrictType(PtrTy));
9559 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9560 /*IsAssignmentOperator=*/true);
9561
9562 if (NeedVolatile) {
9563 // volatile restrict version
9564 ParamTypes[0] =
9567 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9568 /*IsAssignmentOperator=*/true);
9569 }
9570 }
9571 }
9572 }
9573 }
9574
9575 // C++ [over.built]p18:
9576 //
9577 // For every triple (L, VQ, R), where L is an arithmetic type,
9578 // VQ is either volatile or empty, and R is a promoted
9579 // arithmetic type, there exist candidate operator functions of
9580 // the form
9581 //
9582 // VQ L& operator=(VQ L&, R);
9583 // VQ L& operator*=(VQ L&, R);
9584 // VQ L& operator/=(VQ L&, R);
9585 // VQ L& operator+=(VQ L&, R);
9586 // VQ L& operator-=(VQ L&, R);
9587 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9588 if (!HasArithmeticOrEnumeralCandidateType)
9589 return;
9590
9591 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9592 for (unsigned Right = FirstPromotedArithmeticType;
9593 Right < LastPromotedArithmeticType; ++Right) {
9594 QualType ParamTypes[2];
9595 ParamTypes[1] = ArithmeticTypes[Right];
9597 S, ArithmeticTypes[Left], Args[0]);
9598
9600 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9601 ParamTypes[0] =
9602 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9603 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9604 /*IsAssignmentOperator=*/isEqualOp);
9605 });
9606 }
9607 }
9608
9609 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9610 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9611 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9612 QualType ParamTypes[2];
9613 ParamTypes[1] = Vec2Ty;
9614 // Add this built-in operator as a candidate (VQ is empty).
9615 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9616 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9617 /*IsAssignmentOperator=*/isEqualOp);
9618
9619 // Add this built-in operator as a candidate (VQ is 'volatile').
9620 if (VisibleTypeConversionsQuals.hasVolatile()) {
9621 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9622 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9623 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9624 /*IsAssignmentOperator=*/isEqualOp);
9625 }
9626 }
9627 }
9628
9629 // C++ [over.built]p22:
9630 //
9631 // For every triple (L, VQ, R), where L is an integral type, VQ
9632 // is either volatile or empty, and R is a promoted integral
9633 // type, there exist candidate operator functions of the form
9634 //
9635 // VQ L& operator%=(VQ L&, R);
9636 // VQ L& operator<<=(VQ L&, R);
9637 // VQ L& operator>>=(VQ L&, R);
9638 // VQ L& operator&=(VQ L&, R);
9639 // VQ L& operator^=(VQ L&, R);
9640 // VQ L& operator|=(VQ L&, R);
9641 void addAssignmentIntegralOverloads() {
9642 if (!HasArithmeticOrEnumeralCandidateType)
9643 return;
9644
9645 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9646 for (unsigned Right = FirstPromotedIntegralType;
9647 Right < LastPromotedIntegralType; ++Right) {
9648 QualType ParamTypes[2];
9649 ParamTypes[1] = ArithmeticTypes[Right];
9651 S, ArithmeticTypes[Left], Args[0]);
9652
9654 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9655 ParamTypes[0] =
9656 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9657 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9658 });
9659 }
9660 }
9661 }
9662
9663 // C++ [over.operator]p23:
9664 //
9665 // There also exist candidate operator functions of the form
9666 //
9667 // bool operator!(bool);
9668 // bool operator&&(bool, bool);
9669 // bool operator||(bool, bool);
9670 void addExclaimOverload() {
9671 QualType ParamTy = S.Context.BoolTy;
9672 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9673 /*IsAssignmentOperator=*/false,
9674 /*NumContextualBoolArguments=*/1);
9675 }
9676 void addAmpAmpOrPipePipeOverload() {
9677 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9678 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9679 /*IsAssignmentOperator=*/false,
9680 /*NumContextualBoolArguments=*/2);
9681 }
9682
9683 // C++ [over.built]p13:
9684 //
9685 // For every cv-qualified or cv-unqualified object type T there
9686 // exist candidate operator functions of the form
9687 //
9688 // T* operator+(T*, ptrdiff_t); [ABOVE]
9689 // T& operator[](T*, ptrdiff_t);
9690 // T* operator-(T*, ptrdiff_t); [ABOVE]
9691 // T* operator+(ptrdiff_t, T*); [ABOVE]
9692 // T& operator[](ptrdiff_t, T*);
9693 void addSubscriptOverloads() {
9694 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9695 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9696 QualType PointeeType = PtrTy->getPointeeType();
9697 if (!PointeeType->isObjectType())
9698 continue;
9699
9700 // T& operator[](T*, ptrdiff_t)
9701 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9702 }
9703
9704 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9705 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9706 QualType PointeeType = PtrTy->getPointeeType();
9707 if (!PointeeType->isObjectType())
9708 continue;
9709
9710 // T& operator[](ptrdiff_t, T*)
9711 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9712 }
9713 }
9714
9715 // C++ [over.built]p11:
9716 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9717 // C1 is the same type as C2 or is a derived class of C2, T is an object
9718 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9719 // there exist candidate operator functions of the form
9720 //
9721 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9722 //
9723 // where CV12 is the union of CV1 and CV2.
9724 void addArrowStarOverloads() {
9725 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9726 QualType C1Ty = PtrTy;
9727 QualType C1;
9729 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9730 if (!isa<RecordType>(C1))
9731 continue;
9732 // heuristic to reduce number of builtin candidates in the set.
9733 // Add volatile/restrict version only if there are conversions to a
9734 // volatile/restrict type.
9735 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9736 continue;
9737 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9738 continue;
9739 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9740 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9741 QualType C2 = QualType(mptr->getClass(), 0);
9742 C2 = C2.getUnqualifiedType();
9743 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9744 break;
9745 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9746 // build CV12 T&
9747 QualType T = mptr->getPointeeType();
9748 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9749 T.isVolatileQualified())
9750 continue;
9751 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9752 T.isRestrictQualified())
9753 continue;
9754 T = Q1.apply(S.Context, T);
9755 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9756 }
9757 }
9758 }
9759
9760 // Note that we don't consider the first argument, since it has been
9761 // contextually converted to bool long ago. The candidates below are
9762 // therefore added as binary.
9763 //
9764 // C++ [over.built]p25:
9765 // For every type T, where T is a pointer, pointer-to-member, or scoped
9766 // enumeration type, there exist candidate operator functions of the form
9767 //
9768 // T operator?(bool, T, T);
9769 //
9770 void addConditionalOperatorOverloads() {
9771 /// Set of (canonical) types that we've already handled.
9773
9774 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9775 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9776 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9777 continue;
9778
9779 QualType ParamTypes[2] = {PtrTy, PtrTy};
9780 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9781 }
9782
9783 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9784 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9785 continue;
9786
9787 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9788 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9789 }
9790
9791 if (S.getLangOpts().CPlusPlus11) {
9792 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9793 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9794 continue;
9795
9796 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9797 continue;
9798
9799 QualType ParamTypes[2] = {EnumTy, EnumTy};
9800 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9801 }
9802 }
9803 }
9804 }
9805};
9806
9807} // end anonymous namespace
9808
9810 SourceLocation OpLoc,
9811 ArrayRef<Expr *> Args,
9812 OverloadCandidateSet &CandidateSet) {
9813 // Find all of the types that the arguments can convert to, but only
9814 // if the operator we're looking at has built-in operator candidates
9815 // that make use of these types. Also record whether we encounter non-record
9816 // candidate types or either arithmetic or enumeral candidate types.
9817 QualifiersAndAtomic VisibleTypeConversionsQuals;
9818 VisibleTypeConversionsQuals.addConst();
9819 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9820 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9821 if (Args[ArgIdx]->getType()->isAtomicType())
9822 VisibleTypeConversionsQuals.addAtomic();
9823 }
9824
9825 bool HasNonRecordCandidateType = false;
9826 bool HasArithmeticOrEnumeralCandidateType = false;
9828 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9829 CandidateTypes.emplace_back(*this);
9830 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9831 OpLoc,
9832 true,
9833 (Op == OO_Exclaim ||
9834 Op == OO_AmpAmp ||
9835 Op == OO_PipePipe),
9836 VisibleTypeConversionsQuals);
9837 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9838 CandidateTypes[ArgIdx].hasNonRecordTypes();
9839 HasArithmeticOrEnumeralCandidateType =
9840 HasArithmeticOrEnumeralCandidateType ||
9841 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9842 }
9843
9844 // Exit early when no non-record types have been added to the candidate set
9845 // for any of the arguments to the operator.
9846 //
9847 // We can't exit early for !, ||, or &&, since there we have always have
9848 // 'bool' overloads.
9849 if (!HasNonRecordCandidateType &&
9850 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9851 return;
9852
9853 // Setup an object to manage the common state for building overloads.
9854 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9855 VisibleTypeConversionsQuals,
9856 HasArithmeticOrEnumeralCandidateType,
9857 CandidateTypes, CandidateSet);
9858
9859 // Dispatch over the operation to add in only those overloads which apply.
9860 switch (Op) {
9861 case OO_None:
9863 llvm_unreachable("Expected an overloaded operator");
9864
9865 case OO_New:
9866 case OO_Delete:
9867 case OO_Array_New:
9868 case OO_Array_Delete:
9869 case OO_Call:
9870 llvm_unreachable(
9871 "Special operators don't use AddBuiltinOperatorCandidates");
9872
9873 case OO_Comma:
9874 case OO_Arrow:
9875 case OO_Coawait:
9876 // C++ [over.match.oper]p3:
9877 // -- For the operator ',', the unary operator '&', the
9878 // operator '->', or the operator 'co_await', the
9879 // built-in candidates set is empty.
9880 break;
9881
9882 case OO_Plus: // '+' is either unary or binary
9883 if (Args.size() == 1)
9884 OpBuilder.addUnaryPlusPointerOverloads();
9885 [[fallthrough]];
9886
9887 case OO_Minus: // '-' is either unary or binary
9888 if (Args.size() == 1) {
9889 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9890 } else {
9891 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9892 OpBuilder.addGenericBinaryArithmeticOverloads();
9893 OpBuilder.addMatrixBinaryArithmeticOverloads();
9894 }
9895 break;
9896
9897 case OO_Star: // '*' is either unary or binary
9898 if (Args.size() == 1)
9899 OpBuilder.addUnaryStarPointerOverloads();
9900 else {
9901 OpBuilder.addGenericBinaryArithmeticOverloads();
9902 OpBuilder.addMatrixBinaryArithmeticOverloads();
9903 }
9904 break;
9905
9906 case OO_Slash:
9907 OpBuilder.addGenericBinaryArithmeticOverloads();
9908 break;
9909
9910 case OO_PlusPlus:
9911 case OO_MinusMinus:
9912 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9913 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9914 break;
9915
9916 case OO_EqualEqual:
9917 case OO_ExclaimEqual:
9918 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9919 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9920 OpBuilder.addGenericBinaryArithmeticOverloads();
9921 break;
9922
9923 case OO_Less:
9924 case OO_Greater:
9925 case OO_LessEqual:
9926 case OO_GreaterEqual:
9927 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9928 OpBuilder.addGenericBinaryArithmeticOverloads();
9929 break;
9930
9931 case OO_Spaceship:
9932 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9933 OpBuilder.addThreeWayArithmeticOverloads();
9934 break;
9935
9936 case OO_Percent:
9937 case OO_Caret:
9938 case OO_Pipe:
9939 case OO_LessLess:
9940 case OO_GreaterGreater:
9941 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9942 break;
9943
9944 case OO_Amp: // '&' is either unary or binary
9945 if (Args.size() == 1)
9946 // C++ [over.match.oper]p3:
9947 // -- For the operator ',', the unary operator '&', or the
9948 // operator '->', the built-in candidates set is empty.
9949 break;
9950
9951 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9952 break;
9953
9954 case OO_Tilde:
9955 OpBuilder.addUnaryTildePromotedIntegralOverloads();
9956 break;
9957
9958 case OO_Equal:
9959 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9960 [[fallthrough]];
9961
9962 case OO_PlusEqual:
9963 case OO_MinusEqual:
9964 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9965 [[fallthrough]];
9966
9967 case OO_StarEqual:
9968 case OO_SlashEqual:
9969 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9970 break;
9971
9972 case OO_PercentEqual:
9973 case OO_LessLessEqual:
9974 case OO_GreaterGreaterEqual:
9975 case OO_AmpEqual:
9976 case OO_CaretEqual:
9977 case OO_PipeEqual:
9978 OpBuilder.addAssignmentIntegralOverloads();
9979 break;
9980
9981 case OO_Exclaim:
9982 OpBuilder.addExclaimOverload();
9983 break;
9984
9985 case OO_AmpAmp:
9986 case OO_PipePipe:
9987 OpBuilder.addAmpAmpOrPipePipeOverload();
9988 break;
9989
9990 case OO_Subscript:
9991 if (Args.size() == 2)
9992 OpBuilder.addSubscriptOverloads();
9993 break;
9994
9995 case OO_ArrowStar:
9996 OpBuilder.addArrowStarOverloads();
9997 break;
9998
9999 case OO_Conditional:
10000 OpBuilder.addConditionalOperatorOverloads();
10001 OpBuilder.addGenericBinaryArithmeticOverloads();
10002 break;
10003 }
10004}
10005
10006void
10008 SourceLocation Loc,
10009 ArrayRef<Expr *> Args,
10010 TemplateArgumentListInfo *ExplicitTemplateArgs,
10011 OverloadCandidateSet& CandidateSet,
10012 bool PartialOverloading) {
10013 ADLResult Fns;
10014
10015 // FIXME: This approach for uniquing ADL results (and removing
10016 // redundant candidates from the set) relies on pointer-equality,
10017 // which means we need to key off the canonical decl. However,
10018 // always going back to the canonical decl might not get us the
10019 // right set of default arguments. What default arguments are
10020 // we supposed to consider on ADL candidates, anyway?
10021
10022 // FIXME: Pass in the explicit template arguments?
10023 ArgumentDependentLookup(Name, Loc, Args, Fns);
10024
10025 // Erase all of the candidates we already knew about.
10026 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10027 CandEnd = CandidateSet.end();
10028 Cand != CandEnd; ++Cand)
10029 if (Cand->Function) {
10030 FunctionDecl *Fn = Cand->Function;
10031 Fns.erase(Fn);
10032 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10033 Fns.erase(FunTmpl);
10034 }
10035
10036 // For each of the ADL candidates we found, add it to the overload
10037 // set.
10038 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10040
10041 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10042 if (ExplicitTemplateArgs)
10043 continue;
10044
10045 AddOverloadCandidate(
10046 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10047 PartialOverloading, /*AllowExplicit=*/true,
10048 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10049 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10050 AddOverloadCandidate(
10051 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10052 /*SuppressUserConversions=*/false, PartialOverloading,
10053 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10054 ADLCallKind::UsesADL, std::nullopt,
10056 }
10057 } else {
10058 auto *FTD = cast<FunctionTemplateDecl>(*I);
10059 AddTemplateOverloadCandidate(
10060 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10061 /*SuppressUserConversions=*/false, PartialOverloading,
10062 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10063 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10064 *this, Args, FTD->getTemplatedDecl())) {
10065 AddTemplateOverloadCandidate(
10066 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
10067 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10068 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10070 }
10071 }
10072 }
10073}
10074
10075namespace {
10076enum class Comparison { Equal, Better, Worse };
10077}
10078
10079/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10080/// overload resolution.
10081///
10082/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10083/// Cand1's first N enable_if attributes have precisely the same conditions as
10084/// Cand2's first N enable_if attributes (where N = the number of enable_if
10085/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10086///
10087/// Note that you can have a pair of candidates such that Cand1's enable_if
10088/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10089/// worse than Cand1's.
10090static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10091 const FunctionDecl *Cand2) {
10092 // Common case: One (or both) decls don't have enable_if attrs.
10093 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10094 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10095 if (!Cand1Attr || !Cand2Attr) {
10096 if (Cand1Attr == Cand2Attr)
10097 return Comparison::Equal;
10098 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10099 }
10100
10101 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10102 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10103
10104 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10105 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10106 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10107 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10108
10109 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10110 // has fewer enable_if attributes than Cand2, and vice versa.
10111 if (!Cand1A)
10112 return Comparison::Worse;
10113 if (!Cand2A)
10114 return Comparison::Better;
10115
10116 Cand1ID.clear();
10117 Cand2ID.clear();
10118
10119 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10120 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10121 if (Cand1ID != Cand2ID)
10122 return Comparison::Worse;
10123 }
10124
10125 return Comparison::Equal;
10126}
10127
10128static Comparison
10130 const OverloadCandidate &Cand2) {
10131 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10132 !Cand2.Function->isMultiVersion())
10133 return Comparison::Equal;
10134
10135 // If both are invalid, they are equal. If one of them is invalid, the other
10136 // is better.
10137 if (Cand1.Function->isInvalidDecl()) {
10138 if (Cand2.Function->isInvalidDecl())
10139 return Comparison::Equal;
10140 return Comparison::Worse;
10141 }
10142 if (Cand2.Function->isInvalidDecl())
10143 return Comparison::Better;
10144
10145 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10146 // cpu_dispatch, else arbitrarily based on the identifiers.
10147 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10148 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10149 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10150 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10151
10152 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10153 return Comparison::Equal;
10154
10155 if (Cand1CPUDisp && !Cand2CPUDisp)
10156 return Comparison::Better;
10157 if (Cand2CPUDisp && !Cand1CPUDisp)
10158 return Comparison::Worse;
10159
10160 if (Cand1CPUSpec && Cand2CPUSpec) {
10161 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10162 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10163 ? Comparison::Better
10164 : Comparison::Worse;
10165
10166 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10167 FirstDiff = std::mismatch(
10168 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10169 Cand2CPUSpec->cpus_begin(),
10170 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10171 return LHS->getName() == RHS->getName();
10172 });
10173
10174 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10175 "Two different cpu-specific versions should not have the same "
10176 "identifier list, otherwise they'd be the same decl!");
10177 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10178 ? Comparison::Better
10179 : Comparison::Worse;
10180 }
10181 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10182}
10183
10184/// Compute the type of the implicit object parameter for the given function,
10185/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10186/// null QualType if there is a 'matches anything' implicit object parameter.
10187static std::optional<QualType>
10189 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10190 return std::nullopt;
10191
10192 auto *M = cast<CXXMethodDecl>(F);
10193 // Static member functions' object parameters match all types.
10194 if (M->isStatic())
10195 return QualType();
10196 return M->getFunctionObjectParameterReferenceType();
10197}
10198
10199// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10200// represent the same entity.
10201static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10202 const FunctionDecl *F2) {
10203 if (declaresSameEntity(F1, F2))
10204 return true;
10205 auto PT1 = F1->getPrimaryTemplate();
10206 auto PT2 = F2->getPrimaryTemplate();
10207 if (PT1 && PT2) {
10208 if (declaresSameEntity(PT1, PT2) ||
10209 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10210 PT2->getInstantiatedFromMemberTemplate()))
10211 return true;
10212 }
10213 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10214 // different functions with same params). Consider removing this (as no test
10215 // fail w/o it).
10216 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10217 if (First) {
10218 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10219 return *T;
10220 }
10221 assert(I < F->getNumParams());
10222 return F->getParamDecl(I++)->getType();
10223 };
10224
10225 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10226 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10227
10228 if (F1NumParams != F2NumParams)
10229 return false;
10230
10231 unsigned I1 = 0, I2 = 0;
10232 for (unsigned I = 0; I != F1NumParams; ++I) {
10233 QualType T1 = NextParam(F1, I1, I == 0);
10234 QualType T2 = NextParam(F2, I2, I == 0);
10235 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10236 if (!Context.hasSameUnqualifiedType(T1, T2))
10237 return false;
10238 }
10239 return true;
10240}
10241
10242/// We're allowed to use constraints partial ordering only if the candidates
10243/// have the same parameter types:
10244/// [over.match.best.general]p2.6
10245/// F1 and F2 are non-template functions with the same
10246/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10248 const OverloadCandidate &Cand1,
10249 const OverloadCandidate &Cand2) {
10250 if (!Cand1.Function || !Cand2.Function)
10251 return false;
10252
10253 FunctionDecl *Fn1 = Cand1.Function;
10254 FunctionDecl *Fn2 = Cand2.Function;
10255
10256 if (Fn1->isVariadic() != Fn2->isVariadic())
10257 return false;
10258
10260 Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed()))
10261 return false;
10262
10263 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10264 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10265 if (Mem1 && Mem2) {
10266 // if they are member functions, both are direct members of the same class,
10267 // and
10268 if (Mem1->getParent() != Mem2->getParent())
10269 return false;
10270 // if both are non-static member functions, they have the same types for
10271 // their object parameters
10272 if (Mem1->isInstance() && Mem2->isInstance() &&
10274 Mem1->getFunctionObjectParameterReferenceType(),
10275 Mem1->getFunctionObjectParameterReferenceType()))
10276 return false;
10277 }
10278 return true;
10279}
10280
10281/// isBetterOverloadCandidate - Determines whether the first overload
10282/// candidate is a better candidate than the second (C++ 13.3.3p1).
10284 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10286 // Define viable functions to be better candidates than non-viable
10287 // functions.
10288 if (!Cand2.Viable)
10289 return Cand1.Viable;
10290 else if (!Cand1.Viable)
10291 return false;
10292
10293 // [CUDA] A function with 'never' preference is marked not viable, therefore
10294 // is never shown up here. The worst preference shown up here is 'wrong side',
10295 // e.g. an H function called by a HD function in device compilation. This is
10296 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10297 // function which is called only by an H function. A deferred diagnostic will
10298 // be triggered if it is emitted. However a wrong-sided function is still
10299 // a viable candidate here.
10300 //
10301 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10302 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10303 // can be emitted, Cand1 is not better than Cand2. This rule should have
10304 // precedence over other rules.
10305 //
10306 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10307 // other rules should be used to determine which is better. This is because
10308 // host/device based overloading resolution is mostly for determining
10309 // viability of a function. If two functions are both viable, other factors
10310 // should take precedence in preference, e.g. the standard-defined preferences
10311 // like argument conversion ranks or enable_if partial-ordering. The
10312 // preference for pass-object-size parameters is probably most similar to a
10313 // type-based-overloading decision and so should take priority.
10314 //
10315 // If other rules cannot determine which is better, CUDA preference will be
10316 // used again to determine which is better.
10317 //
10318 // TODO: Currently IdentifyPreference does not return correct values
10319 // for functions called in global variable initializers due to missing
10320 // correct context about device/host. Therefore we can only enforce this
10321 // rule when there is a caller. We should enforce this rule for functions
10322 // in global variable initializers once proper context is added.
10323 //
10324 // TODO: We can only enable the hostness based overloading resolution when
10325 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10326 // overloading resolution diagnostics.
10327 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10328 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10329 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10330 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10331 bool IsCand1ImplicitHD =
10333 bool IsCand2ImplicitHD =
10335 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10336 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10337 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10338 // The implicit HD function may be a function in a system header which
10339 // is forced by pragma. In device compilation, if we prefer HD candidates
10340 // over wrong-sided candidates, overloading resolution may change, which
10341 // may result in non-deferrable diagnostics. As a workaround, we let
10342 // implicit HD candidates take equal preference as wrong-sided candidates.
10343 // This will preserve the overloading resolution.
10344 // TODO: We still need special handling of implicit HD functions since
10345 // they may incur other diagnostics to be deferred. We should make all
10346 // host/device related diagnostics deferrable and remove special handling
10347 // of implicit HD functions.
10348 auto EmitThreshold =
10349 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10350 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10353 auto Cand1Emittable = P1 > EmitThreshold;
10354 auto Cand2Emittable = P2 > EmitThreshold;
10355 if (Cand1Emittable && !Cand2Emittable)
10356 return true;
10357 if (!Cand1Emittable && Cand2Emittable)
10358 return false;
10359 }
10360 }
10361
10362 // C++ [over.match.best]p1: (Changed in C++23)
10363 //
10364 // -- if F is a static member function, ICS1(F) is defined such
10365 // that ICS1(F) is neither better nor worse than ICS1(G) for
10366 // any function G, and, symmetrically, ICS1(G) is neither
10367 // better nor worse than ICS1(F).
10368 unsigned StartArg = 0;
10369 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10370 StartArg = 1;
10371
10372 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10373 // We don't allow incompatible pointer conversions in C++.
10374 if (!S.getLangOpts().CPlusPlus)
10375 return ICS.isStandard() &&
10376 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10377
10378 // The only ill-formed conversion we allow in C++ is the string literal to
10379 // char* conversion, which is only considered ill-formed after C++11.
10380 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10382 };
10383
10384 // Define functions that don't require ill-formed conversions for a given
10385 // argument to be better candidates than functions that do.
10386 unsigned NumArgs = Cand1.Conversions.size();
10387 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10388 bool HasBetterConversion = false;
10389 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10390 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10391 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10392 if (Cand1Bad != Cand2Bad) {
10393 if (Cand1Bad)
10394 return false;
10395 HasBetterConversion = true;
10396 }
10397 }
10398
10399 if (HasBetterConversion)
10400 return true;
10401
10402 // C++ [over.match.best]p1:
10403 // A viable function F1 is defined to be a better function than another
10404 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10405 // conversion sequence than ICSi(F2), and then...
10406 bool HasWorseConversion = false;
10407 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10409 Cand1.Conversions[ArgIdx],
10410 Cand2.Conversions[ArgIdx])) {
10412 // Cand1 has a better conversion sequence.
10413 HasBetterConversion = true;
10414 break;
10415
10417 if (Cand1.Function && Cand2.Function &&
10418 Cand1.isReversed() != Cand2.isReversed() &&
10419 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10420 // Work around large-scale breakage caused by considering reversed
10421 // forms of operator== in C++20:
10422 //
10423 // When comparing a function against a reversed function, if we have a
10424 // better conversion for one argument and a worse conversion for the
10425 // other, the implicit conversion sequences are treated as being equally
10426 // good.
10427 //
10428 // This prevents a comparison function from being considered ambiguous
10429 // with a reversed form that is written in the same way.
10430 //
10431 // We diagnose this as an extension from CreateOverloadedBinOp.
10432 HasWorseConversion = true;
10433 break;
10434 }
10435
10436 // Cand1 can't be better than Cand2.
10437 return false;
10438
10440 // Do nothing.
10441 break;
10442 }
10443 }
10444
10445 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10446 // ICSj(F2), or, if not that,
10447 if (HasBetterConversion && !HasWorseConversion)
10448 return true;
10449
10450 // -- the context is an initialization by user-defined conversion
10451 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10452 // from the return type of F1 to the destination type (i.e.,
10453 // the type of the entity being initialized) is a better
10454 // conversion sequence than the standard conversion sequence
10455 // from the return type of F2 to the destination type.
10457 Cand1.Function && Cand2.Function &&
10458 isa<CXXConversionDecl>(Cand1.Function) &&
10459 isa<CXXConversionDecl>(Cand2.Function)) {
10460 // First check whether we prefer one of the conversion functions over the
10461 // other. This only distinguishes the results in non-standard, extension
10462 // cases such as the conversion from a lambda closure type to a function
10463 // pointer or block.
10468 Cand1.FinalConversion,
10469 Cand2.FinalConversion);
10470
10473
10474 // FIXME: Compare kind of reference binding if conversion functions
10475 // convert to a reference type used in direct reference binding, per
10476 // C++14 [over.match.best]p1 section 2 bullet 3.
10477 }
10478
10479 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10480 // as combined with the resolution to CWG issue 243.
10481 //
10482 // When the context is initialization by constructor ([over.match.ctor] or
10483 // either phase of [over.match.list]), a constructor is preferred over
10484 // a conversion function.
10485 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10486 Cand1.Function && Cand2.Function &&
10487 isa<CXXConstructorDecl>(Cand1.Function) !=
10488 isa<CXXConstructorDecl>(Cand2.Function))
10489 return isa<CXXConstructorDecl>(Cand1.Function);
10490
10491 // -- F1 is a non-template function and F2 is a function template
10492 // specialization, or, if not that,
10493 bool Cand1IsSpecialization = Cand1.Function &&
10495 bool Cand2IsSpecialization = Cand2.Function &&
10497 if (Cand1IsSpecialization != Cand2IsSpecialization)
10498 return Cand2IsSpecialization;
10499
10500 // -- F1 and F2 are function template specializations, and the function
10501 // template for F1 is more specialized than the template for F2
10502 // according to the partial ordering rules described in 14.5.5.2, or,
10503 // if not that,
10504 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10505 const auto *Obj1Context =
10506 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10507 const auto *Obj2Context =
10508 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10509 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10512 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10513 : TPOC_Call,
10515 Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10516 : QualType{},
10517 Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10518 : QualType{},
10519 Cand1.isReversed() ^ Cand2.isReversed())) {
10520 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10521 }
10522 }
10523
10524 // -— F1 and F2 are non-template functions with the same
10525 // parameter-type-lists, and F1 is more constrained than F2 [...],
10526 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10527 sameFunctionParameterTypeLists(S, Cand1, Cand2) &&
10529 Cand1.Function)
10530 return true;
10531
10532 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10533 // class B of D, and for all arguments the corresponding parameters of
10534 // F1 and F2 have the same type.
10535 // FIXME: Implement the "all parameters have the same type" check.
10536 bool Cand1IsInherited =
10537 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10538 bool Cand2IsInherited =
10539 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10540 if (Cand1IsInherited != Cand2IsInherited)
10541 return Cand2IsInherited;
10542 else if (Cand1IsInherited) {
10543 assert(Cand2IsInherited);
10544 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10545 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10546 if (Cand1Class->isDerivedFrom(Cand2Class))
10547 return true;
10548 if (Cand2Class->isDerivedFrom(Cand1Class))
10549 return false;
10550 // Inherited from sibling base classes: still ambiguous.
10551 }
10552
10553 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10554 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10555 // with reversed order of parameters and F1 is not
10556 //
10557 // We rank reversed + different operator as worse than just reversed, but
10558 // that comparison can never happen, because we only consider reversing for
10559 // the maximally-rewritten operator (== or <=>).
10560 if (Cand1.RewriteKind != Cand2.RewriteKind)
10561 return Cand1.RewriteKind < Cand2.RewriteKind;
10562
10563 // Check C++17 tie-breakers for deduction guides.
10564 {
10565 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10566 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10567 if (Guide1 && Guide2) {
10568 // -- F1 is generated from a deduction-guide and F2 is not
10569 if (Guide1->isImplicit() != Guide2->isImplicit())
10570 return Guide2->isImplicit();
10571
10572 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10573 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10574 return true;
10575 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10576 return false;
10577
10578 // --F1 is generated from a non-template constructor and F2 is generated
10579 // from a constructor template
10580 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10581 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10582 if (Constructor1 && Constructor2) {
10583 bool isC1Templated = Constructor1->getTemplatedKind() !=
10585 bool isC2Templated = Constructor2->getTemplatedKind() !=
10587 if (isC1Templated != isC2Templated)
10588 return isC2Templated;
10589 }
10590 }
10591 }
10592
10593 // Check for enable_if value-based overload resolution.
10594 if (Cand1.Function && Cand2.Function) {
10595 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10596 if (Cmp != Comparison::Equal)
10597 return Cmp == Comparison::Better;
10598 }
10599
10600 bool HasPS1 = Cand1.Function != nullptr &&
10602 bool HasPS2 = Cand2.Function != nullptr &&
10604 if (HasPS1 != HasPS2 && HasPS1)
10605 return true;
10606
10607 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10608 if (MV == Comparison::Better)
10609 return true;
10610 if (MV == Comparison::Worse)
10611 return false;
10612
10613 // If other rules cannot determine which is better, CUDA preference is used
10614 // to determine which is better.
10615 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10616 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10617 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
10618 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10619 }
10620
10621 // General member function overloading is handled above, so this only handles
10622 // constructors with address spaces.
10623 // This only handles address spaces since C++ has no other
10624 // qualifier that can be used with constructors.
10625 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10626 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10627 if (CD1 && CD2) {
10628 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10629 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10630 if (AS1 != AS2) {
10632 return true;
10634 return false;
10635 }
10636 }
10637
10638 return false;
10639}
10640
10641/// Determine whether two declarations are "equivalent" for the purposes of
10642/// name lookup and overload resolution. This applies when the same internal/no
10643/// linkage entity is defined by two modules (probably by textually including
10644/// the same header). In such a case, we don't consider the declarations to
10645/// declare the same entity, but we also don't want lookups with both
10646/// declarations visible to be ambiguous in some cases (this happens when using
10647/// a modularized libstdc++).
10649 const NamedDecl *B) {
10650 auto *VA = dyn_cast_or_null<ValueDecl>(A);
10651 auto *VB = dyn_cast_or_null<ValueDecl>(B);
10652 if (!VA || !VB)
10653 return false;
10654
10655 // The declarations must be declaring the same name as an internal linkage
10656 // entity in different modules.
10657 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10658 VB->getDeclContext()->getRedeclContext()) ||
10659 getOwningModule(VA) == getOwningModule(VB) ||
10660 VA->isExternallyVisible() || VB->isExternallyVisible())
10661 return false;
10662
10663 // Check that the declarations appear to be equivalent.
10664 //
10665 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10666 // For constants and functions, we should check the initializer or body is
10667 // the same. For non-constant variables, we shouldn't allow it at all.
10668 if (Context.hasSameType(VA->getType(), VB->getType()))
10669 return true;
10670
10671 // Enum constants within unnamed enumerations will have different types, but
10672 // may still be similar enough to be interchangeable for our purposes.
10673 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10674 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10675 // Only handle anonymous enums. If the enumerations were named and
10676 // equivalent, they would have been merged to the same type.
10677 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10678 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10679 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10680 !Context.hasSameType(EnumA->getIntegerType(),
10681 EnumB->getIntegerType()))
10682 return false;
10683 // Allow this only if the value is the same for both enumerators.
10684 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10685 }
10686 }
10687
10688 // Nothing else is sufficiently similar.
10689 return false;
10690}
10691
10694 assert(D && "Unknown declaration");
10695 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10696
10697 Module *M = getOwningModule(D);
10698 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10699 << !M << (M ? M->getFullModuleName() : "");
10700
10701 for (auto *E : Equiv) {
10702 Module *M = getOwningModule(E);
10703 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10704 << !M << (M ? M->getFullModuleName() : "");
10705 }
10706}
10707
10709 return FailureKind == ovl_fail_bad_deduction &&
10710 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
10712 static_cast<CNSInfo *>(DeductionFailure.Data)
10713 ->Satisfaction.ContainsErrors;
10714}
10715
10716/// Computes the best viable function (C++ 13.3.3)
10717/// within an overload candidate set.
10718///
10719/// \param Loc The location of the function name (or operator symbol) for
10720/// which overload resolution occurs.
10721///
10722/// \param Best If overload resolution was successful or found a deleted
10723/// function, \p Best points to the candidate function found.
10724///
10725/// \returns The result of overload resolution.
10728 iterator &Best) {
10730 std::transform(begin(), end(), std::back_inserter(Candidates),
10731 [](OverloadCandidate &Cand) { return &Cand; });
10732
10733 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10734 // are accepted by both clang and NVCC. However, during a particular
10735 // compilation mode only one call variant is viable. We need to
10736 // exclude non-viable overload candidates from consideration based
10737 // only on their host/device attributes. Specifically, if one
10738 // candidate call is WrongSide and the other is SameSide, we ignore
10739 // the WrongSide candidate.
10740 // We only need to remove wrong-sided candidates here if
10741 // -fgpu-exclude-wrong-side-overloads is off. When
10742 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10743 // uniformly in isBetterOverloadCandidate.
10744 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10745 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10746 bool ContainsSameSideCandidate =
10747 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10748 // Check viable function only.
10749 return Cand->Viable && Cand->Function &&
10750 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10752 });
10753 if (ContainsSameSideCandidate) {
10754 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10755 // Check viable function only to avoid unnecessary data copying/moving.
10756 return Cand->Viable && Cand->Function &&
10757 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10759 };
10760 llvm::erase_if(Candidates, IsWrongSideCandidate);
10761 }
10762 }
10763
10764 // Find the best viable function.
10765 Best = end();
10766 for (auto *Cand : Candidates) {
10767 Cand->Best = false;
10768 if (Cand->Viable) {
10769 if (Best == end() ||
10770 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10771 Best = Cand;
10772 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10773 // This candidate has constraint that we were unable to evaluate because
10774 // it referenced an expression that contained an error. Rather than fall
10775 // back onto a potentially unintended candidate (made worse by
10776 // subsuming constraints), treat this as 'no viable candidate'.
10777 Best = end();
10778 return OR_No_Viable_Function;
10779 }
10780 }
10781
10782 // If we didn't find any viable functions, abort.
10783 if (Best == end())
10784 return OR_No_Viable_Function;
10785
10787
10789 PendingBest.push_back(&*Best);
10790 Best->Best = true;
10791
10792 // Make sure that this function is better than every other viable
10793 // function. If not, we have an ambiguity.
10794 while (!PendingBest.empty()) {
10795 auto *Curr = PendingBest.pop_back_val();
10796 for (auto *Cand : Candidates) {
10797 if (Cand->Viable && !Cand->Best &&
10798 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10799 PendingBest.push_back(Cand);
10800 Cand->Best = true;
10801
10803 Curr->Function))
10804 EquivalentCands.push_back(Cand->Function);
10805 else
10806 Best = end();
10807 }
10808 }
10809 }
10810
10811 // If we found more than one best candidate, this is ambiguous.
10812 if (Best == end())
10813 return OR_Ambiguous;
10814
10815 // Best is the best viable function.
10816 if (Best->Function && Best->Function->isDeleted())
10817 return OR_Deleted;
10818
10819 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
10820 Kind == CSK_AddressOfOverloadSet && M &&
10821 M->isImplicitObjectMemberFunction()) {
10822 return OR_No_Viable_Function;
10823 }
10824
10825 if (!EquivalentCands.empty())
10827 EquivalentCands);
10828
10829 return OR_Success;
10830}
10831
10832namespace {
10833
10834enum OverloadCandidateKind {
10835 oc_function,
10836 oc_method,
10837 oc_reversed_binary_operator,
10838 oc_constructor,
10839 oc_implicit_default_constructor,
10840 oc_implicit_copy_constructor,
10841 oc_implicit_move_constructor,
10842 oc_implicit_copy_assignment,
10843 oc_implicit_move_assignment,
10844 oc_implicit_equality_comparison,
10845 oc_inherited_constructor
10846};
10847
10848enum OverloadCandidateSelect {
10849 ocs_non_template,
10850 ocs_template,
10851 ocs_described_template,
10852};
10853
10854static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10855ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10856 const FunctionDecl *Fn,
10858 std::string &Description) {
10859
10860 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10861 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10862 isTemplate = true;
10863 Description = S.getTemplateArgumentBindingsText(
10864 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10865 }
10866
10867 OverloadCandidateSelect Select = [&]() {
10868 if (!Description.empty())
10869 return ocs_described_template;
10870 return isTemplate ? ocs_template : ocs_non_template;
10871 }();
10872
10873 OverloadCandidateKind Kind = [&]() {
10874 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10875 return oc_implicit_equality_comparison;
10876
10877 if (CRK & CRK_Reversed)
10878 return oc_reversed_binary_operator;
10879
10880 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10881 if (!Ctor->isImplicit()) {
10882 if (isa<ConstructorUsingShadowDecl>(Found))
10883 return oc_inherited_constructor;
10884 else
10885 return oc_constructor;
10886 }
10887
10888 if (Ctor->isDefaultConstructor())
10889 return oc_implicit_default_constructor;
10890
10891 if (Ctor->isMoveConstructor())
10892 return oc_implicit_move_constructor;
10893
10894 assert(Ctor->isCopyConstructor() &&
10895 "unexpected sort of implicit constructor");
10896 return oc_implicit_copy_constructor;
10897 }
10898
10899 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10900 // This actually gets spelled 'candidate function' for now, but
10901 // it doesn't hurt to split it out.
10902 if (!Meth->isImplicit())
10903 return oc_method;
10904
10905 if (Meth->isMoveAssignmentOperator())
10906 return oc_implicit_move_assignment;
10907
10908 if (Meth->isCopyAssignmentOperator())
10909 return oc_implicit_copy_assignment;
10910
10911 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10912 return oc_method;
10913 }
10914
10915 return oc_function;
10916 }();
10917
10918 return std::make_pair(Kind, Select);
10919}
10920
10921void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
10922 // FIXME: It'd be nice to only emit a note once per using-decl per overload
10923 // set.
10924 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10925 S.Diag(FoundDecl->getLocation(),
10926 diag::note_ovl_candidate_inherited_constructor)
10927 << Shadow->getNominatedBaseClass();
10928}
10929
10930} // end anonymous namespace
10931
10933 const FunctionDecl *FD) {
10934 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10935 bool AlwaysTrue;
10936 if (EnableIf->getCond()->isValueDependent() ||
10937 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10938 return false;
10939 if (!AlwaysTrue)
10940 return false;
10941 }
10942 return true;
10943}
10944
10945/// Returns true if we can take the address of the function.
10946///
10947/// \param Complain - If true, we'll emit a diagnostic
10948/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10949/// we in overload resolution?
10950/// \param Loc - The location of the statement we're complaining about. Ignored
10951/// if we're not complaining, or if we're in overload resolution.
10953 bool Complain,
10954 bool InOverloadResolution,
10955 SourceLocation Loc) {
10956 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10957 if (Complain) {
10958 if (InOverloadResolution)
10959 S.Diag(FD->getBeginLoc(),
10960 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10961 else
10962 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10963 }
10964 return false;
10965 }
10966
10967 if (FD->getTrailingRequiresClause()) {
10968 ConstraintSatisfaction Satisfaction;
10969 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10970 return false;
10971 if (!Satisfaction.IsSatisfied) {
10972 if (Complain) {
10973 if (InOverloadResolution) {
10974 SmallString<128> TemplateArgString;
10975 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
10976 TemplateArgString += " ";
10977 TemplateArgString += S.getTemplateArgumentBindingsText(
10978 FunTmpl->getTemplateParameters(),
10980 }
10981
10982 S.Diag(FD->getBeginLoc(),
10983 diag::note_ovl_candidate_unsatisfied_constraints)
10984 << TemplateArgString;
10985 } else
10986 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10987 << FD;
10988 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10989 }
10990 return false;
10991 }
10992 }
10993
10994 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10995 return P->hasAttr<PassObjectSizeAttr>();
10996 });
10997 if (I == FD->param_end())
10998 return true;
10999
11000 if (Complain) {
11001 // Add one to ParamNo because it's user-facing
11002 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11003 if (InOverloadResolution)
11004 S.Diag(FD->getLocation(),
11005 diag::note_ovl_candidate_has_pass_object_size_params)
11006 << ParamNo;
11007 else
11008 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11009 << FD << ParamNo;
11010 }
11011 return false;
11012}
11013
11015 const FunctionDecl *FD) {
11016 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11017 /*InOverloadResolution=*/true,
11018 /*Loc=*/SourceLocation());
11019}
11020
11022 bool Complain,
11023 SourceLocation Loc) {
11024 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11025 /*InOverloadResolution=*/false,
11026 Loc);
11027}
11028
11029// Don't print candidates other than the one that matches the calling
11030// convention of the call operator, since that is guaranteed to exist.
11032 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11033
11034 if (!ConvD)
11035 return false;
11036 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11037 if (!RD->isLambda())
11038 return false;
11039
11040 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11041 CallingConv CallOpCC =
11042 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11043 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11044 CallingConv ConvToCC =
11045 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11046
11047 return ConvToCC != CallOpCC;
11048}
11049
11050// Notes the location of an overload candidate.
11052 OverloadCandidateRewriteKind RewriteKind,
11053 QualType DestType, bool TakingAddress) {
11054 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11055 return;
11056 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11057 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11058 return;
11059 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11060 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11061 return;
11063 return;
11064
11065 std::string FnDesc;
11066 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11067 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11068 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11069 << (unsigned)KSPair.first << (unsigned)KSPair.second
11070 << Fn << FnDesc;
11071
11072 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11073 Diag(Fn->getLocation(), PD);
11074 MaybeEmitInheritedConstructorNote(*this, Found);
11075}
11076
11077static void
11079 // Perhaps the ambiguity was caused by two atomic constraints that are
11080 // 'identical' but not equivalent:
11081 //
11082 // void foo() requires (sizeof(T) > 4) { } // #1
11083 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11084 //
11085 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11086 // #2 to subsume #1, but these constraint are not considered equivalent
11087 // according to the subsumption rules because they are not the same
11088 // source-level construct. This behavior is quite confusing and we should try
11089 // to help the user figure out what happened.
11090
11091 SmallVector<const Expr *, 3> FirstAC, SecondAC;
11092 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11093 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11094 if (!I->Function)
11095 continue;
11097 if (auto *Template = I->Function->getPrimaryTemplate())
11098 Template->getAssociatedConstraints(AC);
11099 else
11100 I->Function->getAssociatedConstraints(AC);
11101 if (AC.empty())
11102 continue;
11103 if (FirstCand == nullptr) {
11104 FirstCand = I->Function;
11105 FirstAC = AC;
11106 } else if (SecondCand == nullptr) {
11107 SecondCand = I->Function;
11108 SecondAC = AC;
11109 } else {
11110 // We have more than one pair of constrained functions - this check is
11111 // expensive and we'd rather not try to diagnose it.
11112 return;
11113 }
11114 }
11115 if (!SecondCand)
11116 return;
11117 // The diagnostic can only happen if there are associated constraints on
11118 // both sides (there needs to be some identical atomic constraint).
11119 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11120 SecondCand, SecondAC))
11121 // Just show the user one diagnostic, they'll probably figure it out
11122 // from here.
11123 return;
11124}
11125
11126// Notes the location of all overload candidates designated through
11127// OverloadedExpr
11128void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11129 bool TakingAddress) {
11130 assert(OverloadedExpr->getType() == Context.OverloadTy);
11131
11132 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11133 OverloadExpr *OvlExpr = Ovl.Expression;
11134
11135 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11136 IEnd = OvlExpr->decls_end();
11137 I != IEnd; ++I) {
11138 if (FunctionTemplateDecl *FunTmpl =
11139 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11140 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11141 TakingAddress);
11142 } else if (FunctionDecl *Fun
11143 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11144 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11145 }
11146 }
11147}
11148
11149/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11150/// "lead" diagnostic; it will be given two arguments, the source and
11151/// target types of the conversion.
11153 Sema &S,
11154 SourceLocation CaretLoc,
11155 const PartialDiagnostic &PDiag) const {
11156 S.Diag(CaretLoc, PDiag)
11157 << Ambiguous.getFromType() << Ambiguous.getToType();
11158 unsigned CandsShown = 0;
11160 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11161 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11162 break;
11163 ++CandsShown;
11164 S.NoteOverloadCandidate(I->first, I->second);
11165 }
11166 S.Diags.overloadCandidatesShown(CandsShown);
11167 if (I != E)
11168 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11169}
11170
11172 unsigned I, bool TakingCandidateAddress) {
11173 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11174 assert(Conv.isBad());
11175 assert(Cand->Function && "for now, candidate must be a function");
11176 FunctionDecl *Fn = Cand->Function;
11177
11178 // There's a conversion slot for the object argument if this is a
11179 // non-constructor method. Note that 'I' corresponds the
11180 // conversion-slot index.
11181 bool isObjectArgument = false;
11182 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
11183 if (I == 0)
11184 isObjectArgument = true;
11185 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11186 I--;
11187 }
11188
11189 std::string FnDesc;
11190 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11191 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11192 FnDesc);
11193
11194 Expr *FromExpr = Conv.Bad.FromExpr;
11195 QualType FromTy = Conv.Bad.getFromType();
11196 QualType ToTy = Conv.Bad.getToType();
11197 SourceRange ToParamRange;
11198
11199 // FIXME: In presence of parameter packs we can't determine parameter range
11200 // reliably, as we don't have access to instantiation.
11201 bool HasParamPack =
11202 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11203 return Parm->isParameterPack();
11204 });
11205 if (!isObjectArgument && !HasParamPack)
11206 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11207
11208 if (FromTy == S.Context.OverloadTy) {
11209 assert(FromExpr && "overload set argument came from implicit argument?");
11210 Expr *E = FromExpr->IgnoreParens();
11211 if (isa<UnaryOperator>(E))
11212 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11213 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11214
11215 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11216 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11217 << ToParamRange << ToTy << Name << I + 1;
11218 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11219 return;
11220 }
11221
11222 // Do some hand-waving analysis to see if the non-viability is due
11223 // to a qualifier mismatch.
11224 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11225 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11226 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11227 CToTy = RT->getPointeeType();
11228 else {
11229 // TODO: detect and diagnose the full richness of const mismatches.
11230 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11231 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11232 CFromTy = FromPT->getPointeeType();
11233 CToTy = ToPT->getPointeeType();
11234 }
11235 }
11236
11237 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11238 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
11239 Qualifiers FromQs = CFromTy.getQualifiers();
11240 Qualifiers ToQs = CToTy.getQualifiers();
11241
11242 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11243 if (isObjectArgument)
11244 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11245 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11246 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11247 else
11248 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11249 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11250 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11251 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11252 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11253 return;
11254 }
11255
11256 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11257 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11258 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11259 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11260 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11261 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11262 return;
11263 }
11264
11265 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11266 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11267 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11268 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11269 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11270 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11271 return;
11272 }
11273
11274 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11275 assert(CVR && "expected qualifiers mismatch");
11276
11277 if (isObjectArgument) {
11278 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11279 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11280 << FromTy << (CVR - 1);
11281 } else {
11282 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11283 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11284 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11285 }
11286 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11287 return;
11288 }
11289
11292 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11293 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11294 << (unsigned)isObjectArgument << I + 1
11296 << ToParamRange;
11297 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11298 return;
11299 }
11300
11301 // Special diagnostic for failure to convert an initializer list, since
11302 // telling the user that it has type void is not useful.
11303 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11304 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11305 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11306 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11309 ? 2
11310 : 0);
11311 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11312 return;
11313 }
11314
11315 // Diagnose references or pointers to incomplete types differently,
11316 // since it's far from impossible that the incompleteness triggered
11317 // the failure.
11318 QualType TempFromTy = FromTy.getNonReferenceType();
11319 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11320 TempFromTy = PTy->getPointeeType();
11321 if (TempFromTy->isIncompleteType()) {
11322 // Emit the generic diagnostic and, optionally, add the hints to it.
11323 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11324 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11325 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11326 << (unsigned)(Cand->Fix.Kind);
11327
11328 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11329 return;
11330 }
11331
11332 // Diagnose base -> derived pointer conversions.
11333 unsigned BaseToDerivedConversion = 0;
11334 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11335 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11336 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11337 FromPtrTy->getPointeeType()) &&
11338 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11339 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11340 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11341 FromPtrTy->getPointeeType()))
11342 BaseToDerivedConversion = 1;
11343 }
11344 } else if (const ObjCObjectPointerType *FromPtrTy
11345 = FromTy->getAs<ObjCObjectPointerType>()) {
11346 if (const ObjCObjectPointerType *ToPtrTy
11347 = ToTy->getAs<ObjCObjectPointerType>())
11348 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11349 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11350 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11351 FromPtrTy->getPointeeType()) &&
11352 FromIface->isSuperClassOf(ToIface))
11353 BaseToDerivedConversion = 2;
11354 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11355 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
11356 !FromTy->isIncompleteType() &&
11357 !ToRefTy->getPointeeType()->isIncompleteType() &&
11358 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11359 BaseToDerivedConversion = 3;
11360 }
11361 }
11362
11363 if (BaseToDerivedConversion) {
11364 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11365 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11366 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11367 << I + 1;
11368 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11369 return;
11370 }
11371
11372 if (isa<ObjCObjectPointerType>(CFromTy) &&
11373 isa<PointerType>(CToTy)) {
11374 Qualifiers FromQs = CFromTy.getQualifiers();
11375 Qualifiers ToQs = CToTy.getQualifiers();
11376 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11377 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11378 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11379 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11380 << I + 1;
11381 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11382 return;
11383 }
11384 }
11385
11386 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
11387 return;
11388
11389 // Emit the generic diagnostic and, optionally, add the hints to it.
11390 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11391 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11392 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11393 << (unsigned)(Cand->Fix.Kind);
11394
11395 // Check that location of Fn is not in system header.
11396 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
11397 // If we can fix the conversion, suggest the FixIts.
11398 for (const FixItHint &HI : Cand->Fix.Hints)
11399 FDiag << HI;
11400 }
11401
11402 S.Diag(Fn->getLocation(), FDiag);
11403
11404 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11405}
11406
11407/// Additional arity mismatch diagnosis specific to a function overload
11408/// candidates. This is not covered by the more general DiagnoseArityMismatch()
11409/// over a candidate in any candidate set.
11411 unsigned NumArgs, bool IsAddressOf = false) {
11412 assert(Cand->Function && "Candidate is required to be a function.");
11413 FunctionDecl *Fn = Cand->Function;
11414 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11415 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11416
11417 // With invalid overloaded operators, it's possible that we think we
11418 // have an arity mismatch when in fact it looks like we have the
11419 // right number of arguments, because only overloaded operators have
11420 // the weird behavior of overloading member and non-member functions.
11421 // Just don't report anything.
11422 if (Fn->isInvalidDecl() &&
11423 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
11424 return true;
11425
11426 if (NumArgs < MinParams) {
11427 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11429 Cand->DeductionFailure.getResult() ==
11431 } else {
11432 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11434 Cand->DeductionFailure.getResult() ==
11436 }
11437
11438 return false;
11439}
11440
11441/// General arity mismatch diagnosis over a candidate in a candidate set.
11443 unsigned NumFormalArgs,
11444 bool IsAddressOf = false) {
11445 assert(isa<FunctionDecl>(D) &&
11446 "The templated declaration should at least be a function"
11447 " when diagnosing bad template argument deduction due to too many"
11448 " or too few arguments");
11449
11450 FunctionDecl *Fn = cast<FunctionDecl>(D);
11451
11452 // TODO: treat calls to a missing default constructor as a special case
11453 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11454 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11455 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11456
11457 // at least / at most / exactly
11458 bool HasExplicitObjectParam =
11459 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
11460
11461 unsigned ParamCount =
11462 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11463 unsigned mode, modeCount;
11464
11465 if (NumFormalArgs < MinParams) {
11466 if (MinParams != ParamCount || FnTy->isVariadic() ||
11467 FnTy->isTemplateVariadic())
11468 mode = 0; // "at least"
11469 else
11470 mode = 2; // "exactly"
11471 modeCount = MinParams;
11472 } else {
11473 if (MinParams != ParamCount)
11474 mode = 1; // "at most"
11475 else
11476 mode = 2; // "exactly"
11477 modeCount = ParamCount;
11478 }
11479
11480 std::string Description;
11481 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11482 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11483
11484 if (modeCount == 1 && !IsAddressOf &&
11485 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11486 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11487 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11488 << Description << mode
11489 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11490 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11491 else
11492 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11493 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11494 << Description << mode << modeCount << NumFormalArgs
11495 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11496
11497 MaybeEmitInheritedConstructorNote(S, Found);
11498}
11499
11500/// Arity mismatch diagnosis specific to a function overload candidate.
11502 unsigned NumFormalArgs) {
11503 assert(Cand->Function && "Candidate must be a function");
11504 FunctionDecl *Fn = Cand->Function;
11505 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
11506 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
11507 Cand->TookAddressOfOverload);
11508}
11509
11511 if (TemplateDecl *TD = Templated->getDescribedTemplate())
11512 return TD;
11513 llvm_unreachable("Unsupported: Getting the described template declaration"
11514 " for bad deduction diagnosis");
11515}
11516
11517/// Diagnose a failed template-argument deduction.
11518static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11519 DeductionFailureInfo &DeductionFailure,
11520 unsigned NumArgs,
11521 bool TakingCandidateAddress) {
11522 TemplateParameter Param = DeductionFailure.getTemplateParameter();
11523 NamedDecl *ParamD;
11524 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11525 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11526 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11527 switch (DeductionFailure.getResult()) {
11529 llvm_unreachable(
11530 "TemplateDeductionResult::Success while diagnosing bad deduction");
11532 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
11533 "while diagnosing bad deduction");
11536 return;
11537
11539 assert(ParamD && "no parameter found for incomplete deduction result");
11540 S.Diag(Templated->getLocation(),
11541 diag::note_ovl_candidate_incomplete_deduction)
11542 << ParamD->getDeclName();
11543 MaybeEmitInheritedConstructorNote(S, Found);
11544 return;
11545 }
11546
11548 assert(ParamD && "no parameter found for incomplete deduction result");
11549 S.Diag(Templated->getLocation(),
11550 diag::note_ovl_candidate_incomplete_deduction_pack)
11551 << ParamD->getDeclName()
11552 << (DeductionFailure.getFirstArg()->pack_size() + 1)
11553 << *DeductionFailure.getFirstArg();
11554 MaybeEmitInheritedConstructorNote(S, Found);
11555 return;
11556 }
11557
11559 assert(ParamD && "no parameter found for bad qualifiers deduction result");
11560 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11561
11562 QualType Param = DeductionFailure.getFirstArg()->getAsType();
11563
11564 // Param will have been canonicalized, but it should just be a
11565 // qualified version of ParamD, so move the qualifiers to that.
11567 Qs.strip(Param);
11568 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11569 assert(S.Context.hasSameType(Param, NonCanonParam));
11570
11571 // Arg has also been canonicalized, but there's nothing we can do
11572 // about that. It also doesn't matter as much, because it won't
11573 // have any template parameters in it (because deduction isn't
11574 // done on dependent types).
11575 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11576
11577 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11578 << ParamD->getDeclName() << Arg << NonCanonParam;
11579 MaybeEmitInheritedConstructorNote(S, Found);
11580 return;
11581 }
11582
11584 assert(ParamD && "no parameter found for inconsistent deduction result");
11585 int which = 0;
11586 if (isa<TemplateTypeParmDecl>(ParamD))
11587 which = 0;
11588 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11589 // Deduction might have failed because we deduced arguments of two
11590 // different types for a non-type template parameter.
11591 // FIXME: Use a different TDK value for this.
11592 QualType T1 =
11593 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11594 QualType T2 =
11595 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11596 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11597 S.Diag(Templated->getLocation(),
11598 diag::note_ovl_candidate_inconsistent_deduction_types)
11599 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11600 << *DeductionFailure.getSecondArg() << T2;
11601 MaybeEmitInheritedConstructorNote(S, Found);
11602 return;
11603 }
11604
11605 which = 1;
11606 } else {
11607 which = 2;
11608 }
11609
11610 // Tweak the diagnostic if the problem is that we deduced packs of
11611 // different arities. We'll print the actual packs anyway in case that
11612 // includes additional useful information.
11613 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11614 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11615 DeductionFailure.getFirstArg()->pack_size() !=
11616 DeductionFailure.getSecondArg()->pack_size()) {
11617 which = 3;
11618 }
11619
11620 S.Diag(Templated->getLocation(),
11621 diag::note_ovl_candidate_inconsistent_deduction)
11622 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11623 << *DeductionFailure.getSecondArg();
11624 MaybeEmitInheritedConstructorNote(S, Found);
11625 return;
11626 }
11627
11629 assert(ParamD && "no parameter found for invalid explicit arguments");
11630 if (ParamD->getDeclName())
11631 S.Diag(Templated->getLocation(),
11632 diag::note_ovl_candidate_explicit_arg_mismatch_named)
11633 << ParamD->getDeclName();
11634 else {
11635 int index = 0;
11636 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11637 index = TTP->getIndex();
11638 else if (NonTypeTemplateParmDecl *NTTP
11639 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11640 index = NTTP->getIndex();
11641 else
11642 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11643 S.Diag(Templated->getLocation(),
11644 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11645 << (index + 1);
11646 }
11647 MaybeEmitInheritedConstructorNote(S, Found);
11648 return;
11649
11651 // Format the template argument list into the argument string.
11652 SmallString<128> TemplateArgString;
11653 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11654 TemplateArgString = " ";
11655 TemplateArgString += S.getTemplateArgumentBindingsText(
11656 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11657 if (TemplateArgString.size() == 1)
11658 TemplateArgString.clear();
11659 S.Diag(Templated->getLocation(),
11660 diag::note_ovl_candidate_unsatisfied_constraints)
11661 << TemplateArgString;
11662
11664 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11665 return;
11666 }
11669 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11670 return;
11671
11673 S.Diag(Templated->getLocation(),
11674 diag::note_ovl_candidate_instantiation_depth);
11675 MaybeEmitInheritedConstructorNote(S, Found);
11676 return;
11677
11679 // Format the template argument list into the argument string.
11680 SmallString<128> TemplateArgString;
11681 if (TemplateArgumentList *Args =
11682 DeductionFailure.getTemplateArgumentList()) {
11683 TemplateArgString = " ";
11684 TemplateArgString += S.getTemplateArgumentBindingsText(
11685 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11686 if (TemplateArgString.size() == 1)
11687 TemplateArgString.clear();
11688 }
11689
11690 // If this candidate was disabled by enable_if, say so.
11691 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11692 if (PDiag && PDiag->second.getDiagID() ==
11693 diag::err_typename_nested_not_found_enable_if) {
11694 // FIXME: Use the source range of the condition, and the fully-qualified
11695 // name of the enable_if template. These are both present in PDiag.
11696 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11697 << "'enable_if'" << TemplateArgString;
11698 return;
11699 }
11700
11701 // We found a specific requirement that disabled the enable_if.
11702 if (PDiag && PDiag->second.getDiagID() ==
11703 diag::err_typename_nested_not_found_requirement) {
11704 S.Diag(Templated->getLocation(),
11705 diag::note_ovl_candidate_disabled_by_requirement)
11706 << PDiag->second.getStringArg(0) << TemplateArgString;
11707 return;
11708 }
11709
11710 // Format the SFINAE diagnostic into the argument string.
11711 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11712 // formatted message in another diagnostic.
11713 SmallString<128> SFINAEArgString;
11714 SourceRange R;
11715 if (PDiag) {
11716 SFINAEArgString = ": ";
11717 R = SourceRange(PDiag->first, PDiag->first);
11718 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11719 }
11720
11721 S.Diag(Templated->getLocation(),
11722 diag::note_ovl_candidate_substitution_failure)
11723 << TemplateArgString << SFINAEArgString << R;
11724 MaybeEmitInheritedConstructorNote(S, Found);
11725 return;
11726 }
11727
11730 // Format the template argument list into the argument string.
11731 SmallString<128> TemplateArgString;
11732 if (TemplateArgumentList *Args =
11733 DeductionFailure.getTemplateArgumentList()) {
11734 TemplateArgString = " ";
11735 TemplateArgString += S.getTemplateArgumentBindingsText(
11736 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11737 if (TemplateArgString.size() == 1)
11738 TemplateArgString.clear();
11739 }
11740
11741 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11742 << (*DeductionFailure.getCallArgIndex() + 1)
11743 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11744 << TemplateArgString
11745 << (DeductionFailure.getResult() ==
11747 break;
11748 }
11749
11751 // FIXME: Provide a source location to indicate what we couldn't match.
11752 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11753 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11754 if (FirstTA.getKind() == TemplateArgument::Template &&
11755 SecondTA.getKind() == TemplateArgument::Template) {
11756 TemplateName FirstTN = FirstTA.getAsTemplate();
11757 TemplateName SecondTN = SecondTA.getAsTemplate();
11758 if (FirstTN.getKind() == TemplateName::Template &&
11759 SecondTN.getKind() == TemplateName::Template) {
11760 if (FirstTN.getAsTemplateDecl()->getName() ==
11761 SecondTN.getAsTemplateDecl()->getName()) {
11762 // FIXME: This fixes a bad diagnostic where both templates are named
11763 // the same. This particular case is a bit difficult since:
11764 // 1) It is passed as a string to the diagnostic printer.
11765 // 2) The diagnostic printer only attempts to find a better
11766 // name for types, not decls.
11767 // Ideally, this should folded into the diagnostic printer.
11768 S.Diag(Templated->getLocation(),
11769 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11770 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11771 return;
11772 }
11773 }
11774 }
11775
11776 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11777 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11778 return;
11779
11780 // FIXME: For generic lambda parameters, check if the function is a lambda
11781 // call operator, and if so, emit a prettier and more informative
11782 // diagnostic that mentions 'auto' and lambda in addition to
11783 // (or instead of?) the canonical template type parameters.
11784 S.Diag(Templated->getLocation(),
11785 diag::note_ovl_candidate_non_deduced_mismatch)
11786 << FirstTA << SecondTA;
11787 return;
11788 }
11789 // TODO: diagnose these individually, then kill off
11790 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11792 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11793 MaybeEmitInheritedConstructorNote(S, Found);
11794 return;
11796 S.Diag(Templated->getLocation(),
11797 diag::note_cuda_ovl_candidate_target_mismatch);
11798 return;
11799 }
11800}
11801
11802/// Diagnose a failed template-argument deduction, for function calls.
11804 unsigned NumArgs,
11805 bool TakingCandidateAddress) {
11806 assert(Cand->Function && "Candidate must be a function");
11807 FunctionDecl *Fn = Cand->Function;
11811 if (CheckArityMismatch(S, Cand, NumArgs))
11812 return;
11813 }
11814 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
11815 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11816}
11817
11818/// CUDA: diagnose an invalid call across targets.
11820 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11821 assert(Cand->Function && "Candidate must be a Function.");
11822 FunctionDecl *Callee = Cand->Function;
11823
11824 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
11825 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
11826
11827 std::string FnDesc;
11828 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11829 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11830 Cand->getRewriteKind(), FnDesc);
11831
11832 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11833 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11834 << FnDesc /* Ignored */
11835 << llvm::to_underlying(CalleeTarget) << llvm::to_underlying(CallerTarget);
11836
11837 // This could be an implicit constructor for which we could not infer the
11838 // target due to a collsion. Diagnose that case.
11839 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11840 if (Meth != nullptr && Meth->isImplicit()) {
11841 CXXRecordDecl *ParentClass = Meth->getParent();
11843
11844 switch (FnKindPair.first) {
11845 default:
11846 return;
11847 case oc_implicit_default_constructor:
11849 break;
11850 case oc_implicit_copy_constructor:
11852 break;
11853 case oc_implicit_move_constructor:
11855 break;
11856 case oc_implicit_copy_assignment:
11858 break;
11859 case oc_implicit_move_assignment:
11861 break;
11862 };
11863
11864 bool ConstRHS = false;
11865 if (Meth->getNumParams()) {
11866 if (const ReferenceType *RT =
11867 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11868 ConstRHS = RT->getPointeeType().isConstQualified();
11869 }
11870 }
11871
11872 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11873 /* ConstRHS */ ConstRHS,
11874 /* Diagnose */ true);
11875 }
11876}
11877
11879 assert(Cand->Function && "Candidate must be a function");
11880 FunctionDecl *Callee = Cand->Function;
11881 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11882
11883 S.Diag(Callee->getLocation(),
11884 diag::note_ovl_candidate_disabled_by_function_cond_attr)
11885 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11886}
11887
11889 assert(Cand->Function && "Candidate must be a function");
11890 FunctionDecl *Fn = Cand->Function;
11892 assert(ES.isExplicit() && "not an explicit candidate");
11893
11894 unsigned Kind;
11895 switch (Fn->getDeclKind()) {
11896 case Decl::Kind::CXXConstructor:
11897 Kind = 0;
11898 break;
11899 case Decl::Kind::CXXConversion:
11900 Kind = 1;
11901 break;
11902 case Decl::Kind::CXXDeductionGuide:
11903 Kind = Fn->isImplicit() ? 0 : 2;
11904 break;
11905 default:
11906 llvm_unreachable("invalid Decl");
11907 }
11908
11909 // Note the location of the first (in-class) declaration; a redeclaration
11910 // (particularly an out-of-class definition) will typically lack the
11911 // 'explicit' specifier.
11912 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11913 FunctionDecl *First = Fn->getFirstDecl();
11914 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11915 First = Pattern->getFirstDecl();
11916
11917 S.Diag(First->getLocation(),
11918 diag::note_ovl_candidate_explicit)
11919 << Kind << (ES.getExpr() ? 1 : 0)
11920 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11921}
11922
11924 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
11925 if (!DG)
11926 return;
11927 TemplateDecl *OriginTemplate =
11929 // We want to always print synthesized deduction guides for type aliases.
11930 // They would retain the explicit bit of the corresponding constructor.
11931 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
11932 return;
11933 std::string FunctionProto;
11934 llvm::raw_string_ostream OS(FunctionProto);
11935 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
11936 if (!Template) {
11937 // This also could be an instantiation. Find out the primary template.
11938 FunctionDecl *Pattern =
11939 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
11940 if (!Pattern) {
11941 // The implicit deduction guide is built on an explicit non-template
11942 // deduction guide. Currently, this might be the case only for type
11943 // aliases.
11944 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
11945 // gets merged.
11946 assert(OriginTemplate->isTypeAlias() &&
11947 "Non-template implicit deduction guides are only possible for "
11948 "type aliases");
11949 DG->print(OS);
11950 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
11951 << FunctionProto;
11952 return;
11953 }
11954 Template = Pattern->getDescribedFunctionTemplate();
11955 assert(Template && "Cannot find the associated function template of "
11956 "CXXDeductionGuideDecl?");
11957 }
11958 Template->print(OS);
11959 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
11960 << FunctionProto;
11961}
11962
11963/// Generates a 'note' diagnostic for an overload candidate. We've
11964/// already generated a primary error at the call site.
11965///
11966/// It really does need to be a single diagnostic with its caret
11967/// pointed at the candidate declaration. Yes, this creates some
11968/// major challenges of technical writing. Yes, this makes pointing
11969/// out problems with specific arguments quite awkward. It's still
11970/// better than generating twenty screens of text for every failed
11971/// overload.
11972///
11973/// It would be great to be able to express per-candidate problems
11974/// more richly for those diagnostic clients that cared, but we'd
11975/// still have to be just as careful with the default diagnostics.
11976/// \param CtorDestAS Addr space of object being constructed (for ctor
11977/// candidates only).
11979 unsigned NumArgs,
11980 bool TakingCandidateAddress,
11981 LangAS CtorDestAS = LangAS::Default) {
11982 assert(Cand->Function && "Candidate must be a function");
11983 FunctionDecl *Fn = Cand->Function;
11985 return;
11986
11987 // There is no physical candidate declaration to point to for OpenCL builtins.
11988 // Except for failed conversions, the notes are identical for each candidate,
11989 // so do not generate such notes.
11990 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
11992 return;
11993
11994 // Skip implicit member functions when trying to resolve
11995 // the address of a an overload set for a function pointer.
11996 if (Cand->TookAddressOfOverload &&
11997 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
11998 return;
11999
12000 // Note deleted candidates, but only if they're viable.
12001 if (Cand->Viable) {
12002 if (Fn->isDeleted()) {
12003 std::string FnDesc;
12004 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12005 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12006 Cand->getRewriteKind(), FnDesc);
12007
12008 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12009 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12010 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12011 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12012 return;
12013 }
12014
12015 // We don't really have anything else to say about viable candidates.
12016 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12017 return;
12018 }
12019
12020 // If this is a synthesized deduction guide we're deducing against, add a note
12021 // for it. These deduction guides are not explicitly spelled in the source
12022 // code, so simply printing a deduction failure note mentioning synthesized
12023 // template parameters or pointing to the header of the surrounding RecordDecl
12024 // would be confusing.
12025 //
12026 // We prefer adding such notes at the end of the deduction failure because
12027 // duplicate code snippets appearing in the diagnostic would likely become
12028 // noisy.
12029 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12030
12031 switch (Cand->FailureKind) {
12034 return DiagnoseArityMismatch(S, Cand, NumArgs);
12035
12037 return DiagnoseBadDeduction(S, Cand, NumArgs,
12038 TakingCandidateAddress);
12039
12041 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12042 << (Fn->getPrimaryTemplate() ? 1 : 0);
12043 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12044 return;
12045 }
12046
12048 Qualifiers QualsForPrinting;
12049 QualsForPrinting.setAddressSpace(CtorDestAS);
12050 S.Diag(Fn->getLocation(),
12051 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12052 << QualsForPrinting;
12053 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12054 return;
12055 }
12056
12060 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12061
12063 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12064 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12065 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12066 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12067
12068 // FIXME: this currently happens when we're called from SemaInit
12069 // when user-conversion overload fails. Figure out how to handle
12070 // those conditions and diagnose them well.
12071 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12072 }
12073
12075 return DiagnoseBadTarget(S, Cand);
12076
12077 case ovl_fail_enable_if:
12078 return DiagnoseFailedEnableIfAttr(S, Cand);
12079
12080 case ovl_fail_explicit:
12081 return DiagnoseFailedExplicitSpec(S, Cand);
12082
12084 // It's generally not interesting to note copy/move constructors here.
12085 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12086 return;
12087 S.Diag(Fn->getLocation(),
12088 diag::note_ovl_candidate_inherited_constructor_slice)
12089 << (Fn->getPrimaryTemplate() ? 1 : 0)
12090 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12091 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12092 return;
12093
12095 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12096 (void)Available;
12097 assert(!Available);
12098 break;
12099 }
12101 // Do nothing, these should simply be ignored.
12102 break;
12103
12105 std::string FnDesc;
12106 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12107 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12108 Cand->getRewriteKind(), FnDesc);
12109
12110 S.Diag(Fn->getLocation(),
12111 diag::note_ovl_candidate_constraints_not_satisfied)
12112 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12113 << FnDesc /* Ignored */;
12114 ConstraintSatisfaction Satisfaction;
12115 if (S.CheckFunctionConstraints(Fn, Satisfaction))
12116 break;
12117 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12118 }
12119 }
12120}
12121
12124 return;
12125
12126 // Desugar the type of the surrogate down to a function type,
12127 // retaining as many typedefs as possible while still showing
12128 // the function type (and, therefore, its parameter types).
12129 QualType FnType = Cand->Surrogate->getConversionType();
12130 bool isLValueReference = false;
12131 bool isRValueReference = false;
12132 bool isPointer = false;
12133 if (const LValueReferenceType *FnTypeRef =
12134 FnType->getAs<LValueReferenceType>()) {
12135 FnType = FnTypeRef->getPointeeType();
12136 isLValueReference = true;
12137 } else if (const RValueReferenceType *FnTypeRef =
12138 FnType->getAs<RValueReferenceType>()) {
12139 FnType = FnTypeRef->getPointeeType();
12140 isRValueReference = true;
12141 }
12142 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12143 FnType = FnTypePtr->getPointeeType();
12144 isPointer = true;
12145 }
12146 // Desugar down to a function type.
12147 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12148 // Reconstruct the pointer/reference as appropriate.
12149 if (isPointer) FnType = S.Context.getPointerType(FnType);
12150 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12151 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12152
12153 if (!Cand->Viable &&
12155 S.Diag(Cand->Surrogate->getLocation(),
12156 diag::note_ovl_surrogate_constraints_not_satisfied)
12157 << Cand->Surrogate;
12158 ConstraintSatisfaction Satisfaction;
12159 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12160 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12161 } else {
12162 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12163 << FnType;
12164 }
12165}
12166
12167static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12168 SourceLocation OpLoc,
12169 OverloadCandidate *Cand) {
12170 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12171 std::string TypeStr("operator");
12172 TypeStr += Opc;
12173 TypeStr += "(";
12174 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12175 if (Cand->Conversions.size() == 1) {
12176 TypeStr += ")";
12177 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12178 } else {
12179 TypeStr += ", ";
12180 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12181 TypeStr += ")";
12182 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12183 }
12184}
12185
12187 OverloadCandidate *Cand) {
12188 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12189 if (ICS.isBad()) break; // all meaningless after first invalid
12190 if (!ICS.isAmbiguous()) continue;
12191
12193 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12194 }
12195}
12196
12198 if (Cand->Function)
12199 return Cand->Function->getLocation();
12200 if (Cand->IsSurrogate)
12201 return Cand->Surrogate->getLocation();
12202 return SourceLocation();
12203}
12204
12205static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12206 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12210 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12211
12215 return 1;
12216
12219 return 2;
12220
12228 return 3;
12229
12231 return 4;
12232
12234 return 5;
12235
12238 return 6;
12239 }
12240 llvm_unreachable("Unhandled deduction result");
12241}
12242
12243namespace {
12244
12245struct CompareOverloadCandidatesForDisplay {
12246 Sema &S;
12248 size_t NumArgs;
12250
12251 CompareOverloadCandidatesForDisplay(
12252 Sema &S, SourceLocation Loc, size_t NArgs,
12254 : S(S), NumArgs(NArgs), CSK(CSK) {}
12255
12256 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12257 // If there are too many or too few arguments, that's the high-order bit we
12258 // want to sort by, even if the immediate failure kind was something else.
12259 if (C->FailureKind == ovl_fail_too_many_arguments ||
12260 C->FailureKind == ovl_fail_too_few_arguments)
12261 return static_cast<OverloadFailureKind>(C->FailureKind);
12262
12263 if (C->Function) {
12264 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12266 if (NumArgs < C->Function->getMinRequiredArguments())
12268 }
12269
12270 return static_cast<OverloadFailureKind>(C->FailureKind);
12271 }
12272
12273 bool operator()(const OverloadCandidate *L,
12274 const OverloadCandidate *R) {
12275 // Fast-path this check.
12276 if (L == R) return false;
12277
12278 // Order first by viability.
12279 if (L->Viable) {
12280 if (!R->Viable) return true;
12281
12282 if (int Ord = CompareConversions(*L, *R))
12283 return Ord < 0;
12284 // Use other tie breakers.
12285 } else if (R->Viable)
12286 return false;
12287
12288 assert(L->Viable == R->Viable);
12289
12290 // Criteria by which we can sort non-viable candidates:
12291 if (!L->Viable) {
12292 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12293 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12294
12295 // 1. Arity mismatches come after other candidates.
12296 if (LFailureKind == ovl_fail_too_many_arguments ||
12297 LFailureKind == ovl_fail_too_few_arguments) {
12298 if (RFailureKind == ovl_fail_too_many_arguments ||
12299 RFailureKind == ovl_fail_too_few_arguments) {
12300 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12301 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12302 if (LDist == RDist) {
12303 if (LFailureKind == RFailureKind)
12304 // Sort non-surrogates before surrogates.
12305 return !L->IsSurrogate && R->IsSurrogate;
12306 // Sort candidates requiring fewer parameters than there were
12307 // arguments given after candidates requiring more parameters
12308 // than there were arguments given.
12309 return LFailureKind == ovl_fail_too_many_arguments;
12310 }
12311 return LDist < RDist;
12312 }
12313 return false;
12314 }
12315 if (RFailureKind == ovl_fail_too_many_arguments ||
12316 RFailureKind == ovl_fail_too_few_arguments)
12317 return true;
12318
12319 // 2. Bad conversions come first and are ordered by the number
12320 // of bad conversions and quality of good conversions.
12321 if (LFailureKind == ovl_fail_bad_conversion) {
12322 if (RFailureKind != ovl_fail_bad_conversion)
12323 return true;
12324
12325 // The conversion that can be fixed with a smaller number of changes,
12326 // comes first.
12327 unsigned numLFixes = L->Fix.NumConversionsFixed;
12328 unsigned numRFixes = R->Fix.NumConversionsFixed;
12329 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12330 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12331 if (numLFixes != numRFixes) {
12332 return numLFixes < numRFixes;
12333 }
12334
12335 // If there's any ordering between the defined conversions...
12336 if (int Ord = CompareConversions(*L, *R))
12337 return Ord < 0;
12338 } else if (RFailureKind == ovl_fail_bad_conversion)
12339 return false;
12340
12341 if (LFailureKind == ovl_fail_bad_deduction) {
12342 if (RFailureKind != ovl_fail_bad_deduction)
12343 return true;
12344
12346 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12347 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12348 if (LRank != RRank)
12349 return LRank < RRank;
12350 }
12351 } else if (RFailureKind == ovl_fail_bad_deduction)
12352 return false;
12353
12354 // TODO: others?
12355 }
12356
12357 // Sort everything else by location.
12360
12361 // Put candidates without locations (e.g. builtins) at the end.
12362 if (LLoc.isValid() && RLoc.isValid())
12363 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12364 if (LLoc.isValid() && !RLoc.isValid())
12365 return true;
12366 if (RLoc.isValid() && !LLoc.isValid())
12367 return false;
12368 assert(!LLoc.isValid() && !RLoc.isValid());
12369 // For builtins and other functions without locations, fallback to the order
12370 // in which they were added into the candidate set.
12371 return L < R;
12372 }
12373
12374private:
12375 struct ConversionSignals {
12376 unsigned KindRank = 0;
12378
12379 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12380 ConversionSignals Sig;
12381 Sig.KindRank = Seq.getKindRank();
12382 if (Seq.isStandard())
12383 Sig.Rank = Seq.Standard.getRank();
12384 else if (Seq.isUserDefined())
12385 Sig.Rank = Seq.UserDefined.After.getRank();
12386 // We intend StaticObjectArgumentConversion to compare the same as
12387 // StandardConversion with ICR_ExactMatch rank.
12388 return Sig;
12389 }
12390
12391 static ConversionSignals ForObjectArgument() {
12392 // We intend StaticObjectArgumentConversion to compare the same as
12393 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12394 return {};
12395 }
12396 };
12397
12398 // Returns -1 if conversions in L are considered better.
12399 // 0 if they are considered indistinguishable.
12400 // 1 if conversions in R are better.
12401 int CompareConversions(const OverloadCandidate &L,
12402 const OverloadCandidate &R) {
12403 // We cannot use `isBetterOverloadCandidate` because it is defined
12404 // according to the C++ standard and provides a partial order, but we need
12405 // a total order as this function is used in sort.
12406 assert(L.Conversions.size() == R.Conversions.size());
12407 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12408 auto LS = L.IgnoreObjectArgument && I == 0
12409 ? ConversionSignals::ForObjectArgument()
12410 : ConversionSignals::ForSequence(L.Conversions[I]);
12411 auto RS = R.IgnoreObjectArgument
12412 ? ConversionSignals::ForObjectArgument()
12413 : ConversionSignals::ForSequence(R.Conversions[I]);
12414 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
12415 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
12416 ? -1
12417 : 1;
12418 }
12419 // FIXME: find a way to compare templates for being more or less
12420 // specialized that provides a strict weak ordering.
12421 return 0;
12422 }
12423};
12424}
12425
12426/// CompleteNonViableCandidate - Normally, overload resolution only
12427/// computes up to the first bad conversion. Produces the FixIt set if
12428/// possible.
12429static void
12431 ArrayRef<Expr *> Args,
12433 assert(!Cand->Viable);
12434
12435 // Don't do anything on failures other than bad conversion.
12437 return;
12438
12439 // We only want the FixIts if all the arguments can be corrected.
12440 bool Unfixable = false;
12441 // Use a implicit copy initialization to check conversion fixes.
12443
12444 // Attempt to fix the bad conversion.
12445 unsigned ConvCount = Cand->Conversions.size();
12446 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12447 ++ConvIdx) {
12448 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12449 if (Cand->Conversions[ConvIdx].isInitialized() &&
12450 Cand->Conversions[ConvIdx].isBad()) {
12451 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12452 break;
12453 }
12454 }
12455
12456 // FIXME: this should probably be preserved from the overload
12457 // operation somehow.
12458 bool SuppressUserConversions = false;
12459
12460 unsigned ConvIdx = 0;
12461 unsigned ArgIdx = 0;
12462 ArrayRef<QualType> ParamTypes;
12463 bool Reversed = Cand->isReversed();
12464
12465 if (Cand->IsSurrogate) {
12466 QualType ConvType
12468 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12469 ConvType = ConvPtrType->getPointeeType();
12470 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12471 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12472 ConvIdx = 1;
12473 } else if (Cand->Function) {
12474 ParamTypes =
12475 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12476 if (isa<CXXMethodDecl>(Cand->Function) &&
12477 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
12478 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12479 ConvIdx = 1;
12481 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12483 OO_Subscript)
12484 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12485 ArgIdx = 1;
12486 }
12487 } else {
12488 // Builtin operator.
12489 assert(ConvCount <= 3);
12490 ParamTypes = Cand->BuiltinParamTypes;
12491 }
12492
12493 // Fill in the rest of the conversions.
12494 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12495 ConvIdx != ConvCount;
12496 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12497 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12498 if (Cand->Conversions[ConvIdx].isInitialized()) {
12499 // We've already checked this conversion.
12500 } else if (ParamIdx < ParamTypes.size()) {
12501 if (ParamTypes[ParamIdx]->isDependentType())
12502 Cand->Conversions[ConvIdx].setAsIdentityConversion(
12503 Args[ArgIdx]->getType());
12504 else {
12505 Cand->Conversions[ConvIdx] =
12506 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
12507 SuppressUserConversions,
12508 /*InOverloadResolution=*/true,
12509 /*AllowObjCWritebackConversion=*/
12510 S.getLangOpts().ObjCAutoRefCount);
12511 // Store the FixIt in the candidate if it exists.
12512 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12513 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12514 }
12515 } else
12516 Cand->Conversions[ConvIdx].setEllipsis();
12517 }
12518}
12519
12522 SourceLocation OpLoc,
12523 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12524 // Sort the candidates by viability and position. Sorting directly would
12525 // be prohibitive, so we make a set of pointers and sort those.
12527 if (OCD == OCD_AllCandidates) Cands.reserve(size());
12528 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12529 if (!Filter(*Cand))
12530 continue;
12531 switch (OCD) {
12532 case OCD_AllCandidates:
12533 if (!Cand->Viable) {
12534 if (!Cand->Function && !Cand->IsSurrogate) {
12535 // This a non-viable builtin candidate. We do not, in general,
12536 // want to list every possible builtin candidate.
12537 continue;
12538 }
12539 CompleteNonViableCandidate(S, Cand, Args, Kind);
12540 }
12541 break;
12542
12544 if (!Cand->Viable)
12545 continue;
12546 break;
12547
12549 if (!Cand->Best)
12550 continue;
12551 break;
12552 }
12553
12554 Cands.push_back(Cand);
12555 }
12556
12557 llvm::stable_sort(
12558 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12559
12560 return Cands;
12561}
12562
12564 SourceLocation OpLoc) {
12565 bool DeferHint = false;
12566 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12567 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12568 // host device candidates.
12569 auto WrongSidedCands =
12570 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12571 return (Cand.Viable == false &&
12572 Cand.FailureKind == ovl_fail_bad_target) ||
12573 (Cand.Function &&
12574 Cand.Function->template hasAttr<CUDAHostAttr>() &&
12575 Cand.Function->template hasAttr<CUDADeviceAttr>());
12576 });
12577 DeferHint = !WrongSidedCands.empty();
12578 }
12579 return DeferHint;
12580}
12581
12582/// When overload resolution fails, prints diagnostic messages containing the
12583/// candidates in the candidate set.
12586 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12587 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12588
12589 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12590
12591 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12592
12593 // In WebAssembly we don't want to emit further diagnostics if a table is
12594 // passed as an argument to a function.
12595 bool NoteCands = true;
12596 for (const Expr *Arg : Args) {
12597 if (Arg->getType()->isWebAssemblyTableType())
12598 NoteCands = false;
12599 }
12600
12601 if (NoteCands)
12602 NoteCandidates(S, Args, Cands, Opc, OpLoc);
12603
12604 if (OCD == OCD_AmbiguousCandidates)
12606}
12607
12610 StringRef Opc, SourceLocation OpLoc) {
12611 bool ReportedAmbiguousConversions = false;
12612
12613 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12614 unsigned CandsShown = 0;
12615 auto I = Cands.begin(), E = Cands.end();
12616 for (; I != E; ++I) {
12617 OverloadCandidate *Cand = *I;
12618
12619 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12620 ShowOverloads == Ovl_Best) {
12621 break;
12622 }
12623 ++CandsShown;
12624
12625 if (Cand->Function)
12626 NoteFunctionCandidate(S, Cand, Args.size(),
12627 /*TakingCandidateAddress=*/false, DestAS);
12628 else if (Cand->IsSurrogate)
12629 NoteSurrogateCandidate(S, Cand);
12630 else {
12631 assert(Cand->Viable &&
12632 "Non-viable built-in candidates are not added to Cands.");
12633 // Generally we only see ambiguities including viable builtin
12634 // operators if overload resolution got screwed up by an
12635 // ambiguous user-defined conversion.
12636 //
12637 // FIXME: It's quite possible for different conversions to see
12638 // different ambiguities, though.
12639 if (!ReportedAmbiguousConversions) {
12640 NoteAmbiguousUserConversions(S, OpLoc, Cand);
12641 ReportedAmbiguousConversions = true;
12642 }
12643
12644 // If this is a viable builtin, print it.
12645 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12646 }
12647 }
12648
12649 // Inform S.Diags that we've shown an overload set with N elements. This may
12650 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12651 S.Diags.overloadCandidatesShown(CandsShown);
12652
12653 if (I != E)
12654 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12655 shouldDeferDiags(S, Args, OpLoc))
12656 << int(E - I);
12657}
12658
12659static SourceLocation
12661 return Cand->Specialization ? Cand->Specialization->getLocation()
12662 : SourceLocation();
12663}
12664
12665namespace {
12666struct CompareTemplateSpecCandidatesForDisplay {
12667 Sema &S;
12668 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12669
12670 bool operator()(const TemplateSpecCandidate *L,
12671 const TemplateSpecCandidate *R) {
12672 // Fast-path this check.
12673 if (L == R)
12674 return false;
12675
12676 // Assuming that both candidates are not matches...
12677
12678 // Sort by the ranking of deduction failures.
12682
12683 // Sort everything else by location.
12686
12687 // Put candidates without locations (e.g. builtins) at the end.
12688 if (LLoc.isInvalid())
12689 return false;
12690 if (RLoc.isInvalid())
12691 return true;
12692
12693 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12694 }
12695};
12696}
12697
12698/// Diagnose a template argument deduction failure.
12699/// We are treating these failures as overload failures due to bad
12700/// deductions.
12702 bool ForTakingAddress) {
12703 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12704 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12705}
12706
12707void TemplateSpecCandidateSet::destroyCandidates() {
12708 for (iterator i = begin(), e = end(); i != e; ++i) {
12709 i->DeductionFailure.Destroy();
12710 }
12711}
12712
12714 destroyCandidates();
12715 Candidates.clear();
12716}
12717
12718/// NoteCandidates - When no template specialization match is found, prints
12719/// diagnostic messages containing the non-matching specializations that form
12720/// the candidate set.
12721/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12722/// OCD == OCD_AllCandidates and Cand->Viable == false.
12724 // Sort the candidates by position (assuming no candidate is a match).
12725 // Sorting directly would be prohibitive, so we make a set of pointers
12726 // and sort those.
12728 Cands.reserve(size());
12729 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12730 if (Cand->Specialization)
12731 Cands.push_back(Cand);
12732 // Otherwise, this is a non-matching builtin candidate. We do not,
12733 // in general, want to list every possible builtin candidate.
12734 }
12735
12736 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12737
12738 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12739 // for generalization purposes (?).
12740 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12741
12743 unsigned CandsShown = 0;
12744 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12745 TemplateSpecCandidate *Cand = *I;
12746
12747 // Set an arbitrary limit on the number of candidates we'll spam
12748 // the user with. FIXME: This limit should depend on details of the
12749 // candidate list.
12750 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12751 break;
12752 ++CandsShown;
12753
12754 assert(Cand->Specialization &&
12755 "Non-matching built-in candidates are not added to Cands.");
12756 Cand->NoteDeductionFailure(S, ForTakingAddress);
12757 }
12758
12759 if (I != E)
12760 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12761}
12762
12763// [PossiblyAFunctionType] --> [Return]
12764// NonFunctionType --> NonFunctionType
12765// R (A) --> R(A)
12766// R (*)(A) --> R (A)
12767// R (&)(A) --> R (A)
12768// R (S::*)(A) --> R (A)
12770 QualType Ret = PossiblyAFunctionType;
12771 if (const PointerType *ToTypePtr =
12772 PossiblyAFunctionType->getAs<PointerType>())
12773 Ret = ToTypePtr->getPointeeType();
12774 else if (const ReferenceType *ToTypeRef =
12775 PossiblyAFunctionType->getAs<ReferenceType>())
12776 Ret = ToTypeRef->getPointeeType();
12777 else if (const MemberPointerType *MemTypePtr =
12778 PossiblyAFunctionType->getAs<MemberPointerType>())
12779 Ret = MemTypePtr->getPointeeType();
12780 Ret =
12781 Context.getCanonicalType(Ret).getUnqualifiedType();
12782 return Ret;
12783}
12784
12786 bool Complain = true) {
12787 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12788 S.DeduceReturnType(FD, Loc, Complain))
12789 return true;
12790
12791 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12792 if (S.getLangOpts().CPlusPlus17 &&
12793 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12794 !S.ResolveExceptionSpec(Loc, FPT))
12795 return true;
12796
12797 return false;
12798}
12799
12800namespace {
12801// A helper class to help with address of function resolution
12802// - allows us to avoid passing around all those ugly parameters
12803class AddressOfFunctionResolver {
12804 Sema& S;
12805 Expr* SourceExpr;
12806 const QualType& TargetType;
12807 QualType TargetFunctionType; // Extracted function type from target type
12808
12809 bool Complain;
12810 //DeclAccessPair& ResultFunctionAccessPair;
12811 ASTContext& Context;
12812
12813 bool TargetTypeIsNonStaticMemberFunction;
12814 bool FoundNonTemplateFunction;
12815 bool StaticMemberFunctionFromBoundPointer;
12816 bool HasComplained;
12817
12818 OverloadExpr::FindResult OvlExprInfo;
12819 OverloadExpr *OvlExpr;
12820 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12822 TemplateSpecCandidateSet FailedCandidates;
12823
12824public:
12825 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12826 const QualType &TargetType, bool Complain)
12827 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12828 Complain(Complain), Context(S.getASTContext()),
12829 TargetTypeIsNonStaticMemberFunction(
12830 !!TargetType->getAs<MemberPointerType>()),
12831 FoundNonTemplateFunction(false),
12832 StaticMemberFunctionFromBoundPointer(false),
12833 HasComplained(false),
12834 OvlExprInfo(OverloadExpr::find(SourceExpr)),
12835 OvlExpr(OvlExprInfo.Expression),
12836 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12837 ExtractUnqualifiedFunctionTypeFromTargetType();
12838
12839 if (TargetFunctionType->isFunctionType()) {
12840 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12841 if (!UME->isImplicitAccess() &&
12843 StaticMemberFunctionFromBoundPointer = true;
12844 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12845 DeclAccessPair dap;
12847 OvlExpr, false, &dap)) {
12848 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12849 if (!Method->isStatic()) {
12850 // If the target type is a non-function type and the function found
12851 // is a non-static member function, pretend as if that was the
12852 // target, it's the only possible type to end up with.
12853 TargetTypeIsNonStaticMemberFunction = true;
12854
12855 // And skip adding the function if its not in the proper form.
12856 // We'll diagnose this due to an empty set of functions.
12857 if (!OvlExprInfo.HasFormOfMemberPointer)
12858 return;
12859 }
12860
12861 Matches.push_back(std::make_pair(dap, Fn));
12862 }
12863 return;
12864 }
12865
12866 if (OvlExpr->hasExplicitTemplateArgs())
12867 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12868
12869 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12870 // C++ [over.over]p4:
12871 // If more than one function is selected, [...]
12872 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12873 if (FoundNonTemplateFunction)
12874 EliminateAllTemplateMatches();
12875 else
12876 EliminateAllExceptMostSpecializedTemplate();
12877 }
12878 }
12879
12880 if (S.getLangOpts().CUDA && Matches.size() > 1)
12881 EliminateSuboptimalCudaMatches();
12882 }
12883
12884 bool hasComplained() const { return HasComplained; }
12885
12886private:
12887 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12888 QualType Discard;
12889 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12890 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12891 }
12892
12893 /// \return true if A is considered a better overload candidate for the
12894 /// desired type than B.
12895 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12896 // If A doesn't have exactly the correct type, we don't want to classify it
12897 // as "better" than anything else. This way, the user is required to
12898 // disambiguate for us if there are multiple candidates and no exact match.
12899 return candidateHasExactlyCorrectType(A) &&
12900 (!candidateHasExactlyCorrectType(B) ||
12901 compareEnableIfAttrs(S, A, B) == Comparison::Better);
12902 }
12903
12904 /// \return true if we were able to eliminate all but one overload candidate,
12905 /// false otherwise.
12906 bool eliminiateSuboptimalOverloadCandidates() {
12907 // Same algorithm as overload resolution -- one pass to pick the "best",
12908 // another pass to be sure that nothing is better than the best.
12909 auto Best = Matches.begin();
12910 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12911 if (isBetterCandidate(I->second, Best->second))
12912 Best = I;
12913
12914 const FunctionDecl *BestFn = Best->second;
12915 auto IsBestOrInferiorToBest = [this, BestFn](
12916 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12917 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12918 };
12919
12920 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12921 // option, so we can potentially give the user a better error
12922 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12923 return false;
12924 Matches[0] = *Best;
12925 Matches.resize(1);
12926 return true;
12927 }
12928
12929 bool isTargetTypeAFunction() const {
12930 return TargetFunctionType->isFunctionType();
12931 }
12932
12933 // [ToType] [Return]
12934
12935 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12936 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12937 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12938 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12939 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12940 }
12941
12942 // return true if any matching specializations were found
12943 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12944 const DeclAccessPair& CurAccessFunPair) {
12945 if (CXXMethodDecl *Method
12946 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12947 // Skip non-static function templates when converting to pointer, and
12948 // static when converting to member pointer.
12949 bool CanConvertToFunctionPointer =
12950 Method->isStatic() || Method->isExplicitObjectMemberFunction();
12951 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
12952 return false;
12953 }
12954 else if (TargetTypeIsNonStaticMemberFunction)
12955 return false;
12956
12957 // C++ [over.over]p2:
12958 // If the name is a function template, template argument deduction is
12959 // done (14.8.2.2), and if the argument deduction succeeds, the
12960 // resulting template argument list is used to generate a single
12961 // function template specialization, which is added to the set of
12962 // overloaded functions considered.
12963 FunctionDecl *Specialization = nullptr;
12964 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12966 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
12967 Specialization, Info, /*IsAddressOfFunction*/ true);
12968 Result != TemplateDeductionResult::Success) {
12969 // Make a note of the failed deduction for diagnostics.
12970 FailedCandidates.addCandidate()
12971 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12972 MakeDeductionFailureInfo(Context, Result, Info));
12973 return false;
12974 }
12975
12976 // Template argument deduction ensures that we have an exact match or
12977 // compatible pointer-to-function arguments that would be adjusted by ICS.
12978 // This function template specicalization works.
12980 Context.getCanonicalType(Specialization->getType()),
12981 Context.getCanonicalType(TargetFunctionType)));
12982
12984 return false;
12985
12986 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12987 return true;
12988 }
12989
12990 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12991 const DeclAccessPair& CurAccessFunPair) {
12992 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12993 // Skip non-static functions when converting to pointer, and static
12994 // when converting to member pointer.
12995 bool CanConvertToFunctionPointer =
12996 Method->isStatic() || Method->isExplicitObjectMemberFunction();
12997 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
12998 return false;
12999 }
13000 else if (TargetTypeIsNonStaticMemberFunction)
13001 return false;
13002
13003 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13004 if (S.getLangOpts().CUDA) {
13005 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13006 if (!(Caller && Caller->isImplicit()) &&
13007 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13008 return false;
13009 }
13010 if (FunDecl->isMultiVersion()) {
13011 const auto *TA = FunDecl->getAttr<TargetAttr>();
13012 if (TA && !TA->isDefaultVersion())
13013 return false;
13014 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13015 if (TVA && !TVA->isDefaultVersion())
13016 return false;
13017 }
13018
13019 // If any candidate has a placeholder return type, trigger its deduction
13020 // now.
13021 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13022 Complain)) {
13023 HasComplained |= Complain;
13024 return false;
13025 }
13026
13027 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13028 return false;
13029
13030 // If we're in C, we need to support types that aren't exactly identical.
13031 if (!S.getLangOpts().CPlusPlus ||
13032 candidateHasExactlyCorrectType(FunDecl)) {
13033 Matches.push_back(std::make_pair(
13034 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13035 FoundNonTemplateFunction = true;
13036 return true;
13037 }
13038 }
13039
13040 return false;
13041 }
13042
13043 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13044 bool Ret = false;
13045
13046 // If the overload expression doesn't have the form of a pointer to
13047 // member, don't try to convert it to a pointer-to-member type.
13048 if (IsInvalidFormOfPointerToMemberFunction())
13049 return false;
13050
13051 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13052 E = OvlExpr->decls_end();
13053 I != E; ++I) {
13054 // Look through any using declarations to find the underlying function.
13055 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13056
13057 // C++ [over.over]p3:
13058 // Non-member functions and static member functions match
13059 // targets of type "pointer-to-function" or "reference-to-function."
13060 // Nonstatic member functions match targets of
13061 // type "pointer-to-member-function."
13062 // Note that according to DR 247, the containing class does not matter.
13063 if (FunctionTemplateDecl *FunctionTemplate
13064 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13065 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13066 Ret = true;
13067 }
13068 // If we have explicit template arguments supplied, skip non-templates.
13069 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13070 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13071 Ret = true;
13072 }
13073 assert(Ret || Matches.empty());
13074 return Ret;
13075 }
13076
13077 void EliminateAllExceptMostSpecializedTemplate() {
13078 // [...] and any given function template specialization F1 is
13079 // eliminated if the set contains a second function template
13080 // specialization whose function template is more specialized
13081 // than the function template of F1 according to the partial
13082 // ordering rules of 14.5.5.2.
13083
13084 // The algorithm specified above is quadratic. We instead use a
13085 // two-pass algorithm (similar to the one used to identify the
13086 // best viable function in an overload set) that identifies the
13087 // best function template (if it exists).
13088
13089 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13090 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13091 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13092
13093 // TODO: It looks like FailedCandidates does not serve much purpose
13094 // here, since the no_viable diagnostic has index 0.
13096 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13097 SourceExpr->getBeginLoc(), S.PDiag(),
13098 S.PDiag(diag::err_addr_ovl_ambiguous)
13099 << Matches[0].second->getDeclName(),
13100 S.PDiag(diag::note_ovl_candidate)
13101 << (unsigned)oc_function << (unsigned)ocs_described_template,
13102 Complain, TargetFunctionType);
13103
13104 if (Result != MatchesCopy.end()) {
13105 // Make it the first and only element
13106 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13107 Matches[0].second = cast<FunctionDecl>(*Result);
13108 Matches.resize(1);
13109 } else
13110 HasComplained |= Complain;
13111 }
13112
13113 void EliminateAllTemplateMatches() {
13114 // [...] any function template specializations in the set are
13115 // eliminated if the set also contains a non-template function, [...]
13116 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13117 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13118 ++I;
13119 else {
13120 Matches[I] = Matches[--N];
13121 Matches.resize(N);
13122 }
13123 }
13124 }
13125
13126 void EliminateSuboptimalCudaMatches() {
13127 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13128 Matches);
13129 }
13130
13131public:
13132 void ComplainNoMatchesFound() const {
13133 assert(Matches.empty());
13134 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13135 << OvlExpr->getName() << TargetFunctionType
13136 << OvlExpr->getSourceRange();
13137 if (FailedCandidates.empty())
13138 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13139 /*TakingAddress=*/true);
13140 else {
13141 // We have some deduction failure messages. Use them to diagnose
13142 // the function templates, and diagnose the non-template candidates
13143 // normally.
13144 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13145 IEnd = OvlExpr->decls_end();
13146 I != IEnd; ++I)
13147 if (FunctionDecl *Fun =
13148 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13150 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13151 /*TakingAddress=*/true);
13152 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13153 }
13154 }
13155
13156 bool IsInvalidFormOfPointerToMemberFunction() const {
13157 return TargetTypeIsNonStaticMemberFunction &&
13158 !OvlExprInfo.HasFormOfMemberPointer;
13159 }
13160
13161 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13162 // TODO: Should we condition this on whether any functions might
13163 // have matched, or is it more appropriate to do that in callers?
13164 // TODO: a fixit wouldn't hurt.
13165 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13166 << TargetType << OvlExpr->getSourceRange();
13167 }
13168
13169 bool IsStaticMemberFunctionFromBoundPointer() const {
13170 return StaticMemberFunctionFromBoundPointer;
13171 }
13172
13173 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13174 S.Diag(OvlExpr->getBeginLoc(),
13175 diag::err_invalid_form_pointer_member_function)
13176 << OvlExpr->getSourceRange();
13177 }
13178
13179 void ComplainOfInvalidConversion() const {
13180 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13181 << OvlExpr->getName() << TargetType;
13182 }
13183
13184 void ComplainMultipleMatchesFound() const {
13185 assert(Matches.size() > 1);
13186 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13187 << OvlExpr->getName() << OvlExpr->getSourceRange();
13188 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13189 /*TakingAddress=*/true);
13190 }
13191
13192 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13193
13194 int getNumMatches() const { return Matches.size(); }
13195
13196 FunctionDecl* getMatchingFunctionDecl() const {
13197 if (Matches.size() != 1) return nullptr;
13198 return Matches[0].second;
13199 }
13200
13201 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13202 if (Matches.size() != 1) return nullptr;
13203 return &Matches[0].first;
13204 }
13205};
13206}
13207
13210 QualType TargetType,
13211 bool Complain,
13212 DeclAccessPair &FoundResult,
13213 bool *pHadMultipleCandidates) {
13214 assert(AddressOfExpr->getType() == Context.OverloadTy);
13215
13216 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13217 Complain);
13218 int NumMatches = Resolver.getNumMatches();
13219 FunctionDecl *Fn = nullptr;
13220 bool ShouldComplain = Complain && !Resolver.hasComplained();
13221 if (NumMatches == 0 && ShouldComplain) {
13222 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13223 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13224 else
13225 Resolver.ComplainNoMatchesFound();
13226 }
13227 else if (NumMatches > 1 && ShouldComplain)
13228 Resolver.ComplainMultipleMatchesFound();
13229 else if (NumMatches == 1) {
13230 Fn = Resolver.getMatchingFunctionDecl();
13231 assert(Fn);
13232 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13233 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13234 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13235 if (Complain) {
13236 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13237 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13238 else
13239 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13240 }
13241 }
13242
13243 if (pHadMultipleCandidates)
13244 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13245 return Fn;
13246}
13247
13251 OverloadExpr *Ovl = R.Expression;
13252 bool IsResultAmbiguous = false;
13253 FunctionDecl *Result = nullptr;
13254 DeclAccessPair DAP;
13255 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13256
13257 // Return positive for better, negative for worse, 0 for equal preference.
13258 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13259 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13260 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13261 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13262 };
13263
13264 // Don't use the AddressOfResolver because we're specifically looking for
13265 // cases where we have one overload candidate that lacks
13266 // enable_if/pass_object_size/...
13267 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13268 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13269 if (!FD)
13270 return nullptr;
13271
13273 continue;
13274
13275 // If we found a better result, update Result.
13276 auto FoundBetter = [&]() {
13277 IsResultAmbiguous = false;
13278 DAP = I.getPair();
13279 Result = FD;
13280 };
13281
13282 // We have more than one result - see if it is more constrained than the
13283 // previous one.
13284 if (Result) {
13285 // Check CUDA preference first. If the candidates have differennt CUDA
13286 // preference, choose the one with higher CUDA preference. Otherwise,
13287 // choose the one with more constraints.
13288 if (getLangOpts().CUDA) {
13289 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13290 // FD has different preference than Result.
13291 if (PreferenceByCUDA != 0) {
13292 // FD is more preferable than Result.
13293 if (PreferenceByCUDA > 0)
13294 FoundBetter();
13295 continue;
13296 }
13297 }
13298 // FD has the same CUDA prefernece than Result. Continue check
13299 // constraints.
13300 FunctionDecl *MoreConstrained = getMoreConstrainedFunction(FD, Result);
13301 if (MoreConstrained != FD) {
13302 if (!MoreConstrained) {
13303 IsResultAmbiguous = true;
13304 AmbiguousDecls.push_back(FD);
13305 }
13306 continue;
13307 }
13308 // FD is more constrained - replace Result with it.
13309 }
13310 FoundBetter();
13311 }
13312
13313 if (IsResultAmbiguous)
13314 return nullptr;
13315
13316 if (Result) {
13318 // We skipped over some ambiguous declarations which might be ambiguous with
13319 // the selected result.
13320 for (FunctionDecl *Skipped : AmbiguousDecls) {
13321 // If skipped candidate has different CUDA preference than the result,
13322 // there is no ambiguity. Otherwise check whether they have different
13323 // constraints.
13324 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13325 continue;
13326 if (!getMoreConstrainedFunction(Skipped, Result))
13327 return nullptr;
13328 }
13329 Pair = DAP;
13330 }
13331 return Result;
13332}
13333
13335 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13336 Expr *E = SrcExpr.get();
13337 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13338
13339 DeclAccessPair DAP;
13340 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
13341 if (!Found || Found->isCPUDispatchMultiVersion() ||
13342 Found->isCPUSpecificMultiVersion())
13343 return false;
13344
13345 // Emitting multiple diagnostics for a function that is both inaccessible and
13346 // unavailable is consistent with our behavior elsewhere. So, always check
13347 // for both.
13348 DiagnoseUseOfDecl(Found, E->getExprLoc());
13349 CheckAddressOfMemberAccess(E, DAP);
13350 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
13351 if (Res.isInvalid())
13352 return false;
13353 Expr *Fixed = Res.get();
13354 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13355 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
13356 else
13357 SrcExpr = Fixed;
13358 return true;
13359}
13360
13362 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13363 TemplateSpecCandidateSet *FailedTSC) {
13364 // C++ [over.over]p1:
13365 // [...] [Note: any redundant set of parentheses surrounding the
13366 // overloaded function name is ignored (5.1). ]
13367 // C++ [over.over]p1:
13368 // [...] The overloaded function name can be preceded by the &
13369 // operator.
13370
13371 // If we didn't actually find any template-ids, we're done.
13372 if (!ovl->hasExplicitTemplateArgs())
13373 return nullptr;
13374
13375 TemplateArgumentListInfo ExplicitTemplateArgs;
13376 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
13377
13378 // Look through all of the overloaded functions, searching for one
13379 // whose type matches exactly.
13380 FunctionDecl *Matched = nullptr;
13381 for (UnresolvedSetIterator I = ovl->decls_begin(),
13382 E = ovl->decls_end(); I != E; ++I) {
13383 // C++0x [temp.arg.explicit]p3:
13384 // [...] In contexts where deduction is done and fails, or in contexts
13385 // where deduction is not done, if a template argument list is
13386 // specified and it, along with any default template arguments,
13387 // identifies a single function template specialization, then the
13388 // template-id is an lvalue for the function template specialization.
13389 FunctionTemplateDecl *FunctionTemplate
13390 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
13391
13392 // C++ [over.over]p2:
13393 // If the name is a function template, template argument deduction is
13394 // done (14.8.2.2), and if the argument deduction succeeds, the
13395 // resulting template argument list is used to generate a single
13396 // function template specialization, which is added to the set of
13397 // overloaded functions considered.
13398 FunctionDecl *Specialization = nullptr;
13399 TemplateDeductionInfo Info(ovl->getNameLoc());
13401 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
13402 /*IsAddressOfFunction*/ true);
13404 // Make a note of the failed deduction for diagnostics.
13405 if (FailedTSC)
13406 FailedTSC->addCandidate().set(
13407 I.getPair(), FunctionTemplate->getTemplatedDecl(),
13408 MakeDeductionFailureInfo(Context, Result, Info));
13409 continue;
13410 }
13411
13412 assert(Specialization && "no specialization and no error?");
13413
13414 // Multiple matches; we can't resolve to a single declaration.
13415 if (Matched) {
13416 if (Complain) {
13417 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13418 << ovl->getName();
13419 NoteAllOverloadCandidates(ovl);
13420 }
13421 return nullptr;
13422 }
13423
13424 Matched = Specialization;
13425 if (FoundResult) *FoundResult = I.getPair();
13426 }
13427
13428 if (Matched &&
13429 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13430 return nullptr;
13431
13432 return Matched;
13433}
13434
13436 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13437 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13438 unsigned DiagIDForComplaining) {
13439 assert(SrcExpr.get()->getType() == Context.OverloadTy);
13440
13442
13443 DeclAccessPair found;
13444 ExprResult SingleFunctionExpression;
13445 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13446 ovl.Expression, /*complain*/ false, &found)) {
13447 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
13448 SrcExpr = ExprError();
13449 return true;
13450 }
13451
13452 // It is only correct to resolve to an instance method if we're
13453 // resolving a form that's permitted to be a pointer to member.
13454 // Otherwise we'll end up making a bound member expression, which
13455 // is illegal in all the contexts we resolve like this.
13456 if (!ovl.HasFormOfMemberPointer &&
13457 isa<CXXMethodDecl>(fn) &&
13458 cast<CXXMethodDecl>(fn)->isInstance()) {
13459 if (!complain) return false;
13460
13461 Diag(ovl.Expression->getExprLoc(),
13462 diag::err_bound_member_function)
13463 << 0 << ovl.Expression->getSourceRange();
13464
13465 // TODO: I believe we only end up here if there's a mix of
13466 // static and non-static candidates (otherwise the expression
13467 // would have 'bound member' type, not 'overload' type).
13468 // Ideally we would note which candidate was chosen and why
13469 // the static candidates were rejected.
13470 SrcExpr = ExprError();
13471 return true;
13472 }
13473
13474 // Fix the expression to refer to 'fn'.
13475 SingleFunctionExpression =
13476 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
13477
13478 // If desired, do function-to-pointer decay.
13479 if (doFunctionPointerConversion) {
13480 SingleFunctionExpression =
13481 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
13482 if (SingleFunctionExpression.isInvalid()) {
13483 SrcExpr = ExprError();
13484 return true;
13485 }
13486 }
13487 }
13488
13489 if (!SingleFunctionExpression.isUsable()) {
13490 if (complain) {
13491 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13492 << ovl.Expression->getName()
13493 << DestTypeForComplaining
13494 << OpRangeForComplaining
13496 NoteAllOverloadCandidates(SrcExpr.get());
13497
13498 SrcExpr = ExprError();
13499 return true;
13500 }
13501
13502 return false;
13503 }
13504
13505 SrcExpr = SingleFunctionExpression;
13506 return true;
13507}
13508
13509/// Add a single candidate to the overload set.
13511 DeclAccessPair FoundDecl,
13512 TemplateArgumentListInfo *ExplicitTemplateArgs,
13513 ArrayRef<Expr *> Args,
13514 OverloadCandidateSet &CandidateSet,
13515 bool PartialOverloading,
13516 bool KnownValid) {
13517 NamedDecl *Callee = FoundDecl.getDecl();
13518 if (isa<UsingShadowDecl>(Callee))
13519 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13520
13521 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13522 if (ExplicitTemplateArgs) {
13523 assert(!KnownValid && "Explicit template arguments?");
13524 return;
13525 }
13526 // Prevent ill-formed function decls to be added as overload candidates.
13527 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13528 return;
13529
13530 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13531 /*SuppressUserConversions=*/false,
13532 PartialOverloading);
13533 return;
13534 }
13535
13536 if (FunctionTemplateDecl *FuncTemplate
13537 = dyn_cast<FunctionTemplateDecl>(Callee)) {
13538 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13539 ExplicitTemplateArgs, Args, CandidateSet,
13540 /*SuppressUserConversions=*/false,
13541 PartialOverloading);
13542 return;
13543 }
13544
13545 assert(!KnownValid && "unhandled case in overloaded call candidate");
13546}
13547
13549 ArrayRef<Expr *> Args,
13550 OverloadCandidateSet &CandidateSet,
13551 bool PartialOverloading) {
13552
13553#ifndef NDEBUG
13554 // Verify that ArgumentDependentLookup is consistent with the rules
13555 // in C++0x [basic.lookup.argdep]p3:
13556 //
13557 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13558 // and let Y be the lookup set produced by argument dependent
13559 // lookup (defined as follows). If X contains
13560 //
13561 // -- a declaration of a class member, or
13562 //
13563 // -- a block-scope function declaration that is not a
13564 // using-declaration, or
13565 //
13566 // -- a declaration that is neither a function or a function
13567 // template
13568 //
13569 // then Y is empty.
13570
13571 if (ULE->requiresADL()) {
13573 E = ULE->decls_end(); I != E; ++I) {
13574 assert(!(*I)->getDeclContext()->isRecord());
13575 assert(isa<UsingShadowDecl>(*I) ||
13576 !(*I)->getDeclContext()->isFunctionOrMethod());
13577 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13578 }
13579 }
13580#endif
13581
13582 // It would be nice to avoid this copy.
13583 TemplateArgumentListInfo TABuffer;
13584 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13585 if (ULE->hasExplicitTemplateArgs()) {
13586 ULE->copyTemplateArgumentsInto(TABuffer);
13587 ExplicitTemplateArgs = &TABuffer;
13588 }
13589
13591 E = ULE->decls_end(); I != E; ++I)
13592 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13593 CandidateSet, PartialOverloading,
13594 /*KnownValid*/ true);
13595
13596 if (ULE->requiresADL())
13597 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13598 Args, ExplicitTemplateArgs,
13599 CandidateSet, PartialOverloading);
13600}
13601
13603 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13604 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13605 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13606 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13607 CandidateSet, false, /*KnownValid*/ false);
13608}
13609
13610/// Determine whether a declaration with the specified name could be moved into
13611/// a different namespace.
13613 switch (Name.getCXXOverloadedOperator()) {
13614 case OO_New: case OO_Array_New:
13615 case OO_Delete: case OO_Array_Delete:
13616 return false;
13617
13618 default:
13619 return true;
13620 }
13621}
13622
13623/// Attempt to recover from an ill-formed use of a non-dependent name in a
13624/// template, where the non-dependent name was declared after the template
13625/// was defined. This is common in code written for a compilers which do not
13626/// correctly implement two-stage name lookup.
13627///
13628/// Returns true if a viable candidate was found and a diagnostic was issued.
13630 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13632 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13633 CXXRecordDecl **FoundInClass = nullptr) {
13634 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13635 return false;
13636
13637 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13638 if (DC->isTransparentContext())
13639 continue;
13640
13641 SemaRef.LookupQualifiedName(R, DC);
13642
13643 if (!R.empty()) {
13645
13646 OverloadCandidateSet Candidates(FnLoc, CSK);
13647 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13648 Candidates);
13649
13652 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13653
13654 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13655 // We either found non-function declarations or a best viable function
13656 // at class scope. A class-scope lookup result disables ADL. Don't
13657 // look past this, but let the caller know that we found something that
13658 // either is, or might be, usable in this class.
13659 if (FoundInClass) {
13660 *FoundInClass = RD;
13661 if (OR == OR_Success) {
13662 R.clear();
13663 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13664 R.resolveKind();
13665 }
13666 }
13667 return false;
13668 }
13669
13670 if (OR != OR_Success) {
13671 // There wasn't a unique best function or function template.
13672 return false;
13673 }
13674
13675 // Find the namespaces where ADL would have looked, and suggest
13676 // declaring the function there instead.
13677 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13678 Sema::AssociatedClassSet AssociatedClasses;
13679 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13680 AssociatedNamespaces,
13681 AssociatedClasses);
13682 Sema::AssociatedNamespaceSet SuggestedNamespaces;
13684 DeclContext *Std = SemaRef.getStdNamespace();
13685 for (Sema::AssociatedNamespaceSet::iterator
13686 it = AssociatedNamespaces.begin(),
13687 end = AssociatedNamespaces.end(); it != end; ++it) {
13688 // Never suggest declaring a function within namespace 'std'.
13689 if (Std && Std->Encloses(*it))
13690 continue;
13691
13692 // Never suggest declaring a function within a namespace with a
13693 // reserved name, like __gnu_cxx.
13694 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13695 if (NS &&
13696 NS->getQualifiedNameAsString().find("__") != std::string::npos)
13697 continue;
13698
13699 SuggestedNamespaces.insert(*it);
13700 }
13701 }
13702
13703 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13704 << R.getLookupName();
13705 if (SuggestedNamespaces.empty()) {
13706 SemaRef.Diag(Best->Function->getLocation(),
13707 diag::note_not_found_by_two_phase_lookup)
13708 << R.getLookupName() << 0;
13709 } else if (SuggestedNamespaces.size() == 1) {
13710 SemaRef.Diag(Best->Function->getLocation(),
13711 diag::note_not_found_by_two_phase_lookup)
13712 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13713 } else {
13714 // FIXME: It would be useful to list the associated namespaces here,
13715 // but the diagnostics infrastructure doesn't provide a way to produce
13716 // a localized representation of a list of items.
13717 SemaRef.Diag(Best->Function->getLocation(),
13718 diag::note_not_found_by_two_phase_lookup)
13719 << R.getLookupName() << 2;
13720 }
13721
13722 // Try to recover by calling this function.
13723 return true;
13724 }
13725
13726 R.clear();
13727 }
13728
13729 return false;
13730}
13731
13732/// Attempt to recover from ill-formed use of a non-dependent operator in a
13733/// template, where the non-dependent operator was declared after the template
13734/// was defined.
13735///
13736/// Returns true if a viable candidate was found and a diagnostic was issued.
13737static bool
13739 SourceLocation OpLoc,
13740 ArrayRef<Expr *> Args) {
13741 DeclarationName OpName =
13743 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13744 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13746 /*ExplicitTemplateArgs=*/nullptr, Args);
13747}
13748
13749namespace {
13750class BuildRecoveryCallExprRAII {
13751 Sema &SemaRef;
13753
13754public:
13755 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13756 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13757 SemaRef.IsBuildingRecoveryCallExpr = true;
13758 }
13759
13760 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13761};
13762}
13763
13764/// Attempts to recover from a call where no functions were found.
13765///
13766/// This function will do one of three things:
13767/// * Diagnose, recover, and return a recovery expression.
13768/// * Diagnose, fail to recover, and return ExprError().
13769/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13770/// expected to diagnose as appropriate.
13771static ExprResult
13774 SourceLocation LParenLoc,
13776 SourceLocation RParenLoc,
13777 bool EmptyLookup, bool AllowTypoCorrection) {
13778 // Do not try to recover if it is already building a recovery call.
13779 // This stops infinite loops for template instantiations like
13780 //
13781 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13782 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13783 if (SemaRef.IsBuildingRecoveryCallExpr)
13784 return ExprResult();
13785 BuildRecoveryCallExprRAII RCE(SemaRef);
13786
13787 CXXScopeSpec SS;
13788 SS.Adopt(ULE->getQualifierLoc());
13789 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13790
13791 TemplateArgumentListInfo TABuffer;
13792 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13793 if (ULE->hasExplicitTemplateArgs()) {
13794 ULE->copyTemplateArgumentsInto(TABuffer);
13795 ExplicitTemplateArgs = &TABuffer;
13796 }
13797
13798 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13800 CXXRecordDecl *FoundInClass = nullptr;
13801 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13803 ExplicitTemplateArgs, Args, &FoundInClass)) {
13804 // OK, diagnosed a two-phase lookup issue.
13805 } else if (EmptyLookup) {
13806 // Try to recover from an empty lookup with typo correction.
13807 R.clear();
13808 NoTypoCorrectionCCC NoTypoValidator{};
13809 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13810 ExplicitTemplateArgs != nullptr,
13811 dyn_cast<MemberExpr>(Fn));
13812 CorrectionCandidateCallback &Validator =
13813 AllowTypoCorrection
13814 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13815 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13816 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13817 Args))
13818 return ExprError();
13819 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13820 // We found a usable declaration of the name in a dependent base of some
13821 // enclosing class.
13822 // FIXME: We should also explain why the candidates found by name lookup
13823 // were not viable.
13824 if (SemaRef.DiagnoseDependentMemberLookup(R))
13825 return ExprError();
13826 } else {
13827 // We had viable candidates and couldn't recover; let the caller diagnose
13828 // this.
13829 return ExprResult();
13830 }
13831
13832 // If we get here, we should have issued a diagnostic and formed a recovery
13833 // lookup result.
13834 assert(!R.empty() && "lookup results empty despite recovery");
13835
13836 // If recovery created an ambiguity, just bail out.
13837 if (R.isAmbiguous()) {
13839 return ExprError();
13840 }
13841
13842 // Build an implicit member call if appropriate. Just drop the
13843 // casts and such from the call, we don't really care.
13844 ExprResult NewFn = ExprError();
13845 if ((*R.begin())->isCXXClassMember())
13846 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13847 ExplicitTemplateArgs, S);
13848 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13849 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13850 ExplicitTemplateArgs);
13851 else
13852 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13853
13854 if (NewFn.isInvalid())
13855 return ExprError();
13856
13857 // This shouldn't cause an infinite loop because we're giving it
13858 // an expression with viable lookup results, which should never
13859 // end up here.
13860 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13861 MultiExprArg(Args.data(), Args.size()),
13862 RParenLoc);
13863}
13864
13867 MultiExprArg Args,
13868 SourceLocation RParenLoc,
13869 OverloadCandidateSet *CandidateSet,
13870 ExprResult *Result) {
13871#ifndef NDEBUG
13872 if (ULE->requiresADL()) {
13873 // To do ADL, we must have found an unqualified name.
13874 assert(!ULE->getQualifier() && "qualified name with ADL");
13875
13876 // We don't perform ADL for implicit declarations of builtins.
13877 // Verify that this was correctly set up.
13878 FunctionDecl *F;
13879 if (ULE->decls_begin() != ULE->decls_end() &&
13880 ULE->decls_begin() + 1 == ULE->decls_end() &&
13881 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13882 F->getBuiltinID() && F->isImplicit())
13883 llvm_unreachable("performing ADL for builtin");
13884
13885 // We don't perform ADL in C.
13886 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13887 }
13888#endif
13889
13890 UnbridgedCastsSet UnbridgedCasts;
13891 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13892 *Result = ExprError();
13893 return true;
13894 }
13895
13896 // Add the functions denoted by the callee to the set of candidate
13897 // functions, including those from argument-dependent lookup.
13898 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13899
13900 if (getLangOpts().MSVCCompat &&
13901 CurContext->isDependentContext() && !isSFINAEContext() &&
13902 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13903
13905 if (CandidateSet->empty() ||
13906 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13908 // In Microsoft mode, if we are inside a template class member function
13909 // then create a type dependent CallExpr. The goal is to postpone name
13910 // lookup to instantiation time to be able to search into type dependent
13911 // base classes.
13912 CallExpr *CE =
13913 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13914 RParenLoc, CurFPFeatureOverrides());
13916 *Result = CE;
13917 return true;
13918 }
13919 }
13920
13921 if (CandidateSet->empty())
13922 return false;
13923
13924 UnbridgedCasts.restore();
13925 return false;
13926}
13927
13928// Guess at what the return type for an unresolvable overload should be.
13931 std::optional<QualType> Result;
13932 // Adjust Type after seeing a candidate.
13933 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13934 if (!Candidate.Function)
13935 return;
13936 if (Candidate.Function->isInvalidDecl())
13937 return;
13938 QualType T = Candidate.Function->getReturnType();
13939 if (T.isNull())
13940 return;
13941 if (!Result)
13942 Result = T;
13943 else if (Result != T)
13944 Result = QualType();
13945 };
13946
13947 // Look for an unambiguous type from a progressively larger subset.
13948 // e.g. if types disagree, but all *viable* overloads return int, choose int.
13949 //
13950 // First, consider only the best candidate.
13951 if (Best && *Best != CS.end())
13952 ConsiderCandidate(**Best);
13953 // Next, consider only viable candidates.
13954 if (!Result)
13955 for (const auto &C : CS)
13956 if (C.Viable)
13957 ConsiderCandidate(C);
13958 // Finally, consider all candidates.
13959 if (!Result)
13960 for (const auto &C : CS)
13961 ConsiderCandidate(C);
13962
13963 if (!Result)
13964 return QualType();
13965 auto Value = *Result;
13966 if (Value.isNull() || Value->isUndeducedType())
13967 return QualType();
13968 return Value;
13969}
13970
13971/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13972/// the completed call expression. If overload resolution fails, emits
13973/// diagnostics and returns ExprError()
13976 SourceLocation LParenLoc,
13977 MultiExprArg Args,
13978 SourceLocation RParenLoc,
13979 Expr *ExecConfig,
13980 OverloadCandidateSet *CandidateSet,
13982 OverloadingResult OverloadResult,
13983 bool AllowTypoCorrection) {
13984 switch (OverloadResult) {
13985 case OR_Success: {
13986 FunctionDecl *FDecl = (*Best)->Function;
13987 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13988 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13989 return ExprError();
13990 ExprResult Res =
13991 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13992 if (Res.isInvalid())
13993 return ExprError();
13994 return SemaRef.BuildResolvedCallExpr(
13995 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
13996 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
13997 }
13998
13999 case OR_No_Viable_Function: {
14000 if (*Best != CandidateSet->end() &&
14001 CandidateSet->getKind() ==
14003 if (CXXMethodDecl *M =
14004 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14006 CandidateSet->NoteCandidates(
14008 Fn->getBeginLoc(),
14009 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14010 SemaRef, OCD_AmbiguousCandidates, Args);
14011 return ExprError();
14012 }
14013 }
14014
14015 // Try to recover by looking for viable functions which the user might
14016 // have meant to call.
14017 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14018 Args, RParenLoc,
14019 CandidateSet->empty(),
14020 AllowTypoCorrection);
14021 if (Recovery.isInvalid() || Recovery.isUsable())
14022 return Recovery;
14023
14024 // If the user passes in a function that we can't take the address of, we
14025 // generally end up emitting really bad error messages. Here, we attempt to
14026 // emit better ones.
14027 for (const Expr *Arg : Args) {
14028 if (!Arg->getType()->isFunctionType())
14029 continue;
14030 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14031 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14032 if (FD &&
14033 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14034 Arg->getExprLoc()))
14035 return ExprError();
14036 }
14037 }
14038
14039 CandidateSet->NoteCandidates(
14041 Fn->getBeginLoc(),
14042 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14043 << ULE->getName() << Fn->getSourceRange()),
14044 SemaRef, OCD_AllCandidates, Args);
14045 break;
14046 }
14047
14048 case OR_Ambiguous:
14049 CandidateSet->NoteCandidates(
14050 PartialDiagnosticAt(Fn->getBeginLoc(),
14051 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14052 << ULE->getName() << Fn->getSourceRange()),
14053 SemaRef, OCD_AmbiguousCandidates, Args);
14054 break;
14055
14056 case OR_Deleted: {
14057 FunctionDecl *FDecl = (*Best)->Function;
14058 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14059 Fn->getSourceRange(), ULE->getName(),
14060 *CandidateSet, FDecl, Args);
14061
14062 // We emitted an error for the unavailable/deleted function call but keep
14063 // the call in the AST.
14064 ExprResult Res =
14065 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14066 if (Res.isInvalid())
14067 return ExprError();
14068 return SemaRef.BuildResolvedCallExpr(
14069 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14070 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14071 }
14072 }
14073
14074 // Overload resolution failed, try to recover.
14075 SmallVector<Expr *, 8> SubExprs = {Fn};
14076 SubExprs.append(Args.begin(), Args.end());
14077 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14078 chooseRecoveryType(*CandidateSet, Best));
14079}
14080
14083 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14084 if (I->Viable &&
14085 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14086 I->Viable = false;
14087 I->FailureKind = ovl_fail_addr_not_available;
14088 }
14089 }
14090}
14091
14094 SourceLocation LParenLoc,
14095 MultiExprArg Args,
14096 SourceLocation RParenLoc,
14097 Expr *ExecConfig,
14098 bool AllowTypoCorrection,
14099 bool CalleesAddressIsTaken) {
14100 OverloadCandidateSet CandidateSet(
14101 Fn->getExprLoc(), CalleesAddressIsTaken
14104 ExprResult result;
14105
14106 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14107 &result))
14108 return result;
14109
14110 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14111 // functions that aren't addressible are considered unviable.
14112 if (CalleesAddressIsTaken)
14113 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14114
14116 OverloadingResult OverloadResult =
14117 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14118
14119 // Model the case with a call to a templated function whose definition
14120 // encloses the call and whose return type contains a placeholder type as if
14121 // the UnresolvedLookupExpr was type-dependent.
14122 if (OverloadResult == OR_Success) {
14123 const FunctionDecl *FDecl = Best->Function;
14124 if (FDecl && FDecl->isTemplateInstantiation() &&
14125 FDecl->getReturnType()->isUndeducedType()) {
14126 if (const auto *TP =
14127 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14128 TP && TP->willHaveBody()) {
14129 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14130 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14131 }
14132 }
14133 }
14134
14135 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14136 ExecConfig, &CandidateSet, &Best,
14137 OverloadResult, AllowTypoCorrection);
14138}
14139
14143 const UnresolvedSetImpl &Fns,
14144 bool PerformADL) {
14146 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14147 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14148}
14149
14151 CXXConversionDecl *Method,
14152 bool HadMultipleCandidates) {
14153 // Convert the expression to match the conversion function's implicit object
14154 // parameter.
14155 ExprResult Exp;
14156 if (Method->isExplicitObjectMemberFunction())
14157 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14158 else
14159 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14160 FoundDecl, Method);
14161 if (Exp.isInvalid())
14162 return true;
14163
14164 if (Method->getParent()->isLambda() &&
14166 // This is a lambda conversion to block pointer; check if the argument
14167 // was a LambdaExpr.
14168 Expr *SubE = E;
14169 auto *CE = dyn_cast<CastExpr>(SubE);
14170 if (CE && CE->getCastKind() == CK_NoOp)
14171 SubE = CE->getSubExpr();
14172 SubE = SubE->IgnoreParens();
14173 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14174 SubE = BE->getSubExpr();
14175 if (isa<LambdaExpr>(SubE)) {
14176 // For the conversion to block pointer on a lambda expression, we
14177 // construct a special BlockLiteral instead; this doesn't really make
14178 // a difference in ARC, but outside of ARC the resulting block literal
14179 // follows the normal lifetime rules for block literals instead of being
14180 // autoreleased.
14181 PushExpressionEvaluationContext(
14182 ExpressionEvaluationContext::PotentiallyEvaluated);
14183 ExprResult BlockExp = BuildBlockForLambdaConversion(
14184 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14185 PopExpressionEvaluationContext();
14186
14187 // FIXME: This note should be produced by a CodeSynthesisContext.
14188 if (BlockExp.isInvalid())
14189 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14190 return BlockExp;
14191 }
14192 }
14193 CallExpr *CE;
14194 QualType ResultType = Method->getReturnType();
14196 ResultType = ResultType.getNonLValueExprType(Context);
14197 if (Method->isExplicitObjectMemberFunction()) {
14198 ExprResult FnExpr =
14199 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14200 HadMultipleCandidates, E->getBeginLoc());
14201 if (FnExpr.isInvalid())
14202 return ExprError();
14203 Expr *ObjectParam = Exp.get();
14204 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14205 ResultType, VK, Exp.get()->getEndLoc(),
14206 CurFPFeatureOverrides());
14207 } else {
14208 MemberExpr *ME =
14209 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14211 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14212 HadMultipleCandidates, DeclarationNameInfo(),
14214
14215 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14216 Exp.get()->getEndLoc(),
14217 CurFPFeatureOverrides());
14218 }
14219
14220 if (CheckFunctionCall(Method, CE,
14221 Method->getType()->castAs<FunctionProtoType>()))
14222 return ExprError();
14223
14224 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14225}
14226
14229 const UnresolvedSetImpl &Fns,
14230 Expr *Input, bool PerformADL) {
14232 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14234 // TODO: provide better source location info.
14235 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14236
14237 if (checkPlaceholderForOverload(*this, Input))
14238 return ExprError();
14239
14240 Expr *Args[2] = { Input, nullptr };
14241 unsigned NumArgs = 1;
14242
14243 // For post-increment and post-decrement, add the implicit '0' as
14244 // the second argument, so that we know this is a post-increment or
14245 // post-decrement.
14246 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14247 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14248 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14249 SourceLocation());
14250 NumArgs = 2;
14251 }
14252
14253 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14254
14255 if (Input->isTypeDependent()) {
14257 // [C++26][expr.unary.op][expr.pre.incr]
14258 // The * operator yields an lvalue of type
14259 // The pre/post increment operators yied an lvalue.
14260 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14261 VK = VK_LValue;
14262
14263 if (Fns.empty())
14264 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14265 OK_Ordinary, OpLoc, false,
14266 CurFPFeatureOverrides());
14267
14268 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14269 ExprResult Fn = CreateUnresolvedLookupExpr(
14270 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14271 if (Fn.isInvalid())
14272 return ExprError();
14273 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14274 Context.DependentTy, VK_PRValue, OpLoc,
14275 CurFPFeatureOverrides());
14276 }
14277
14278 // Build an empty overload set.
14280
14281 // Add the candidates from the given function set.
14282 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14283
14284 // Add operator candidates that are member functions.
14285 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14286
14287 // Add candidates from ADL.
14288 if (PerformADL) {
14289 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14290 /*ExplicitTemplateArgs*/nullptr,
14291 CandidateSet);
14292 }
14293
14294 // Add builtin operator candidates.
14295 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14296
14297 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14298
14299 // Perform overload resolution.
14301 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14302 case OR_Success: {
14303 // We found a built-in operator or an overloaded operator.
14304 FunctionDecl *FnDecl = Best->Function;
14305
14306 if (FnDecl) {
14307 Expr *Base = nullptr;
14308 // We matched an overloaded operator. Build a call to that
14309 // operator.
14310
14311 // Convert the arguments.
14312 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14313 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
14314
14315 ExprResult InputInit;
14316 if (Method->isExplicitObjectMemberFunction())
14317 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14318 else
14319 InputInit = PerformImplicitObjectArgumentInitialization(
14320 Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14321 if (InputInit.isInvalid())
14322 return ExprError();
14323 Base = Input = InputInit.get();
14324 } else {
14325 // Convert the arguments.
14326 ExprResult InputInit
14327 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14328 Context,
14329 FnDecl->getParamDecl(0)),
14331 Input);
14332 if (InputInit.isInvalid())
14333 return ExprError();
14334 Input = InputInit.get();
14335 }
14336
14337 // Build the actual expression node.
14338 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
14339 Base, HadMultipleCandidates,
14340 OpLoc);
14341 if (FnExpr.isInvalid())
14342 return ExprError();
14343
14344 // Determine the result type.
14345 QualType ResultTy = FnDecl->getReturnType();
14347 ResultTy = ResultTy.getNonLValueExprType(Context);
14348
14349 Args[0] = Input;
14351 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
14352 CurFPFeatureOverrides(), Best->IsADLCandidate);
14353
14354 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
14355 return ExprError();
14356
14357 if (CheckFunctionCall(FnDecl, TheCall,
14358 FnDecl->getType()->castAs<FunctionProtoType>()))
14359 return ExprError();
14360 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
14361 } else {
14362 // We matched a built-in operator. Convert the arguments, then
14363 // break out so that we will build the appropriate built-in
14364 // operator node.
14365 ExprResult InputRes = PerformImplicitConversion(
14366 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
14368 if (InputRes.isInvalid())
14369 return ExprError();
14370 Input = InputRes.get();
14371 break;
14372 }
14373 }
14374
14376 // This is an erroneous use of an operator which can be overloaded by
14377 // a non-member function. Check for non-member operators which were
14378 // defined too late to be candidates.
14379 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
14380 // FIXME: Recover by calling the found function.
14381 return ExprError();
14382
14383 // No viable function; fall through to handling this as a
14384 // built-in operator, which will produce an error message for us.
14385 break;
14386
14387 case OR_Ambiguous:
14388 CandidateSet.NoteCandidates(
14389 PartialDiagnosticAt(OpLoc,
14390 PDiag(diag::err_ovl_ambiguous_oper_unary)
14392 << Input->getType() << Input->getSourceRange()),
14393 *this, OCD_AmbiguousCandidates, ArgsArray,
14394 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14395 return ExprError();
14396
14397 case OR_Deleted: {
14398 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14399 // object whose method was called. Later in NoteCandidates size of ArgsArray
14400 // is passed further and it eventually ends up compared to number of
14401 // function candidate parameters which never includes the object parameter,
14402 // so slice ArgsArray to make sure apples are compared to apples.
14403 StringLiteral *Msg = Best->Function->getDeletedMessage();
14404 CandidateSet.NoteCandidates(
14405 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14407 << (Msg != nullptr)
14408 << (Msg ? Msg->getString() : StringRef())
14409 << Input->getSourceRange()),
14410 *this, OCD_AllCandidates, ArgsArray.drop_front(),
14411 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14412 return ExprError();
14413 }
14414 }
14415
14416 // Either we found no viable overloaded operator or we matched a
14417 // built-in operator. In either case, fall through to trying to
14418 // build a built-in operation.
14419 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14420}
14421
14424 const UnresolvedSetImpl &Fns,
14425 ArrayRef<Expr *> Args, bool PerformADL) {
14426 SourceLocation OpLoc = CandidateSet.getLocation();
14427
14428 OverloadedOperatorKind ExtraOp =
14431 : OO_None;
14432
14433 // Add the candidates from the given function set. This also adds the
14434 // rewritten candidates using these functions if necessary.
14435 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14436
14437 // Add operator candidates that are member functions.
14438 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14439 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14440 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
14442
14443 // In C++20, also add any rewritten member candidates.
14444 if (ExtraOp) {
14445 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
14446 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
14447 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
14448 CandidateSet,
14450 }
14451
14452 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14453 // performed for an assignment operator (nor for operator[] nor operator->,
14454 // which don't get here).
14455 if (Op != OO_Equal && PerformADL) {
14457 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
14458 /*ExplicitTemplateArgs*/ nullptr,
14459 CandidateSet);
14460 if (ExtraOp) {
14461 DeclarationName ExtraOpName =
14462 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
14463 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
14464 /*ExplicitTemplateArgs*/ nullptr,
14465 CandidateSet);
14466 }
14467 }
14468
14469 // Add builtin operator candidates.
14470 //
14471 // FIXME: We don't add any rewritten candidates here. This is strictly
14472 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14473 // resulting in our selecting a rewritten builtin candidate. For example:
14474 //
14475 // enum class E { e };
14476 // bool operator!=(E, E) requires false;
14477 // bool k = E::e != E::e;
14478 //
14479 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14480 // it seems unreasonable to consider rewritten builtin candidates. A core
14481 // issue has been filed proposing to removed this requirement.
14482 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14483}
14484
14487 const UnresolvedSetImpl &Fns, Expr *LHS,
14488 Expr *RHS, bool PerformADL,
14489 bool AllowRewrittenCandidates,
14490 FunctionDecl *DefaultedFn) {
14491 Expr *Args[2] = { LHS, RHS };
14492 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14493
14494 if (!getLangOpts().CPlusPlus20)
14495 AllowRewrittenCandidates = false;
14496
14498
14499 // If either side is type-dependent, create an appropriate dependent
14500 // expression.
14501 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14502 if (Fns.empty()) {
14503 // If there are no functions to store, just build a dependent
14504 // BinaryOperator or CompoundAssignment.
14507 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
14508 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
14509 Context.DependentTy);
14511 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
14512 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
14513 }
14514
14515 // FIXME: save results of ADL from here?
14516 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14517 // TODO: provide better source location info in DNLoc component.
14519 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14520 ExprResult Fn = CreateUnresolvedLookupExpr(
14521 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
14522 if (Fn.isInvalid())
14523 return ExprError();
14524 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
14525 Context.DependentTy, VK_PRValue, OpLoc,
14526 CurFPFeatureOverrides());
14527 }
14528
14529 // If this is the .* operator, which is not overloadable, just
14530 // create a built-in binary operator.
14531 if (Opc == BO_PtrMemD) {
14532 auto CheckPlaceholder = [&](Expr *&Arg) {
14533 ExprResult Res = CheckPlaceholderExpr(Arg);
14534 if (Res.isUsable())
14535 Arg = Res.get();
14536 return !Res.isUsable();
14537 };
14538
14539 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14540 // expression that contains placeholders (in either the LHS or RHS).
14541 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14542 return ExprError();
14543 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14544 }
14545
14546 // Always do placeholder-like conversions on the RHS.
14547 if (checkPlaceholderForOverload(*this, Args[1]))
14548 return ExprError();
14549
14550 // Do placeholder-like conversion on the LHS; note that we should
14551 // not get here with a PseudoObject LHS.
14552 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14553 if (checkPlaceholderForOverload(*this, Args[0]))
14554 return ExprError();
14555
14556 // If this is the assignment operator, we only perform overload resolution
14557 // if the left-hand side is a class or enumeration type. This is actually
14558 // a hack. The standard requires that we do overload resolution between the
14559 // various built-in candidates, but as DR507 points out, this can lead to
14560 // problems. So we do it this way, which pretty much follows what GCC does.
14561 // Note that we go the traditional code path for compound assignment forms.
14562 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14563 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14564
14565 // Build the overload set.
14568 Op, OpLoc, AllowRewrittenCandidates));
14569 if (DefaultedFn)
14570 CandidateSet.exclude(DefaultedFn);
14571 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14572
14573 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14574
14575 // Perform overload resolution.
14577 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14578 case OR_Success: {
14579 // We found a built-in operator or an overloaded operator.
14580 FunctionDecl *FnDecl = Best->Function;
14581
14582 bool IsReversed = Best->isReversed();
14583 if (IsReversed)
14584 std::swap(Args[0], Args[1]);
14585
14586 if (FnDecl) {
14587
14588 if (FnDecl->isInvalidDecl())
14589 return ExprError();
14590
14591 Expr *Base = nullptr;
14592 // We matched an overloaded operator. Build a call to that
14593 // operator.
14594
14595 OverloadedOperatorKind ChosenOp =
14597
14598 // C++2a [over.match.oper]p9:
14599 // If a rewritten operator== candidate is selected by overload
14600 // resolution for an operator@, its return type shall be cv bool
14601 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14602 !FnDecl->getReturnType()->isBooleanType()) {
14603 bool IsExtension =
14605 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14606 : diag::err_ovl_rewrite_equalequal_not_bool)
14607 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14608 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14609 Diag(FnDecl->getLocation(), diag::note_declared_at);
14610 if (!IsExtension)
14611 return ExprError();
14612 }
14613
14614 if (AllowRewrittenCandidates && !IsReversed &&
14615 CandidateSet.getRewriteInfo().isReversible()) {
14616 // We could have reversed this operator, but didn't. Check if some
14617 // reversed form was a viable candidate, and if so, if it had a
14618 // better conversion for either parameter. If so, this call is
14619 // formally ambiguous, and allowing it is an extension.
14621 for (OverloadCandidate &Cand : CandidateSet) {
14622 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14623 allowAmbiguity(Context, Cand.Function, FnDecl)) {
14624 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14626 *this, OpLoc, Cand.Conversions[ArgIdx],
14627 Best->Conversions[ArgIdx]) ==
14629 AmbiguousWith.push_back(Cand.Function);
14630 break;
14631 }
14632 }
14633 }
14634 }
14635
14636 if (!AmbiguousWith.empty()) {
14637 bool AmbiguousWithSelf =
14638 AmbiguousWith.size() == 1 &&
14639 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14640 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14642 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14643 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14644 if (AmbiguousWithSelf) {
14645 Diag(FnDecl->getLocation(),
14646 diag::note_ovl_ambiguous_oper_binary_reversed_self);
14647 // Mark member== const or provide matching != to disallow reversed
14648 // args. Eg.
14649 // struct S { bool operator==(const S&); };
14650 // S()==S();
14651 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14652 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14653 !MD->isConst() &&
14654 !MD->hasCXXExplicitFunctionObjectParameter() &&
14655 Context.hasSameUnqualifiedType(
14656 MD->getFunctionObjectParameterType(),
14657 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14658 Context.hasSameUnqualifiedType(
14659 MD->getFunctionObjectParameterType(),
14660 Args[0]->getType()) &&
14661 Context.hasSameUnqualifiedType(
14662 MD->getFunctionObjectParameterType(),
14663 Args[1]->getType()))
14664 Diag(FnDecl->getLocation(),
14665 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14666 } else {
14667 Diag(FnDecl->getLocation(),
14668 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14669 for (auto *F : AmbiguousWith)
14670 Diag(F->getLocation(),
14671 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14672 }
14673 }
14674 }
14675
14676 // Check for nonnull = nullable.
14677 // This won't be caught in the arg's initialization: the parameter to
14678 // the assignment operator is not marked nonnull.
14679 if (Op == OO_Equal)
14680 diagnoseNullableToNonnullConversion(Args[0]->getType(),
14681 Args[1]->getType(), OpLoc);
14682
14683 // Convert the arguments.
14684 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14685 // Best->Access is only meaningful for class members.
14686 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14687
14688 ExprResult Arg0, Arg1;
14689 unsigned ParamIdx = 0;
14690 if (Method->isExplicitObjectMemberFunction()) {
14691 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
14692 ParamIdx = 1;
14693 } else {
14694 Arg0 = PerformImplicitObjectArgumentInitialization(
14695 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14696 }
14697 Arg1 = PerformCopyInitialization(
14699 Context, FnDecl->getParamDecl(ParamIdx)),
14700 SourceLocation(), Args[1]);
14701 if (Arg0.isInvalid() || Arg1.isInvalid())
14702 return ExprError();
14703
14704 Base = Args[0] = Arg0.getAs<Expr>();
14705 Args[1] = RHS = Arg1.getAs<Expr>();
14706 } else {
14707 // Convert the arguments.
14708 ExprResult Arg0 = PerformCopyInitialization(
14710 FnDecl->getParamDecl(0)),
14711 SourceLocation(), Args[0]);
14712 if (Arg0.isInvalid())
14713 return ExprError();
14714
14715 ExprResult Arg1 =
14716 PerformCopyInitialization(
14718 FnDecl->getParamDecl(1)),
14719 SourceLocation(), Args[1]);
14720 if (Arg1.isInvalid())
14721 return ExprError();
14722 Args[0] = LHS = Arg0.getAs<Expr>();
14723 Args[1] = RHS = Arg1.getAs<Expr>();
14724 }
14725
14726 // Build the actual expression node.
14727 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14728 Best->FoundDecl, Base,
14729 HadMultipleCandidates, OpLoc);
14730 if (FnExpr.isInvalid())
14731 return ExprError();
14732
14733 // Determine the result type.
14734 QualType ResultTy = FnDecl->getReturnType();
14736 ResultTy = ResultTy.getNonLValueExprType(Context);
14737
14738 CallExpr *TheCall;
14739 ArrayRef<const Expr *> ArgsArray(Args, 2);
14740 const Expr *ImplicitThis = nullptr;
14741
14742 // We always create a CXXOperatorCallExpr, even for explicit object
14743 // members; CodeGen should take care not to emit the this pointer.
14745 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14746 CurFPFeatureOverrides(), Best->IsADLCandidate);
14747
14748 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
14749 Method && Method->isImplicitObjectMemberFunction()) {
14750 // Cut off the implicit 'this'.
14751 ImplicitThis = ArgsArray[0];
14752 ArgsArray = ArgsArray.slice(1);
14753 }
14754
14755 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14756 FnDecl))
14757 return ExprError();
14758
14759 if (Op == OO_Equal) {
14760 // Check for a self move.
14761 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14762 // lifetime check.
14763 checkExprLifetime(*this, AssignedEntity{Args[0]}, Args[1]);
14764 }
14765 if (ImplicitThis) {
14766 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14767 QualType ThisTypeFromDecl = Context.getPointerType(
14768 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
14769
14770 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14771 ThisTypeFromDecl);
14772 }
14773
14774 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14775 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14776 VariadicDoesNotApply);
14777
14778 ExprResult R = MaybeBindToTemporary(TheCall);
14779 if (R.isInvalid())
14780 return ExprError();
14781
14782 R = CheckForImmediateInvocation(R, FnDecl);
14783 if (R.isInvalid())
14784 return ExprError();
14785
14786 // For a rewritten candidate, we've already reversed the arguments
14787 // if needed. Perform the rest of the rewrite now.
14788 if ((Best->RewriteKind & CRK_DifferentOperator) ||
14789 (Op == OO_Spaceship && IsReversed)) {
14790 if (Op == OO_ExclaimEqual) {
14791 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14792 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14793 } else {
14794 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14795 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14796 Expr *ZeroLiteral =
14797 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14798
14801 Ctx.Entity = FnDecl;
14802 pushCodeSynthesisContext(Ctx);
14803
14804 R = CreateOverloadedBinOp(
14805 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14806 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14807 /*AllowRewrittenCandidates=*/false);
14808
14809 popCodeSynthesisContext();
14810 }
14811 if (R.isInvalid())
14812 return ExprError();
14813 } else {
14814 assert(ChosenOp == Op && "unexpected operator name");
14815 }
14816
14817 // Make a note in the AST if we did any rewriting.
14818 if (Best->RewriteKind != CRK_None)
14819 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14820
14821 return R;
14822 } else {
14823 // We matched a built-in operator. Convert the arguments, then
14824 // break out so that we will build the appropriate built-in
14825 // operator node.
14826 ExprResult ArgsRes0 = PerformImplicitConversion(
14827 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14829 if (ArgsRes0.isInvalid())
14830 return ExprError();
14831 Args[0] = ArgsRes0.get();
14832
14833 ExprResult ArgsRes1 = PerformImplicitConversion(
14834 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14836 if (ArgsRes1.isInvalid())
14837 return ExprError();
14838 Args[1] = ArgsRes1.get();
14839 break;
14840 }
14841 }
14842
14843 case OR_No_Viable_Function: {
14844 // C++ [over.match.oper]p9:
14845 // If the operator is the operator , [...] and there are no
14846 // viable functions, then the operator is assumed to be the
14847 // built-in operator and interpreted according to clause 5.
14848 if (Opc == BO_Comma)
14849 break;
14850
14851 // When defaulting an 'operator<=>', we can try to synthesize a three-way
14852 // compare result using '==' and '<'.
14853 if (DefaultedFn && Opc == BO_Cmp) {
14854 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14855 Args[1], DefaultedFn);
14856 if (E.isInvalid() || E.isUsable())
14857 return E;
14858 }
14859
14860 // For class as left operand for assignment or compound assignment
14861 // operator do not fall through to handling in built-in, but report that
14862 // no overloaded assignment operator found
14864 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14865 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14866 Args, OpLoc);
14867 DeferDiagsRAII DDR(*this,
14868 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14869 if (Args[0]->getType()->isRecordType() &&
14870 Opc >= BO_Assign && Opc <= BO_OrAssign) {
14871 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14873 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14874 if (Args[0]->getType()->isIncompleteType()) {
14875 Diag(OpLoc, diag::note_assign_lhs_incomplete)
14876 << Args[0]->getType()
14877 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14878 }
14879 } else {
14880 // This is an erroneous use of an operator which can be overloaded by
14881 // a non-member function. Check for non-member operators which were
14882 // defined too late to be candidates.
14883 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14884 // FIXME: Recover by calling the found function.
14885 return ExprError();
14886
14887 // No viable function; try to create a built-in operation, which will
14888 // produce an error. Then, show the non-viable candidates.
14889 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14890 }
14891 assert(Result.isInvalid() &&
14892 "C++ binary operator overloading is missing candidates!");
14893 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14894 return Result;
14895 }
14896
14897 case OR_Ambiguous:
14898 CandidateSet.NoteCandidates(
14899 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14901 << Args[0]->getType()
14902 << Args[1]->getType()
14903 << Args[0]->getSourceRange()
14904 << Args[1]->getSourceRange()),
14906 OpLoc);
14907 return ExprError();
14908
14909 case OR_Deleted: {
14910 if (isImplicitlyDeleted(Best->Function)) {
14911 FunctionDecl *DeletedFD = Best->Function;
14912 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
14913 if (DFK.isSpecialMember()) {
14914 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
14915 << Args[0]->getType()
14916 << llvm::to_underlying(DFK.asSpecialMember());
14917 } else {
14918 assert(DFK.isComparison());
14919 Diag(OpLoc, diag::err_ovl_deleted_comparison)
14920 << Args[0]->getType() << DeletedFD;
14921 }
14922
14923 // The user probably meant to call this special member. Just
14924 // explain why it's deleted.
14925 NoteDeletedFunction(DeletedFD);
14926 return ExprError();
14927 }
14928
14929 StringLiteral *Msg = Best->Function->getDeletedMessage();
14930 CandidateSet.NoteCandidates(
14932 OpLoc,
14933 PDiag(diag::err_ovl_deleted_oper)
14934 << getOperatorSpelling(Best->Function->getDeclName()
14935 .getCXXOverloadedOperator())
14936 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
14937 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
14939 OpLoc);
14940 return ExprError();
14941 }
14942 }
14943
14944 // We matched a built-in operator; build it.
14945 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14946}
14947
14949 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
14950 FunctionDecl *DefaultedFn) {
14951 const ComparisonCategoryInfo *Info =
14952 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
14953 // If we're not producing a known comparison category type, we can't
14954 // synthesize a three-way comparison. Let the caller diagnose this.
14955 if (!Info)
14956 return ExprResult((Expr*)nullptr);
14957
14958 // If we ever want to perform this synthesis more generally, we will need to
14959 // apply the temporary materialization conversion to the operands.
14960 assert(LHS->isGLValue() && RHS->isGLValue() &&
14961 "cannot use prvalue expressions more than once");
14962 Expr *OrigLHS = LHS;
14963 Expr *OrigRHS = RHS;
14964
14965 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14966 // each of them multiple times below.
14967 LHS = new (Context)
14968 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
14969 LHS->getObjectKind(), LHS);
14970 RHS = new (Context)
14971 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
14972 RHS->getObjectKind(), RHS);
14973
14974 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
14975 DefaultedFn);
14976 if (Eq.isInvalid())
14977 return ExprError();
14978
14979 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
14980 true, DefaultedFn);
14981 if (Less.isInvalid())
14982 return ExprError();
14983
14985 if (Info->isPartial()) {
14986 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14987 DefaultedFn);
14988 if (Greater.isInvalid())
14989 return ExprError();
14990 }
14991
14992 // Form the list of comparisons we're going to perform.
14993 struct Comparison {
14994 ExprResult Cmp;
14996 } Comparisons[4] =
15002 };
15003
15004 int I = Info->isPartial() ? 3 : 2;
15005
15006 // Combine the comparisons with suitable conditional expressions.
15008 for (; I >= 0; --I) {
15009 // Build a reference to the comparison category constant.
15010 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15011 // FIXME: Missing a constant for a comparison category. Diagnose this?
15012 if (!VI)
15013 return ExprResult((Expr*)nullptr);
15014 ExprResult ThisResult =
15015 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15016 if (ThisResult.isInvalid())
15017 return ExprError();
15018
15019 // Build a conditional unless this is the final case.
15020 if (Result.get()) {
15021 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15022 ThisResult.get(), Result.get());
15023 if (Result.isInvalid())
15024 return ExprError();
15025 } else {
15026 Result = ThisResult;
15027 }
15028 }
15029
15030 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15031 // bind the OpaqueValueExprs before they're (repeatedly) used.
15032 Expr *SyntacticForm = BinaryOperator::Create(
15033 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15034 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15035 CurFPFeatureOverrides());
15036 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15037 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15038}
15039
15041 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15042 MultiExprArg Args, SourceLocation LParenLoc) {
15043
15044 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15045 unsigned NumParams = Proto->getNumParams();
15046 unsigned NumArgsSlots =
15047 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15048 // Build the full argument list for the method call (the implicit object
15049 // parameter is placed at the beginning of the list).
15050 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15051 bool IsError = false;
15052 // Initialize the implicit object parameter.
15053 // Check the argument types.
15054 for (unsigned i = 0; i != NumParams; i++) {
15055 Expr *Arg;
15056 if (i < Args.size()) {
15057 Arg = Args[i];
15058 ExprResult InputInit =
15060 S.Context, Method->getParamDecl(i)),
15061 SourceLocation(), Arg);
15062 IsError |= InputInit.isInvalid();
15063 Arg = InputInit.getAs<Expr>();
15064 } else {
15065 ExprResult DefArg =
15066 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15067 if (DefArg.isInvalid()) {
15068 IsError = true;
15069 break;
15070 }
15071 Arg = DefArg.getAs<Expr>();
15072 }
15073
15074 MethodArgs.push_back(Arg);
15075 }
15076 return IsError;
15077}
15078
15080 SourceLocation RLoc,
15081 Expr *Base,
15082 MultiExprArg ArgExpr) {
15084 Args.push_back(Base);
15085 for (auto *e : ArgExpr) {
15086 Args.push_back(e);
15087 }
15088 DeclarationName OpName =
15089 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15090
15091 SourceRange Range = ArgExpr.empty()
15092 ? SourceRange{}
15093 : SourceRange(ArgExpr.front()->getBeginLoc(),
15094 ArgExpr.back()->getEndLoc());
15095
15096 // If either side is type-dependent, create an appropriate dependent
15097 // expression.
15099
15100 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15101 // CHECKME: no 'operator' keyword?
15102 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15103 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15104 ExprResult Fn = CreateUnresolvedLookupExpr(
15105 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15106 if (Fn.isInvalid())
15107 return ExprError();
15108 // Can't add any actual overloads yet
15109
15110 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15111 Context.DependentTy, VK_PRValue, RLoc,
15112 CurFPFeatureOverrides());
15113 }
15114
15115 // Handle placeholders
15116 UnbridgedCastsSet UnbridgedCasts;
15117 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15118 return ExprError();
15119 }
15120 // Build an empty overload set.
15122
15123 // Subscript can only be overloaded as a member function.
15124
15125 // Add operator candidates that are member functions.
15126 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15127
15128 // Add builtin operator candidates.
15129 if (Args.size() == 2)
15130 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15131
15132 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15133
15134 // Perform overload resolution.
15136 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15137 case OR_Success: {
15138 // We found a built-in operator or an overloaded operator.
15139 FunctionDecl *FnDecl = Best->Function;
15140
15141 if (FnDecl) {
15142 // We matched an overloaded operator. Build a call to that
15143 // operator.
15144
15145 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15146
15147 // Convert the arguments.
15148 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15149 SmallVector<Expr *, 2> MethodArgs;
15150
15151 // Initialize the object parameter.
15152 if (Method->isExplicitObjectMemberFunction()) {
15153 ExprResult Res =
15154 InitializeExplicitObjectArgument(*this, Args[0], Method);
15155 if (Res.isInvalid())
15156 return ExprError();
15157 Args[0] = Res.get();
15158 ArgExpr = Args;
15159 } else {
15160 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15161 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15162 if (Arg0.isInvalid())
15163 return ExprError();
15164
15165 MethodArgs.push_back(Arg0.get());
15166 }
15167
15169 *this, MethodArgs, Method, ArgExpr, LLoc);
15170 if (IsError)
15171 return ExprError();
15172
15173 // Build the actual expression node.
15174 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15175 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15177 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15178 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15179 if (FnExpr.isInvalid())
15180 return ExprError();
15181
15182 // Determine the result type
15183 QualType ResultTy = FnDecl->getReturnType();
15185 ResultTy = ResultTy.getNonLValueExprType(Context);
15186
15188 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15189 CurFPFeatureOverrides());
15190
15191 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15192 return ExprError();
15193
15194 if (CheckFunctionCall(Method, TheCall,
15195 Method->getType()->castAs<FunctionProtoType>()))
15196 return ExprError();
15197
15198 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15199 FnDecl);
15200 } else {
15201 // We matched a built-in operator. Convert the arguments, then
15202 // break out so that we will build the appropriate built-in
15203 // operator node.
15204 ExprResult ArgsRes0 = PerformImplicitConversion(
15205 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15207 if (ArgsRes0.isInvalid())
15208 return ExprError();
15209 Args[0] = ArgsRes0.get();
15210
15211 ExprResult ArgsRes1 = PerformImplicitConversion(
15212 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15214 if (ArgsRes1.isInvalid())
15215 return ExprError();
15216 Args[1] = ArgsRes1.get();
15217
15218 break;
15219 }
15220 }
15221
15222 case OR_No_Viable_Function: {
15224 CandidateSet.empty()
15225 ? (PDiag(diag::err_ovl_no_oper)
15226 << Args[0]->getType() << /*subscript*/ 0
15227 << Args[0]->getSourceRange() << Range)
15228 : (PDiag(diag::err_ovl_no_viable_subscript)
15229 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15230 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15231 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15232 return ExprError();
15233 }
15234
15235 case OR_Ambiguous:
15236 if (Args.size() == 2) {
15237 CandidateSet.NoteCandidates(
15239 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15240 << "[]" << Args[0]->getType() << Args[1]->getType()
15241 << Args[0]->getSourceRange() << Range),
15242 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15243 } else {
15244 CandidateSet.NoteCandidates(
15246 PDiag(diag::err_ovl_ambiguous_subscript_call)
15247 << Args[0]->getType()
15248 << Args[0]->getSourceRange() << Range),
15249 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15250 }
15251 return ExprError();
15252
15253 case OR_Deleted: {
15254 StringLiteral *Msg = Best->Function->getDeletedMessage();
15255 CandidateSet.NoteCandidates(
15257 PDiag(diag::err_ovl_deleted_oper)
15258 << "[]" << (Msg != nullptr)
15259 << (Msg ? Msg->getString() : StringRef())
15260 << Args[0]->getSourceRange() << Range),
15261 *this, OCD_AllCandidates, Args, "[]", LLoc);
15262 return ExprError();
15263 }
15264 }
15265
15266 // We matched a built-in operator; build it.
15267 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15268}
15269
15271 SourceLocation LParenLoc,
15272 MultiExprArg Args,
15273 SourceLocation RParenLoc,
15274 Expr *ExecConfig, bool IsExecConfig,
15275 bool AllowRecovery) {
15276 assert(MemExprE->getType() == Context.BoundMemberTy ||
15277 MemExprE->getType() == Context.OverloadTy);
15278
15279 // Dig out the member expression. This holds both the object
15280 // argument and the member function we're referring to.
15281 Expr *NakedMemExpr = MemExprE->IgnoreParens();
15282
15283 // Determine whether this is a call to a pointer-to-member function.
15284 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
15285 assert(op->getType() == Context.BoundMemberTy);
15286 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15287
15288 QualType fnType =
15289 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15290
15291 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15292 QualType resultType = proto->getCallResultType(Context);
15294
15295 // Check that the object type isn't more qualified than the
15296 // member function we're calling.
15297 Qualifiers funcQuals = proto->getMethodQuals();
15298
15299 QualType objectType = op->getLHS()->getType();
15300 if (op->getOpcode() == BO_PtrMemI)
15301 objectType = objectType->castAs<PointerType>()->getPointeeType();
15302 Qualifiers objectQuals = objectType.getQualifiers();
15303
15304 Qualifiers difference = objectQuals - funcQuals;
15305 difference.removeObjCGCAttr();
15306 difference.removeAddressSpace();
15307 if (difference) {
15308 std::string qualsString = difference.getAsString();
15309 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15310 << fnType.getUnqualifiedType()
15311 << qualsString
15312 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15313 }
15314
15316 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
15317 CurFPFeatureOverrides(), proto->getNumParams());
15318
15319 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
15320 call, nullptr))
15321 return ExprError();
15322
15323 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15324 return ExprError();
15325
15326 if (CheckOtherCall(call, proto))
15327 return ExprError();
15328
15329 return MaybeBindToTemporary(call);
15330 }
15331
15332 // We only try to build a recovery expr at this level if we can preserve
15333 // the return type, otherwise we return ExprError() and let the caller
15334 // recover.
15335 auto BuildRecoveryExpr = [&](QualType Type) {
15336 if (!AllowRecovery)
15337 return ExprError();
15338 std::vector<Expr *> SubExprs = {MemExprE};
15339 llvm::append_range(SubExprs, Args);
15340 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15341 Type);
15342 };
15343 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
15344 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
15345 RParenLoc, CurFPFeatureOverrides());
15346
15347 UnbridgedCastsSet UnbridgedCasts;
15348 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15349 return ExprError();
15350
15351 MemberExpr *MemExpr;
15352 CXXMethodDecl *Method = nullptr;
15353 bool HadMultipleCandidates = false;
15354 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
15355 NestedNameSpecifier *Qualifier = nullptr;
15356 if (isa<MemberExpr>(NakedMemExpr)) {
15357 MemExpr = cast<MemberExpr>(NakedMemExpr);
15358 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
15359 FoundDecl = MemExpr->getFoundDecl();
15360 Qualifier = MemExpr->getQualifier();
15361 UnbridgedCasts.restore();
15362 } else {
15363 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
15364 Qualifier = UnresExpr->getQualifier();
15365
15366 QualType ObjectType = UnresExpr->getBaseType();
15367 Expr::Classification ObjectClassification
15369 : UnresExpr->getBase()->Classify(Context);
15370
15371 // Add overload candidates
15372 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15374
15375 // FIXME: avoid copy.
15376 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15377 if (UnresExpr->hasExplicitTemplateArgs()) {
15378 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15379 TemplateArgs = &TemplateArgsBuffer;
15380 }
15381
15383 E = UnresExpr->decls_end(); I != E; ++I) {
15384
15385 QualType ExplicitObjectType = ObjectType;
15386
15387 NamedDecl *Func = *I;
15388 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15389 if (isa<UsingShadowDecl>(Func))
15390 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
15391
15392 bool HasExplicitParameter = false;
15393 if (const auto *M = dyn_cast<FunctionDecl>(Func);
15394 M && M->hasCXXExplicitFunctionObjectParameter())
15395 HasExplicitParameter = true;
15396 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
15397 M &&
15398 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15399 HasExplicitParameter = true;
15400
15401 if (HasExplicitParameter)
15402 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15403
15404 // Microsoft supports direct constructor calls.
15405 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
15406 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
15407 CandidateSet,
15408 /*SuppressUserConversions*/ false);
15409 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
15410 // If explicit template arguments were provided, we can't call a
15411 // non-template member function.
15412 if (TemplateArgs)
15413 continue;
15414
15415 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
15416 ObjectClassification, Args, CandidateSet,
15417 /*SuppressUserConversions=*/false);
15418 } else {
15419 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
15420 I.getPair(), ActingDC, TemplateArgs,
15421 ExplicitObjectType, ObjectClassification,
15422 Args, CandidateSet,
15423 /*SuppressUserConversions=*/false);
15424 }
15425 }
15426
15427 HadMultipleCandidates = (CandidateSet.size() > 1);
15428
15429 DeclarationName DeclName = UnresExpr->getMemberName();
15430
15431 UnbridgedCasts.restore();
15432
15434 bool Succeeded = false;
15435 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
15436 Best)) {
15437 case OR_Success:
15438 Method = cast<CXXMethodDecl>(Best->Function);
15439 FoundDecl = Best->FoundDecl;
15440 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
15441 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
15442 break;
15443 // If FoundDecl is different from Method (such as if one is a template
15444 // and the other a specialization), make sure DiagnoseUseOfDecl is
15445 // called on both.
15446 // FIXME: This would be more comprehensively addressed by modifying
15447 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15448 // being used.
15449 if (Method != FoundDecl.getDecl() &&
15450 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
15451 break;
15452 Succeeded = true;
15453 break;
15454
15456 CandidateSet.NoteCandidates(
15458 UnresExpr->getMemberLoc(),
15459 PDiag(diag::err_ovl_no_viable_member_function_in_call)
15460 << DeclName << MemExprE->getSourceRange()),
15461 *this, OCD_AllCandidates, Args);
15462 break;
15463 case OR_Ambiguous:
15464 CandidateSet.NoteCandidates(
15465 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15466 PDiag(diag::err_ovl_ambiguous_member_call)
15467 << DeclName << MemExprE->getSourceRange()),
15468 *this, OCD_AmbiguousCandidates, Args);
15469 break;
15470 case OR_Deleted:
15471 DiagnoseUseOfDeletedFunction(
15472 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
15473 CandidateSet, Best->Function, Args, /*IsMember=*/true);
15474 break;
15475 }
15476 // Overload resolution fails, try to recover.
15477 if (!Succeeded)
15478 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
15479
15480 ExprResult Res =
15481 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15482 if (Res.isInvalid())
15483 return ExprError();
15484 MemExprE = Res.get();
15485
15486 // If overload resolution picked a static member
15487 // build a non-member call based on that function.
15488 if (Method->isStatic()) {
15489 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15490 ExecConfig, IsExecConfig);
15491 }
15492
15493 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
15494 }
15495
15496 QualType ResultType = Method->getReturnType();
15498 ResultType = ResultType.getNonLValueExprType(Context);
15499
15500 assert(Method && "Member call to something that isn't a method?");
15501 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15502
15503 CallExpr *TheCall = nullptr;
15505 if (Method->isExplicitObjectMemberFunction()) {
15506 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
15507 NewArgs))
15508 return ExprError();
15509
15510 // Build the actual expression node.
15511 ExprResult FnExpr =
15512 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15513 HadMultipleCandidates, MemExpr->getExprLoc());
15514 if (FnExpr.isInvalid())
15515 return ExprError();
15516
15517 TheCall =
15518 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
15519 CurFPFeatureOverrides(), Proto->getNumParams());
15520 } else {
15521 // Convert the object argument (for a non-static member function call).
15522 // We only need to do this if there was actually an overload; otherwise
15523 // it was done at lookup.
15524 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15525 MemExpr->getBase(), Qualifier, FoundDecl, Method);
15526 if (ObjectArg.isInvalid())
15527 return ExprError();
15528 MemExpr->setBase(ObjectArg.get());
15529 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
15530 RParenLoc, CurFPFeatureOverrides(),
15531 Proto->getNumParams());
15532 }
15533
15534 // Check for a valid return type.
15535 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
15536 TheCall, Method))
15537 return BuildRecoveryExpr(ResultType);
15538
15539 // Convert the rest of the arguments
15540 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
15541 RParenLoc))
15542 return BuildRecoveryExpr(ResultType);
15543
15544 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15545
15546 if (CheckFunctionCall(Method, TheCall, Proto))
15547 return ExprError();
15548
15549 // In the case the method to call was not selected by the overloading
15550 // resolution process, we still need to handle the enable_if attribute. Do
15551 // that here, so it will not hide previous -- and more relevant -- errors.
15552 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
15553 if (const EnableIfAttr *Attr =
15554 CheckEnableIf(Method, LParenLoc, Args, true)) {
15555 Diag(MemE->getMemberLoc(),
15556 diag::err_ovl_no_viable_member_function_in_call)
15557 << Method << Method->getSourceRange();
15558 Diag(Method->getLocation(),
15559 diag::note_ovl_candidate_disabled_by_function_cond_attr)
15560 << Attr->getCond()->getSourceRange() << Attr->getMessage();
15561 return ExprError();
15562 }
15563 }
15564
15565 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
15566 TheCall->getDirectCallee()->isPureVirtual()) {
15567 const FunctionDecl *MD = TheCall->getDirectCallee();
15568
15569 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
15570 MemExpr->performsVirtualDispatch(getLangOpts())) {
15571 Diag(MemExpr->getBeginLoc(),
15572 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15573 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15574 << MD->getParent();
15575
15576 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15577 if (getLangOpts().AppleKext)
15578 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15579 << MD->getParent() << MD->getDeclName();
15580 }
15581 }
15582
15583 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
15584 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15585 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15586 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
15587 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15588 MemExpr->getMemberLoc());
15589 }
15590
15591 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15592 TheCall->getDirectCallee());
15593}
15594
15597 SourceLocation LParenLoc,
15598 MultiExprArg Args,
15599 SourceLocation RParenLoc) {
15600 if (checkPlaceholderForOverload(*this, Obj))
15601 return ExprError();
15602 ExprResult Object = Obj;
15603
15604 UnbridgedCastsSet UnbridgedCasts;
15605 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15606 return ExprError();
15607
15608 assert(Object.get()->getType()->isRecordType() &&
15609 "Requires object type argument");
15610
15611 // C++ [over.call.object]p1:
15612 // If the primary-expression E in the function call syntax
15613 // evaluates to a class object of type "cv T", then the set of
15614 // candidate functions includes at least the function call
15615 // operators of T. The function call operators of T are obtained by
15616 // ordinary lookup of the name operator() in the context of
15617 // (E).operator().
15618 OverloadCandidateSet CandidateSet(LParenLoc,
15620 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
15621
15622 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15623 diag::err_incomplete_object_call, Object.get()))
15624 return true;
15625
15626 const auto *Record = Object.get()->getType()->castAs<RecordType>();
15627 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15628 LookupQualifiedName(R, Record->getDecl());
15629 R.suppressAccessDiagnostics();
15630
15631 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15632 Oper != OperEnd; ++Oper) {
15633 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
15634 Object.get()->Classify(Context), Args, CandidateSet,
15635 /*SuppressUserConversion=*/false);
15636 }
15637
15638 // When calling a lambda, both the call operator, and
15639 // the conversion operator to function pointer
15640 // are considered. But when constraint checking
15641 // on the call operator fails, it will also fail on the
15642 // conversion operator as the constraints are always the same.
15643 // As the user probably does not intend to perform a surrogate call,
15644 // we filter them out to produce better error diagnostics, ie to avoid
15645 // showing 2 failed overloads instead of one.
15646 bool IgnoreSurrogateFunctions = false;
15647 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15648 const OverloadCandidate &Candidate = *CandidateSet.begin();
15649 if (!Candidate.Viable &&
15651 IgnoreSurrogateFunctions = true;
15652 }
15653
15654 // C++ [over.call.object]p2:
15655 // In addition, for each (non-explicit in C++0x) conversion function
15656 // declared in T of the form
15657 //
15658 // operator conversion-type-id () cv-qualifier;
15659 //
15660 // where cv-qualifier is the same cv-qualification as, or a
15661 // greater cv-qualification than, cv, and where conversion-type-id
15662 // denotes the type "pointer to function of (P1,...,Pn) returning
15663 // R", or the type "reference to pointer to function of
15664 // (P1,...,Pn) returning R", or the type "reference to function
15665 // of (P1,...,Pn) returning R", a surrogate call function [...]
15666 // is also considered as a candidate function. Similarly,
15667 // surrogate call functions are added to the set of candidate
15668 // functions for each conversion function declared in an
15669 // accessible base class provided the function is not hidden
15670 // within T by another intervening declaration.
15671 const auto &Conversions =
15672 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15673 for (auto I = Conversions.begin(), E = Conversions.end();
15674 !IgnoreSurrogateFunctions && I != E; ++I) {
15675 NamedDecl *D = *I;
15676 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15677 if (isa<UsingShadowDecl>(D))
15678 D = cast<UsingShadowDecl>(D)->getTargetDecl();
15679
15680 // Skip over templated conversion functions; they aren't
15681 // surrogates.
15682 if (isa<FunctionTemplateDecl>(D))
15683 continue;
15684
15685 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15686 if (!Conv->isExplicit()) {
15687 // Strip the reference type (if any) and then the pointer type (if
15688 // any) to get down to what might be a function type.
15689 QualType ConvType = Conv->getConversionType().getNonReferenceType();
15690 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15691 ConvType = ConvPtrType->getPointeeType();
15692
15693 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15694 {
15695 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15696 Object.get(), Args, CandidateSet);
15697 }
15698 }
15699 }
15700
15701 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15702
15703 // Perform overload resolution.
15705 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15706 Best)) {
15707 case OR_Success:
15708 // Overload resolution succeeded; we'll build the appropriate call
15709 // below.
15710 break;
15711
15712 case OR_No_Viable_Function: {
15714 CandidateSet.empty()
15715 ? (PDiag(diag::err_ovl_no_oper)
15716 << Object.get()->getType() << /*call*/ 1
15717 << Object.get()->getSourceRange())
15718 : (PDiag(diag::err_ovl_no_viable_object_call)
15719 << Object.get()->getType() << Object.get()->getSourceRange());
15720 CandidateSet.NoteCandidates(
15721 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15722 OCD_AllCandidates, Args);
15723 break;
15724 }
15725 case OR_Ambiguous:
15726 if (!R.isAmbiguous())
15727 CandidateSet.NoteCandidates(
15728 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15729 PDiag(diag::err_ovl_ambiguous_object_call)
15730 << Object.get()->getType()
15731 << Object.get()->getSourceRange()),
15732 *this, OCD_AmbiguousCandidates, Args);
15733 break;
15734
15735 case OR_Deleted: {
15736 // FIXME: Is this diagnostic here really necessary? It seems that
15737 // 1. we don't have any tests for this diagnostic, and
15738 // 2. we already issue err_deleted_function_use for this later on anyway.
15739 StringLiteral *Msg = Best->Function->getDeletedMessage();
15740 CandidateSet.NoteCandidates(
15741 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15742 PDiag(diag::err_ovl_deleted_object_call)
15743 << Object.get()->getType() << (Msg != nullptr)
15744 << (Msg ? Msg->getString() : StringRef())
15745 << Object.get()->getSourceRange()),
15746 *this, OCD_AllCandidates, Args);
15747 break;
15748 }
15749 }
15750
15751 if (Best == CandidateSet.end())
15752 return true;
15753
15754 UnbridgedCasts.restore();
15755
15756 if (Best->Function == nullptr) {
15757 // Since there is no function declaration, this is one of the
15758 // surrogate candidates. Dig out the conversion function.
15759 CXXConversionDecl *Conv
15760 = cast<CXXConversionDecl>(
15761 Best->Conversions[0].UserDefined.ConversionFunction);
15762
15763 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15764 Best->FoundDecl);
15765 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15766 return ExprError();
15767 assert(Conv == Best->FoundDecl.getDecl() &&
15768 "Found Decl & conversion-to-functionptr should be same, right?!");
15769 // We selected one of the surrogate functions that converts the
15770 // object parameter to a function pointer. Perform the conversion
15771 // on the object argument, then let BuildCallExpr finish the job.
15772
15773 // Create an implicit member expr to refer to the conversion operator.
15774 // and then call it.
15775 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15776 Conv, HadMultipleCandidates);
15777 if (Call.isInvalid())
15778 return ExprError();
15779 // Record usage of conversion in an implicit cast.
15781 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15782 nullptr, VK_PRValue, CurFPFeatureOverrides());
15783
15784 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15785 }
15786
15787 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15788
15789 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15790 // that calls this method, using Object for the implicit object
15791 // parameter and passing along the remaining arguments.
15792 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15793
15794 // An error diagnostic has already been printed when parsing the declaration.
15795 if (Method->isInvalidDecl())
15796 return ExprError();
15797
15798 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15799 unsigned NumParams = Proto->getNumParams();
15800
15801 DeclarationNameInfo OpLocInfo(
15802 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15803 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15804 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15805 Obj, HadMultipleCandidates,
15806 OpLocInfo.getLoc(),
15807 OpLocInfo.getInfo());
15808 if (NewFn.isInvalid())
15809 return true;
15810
15811 SmallVector<Expr *, 8> MethodArgs;
15812 MethodArgs.reserve(NumParams + 1);
15813
15814 bool IsError = false;
15815
15816 // Initialize the object parameter.
15818 if (Method->isExplicitObjectMemberFunction()) {
15819 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
15820 } else {
15821 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15822 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15823 if (ObjRes.isInvalid())
15824 IsError = true;
15825 else
15826 Object = ObjRes;
15827 MethodArgs.push_back(Object.get());
15828 }
15829
15831 *this, MethodArgs, Method, Args, LParenLoc);
15832
15833 // If this is a variadic call, handle args passed through "...".
15834 if (Proto->isVariadic()) {
15835 // Promote the arguments (C99 6.5.2.2p7).
15836 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15837 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
15838 nullptr);
15839 IsError |= Arg.isInvalid();
15840 MethodArgs.push_back(Arg.get());
15841 }
15842 }
15843
15844 if (IsError)
15845 return true;
15846
15847 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15848
15849 // Once we've built TheCall, all of the expressions are properly owned.
15850 QualType ResultTy = Method->getReturnType();
15852 ResultTy = ResultTy.getNonLValueExprType(Context);
15853
15855 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
15856 CurFPFeatureOverrides());
15857
15858 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
15859 return true;
15860
15861 if (CheckFunctionCall(Method, TheCall, Proto))
15862 return true;
15863
15864 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15865}
15866
15869 bool *NoArrowOperatorFound) {
15870 assert(Base->getType()->isRecordType() &&
15871 "left-hand side must have class type");
15872
15874 return ExprError();
15875
15876 SourceLocation Loc = Base->getExprLoc();
15877
15878 // C++ [over.ref]p1:
15879 //
15880 // [...] An expression x->m is interpreted as (x.operator->())->m
15881 // for a class object x of type T if T::operator->() exists and if
15882 // the operator is selected as the best match function by the
15883 // overload resolution mechanism (13.3).
15884 DeclarationName OpName =
15885 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
15887
15888 if (RequireCompleteType(Loc, Base->getType(),
15889 diag::err_typecheck_incomplete_tag, Base))
15890 return ExprError();
15891
15892 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
15893 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
15895
15896 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15897 Oper != OperEnd; ++Oper) {
15898 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
15899 std::nullopt, CandidateSet,
15900 /*SuppressUserConversion=*/false);
15901 }
15902
15903 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15904
15905 // Perform overload resolution.
15907 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15908 case OR_Success:
15909 // Overload resolution succeeded; we'll build the call below.
15910 break;
15911
15912 case OR_No_Viable_Function: {
15913 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
15914 if (CandidateSet.empty()) {
15915 QualType BaseType = Base->getType();
15916 if (NoArrowOperatorFound) {
15917 // Report this specific error to the caller instead of emitting a
15918 // diagnostic, as requested.
15919 *NoArrowOperatorFound = true;
15920 return ExprError();
15921 }
15922 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
15923 << BaseType << Base->getSourceRange();
15924 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
15925 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
15926 << FixItHint::CreateReplacement(OpLoc, ".");
15927 }
15928 } else
15929 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15930 << "operator->" << Base->getSourceRange();
15931 CandidateSet.NoteCandidates(*this, Base, Cands);
15932 return ExprError();
15933 }
15934 case OR_Ambiguous:
15935 if (!R.isAmbiguous())
15936 CandidateSet.NoteCandidates(
15937 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
15938 << "->" << Base->getType()
15939 << Base->getSourceRange()),
15941 return ExprError();
15942
15943 case OR_Deleted: {
15944 StringLiteral *Msg = Best->Function->getDeletedMessage();
15945 CandidateSet.NoteCandidates(
15946 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15947 << "->" << (Msg != nullptr)
15948 << (Msg ? Msg->getString() : StringRef())
15949 << Base->getSourceRange()),
15950 *this, OCD_AllCandidates, Base);
15951 return ExprError();
15952 }
15953 }
15954
15955 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
15956
15957 // Convert the object parameter.
15958 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15959
15960 if (Method->isExplicitObjectMemberFunction()) {
15961 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
15962 if (R.isInvalid())
15963 return ExprError();
15964 Base = R.get();
15965 } else {
15966 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
15967 Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15968 if (BaseResult.isInvalid())
15969 return ExprError();
15970 Base = BaseResult.get();
15971 }
15972
15973 // Build the operator call.
15974 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15975 Base, HadMultipleCandidates, OpLoc);
15976 if (FnExpr.isInvalid())
15977 return ExprError();
15978
15979 QualType ResultTy = Method->getReturnType();
15981 ResultTy = ResultTy.getNonLValueExprType(Context);
15982
15983 CallExpr *TheCall =
15984 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
15985 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
15986
15987 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
15988 return ExprError();
15989
15990 if (CheckFunctionCall(Method, TheCall,
15991 Method->getType()->castAs<FunctionProtoType>()))
15992 return ExprError();
15993
15994 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15995}
15996
15998 DeclarationNameInfo &SuffixInfo,
15999 ArrayRef<Expr*> Args,
16000 SourceLocation LitEndLoc,
16001 TemplateArgumentListInfo *TemplateArgs) {
16002 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16003
16004 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16006 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16007 TemplateArgs);
16008
16009 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16010
16011 // Perform overload resolution. This will usually be trivial, but might need
16012 // to perform substitutions for a literal operator template.
16014 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16015 case OR_Success:
16016 case OR_Deleted:
16017 break;
16018
16020 CandidateSet.NoteCandidates(
16021 PartialDiagnosticAt(UDSuffixLoc,
16022 PDiag(diag::err_ovl_no_viable_function_in_call)
16023 << R.getLookupName()),
16024 *this, OCD_AllCandidates, Args);
16025 return ExprError();
16026
16027 case OR_Ambiguous:
16028 CandidateSet.NoteCandidates(
16029 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16030 << R.getLookupName()),
16031 *this, OCD_AmbiguousCandidates, Args);
16032 return ExprError();
16033 }
16034
16035 FunctionDecl *FD = Best->Function;
16036 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16037 nullptr, HadMultipleCandidates,
16038 SuffixInfo.getLoc(),
16039 SuffixInfo.getInfo());
16040 if (Fn.isInvalid())
16041 return true;
16042
16043 // Check the argument types. This should almost always be a no-op, except
16044 // that array-to-pointer decay is applied to string literals.
16045 Expr *ConvArgs[2];
16046 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16047 ExprResult InputInit = PerformCopyInitialization(
16049 SourceLocation(), Args[ArgIdx]);
16050 if (InputInit.isInvalid())
16051 return true;
16052 ConvArgs[ArgIdx] = InputInit.get();
16053 }
16054
16055 QualType ResultTy = FD->getReturnType();
16057 ResultTy = ResultTy.getNonLValueExprType(Context);
16058
16060 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16061 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16062
16063 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16064 return ExprError();
16065
16066 if (CheckFunctionCall(FD, UDL, nullptr))
16067 return ExprError();
16068
16069 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16070}
16071
16074 SourceLocation RangeLoc,
16075 const DeclarationNameInfo &NameInfo,
16076 LookupResult &MemberLookup,
16077 OverloadCandidateSet *CandidateSet,
16079 Scope *S = nullptr;
16080
16082 if (!MemberLookup.empty()) {
16083 ExprResult MemberRef =
16084 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16085 /*IsPtr=*/false, CXXScopeSpec(),
16086 /*TemplateKWLoc=*/SourceLocation(),
16087 /*FirstQualifierInScope=*/nullptr,
16088 MemberLookup,
16089 /*TemplateArgs=*/nullptr, S);
16090 if (MemberRef.isInvalid()) {
16091 *CallExpr = ExprError();
16092 return FRS_DiagnosticIssued;
16093 }
16094 *CallExpr =
16095 BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr);
16096 if (CallExpr->isInvalid()) {
16097 *CallExpr = ExprError();
16098 return FRS_DiagnosticIssued;
16099 }
16100 } else {
16101 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16103 NameInfo, UnresolvedSet<0>());
16104 if (FnR.isInvalid())
16105 return FRS_DiagnosticIssued;
16106 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16107
16108 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16109 CandidateSet, CallExpr);
16110 if (CandidateSet->empty() || CandidateSetError) {
16111 *CallExpr = ExprError();
16112 return FRS_NoViableFunction;
16113 }
16115 OverloadingResult OverloadResult =
16116 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16117
16118 if (OverloadResult == OR_No_Viable_Function) {
16119 *CallExpr = ExprError();
16120 return FRS_NoViableFunction;
16121 }
16122 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16123 Loc, nullptr, CandidateSet, &Best,
16124 OverloadResult,
16125 /*AllowTypoCorrection=*/false);
16126 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16127 *CallExpr = ExprError();
16128 return FRS_DiagnosticIssued;
16129 }
16130 }
16131 return FRS_Success;
16132}
16133
16135 FunctionDecl *Fn) {
16136 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16137 ExprResult SubExpr =
16138 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16139 if (SubExpr.isInvalid())
16140 return ExprError();
16141 if (SubExpr.get() == PE->getSubExpr())
16142 return PE;
16143
16144 return new (Context)
16145 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16146 }
16147
16148 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16149 ExprResult SubExpr =
16150 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16151 if (SubExpr.isInvalid())
16152 return ExprError();
16153 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16154 SubExpr.get()->getType()) &&
16155 "Implicit cast type cannot be determined from overload");
16156 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16157 if (SubExpr.get() == ICE->getSubExpr())
16158 return ICE;
16159
16160 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16161 SubExpr.get(), nullptr, ICE->getValueKind(),
16162 CurFPFeatureOverrides());
16163 }
16164
16165 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16166 if (!GSE->isResultDependent()) {
16167 ExprResult SubExpr =
16168 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16169 if (SubExpr.isInvalid())
16170 return ExprError();
16171 if (SubExpr.get() == GSE->getResultExpr())
16172 return GSE;
16173
16174 // Replace the resulting type information before rebuilding the generic
16175 // selection expression.
16176 ArrayRef<Expr *> A = GSE->getAssocExprs();
16177 SmallVector<Expr *, 4> AssocExprs(A);
16178 unsigned ResultIdx = GSE->getResultIndex();
16179 AssocExprs[ResultIdx] = SubExpr.get();
16180
16181 if (GSE->isExprPredicate())
16183 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16184 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16185 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16186 ResultIdx);
16188 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16189 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16190 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16191 ResultIdx);
16192 }
16193 // Rather than fall through to the unreachable, return the original generic
16194 // selection expression.
16195 return GSE;
16196 }
16197
16198 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16199 assert(UnOp->getOpcode() == UO_AddrOf &&
16200 "Can only take the address of an overloaded function");
16201 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16202 if (!Method->isImplicitObjectMemberFunction()) {
16203 // Do nothing: the address of static and
16204 // explicit object member functions is a (non-member) function pointer.
16205 } else {
16206 // Fix the subexpression, which really has to be an
16207 // UnresolvedLookupExpr holding an overloaded member function
16208 // or template.
16209 ExprResult SubExpr =
16210 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16211 if (SubExpr.isInvalid())
16212 return ExprError();
16213 if (SubExpr.get() == UnOp->getSubExpr())
16214 return UnOp;
16215
16216 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16217 SubExpr.get(), Method))
16218 return ExprError();
16219
16220 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16221 "fixed to something other than a decl ref");
16222 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16223 "fixed to a member ref with no nested name qualifier");
16224
16225 // We have taken the address of a pointer to member
16226 // function. Perform the computation here so that we get the
16227 // appropriate pointer to member type.
16228 QualType ClassType
16229 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
16230 QualType MemPtrType
16231 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
16232 // Under the MS ABI, lock down the inheritance model now.
16233 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16234 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16235
16236 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16237 MemPtrType, VK_PRValue, OK_Ordinary,
16238 UnOp->getOperatorLoc(), false,
16239 CurFPFeatureOverrides());
16240 }
16241 }
16242 ExprResult SubExpr =
16243 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16244 if (SubExpr.isInvalid())
16245 return ExprError();
16246 if (SubExpr.get() == UnOp->getSubExpr())
16247 return UnOp;
16248
16249 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16250 SubExpr.get());
16251 }
16252
16253 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16254 // FIXME: avoid copy.
16255 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16256 if (ULE->hasExplicitTemplateArgs()) {
16257 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16258 TemplateArgs = &TemplateArgsBuffer;
16259 }
16260
16261 QualType Type = Fn->getType();
16262 ExprValueKind ValueKind =
16263 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16264 ? VK_LValue
16265 : VK_PRValue;
16266
16267 // FIXME: Duplicated from BuildDeclarationNameExpr.
16268 if (unsigned BID = Fn->getBuiltinID()) {
16269 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16270 Type = Context.BuiltinFnTy;
16271 ValueKind = VK_PRValue;
16272 }
16273 }
16274
16275 DeclRefExpr *DRE = BuildDeclRefExpr(
16276 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16277 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16278 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16279 return DRE;
16280 }
16281
16282 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
16283 // FIXME: avoid copy.
16284 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16285 if (MemExpr->hasExplicitTemplateArgs()) {
16286 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16287 TemplateArgs = &TemplateArgsBuffer;
16288 }
16289
16290 Expr *Base;
16291
16292 // If we're filling in a static method where we used to have an
16293 // implicit member access, rewrite to a simple decl ref.
16294 if (MemExpr->isImplicitAccess()) {
16295 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16296 DeclRefExpr *DRE = BuildDeclRefExpr(
16297 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16298 MemExpr->getQualifierLoc(), Found.getDecl(),
16299 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16300 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16301 return DRE;
16302 } else {
16303 SourceLocation Loc = MemExpr->getMemberLoc();
16304 if (MemExpr->getQualifier())
16305 Loc = MemExpr->getQualifierLoc().getBeginLoc();
16306 Base =
16307 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
16308 }
16309 } else
16310 Base = MemExpr->getBase();
16311
16312 ExprValueKind valueKind;
16313 QualType type;
16314 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16315 valueKind = VK_LValue;
16316 type = Fn->getType();
16317 } else {
16318 valueKind = VK_PRValue;
16319 type = Context.BoundMemberTy;
16320 }
16321
16322 return BuildMemberExpr(
16323 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16324 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16325 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16326 type, valueKind, OK_Ordinary, TemplateArgs);
16327 }
16328
16329 llvm_unreachable("Invalid reference to overloaded function");
16330}
16331
16334 FunctionDecl *Fn) {
16335 return FixOverloadedFunctionReference(E.get(), Found, Fn);
16336}
16337
16338bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16340 if (!PartialOverloading || !Function)
16341 return true;
16342 if (Function->isVariadic())
16343 return false;
16344 if (const auto *Proto =
16345 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16346 if (Proto->isTemplateVariadic())
16347 return false;
16348 if (auto *Pattern = Function->getTemplateInstantiationPattern())
16349 if (const auto *Proto =
16350 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16351 if (Proto->isTemplateVariadic())
16352 return false;
16353 return true;
16354}
16355
16357 DeclarationName Name,
16358 OverloadCandidateSet &CandidateSet,
16359 FunctionDecl *Fn, MultiExprArg Args,
16360 bool IsMember) {
16361 StringLiteral *Msg = Fn->getDeletedMessage();
16362 CandidateSet.NoteCandidates(
16363 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
16364 << IsMember << Name << (Msg != nullptr)
16365 << (Msg ? Msg->getString() : StringRef())
16366 << Range),
16367 *this, OCD_AllCandidates, Args);
16368}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3341
This file provides some common utility functions for processing Lambda related AST Constructs.
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:143
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:5854
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.
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 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 isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
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)
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
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, PackFold PackFold=PackFold::ParameterToArgument)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
Allows QualTypes to be sorted and hence used in maps and sets.
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:397
bool isFloat() const
Definition: APValue.h:402
bool isInt() const
Definition: APValue.h:401
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
APFloat & getFloat()
Definition: APValue.h:437
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2825
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:1128
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:1128
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.
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
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:664
QualType getRecordType(const RecordDecl *Decl) const
CanQualType FloatTy
Definition: ASTContext.h:1131
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:2628
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:2644
CanQualType DoubleTy
Definition: ASTContext.h:1131
CanQualType LongDoubleTy
Definition: ASTContext.h:1131
CanQualType Char16Ty
Definition: ASTContext.h:1126
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:1147
CanQualType NullPtrTy
Definition: ASTContext.h:1146
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:1637
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:662
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:797
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:1131
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:2325
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:1120
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:780
CanQualType Float128Ty
Definition: ASTContext.h:1131
CanQualType UnsignedLongTy
Definition: ASTContext.h:1129
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:2924
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
Definition: ASTContext.h:1325
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType BoundMemberTy
Definition: ASTContext.h:1147
CanQualType CharTy
Definition: ASTContext.h:1121
CanQualType IntTy
Definition: ASTContext.h:1128
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2210
CanQualType SignedCharTy
Definition: ASTContext.h:1128
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1147
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2117
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2675
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:2394
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1130
CanQualType BuiltinFnTy
Definition: ASTContext.h:1149
CanQualType VoidTy
Definition: ASTContext.h:1119
CanQualType UnsignedCharTy
Definition: ASTContext.h:1129
CanQualType UnsignedIntTy
Definition: ASTContext.h:1129
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1334
CanQualType UnknownAnyTy
Definition: ASTContext.h:1148
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1130
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1129
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:1615
CanQualType ShortTy
Definition: ASTContext.h:1128
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true)
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
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:1127
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:2205
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:779
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
Definition: ASTContext.h:1128
CanQualType WCharTy
Definition: ASTContext.h:1122
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
CanQualType Char8Ty
Definition: ASTContext.h:1125
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 an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3566
QualType getElementType() const
Definition: Type.h:3578
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7580
Attr - This represents one attribute.
Definition: Attr.h:42
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2181
StringRef getOpcodeStr() const
Definition: Expr.h:3926
bool isCompoundAssignmentOp() const
Definition: Expr.h:4004
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:4859
Pointer to a block type.
Definition: Type.h:3397
This class is used for builtin types like 'int'.
Definition: Type.h:3023
Kind getKind() const
Definition: Type.h:3071
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:188
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:2539
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2866
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2902
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2906
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:676
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
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:2493
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:2500
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2614
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2240
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2190
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2603
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2526
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2225
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2214
bool isStatic() const
Definition: DeclCXX.cpp:2224
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:612
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:1023
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1872
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:1633
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:132
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
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:1494
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3000
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition: Expr.h:3157
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:1508
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 isAtLeastAsQualifiedAs(CanQual< T > Other) const
Determines whether this canonical type is at least as qualified as the Other canonical type.
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:3134
QualType getElementType() const
Definition: Type.h:3144
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:4881
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3604
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:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2219
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1852
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2006
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:261
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
T * getAttr() const
Definition: DeclBase.h:580
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:600
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1178
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:296
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:249
bool isInvalidDecl() const
Definition: DeclBase.h:595
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:566
SourceLocation getLocation() const
Definition: DeclBase.h:446
DeclContext * getDeclContext()
Definition: DeclBase.h:455
AccessSpecifier getAccess() const
Definition: DeclBase.h:514
specific_attr_iterator< T > specific_attr_end() const
Definition: DeclBase.h:576
specific_attr_iterator< T > specific_attr_begin() const
Definition: DeclBase.h:571
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:908
bool hasAttr() const
Definition: DeclBase.h:584
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:789
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:807
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition: Diagnostic.h:746
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition: Diagnostic.h:731
OverloadsShown getShowOverloads() const
Definition: Diagnostic.h:722
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3844
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4049
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5991
EnumDecl * getDecl() const
Definition: Type.h:5998
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1901
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition: DeclCXX.h:1925
const Expr * getExpr() const
Definition: DeclCXX.h:1910
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition: DeclCXX.cpp:2182
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1447
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:3075
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:3066
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:3290
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4102
@ 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:3941
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:4113
Represents difference between two FPOptions values.
Definition: LangOptions.h:947
Represents a member of a struct/union/class.
Definition: Decl.h:3030
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
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:134
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:97
Represents a function declaration or definition.
Definition: Decl.h:1932
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2562
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3699
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4028
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3618
param_iterator param_end()
Definition: Decl.h:2659
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition: Decl.cpp:3522
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3717
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
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:4099
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4148
param_iterator param_begin()
Definition: Decl.h:2658
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3077
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:4223
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2465
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4164
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3300
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4092
unsigned getNumNonObjectParams() const
Definition: Decl.cpp:3721
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2395
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3294
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2310
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4381
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3965
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4252
bool isConsteval() const
Definition: Decl.h:2407
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition: Decl.cpp:3566
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:2734
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:3571
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3678
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2558
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5002
unsigned getNumParams() const
Definition: Type.h:5255
Qualifiers getMethodQuals() const
Definition: Type.h:5397
QualType getParamType(unsigned i) const
Definition: Type.h:5257
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5379
ArrayRef< QualType > param_types() const
Definition: Type.h:5411
Declaration of a template function.
Definition: DeclTemplate.h:957
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:4419
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4493
bool getNoReturn() const
Definition: Type.h:4467
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4308
ExtInfo getExtInfo() const
Definition: Type.h:4642
CallingConv getCallConv() const
Definition: Type.h:4641
QualType getReturnType() const
Definition: Type.h:4630
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4654
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:4493
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:3675
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
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:5039
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:5146
unsigned getNumInits() const
Definition: Expr.h:5069
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2477
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5085
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2495
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:977
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3472
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:649
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:485
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:3187
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3376
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3270
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition: Expr.h:3284
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3405
Expr * getBase() const
Definition: Expr.h:3264
void setBase(Expr *E)
Definition: Expr.h:3263
NestedNameSpecifier * getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition: Expr.h:3298
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1798
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3382
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:3274
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3508
QualType getPointeeType() const
Definition: Type.h:3524
const Type * getClass() const
Definition: Type.h:3538
Describes a module or submodule.
Definition: Module.h:105
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:244
This represents a decl that may have a name.
Definition: Decl.h:249
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
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:547
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:7343
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:7399
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition: Type.h:7488
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7457
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7411
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7451
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1799
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7463
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
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions=std::nullopt)
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition: Overload.h:1210
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
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:250
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2135
Represents a parameter to a function.
Definition: Decl.h:1722
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3187
QualType getPointeeType() const
Definition: Type.h:3197
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4953
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7834
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7828
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7839
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3476
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1232
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:7932
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7750
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7876
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7790
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:7951
QualType getCanonicalType() const
Definition: Type.h:7802
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7844
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1093
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:7922
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7823
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7871
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7796
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1339
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7782
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7690
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7697
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4356
bool hasAtomic() const
Definition: Type.h:845
bool hasRestrict() const
Definition: Type.h:844
QualifiersAndAtomic withVolatile()
Definition: Type.h:857
QualifiersAndAtomic withAtomic()
Definition: Type.h:864
bool hasVolatile() const
Definition: Type.h:842
The collection of all-type qualifiers we support.
Definition: Type.h:319
unsigned getCVRQualifiers() const
Definition: Type.h:475
GC getObjCGCAttr() const
Definition: Type.h:506
bool hasOnlyConst() const
Definition: Type.h:445
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:341
void removeObjCLifetime()
Definition: Type.h:538
bool hasConst() const
Definition: Type.h:444
void addRestrict()
Definition: Type.h:467
bool hasRestrict() const
Definition: Type.h:464
void removeObjCGCAttr()
Definition: Type.h:510
void removeUnaligned()
Definition: Type.h:502
void removeAddressSpace()
Definition: Type.h:583
void addConst()
Definition: Type.h:447
void setAddressSpace(LangAS space)
Definition: Type.h:578
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:695
bool hasVolatile() const
Definition: Type.h:454
bool hasObjCGCAttr() const
Definition: Type.h:505
ObjCLifetime getObjCLifetime() const
Definition: Type.h:532
std::string getAsString() const
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:732
LangAS getAddressSpace() const
Definition: Type.h:558
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:755
void addVolatile()
Definition: Type.h:457
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3490
Represents a struct/union/class.
Definition: Decl.h:4145
field_range fields() const
Definition: Decl.h:4351
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5965
RecordDecl * getDecl() const
Definition: Type.h:5975
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3428
QualType getPointeeType() const
Definition: Type.h:3446
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:136
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:372
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition: SemaCUDA.cpp:314
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:320
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:227
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:10056
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:5901
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5930
RAII class to control scope of DeferDiags.
Definition: Sema.h:9783
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:12099
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12129
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:493
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 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args=std::nullopt, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2446
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition: Sema.h:9799
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:9015
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:9027
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9023
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition: SemaInit.cpp:169
ExprResult 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:1124
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:10139
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:10142
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:10148
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:10146
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:1710
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:1567
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:962
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:557
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:1164
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:560
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:702
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:10502
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:9859
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:868
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:11802
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:84
const LangOptions & getLangOpts() const
Definition: Sema.h:553
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:6408
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:960
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:6659
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:9557
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:3175
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:14990
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:1097
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:7466
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:7599
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:7638
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:7617
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7601
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:7634
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:19762
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20717
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:13497
AssignmentAction
Definition: Sema.h:6495
@ AA_Converting
Definition: Sema.h:6499
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:5453
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=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7491
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:7528
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:14945
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3444
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:10023
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:10028
@ CCEK_Noexcept
Condition in a noexcept(bool) specifier.
Definition: Sema.h:10029
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:10027
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:10026
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:9801
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:965
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2387
DiagnosticsEngine & Diags
Definition: Sema.h:964
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9656
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:20914
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:9641
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:8293
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:350
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
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:338
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:1256
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:655
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:708
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:693
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
A template argument list.
Definition: DeclTemplate.h:244
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:394
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
TemplateDecl * getAsTemplateDecl() 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:220
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:6480
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition: Decl.h:3391
The base class of the type hierarchy.
Definition: Type.h:1829
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2434
bool isBlockPointerType() const
Definition: Type.h:8017
bool isVoidType() const
Definition: Type.h:8319
bool isBooleanType() const
Definition: Type.h:8447
bool isObjCBuiltinType() const
Definition: Type.h:8196
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2167
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:1899
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isIncompleteArrayType() const
Definition: Type.h:8083
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2146
bool isFloat16Type() const
Definition: Type.h:8328
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:677
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2071
bool isRValueReferenceType() const
Definition: Type.h:8029
bool isConstantArrayType() const
Definition: Type.h:8079
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8477
bool isArrayType() const
Definition: Type.h:8075
bool isCharType() const
Definition: Type.cpp:2089
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition: Type.h:8384
bool isArithmeticType() const
Definition: Type.cpp:2281
bool isPointerType() const
Definition: Type.h:8003
bool isArrayParameterType() const
Definition: Type.h:8091
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8359
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2483
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8607
bool isReferenceType() const
Definition: Type.h:8021
bool isEnumeralType() const
Definition: Type.h:8107
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2058
bool isObjCQualifiedIdType() const
Definition: Type.h:8166
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8434
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2125
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:8153
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2703
bool isLValueReferenceType() const
Definition: Type.h:8025
bool isBitIntType() const
Definition: Type.h:8241
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2695
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2338
bool isAnyComplexType() const
Definition: Type.h:8111
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8372
bool isHalfType() const
Definition: Type.h:8323
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:8301
bool isQueueT() const
Definition: Type.h:8222
bool isMemberPointerType() const
Definition: Type.h:8057
bool isObjCIdType() const
Definition: Type.h:8178
bool isMatrixType() const
Definition: Type.h:8133
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8453
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2439
bool isEventT() const
Definition: Type.h:8214
bool isBFloat16Type() const
Definition: Type.h:8340
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool isFunctionType() const
Definition: Type.h:7999
bool isObjCObjectPointerType() const
Definition: Type.h:8145
bool isVectorType() const
Definition: Type.h:8115
bool isObjCClassType() const
Definition: Type.h:8184
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2266
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2497
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:2196
bool isAnyPointerType() const
Definition: Type.h:8011
TypeClass getTypeClass() const
Definition: Type.h:2334
bool isSamplerT() const
Definition: Type.h:8210
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
bool isNullPtrType() const
Definition: Type.h:8352
bool isRecordType() const
Definition: Type.h:8103
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1429
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4916
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:1405
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h: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:420
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
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:950
QualType getType() const
Definition: Decl.h:678
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:33
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, APValue &Result)
Definition: Interp.h:276
void checkExprLifetime(Sema &SemaRef, const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for initializing the ent...
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
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:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:58
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:140
@ 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:1778
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1781
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1784
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition: Overload.h:215
@ ICR_Conversion
Conversion.
Definition: Overload.h:232
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition: Overload.h:244
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition: Overload.h:229
@ 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:247
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition: Overload.h:235
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition: Overload.h:241
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition: Overload.h:238
@ 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:251
@ 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
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.
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:403
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:1275
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:345
@ 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
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:1273
@ 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:5087
FunctionEffectsRef FunctionEffects
Definition: Type.h:5097
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5095
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:12673
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:12761
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:12793
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:10156
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7887
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.