1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides Sema routines for C++ overloading.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
39 using namespace clang;
42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
43 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44 return P->hasAttr<PassObjectSizeAttr>();
48 /// A convenience routine for creating a decayed reference to a function.
50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51 bool HadMultipleCandidates,
52 SourceLocation Loc = SourceLocation(),
53 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
54 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
56 // If FoundDecl is different from Fn (such as if one is a template
57 // and the other a specialization), make sure DiagnoseUseOfDecl is
59 // FIXME: This would be more comprehensively addressed by modifying
60 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
62 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
64 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65 S.ResolveExceptionSpec(Loc, FPT);
66 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
67 VK_LValue, Loc, LocInfo);
68 if (HadMultipleCandidates)
69 DRE->setHadMultipleCandidates(true);
71 S.MarkDeclRefReferenced(DRE);
72 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73 CK_FunctionToPointerDecay);
76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77 bool InOverloadResolution,
78 StandardConversionSequence &SCS,
80 bool AllowObjCWritebackConversion);
82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
84 bool InOverloadResolution,
85 StandardConversionSequence &SCS,
87 static OverloadingResult
88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89 UserDefinedConversionSequence& User,
90 OverloadCandidateSet& Conversions,
92 bool AllowObjCConversionOnExplicit);
95 static ImplicitConversionSequence::CompareKind
96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
100 static ImplicitConversionSequence::CompareKind
101 CompareQualificationConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
105 static ImplicitConversionSequence::CompareKind
106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
107 const StandardConversionSequence& SCS1,
108 const StandardConversionSequence& SCS2);
110 /// GetConversionRank - Retrieve the implicit conversion rank
111 /// corresponding to the given implicit conversion kind.
112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
113 static const ImplicitConversionRank
114 Rank[(int)ICK_Num_Conversion_Kinds] = {
135 ICR_Complex_Real_Conversion,
138 ICR_Writeback_Conversion,
139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140 // it was omitted by the patch that added
141 // ICK_Zero_Event_Conversion
143 ICR_C_Conversion_Extension
145 return Rank[(int)Kind];
148 /// GetImplicitConversionName - Return the name of this kind of
149 /// implicit conversion.
150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
155 "Function-to-pointer",
156 "Function pointer conversion",
158 "Integral promotion",
159 "Floating point promotion",
161 "Integral conversion",
162 "Floating conversion",
163 "Complex conversion",
164 "Floating-integral conversion",
165 "Pointer conversion",
166 "Pointer-to-member conversion",
167 "Boolean conversion",
168 "Compatible-types conversion",
169 "Derived-to-base conversion",
172 "Complex-real conversion",
173 "Block Pointer conversion",
174 "Transparent Union Conversion",
175 "Writeback conversion",
176 "OpenCL Zero Event Conversion",
177 "C specific type conversion",
178 "Incompatible pointer conversion"
183 /// StandardConversionSequence - Set the standard conversion
184 /// sequence to the identity conversion.
185 void StandardConversionSequence::setAsIdentityConversion() {
186 First = ICK_Identity;
187 Second = ICK_Identity;
188 Third = ICK_Identity;
189 DeprecatedStringLiteralToCharPtr = false;
190 QualificationIncludesObjCLifetime = false;
191 ReferenceBinding = false;
192 DirectBinding = false;
193 IsLvalueReference = true;
194 BindsToFunctionLvalue = false;
195 BindsToRvalue = false;
196 BindsImplicitObjectArgumentWithoutRefQualifier = false;
197 ObjCLifetimeConversionBinding = false;
198 CopyConstructor = nullptr;
201 /// getRank - Retrieve the rank of this standard conversion sequence
202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203 /// implicit conversions.
204 ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
215 /// isPointerConversionToBool - Determines whether this conversion is
216 /// a conversion of a pointer or pointer-to-member to bool. This is
217 /// used as part of the ranking of standard conversion sequences
218 /// (C++ 13.3.3.2p4).
219 bool StandardConversionSequence::isPointerConversionToBool() const {
220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
224 if (getToType(1)->isBooleanType() &&
225 (getFromType()->isPointerType() ||
226 getFromType()->isObjCObjectPointerType() ||
227 getFromType()->isBlockPointerType() ||
228 getFromType()->isNullPtrType() ||
229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
235 /// isPointerConversionToVoidPointer - Determines whether this
236 /// conversion is a conversion of a pointer to a void pointer. This is
237 /// used as part of the ranking of standard conversion sequences (C++
240 StandardConversionSequence::
241 isPointerConversionToVoidPointer(ASTContext& Context) const {
242 QualType FromType = getFromType();
243 QualType ToType = getToType(1);
245 // Note that FromType has not necessarily been transformed by the
246 // array-to-pointer implicit conversion, so check for its presence
247 // and redo the conversion to get a pointer.
248 if (First == ICK_Array_To_Pointer)
249 FromType = Context.getArrayDecayedType(FromType);
251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
253 return ToPtrType->getPointeeType()->isVoidType();
258 /// Skip any implicit casts which could be either part of a narrowing conversion
259 /// or after one in an implicit conversion.
260 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262 switch (ICE->getCastKind()) {
264 case CK_IntegralCast:
265 case CK_IntegralToBoolean:
266 case CK_IntegralToFloating:
267 case CK_BooleanToSignedIntegral:
268 case CK_FloatingToIntegral:
269 case CK_FloatingToBoolean:
270 case CK_FloatingCast:
271 Converted = ICE->getSubExpr();
282 /// Check if this standard conversion sequence represents a narrowing
283 /// conversion, according to C++11 [dcl.init.list]p7.
285 /// \param Ctx The AST context.
286 /// \param Converted The result of applying this standard conversion sequence.
287 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
288 /// value of the expression prior to the narrowing conversion.
289 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
290 /// type of the expression prior to the narrowing conversion.
292 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293 const Expr *Converted,
294 APValue &ConstantValue,
295 QualType &ConstantType) const {
296 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
298 // C++11 [dcl.init.list]p7:
299 // A narrowing conversion is an implicit conversion ...
300 QualType FromType = getToType(0);
301 QualType ToType = getToType(1);
303 // A conversion to an enumeration type is narrowing if the conversion to
304 // the underlying type is narrowing. This only arises for expressions of
305 // the form 'Enum{init}'.
306 if (auto *ET = ToType->getAs<EnumType>())
307 ToType = ET->getDecl()->getIntegerType();
310 // 'bool' is an integral type; dispatch to the right place to handle it.
311 case ICK_Boolean_Conversion:
312 if (FromType->isRealFloatingType())
313 goto FloatingIntegralConversion;
314 if (FromType->isIntegralOrUnscopedEnumerationType())
315 goto IntegralConversion;
316 // Boolean conversions can be from pointers and pointers to members
317 // [conv.bool], and those aren't considered narrowing conversions.
318 return NK_Not_Narrowing;
320 // -- from a floating-point type to an integer type, or
322 // -- from an integer type or unscoped enumeration type to a floating-point
323 // type, except where the source is a constant expression and the actual
324 // value after conversion will fit into the target type and will produce
325 // the original value when converted back to the original type, or
326 case ICK_Floating_Integral:
327 FloatingIntegralConversion:
328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329 return NK_Type_Narrowing;
330 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331 llvm::APSInt IntConstantValue;
332 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334 // If it's value-dependent, we can't tell whether it's narrowing.
335 if (Initializer->isValueDependent())
336 return NK_Dependent_Narrowing;
339 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
340 // Convert the integer to the floating type.
341 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
342 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
343 llvm::APFloat::rmNearestTiesToEven);
345 llvm::APSInt ConvertedValue = IntConstantValue;
347 Result.convertToInteger(ConvertedValue,
348 llvm::APFloat::rmTowardZero, &ignored);
349 // If the resulting value is different, this was a narrowing conversion.
350 if (IntConstantValue != ConvertedValue) {
351 ConstantValue = APValue(IntConstantValue);
352 ConstantType = Initializer->getType();
353 return NK_Constant_Narrowing;
356 // Variables are always narrowings.
357 return NK_Variable_Narrowing;
360 return NK_Not_Narrowing;
362 // -- from long double to double or float, or from double to float, except
363 // where the source is a constant expression and the actual value after
364 // conversion is within the range of values that can be represented (even
365 // if it cannot be represented exactly), or
366 case ICK_Floating_Conversion:
367 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
368 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
369 // FromType is larger than ToType.
370 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
372 // If it's value-dependent, we can't tell whether it's narrowing.
373 if (Initializer->isValueDependent())
374 return NK_Dependent_Narrowing;
376 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
378 assert(ConstantValue.isFloat());
379 llvm::APFloat FloatVal = ConstantValue.getFloat();
380 // Convert the source value into the target type.
382 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
383 Ctx.getFloatTypeSemantics(ToType),
384 llvm::APFloat::rmNearestTiesToEven, &ignored);
385 // If there was no overflow, the source value is within the range of
386 // values that can be represented.
387 if (ConvertStatus & llvm::APFloat::opOverflow) {
388 ConstantType = Initializer->getType();
389 return NK_Constant_Narrowing;
392 return NK_Variable_Narrowing;
395 return NK_Not_Narrowing;
397 // -- from an integer type or unscoped enumeration type to an integer type
398 // that cannot represent all the values of the original type, except where
399 // the source is a constant expression and the actual value after
400 // conversion will fit into the target type and will produce the original
401 // value when converted back to the original type.
402 case ICK_Integral_Conversion:
403 IntegralConversion: {
404 assert(FromType->isIntegralOrUnscopedEnumerationType());
405 assert(ToType->isIntegralOrUnscopedEnumerationType());
406 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
407 const unsigned FromWidth = Ctx.getIntWidth(FromType);
408 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
409 const unsigned ToWidth = Ctx.getIntWidth(ToType);
411 if (FromWidth > ToWidth ||
412 (FromWidth == ToWidth && FromSigned != ToSigned) ||
413 (FromSigned && !ToSigned)) {
414 // Not all values of FromType can be represented in ToType.
415 llvm::APSInt InitializerValue;
416 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
418 // If it's value-dependent, we can't tell whether it's narrowing.
419 if (Initializer->isValueDependent())
420 return NK_Dependent_Narrowing;
422 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
423 // Such conversions on variables are always narrowing.
424 return NK_Variable_Narrowing;
426 bool Narrowing = false;
427 if (FromWidth < ToWidth) {
428 // Negative -> unsigned is narrowing. Otherwise, more bits is never
430 if (InitializerValue.isSigned() && InitializerValue.isNegative())
433 // Add a bit to the InitializerValue so we don't have to worry about
434 // signed vs. unsigned comparisons.
435 InitializerValue = InitializerValue.extend(
436 InitializerValue.getBitWidth() + 1);
437 // Convert the initializer to and from the target width and signed-ness.
438 llvm::APSInt ConvertedValue = InitializerValue;
439 ConvertedValue = ConvertedValue.trunc(ToWidth);
440 ConvertedValue.setIsSigned(ToSigned);
441 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
442 ConvertedValue.setIsSigned(InitializerValue.isSigned());
443 // If the result is different, this was a narrowing conversion.
444 if (ConvertedValue != InitializerValue)
448 ConstantType = Initializer->getType();
449 ConstantValue = APValue(InitializerValue);
450 return NK_Constant_Narrowing;
453 return NK_Not_Narrowing;
457 // Other kinds of conversions are not narrowings.
458 return NK_Not_Narrowing;
462 /// dump - Print this standard conversion sequence to standard
463 /// error. Useful for debugging overloading issues.
464 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
465 raw_ostream &OS = llvm::errs();
466 bool PrintedSomething = false;
467 if (First != ICK_Identity) {
468 OS << GetImplicitConversionName(First);
469 PrintedSomething = true;
472 if (Second != ICK_Identity) {
473 if (PrintedSomething) {
476 OS << GetImplicitConversionName(Second);
478 if (CopyConstructor) {
479 OS << " (by copy constructor)";
480 } else if (DirectBinding) {
481 OS << " (direct reference binding)";
482 } else if (ReferenceBinding) {
483 OS << " (reference binding)";
485 PrintedSomething = true;
488 if (Third != ICK_Identity) {
489 if (PrintedSomething) {
492 OS << GetImplicitConversionName(Third);
493 PrintedSomething = true;
496 if (!PrintedSomething) {
497 OS << "No conversions required";
501 /// dump - Print this user-defined conversion sequence to standard
502 /// error. Useful for debugging overloading issues.
503 void UserDefinedConversionSequence::dump() const {
504 raw_ostream &OS = llvm::errs();
505 if (Before.First || Before.Second || Before.Third) {
509 if (ConversionFunction)
510 OS << '\'' << *ConversionFunction << '\'';
512 OS << "aggregate initialization";
513 if (After.First || After.Second || After.Third) {
519 /// dump - Print this implicit conversion sequence to standard
520 /// error. Useful for debugging overloading issues.
521 void ImplicitConversionSequence::dump() const {
522 raw_ostream &OS = llvm::errs();
523 if (isStdInitializerListElement())
524 OS << "Worst std::initializer_list element conversion: ";
525 switch (ConversionKind) {
526 case StandardConversion:
527 OS << "Standard conversion: ";
530 case UserDefinedConversion:
531 OS << "User-defined conversion: ";
534 case EllipsisConversion:
535 OS << "Ellipsis conversion";
537 case AmbiguousConversion:
538 OS << "Ambiguous conversion";
541 OS << "Bad conversion";
548 void AmbiguousConversionSequence::construct() {
549 new (&conversions()) ConversionSet();
552 void AmbiguousConversionSequence::destruct() {
553 conversions().~ConversionSet();
557 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
558 FromTypePtr = O.FromTypePtr;
559 ToTypePtr = O.ToTypePtr;
560 new (&conversions()) ConversionSet(O.conversions());
564 // Structure used by DeductionFailureInfo to store
565 // template argument information.
566 struct DFIArguments {
567 TemplateArgument FirstArg;
568 TemplateArgument SecondArg;
570 // Structure used by DeductionFailureInfo to store
571 // template parameter and template argument information.
572 struct DFIParamWithArguments : DFIArguments {
573 TemplateParameter Param;
575 // Structure used by DeductionFailureInfo to store template argument
576 // information and the index of the problematic call argument.
577 struct DFIDeducedMismatchArgs : DFIArguments {
578 TemplateArgumentList *TemplateArgs;
579 unsigned CallArgIndex;
583 /// \brief Convert from Sema's representation of template deduction information
584 /// to the form used in overload-candidate information.
586 clang::MakeDeductionFailureInfo(ASTContext &Context,
587 Sema::TemplateDeductionResult TDK,
588 TemplateDeductionInfo &Info) {
589 DeductionFailureInfo Result;
590 Result.Result = static_cast<unsigned>(TDK);
591 Result.HasDiagnostic = false;
593 case Sema::TDK_Invalid:
594 case Sema::TDK_InstantiationDepth:
595 case Sema::TDK_TooManyArguments:
596 case Sema::TDK_TooFewArguments:
597 case Sema::TDK_MiscellaneousDeductionFailure:
598 case Sema::TDK_CUDATargetMismatch:
599 Result.Data = nullptr;
602 case Sema::TDK_Incomplete:
603 case Sema::TDK_InvalidExplicitArguments:
604 Result.Data = Info.Param.getOpaqueValue();
607 case Sema::TDK_DeducedMismatch:
608 case Sema::TDK_DeducedMismatchNested: {
609 // FIXME: Should allocate from normal heap so that we can free this later.
610 auto *Saved = new (Context) DFIDeducedMismatchArgs;
611 Saved->FirstArg = Info.FirstArg;
612 Saved->SecondArg = Info.SecondArg;
613 Saved->TemplateArgs = Info.take();
614 Saved->CallArgIndex = Info.CallArgIndex;
619 case Sema::TDK_NonDeducedMismatch: {
620 // FIXME: Should allocate from normal heap so that we can free this later.
621 DFIArguments *Saved = new (Context) DFIArguments;
622 Saved->FirstArg = Info.FirstArg;
623 Saved->SecondArg = Info.SecondArg;
628 case Sema::TDK_Inconsistent:
629 case Sema::TDK_Underqualified: {
630 // FIXME: Should allocate from normal heap so that we can free this later.
631 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
632 Saved->Param = Info.Param;
633 Saved->FirstArg = Info.FirstArg;
634 Saved->SecondArg = Info.SecondArg;
639 case Sema::TDK_SubstitutionFailure:
640 Result.Data = Info.take();
641 if (Info.hasSFINAEDiagnostic()) {
642 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643 SourceLocation(), PartialDiagnostic::NullDiagnostic());
644 Info.takeSFINAEDiagnostic(*Diag);
645 Result.HasDiagnostic = true;
649 case Sema::TDK_Success:
650 case Sema::TDK_NonDependentConversionFailure:
651 llvm_unreachable("not a deduction failure");
657 void DeductionFailureInfo::Destroy() {
658 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
659 case Sema::TDK_Success:
660 case Sema::TDK_Invalid:
661 case Sema::TDK_InstantiationDepth:
662 case Sema::TDK_Incomplete:
663 case Sema::TDK_TooManyArguments:
664 case Sema::TDK_TooFewArguments:
665 case Sema::TDK_InvalidExplicitArguments:
666 case Sema::TDK_CUDATargetMismatch:
667 case Sema::TDK_NonDependentConversionFailure:
670 case Sema::TDK_Inconsistent:
671 case Sema::TDK_Underqualified:
672 case Sema::TDK_DeducedMismatch:
673 case Sema::TDK_DeducedMismatchNested:
674 case Sema::TDK_NonDeducedMismatch:
675 // FIXME: Destroy the data?
679 case Sema::TDK_SubstitutionFailure:
680 // FIXME: Destroy the template argument list?
682 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
683 Diag->~PartialDiagnosticAt();
684 HasDiagnostic = false;
689 case Sema::TDK_MiscellaneousDeductionFailure:
694 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
696 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
700 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
701 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702 case Sema::TDK_Success:
703 case Sema::TDK_Invalid:
704 case Sema::TDK_InstantiationDepth:
705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
707 case Sema::TDK_SubstitutionFailure:
708 case Sema::TDK_DeducedMismatch:
709 case Sema::TDK_DeducedMismatchNested:
710 case Sema::TDK_NonDeducedMismatch:
711 case Sema::TDK_CUDATargetMismatch:
712 case Sema::TDK_NonDependentConversionFailure:
713 return TemplateParameter();
715 case Sema::TDK_Incomplete:
716 case Sema::TDK_InvalidExplicitArguments:
717 return TemplateParameter::getFromOpaqueValue(Data);
719 case Sema::TDK_Inconsistent:
720 case Sema::TDK_Underqualified:
721 return static_cast<DFIParamWithArguments*>(Data)->Param;
724 case Sema::TDK_MiscellaneousDeductionFailure:
728 return TemplateParameter();
731 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
732 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
733 case Sema::TDK_Success:
734 case Sema::TDK_Invalid:
735 case Sema::TDK_InstantiationDepth:
736 case Sema::TDK_TooManyArguments:
737 case Sema::TDK_TooFewArguments:
738 case Sema::TDK_Incomplete:
739 case Sema::TDK_InvalidExplicitArguments:
740 case Sema::TDK_Inconsistent:
741 case Sema::TDK_Underqualified:
742 case Sema::TDK_NonDeducedMismatch:
743 case Sema::TDK_CUDATargetMismatch:
744 case Sema::TDK_NonDependentConversionFailure:
747 case Sema::TDK_DeducedMismatch:
748 case Sema::TDK_DeducedMismatchNested:
749 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
751 case Sema::TDK_SubstitutionFailure:
752 return static_cast<TemplateArgumentList*>(Data);
755 case Sema::TDK_MiscellaneousDeductionFailure:
762 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
763 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764 case Sema::TDK_Success:
765 case Sema::TDK_Invalid:
766 case Sema::TDK_InstantiationDepth:
767 case Sema::TDK_Incomplete:
768 case Sema::TDK_TooManyArguments:
769 case Sema::TDK_TooFewArguments:
770 case Sema::TDK_InvalidExplicitArguments:
771 case Sema::TDK_SubstitutionFailure:
772 case Sema::TDK_CUDATargetMismatch:
773 case Sema::TDK_NonDependentConversionFailure:
776 case Sema::TDK_Inconsistent:
777 case Sema::TDK_Underqualified:
778 case Sema::TDK_DeducedMismatch:
779 case Sema::TDK_DeducedMismatchNested:
780 case Sema::TDK_NonDeducedMismatch:
781 return &static_cast<DFIArguments*>(Data)->FirstArg;
784 case Sema::TDK_MiscellaneousDeductionFailure:
791 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
792 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
793 case Sema::TDK_Success:
794 case Sema::TDK_Invalid:
795 case Sema::TDK_InstantiationDepth:
796 case Sema::TDK_Incomplete:
797 case Sema::TDK_TooManyArguments:
798 case Sema::TDK_TooFewArguments:
799 case Sema::TDK_InvalidExplicitArguments:
800 case Sema::TDK_SubstitutionFailure:
801 case Sema::TDK_CUDATargetMismatch:
802 case Sema::TDK_NonDependentConversionFailure:
805 case Sema::TDK_Inconsistent:
806 case Sema::TDK_Underqualified:
807 case Sema::TDK_DeducedMismatch:
808 case Sema::TDK_DeducedMismatchNested:
809 case Sema::TDK_NonDeducedMismatch:
810 return &static_cast<DFIArguments*>(Data)->SecondArg;
813 case Sema::TDK_MiscellaneousDeductionFailure:
820 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
821 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
822 case Sema::TDK_DeducedMismatch:
823 case Sema::TDK_DeducedMismatchNested:
824 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
831 void OverloadCandidateSet::destroyCandidates() {
832 for (iterator i = begin(), e = end(); i != e; ++i) {
833 for (auto &C : i->Conversions)
834 C.~ImplicitConversionSequence();
835 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
836 i->DeductionFailure.Destroy();
840 void OverloadCandidateSet::clear() {
842 // DiagnoseIfAttrs are just pointers, so we don't need to destroy them.
843 SlabAllocator.Reset();
844 NumInlineBytesUsed = 0;
850 OverloadCandidateSet::addDiagnoseIfComplaints(ArrayRef<DiagnoseIfAttr *> CA) {
851 auto *DIA = slabAllocate<DiagnoseIfAttr *>(CA.size());
852 std::uninitialized_copy(CA.begin(), CA.end(), DIA);
857 class UnbridgedCastsSet {
862 SmallVector<Entry, 2> Entries;
865 void save(Sema &S, Expr *&E) {
866 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
867 Entry entry = { &E, E };
868 Entries.push_back(entry);
869 E = S.stripARCUnbridgedCast(E);
873 for (SmallVectorImpl<Entry>::iterator
874 i = Entries.begin(), e = Entries.end(); i != e; ++i)
880 /// checkPlaceholderForOverload - Do any interesting placeholder-like
881 /// preprocessing on the given expression.
883 /// \param unbridgedCasts a collection to which to add unbridged casts;
884 /// without this, they will be immediately diagnosed as errors
886 /// Return true on unrecoverable error.
888 checkPlaceholderForOverload(Sema &S, Expr *&E,
889 UnbridgedCastsSet *unbridgedCasts = nullptr) {
890 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
891 // We can't handle overloaded expressions here because overload
892 // resolution might reasonably tweak them.
893 if (placeholder->getKind() == BuiltinType::Overload) return false;
895 // If the context potentially accepts unbridged ARC casts, strip
896 // the unbridged cast and add it to the collection for later restoration.
897 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
899 unbridgedCasts->save(S, E);
903 // Go ahead and check everything else.
904 ExprResult result = S.CheckPlaceholderExpr(E);
905 if (result.isInvalid())
916 /// checkArgPlaceholdersForOverload - Check a set of call operands for
918 static bool checkArgPlaceholdersForOverload(Sema &S,
920 UnbridgedCastsSet &unbridged) {
921 for (unsigned i = 0, e = Args.size(); i != e; ++i)
922 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
928 // IsOverload - Determine whether the given New declaration is an
929 // overload of the declarations in Old. This routine returns false if
930 // New and Old cannot be overloaded, e.g., if New has the same
931 // signature as some function in Old (C++ 1.3.10) or if the Old
932 // declarations aren't functions (or function templates) at all. When
933 // it does return false, MatchedDecl will point to the decl that New
934 // cannot be overloaded with. This decl may be a UsingShadowDecl on
935 // top of the underlying declaration.
937 // Example: Given the following input:
939 // void f(int, float); // #1
940 // void f(int, int); // #2
941 // int f(int, int); // #3
943 // When we process #1, there is no previous declaration of "f",
944 // so IsOverload will not be used.
946 // When we process #2, Old contains only the FunctionDecl for #1. By
947 // comparing the parameter types, we see that #1 and #2 are overloaded
948 // (since they have different signatures), so this routine returns
949 // false; MatchedDecl is unchanged.
951 // When we process #3, Old is an overload set containing #1 and #2. We
952 // compare the signatures of #3 to #1 (they're overloaded, so we do
953 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
954 // identical (return types of functions are not part of the
955 // signature), IsOverload returns false and MatchedDecl will be set to
956 // point to the FunctionDecl for #2.
958 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
959 // into a class by a using declaration. The rules for whether to hide
960 // shadow declarations ignore some properties which otherwise figure
961 // into a function template's signature.
963 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
964 NamedDecl *&Match, bool NewIsUsingDecl) {
965 for (LookupResult::iterator I = Old.begin(), E = Old.end();
967 NamedDecl *OldD = *I;
969 bool OldIsUsingDecl = false;
970 if (isa<UsingShadowDecl>(OldD)) {
971 OldIsUsingDecl = true;
973 // We can always introduce two using declarations into the same
974 // context, even if they have identical signatures.
975 if (NewIsUsingDecl) continue;
977 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
980 // A using-declaration does not conflict with another declaration
981 // if one of them is hidden.
982 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
985 // If either declaration was introduced by a using declaration,
986 // we'll need to use slightly different rules for matching.
987 // Essentially, these rules are the normal rules, except that
988 // function templates hide function templates with different
989 // return types or template parameter lists.
990 bool UseMemberUsingDeclRules =
991 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
992 !New->getFriendObjectKind();
994 if (FunctionDecl *OldF = OldD->getAsFunction()) {
995 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
996 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
997 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1001 if (!isa<FunctionTemplateDecl>(OldD) &&
1002 !shouldLinkPossiblyHiddenDecl(*I, New))
1008 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1009 // We can overload with these, which can show up when doing
1010 // redeclaration checks for UsingDecls.
1011 assert(Old.getLookupKind() == LookupUsingDeclName);
1012 } else if (isa<TagDecl>(OldD)) {
1013 // We can always overload with tags by hiding them.
1014 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1015 // Optimistically assume that an unresolved using decl will
1016 // overload; if it doesn't, we'll have to diagnose during
1017 // template instantiation.
1019 // Exception: if the scope is dependent and this is not a class
1020 // member, the using declaration can only introduce an enumerator.
1021 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1023 return Ovl_NonFunction;
1027 // Only function declarations can be overloaded; object and type
1028 // declarations cannot be overloaded.
1030 return Ovl_NonFunction;
1034 return Ovl_Overload;
1037 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1038 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1039 // C++ [basic.start.main]p2: This function shall not be overloaded.
1043 // MSVCRT user defined entry points cannot be overloaded.
1044 if (New->isMSVCRTEntryPoint())
1047 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1048 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1050 // C++ [temp.fct]p2:
1051 // A function template can be overloaded with other function templates
1052 // and with normal (non-template) functions.
1053 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1056 // Is the function New an overload of the function Old?
1057 QualType OldQType = Context.getCanonicalType(Old->getType());
1058 QualType NewQType = Context.getCanonicalType(New->getType());
1060 // Compare the signatures (C++ 1.3.10) of the two functions to
1061 // determine whether they are overloads. If we find any mismatch
1062 // in the signature, they are overloads.
1064 // If either of these functions is a K&R-style function (no
1065 // prototype), then we consider them to have matching signatures.
1066 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1067 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1070 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1071 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1073 // The signature of a function includes the types of its
1074 // parameters (C++ 1.3.10), which includes the presence or absence
1075 // of the ellipsis; see C++ DR 357).
1076 if (OldQType != NewQType &&
1077 (OldType->getNumParams() != NewType->getNumParams() ||
1078 OldType->isVariadic() != NewType->isVariadic() ||
1079 !FunctionParamTypesAreEqual(OldType, NewType)))
1082 // C++ [temp.over.link]p4:
1083 // The signature of a function template consists of its function
1084 // signature, its return type and its template parameter list. The names
1085 // of the template parameters are significant only for establishing the
1086 // relationship between the template parameters and the rest of the
1089 // We check the return type and template parameter lists for function
1090 // templates first; the remaining checks follow.
1092 // However, we don't consider either of these when deciding whether
1093 // a member introduced by a shadow declaration is hidden.
1094 if (!UseMemberUsingDeclRules && NewTemplate &&
1095 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1096 OldTemplate->getTemplateParameters(),
1097 false, TPL_TemplateMatch) ||
1098 OldType->getReturnType() != NewType->getReturnType()))
1101 // If the function is a class member, its signature includes the
1102 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1104 // As part of this, also check whether one of the member functions
1105 // is static, in which case they are not overloads (C++
1106 // 13.1p2). While not part of the definition of the signature,
1107 // this check is important to determine whether these functions
1108 // can be overloaded.
1109 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1110 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1111 if (OldMethod && NewMethod &&
1112 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1113 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1114 if (!UseMemberUsingDeclRules &&
1115 (OldMethod->getRefQualifier() == RQ_None ||
1116 NewMethod->getRefQualifier() == RQ_None)) {
1117 // C++0x [over.load]p2:
1118 // - Member function declarations with the same name and the same
1119 // parameter-type-list as well as member function template
1120 // declarations with the same name, the same parameter-type-list, and
1121 // the same template parameter lists cannot be overloaded if any of
1122 // them, but not all, have a ref-qualifier (8.3.5).
1123 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1124 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1125 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1130 // We may not have applied the implicit const for a constexpr member
1131 // function yet (because we haven't yet resolved whether this is a static
1132 // or non-static member function). Add it now, on the assumption that this
1133 // is a redeclaration of OldMethod.
1134 unsigned OldQuals = OldMethod->getTypeQualifiers();
1135 unsigned NewQuals = NewMethod->getTypeQualifiers();
1136 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1137 !isa<CXXConstructorDecl>(NewMethod))
1138 NewQuals |= Qualifiers::Const;
1140 // We do not allow overloading based off of '__restrict'.
1141 OldQuals &= ~Qualifiers::Restrict;
1142 NewQuals &= ~Qualifiers::Restrict;
1143 if (OldQuals != NewQuals)
1147 // Though pass_object_size is placed on parameters and takes an argument, we
1148 // consider it to be a function-level modifier for the sake of function
1149 // identity. Either the function has one or more parameters with
1150 // pass_object_size or it doesn't.
1151 if (functionHasPassObjectSizeParams(New) !=
1152 functionHasPassObjectSizeParams(Old))
1155 // enable_if attributes are an order-sensitive part of the signature.
1156 for (specific_attr_iterator<EnableIfAttr>
1157 NewI = New->specific_attr_begin<EnableIfAttr>(),
1158 NewE = New->specific_attr_end<EnableIfAttr>(),
1159 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1160 OldE = Old->specific_attr_end<EnableIfAttr>();
1161 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1162 if (NewI == NewE || OldI == OldE)
1164 llvm::FoldingSetNodeID NewID, OldID;
1165 NewI->getCond()->Profile(NewID, Context, true);
1166 OldI->getCond()->Profile(OldID, Context, true);
1171 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1172 // Don't allow overloading of destructors. (In theory we could, but it
1173 // would be a giant change to clang.)
1174 if (isa<CXXDestructorDecl>(New))
1177 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1178 OldTarget = IdentifyCUDATarget(Old);
1179 if (NewTarget == CFT_InvalidTarget)
1182 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1184 // Allow overloading of functions with same signature and different CUDA
1185 // target attributes.
1186 return NewTarget != OldTarget;
1189 // The signatures match; this is not an overload.
1193 /// \brief Checks availability of the function depending on the current
1194 /// function context. Inside an unavailable function, unavailability is ignored.
1196 /// \returns true if \arg FD is unavailable and current context is inside
1197 /// an available function, false otherwise.
1198 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1199 if (!FD->isUnavailable())
1202 // Walk up the context of the caller.
1203 Decl *C = cast<Decl>(CurContext);
1205 if (C->isUnavailable())
1207 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1211 /// \brief Tries a user-defined conversion from From to ToType.
1213 /// Produces an implicit conversion sequence for when a standard conversion
1214 /// is not an option. See TryImplicitConversion for more information.
1215 static ImplicitConversionSequence
1216 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1217 bool SuppressUserConversions,
1219 bool InOverloadResolution,
1221 bool AllowObjCWritebackConversion,
1222 bool AllowObjCConversionOnExplicit) {
1223 ImplicitConversionSequence ICS;
1225 if (SuppressUserConversions) {
1226 // We're not in the case above, so there is no conversion that
1228 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1232 // Attempt user-defined conversion.
1233 OverloadCandidateSet Conversions(From->getExprLoc(),
1234 OverloadCandidateSet::CSK_Normal);
1235 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1236 Conversions, AllowExplicit,
1237 AllowObjCConversionOnExplicit)) {
1240 ICS.setUserDefined();
1241 // C++ [over.ics.user]p4:
1242 // A conversion of an expression of class type to the same class
1243 // type is given Exact Match rank, and a conversion of an
1244 // expression of class type to a base class of that type is
1245 // given Conversion rank, in spite of the fact that a copy
1246 // constructor (i.e., a user-defined conversion function) is
1247 // called for those cases.
1248 if (CXXConstructorDecl *Constructor
1249 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1251 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1253 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1254 if (Constructor->isCopyConstructor() &&
1255 (FromCanon == ToCanon ||
1256 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1257 // Turn this into a "standard" conversion sequence, so that it
1258 // gets ranked with standard conversion sequences.
1259 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1261 ICS.Standard.setAsIdentityConversion();
1262 ICS.Standard.setFromType(From->getType());
1263 ICS.Standard.setAllToTypes(ToType);
1264 ICS.Standard.CopyConstructor = Constructor;
1265 ICS.Standard.FoundCopyConstructor = Found;
1266 if (ToCanon != FromCanon)
1267 ICS.Standard.Second = ICK_Derived_To_Base;
1274 ICS.Ambiguous.setFromType(From->getType());
1275 ICS.Ambiguous.setToType(ToType);
1276 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1277 Cand != Conversions.end(); ++Cand)
1279 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1283 case OR_No_Viable_Function:
1284 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1291 /// TryImplicitConversion - Attempt to perform an implicit conversion
1292 /// from the given expression (Expr) to the given type (ToType). This
1293 /// function returns an implicit conversion sequence that can be used
1294 /// to perform the initialization. Given
1296 /// void f(float f);
1297 /// void g(int i) { f(i); }
1299 /// this routine would produce an implicit conversion sequence to
1300 /// describe the initialization of f from i, which will be a standard
1301 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1302 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1304 /// Note that this routine only determines how the conversion can be
1305 /// performed; it does not actually perform the conversion. As such,
1306 /// it will not produce any diagnostics if no conversion is available,
1307 /// but will instead return an implicit conversion sequence of kind
1308 /// "BadConversion".
1310 /// If @p SuppressUserConversions, then user-defined conversions are
1312 /// If @p AllowExplicit, then explicit user-defined conversions are
1315 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1316 /// writeback conversion, which allows __autoreleasing id* parameters to
1317 /// be initialized with __strong id* or __weak id* arguments.
1318 static ImplicitConversionSequence
1319 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1320 bool SuppressUserConversions,
1322 bool InOverloadResolution,
1324 bool AllowObjCWritebackConversion,
1325 bool AllowObjCConversionOnExplicit) {
1326 ImplicitConversionSequence ICS;
1327 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1328 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1333 if (!S.getLangOpts().CPlusPlus) {
1334 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1338 // C++ [over.ics.user]p4:
1339 // A conversion of an expression of class type to the same class
1340 // type is given Exact Match rank, and a conversion of an
1341 // expression of class type to a base class of that type is
1342 // given Conversion rank, in spite of the fact that a copy/move
1343 // constructor (i.e., a user-defined conversion function) is
1344 // called for those cases.
1345 QualType FromType = From->getType();
1346 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1347 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1348 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1350 ICS.Standard.setAsIdentityConversion();
1351 ICS.Standard.setFromType(FromType);
1352 ICS.Standard.setAllToTypes(ToType);
1354 // We don't actually check at this point whether there is a valid
1355 // copy/move constructor, since overloading just assumes that it
1356 // exists. When we actually perform initialization, we'll find the
1357 // appropriate constructor to copy the returned object, if needed.
1358 ICS.Standard.CopyConstructor = nullptr;
1360 // Determine whether this is considered a derived-to-base conversion.
1361 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1362 ICS.Standard.Second = ICK_Derived_To_Base;
1367 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1368 AllowExplicit, InOverloadResolution, CStyle,
1369 AllowObjCWritebackConversion,
1370 AllowObjCConversionOnExplicit);
1373 ImplicitConversionSequence
1374 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1375 bool SuppressUserConversions,
1377 bool InOverloadResolution,
1379 bool AllowObjCWritebackConversion) {
1380 return ::TryImplicitConversion(*this, From, ToType,
1381 SuppressUserConversions, AllowExplicit,
1382 InOverloadResolution, CStyle,
1383 AllowObjCWritebackConversion,
1384 /*AllowObjCConversionOnExplicit=*/false);
1387 /// PerformImplicitConversion - Perform an implicit conversion of the
1388 /// expression From to the type ToType. Returns the
1389 /// converted expression. Flavor is the kind of conversion we're
1390 /// performing, used in the error message. If @p AllowExplicit,
1391 /// explicit user-defined conversions are permitted.
1393 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1394 AssignmentAction Action, bool AllowExplicit) {
1395 ImplicitConversionSequence ICS;
1396 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1400 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1401 AssignmentAction Action, bool AllowExplicit,
1402 ImplicitConversionSequence& ICS) {
1403 if (checkPlaceholderForOverload(*this, From))
1406 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1407 bool AllowObjCWritebackConversion
1408 = getLangOpts().ObjCAutoRefCount &&
1409 (Action == AA_Passing || Action == AA_Sending);
1410 if (getLangOpts().ObjC1)
1411 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1412 ToType, From->getType(), From);
1413 ICS = ::TryImplicitConversion(*this, From, ToType,
1414 /*SuppressUserConversions=*/false,
1416 /*InOverloadResolution=*/false,
1418 AllowObjCWritebackConversion,
1419 /*AllowObjCConversionOnExplicit=*/false);
1420 return PerformImplicitConversion(From, ToType, ICS, Action);
1423 /// \brief Determine whether the conversion from FromType to ToType is a valid
1424 /// conversion that strips "noexcept" or "noreturn" off the nested function
1426 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1427 QualType &ResultTy) {
1428 if (Context.hasSameUnqualifiedType(FromType, ToType))
1431 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1432 // or F(t noexcept) -> F(t)
1433 // where F adds one of the following at most once:
1435 // - a member pointer
1436 // - a block pointer
1437 // Changes here need matching changes in FindCompositePointerType.
1438 CanQualType CanTo = Context.getCanonicalType(ToType);
1439 CanQualType CanFrom = Context.getCanonicalType(FromType);
1440 Type::TypeClass TyClass = CanTo->getTypeClass();
1441 if (TyClass != CanFrom->getTypeClass()) return false;
1442 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1443 if (TyClass == Type::Pointer) {
1444 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1445 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1446 } else if (TyClass == Type::BlockPointer) {
1447 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1448 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1449 } else if (TyClass == Type::MemberPointer) {
1450 auto ToMPT = CanTo.getAs<MemberPointerType>();
1451 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1452 // A function pointer conversion cannot change the class of the function.
1453 if (ToMPT->getClass() != FromMPT->getClass())
1455 CanTo = ToMPT->getPointeeType();
1456 CanFrom = FromMPT->getPointeeType();
1461 TyClass = CanTo->getTypeClass();
1462 if (TyClass != CanFrom->getTypeClass()) return false;
1463 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1467 const auto *FromFn = cast<FunctionType>(CanFrom);
1468 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1470 const auto *ToFn = cast<FunctionType>(CanTo);
1471 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1473 bool Changed = false;
1475 // Drop 'noreturn' if not present in target type.
1476 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1477 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1481 // Drop 'noexcept' if not present in target type.
1482 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1483 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1484 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1485 FromFn = cast<FunctionType>(
1486 Context.getFunctionType(FromFPT->getReturnType(),
1487 FromFPT->getParamTypes(),
1488 FromFPT->getExtProtoInfo().withExceptionSpec(
1489 FunctionProtoType::ExceptionSpecInfo()))
1498 assert(QualType(FromFn, 0).isCanonical());
1499 if (QualType(FromFn, 0) != CanTo) return false;
1505 /// \brief Determine whether the conversion from FromType to ToType is a valid
1506 /// vector conversion.
1508 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1510 static bool IsVectorConversion(Sema &S, QualType FromType,
1511 QualType ToType, ImplicitConversionKind &ICK) {
1512 // We need at least one of these types to be a vector type to have a vector
1514 if (!ToType->isVectorType() && !FromType->isVectorType())
1517 // Identical types require no conversions.
1518 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1521 // There are no conversions between extended vector types, only identity.
1522 if (ToType->isExtVectorType()) {
1523 // There are no conversions between extended vector types other than the
1524 // identity conversion.
1525 if (FromType->isExtVectorType())
1528 // Vector splat from any arithmetic type to a vector.
1529 if (FromType->isArithmeticType()) {
1530 ICK = ICK_Vector_Splat;
1535 // We can perform the conversion between vector types in the following cases:
1536 // 1)vector types are equivalent AltiVec and GCC vector types
1537 // 2)lax vector conversions are permitted and the vector types are of the
1539 if (ToType->isVectorType() && FromType->isVectorType()) {
1540 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1541 S.isLaxVectorConversion(FromType, ToType)) {
1542 ICK = ICK_Vector_Conversion;
1550 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1551 bool InOverloadResolution,
1552 StandardConversionSequence &SCS,
1555 /// IsStandardConversion - Determines whether there is a standard
1556 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1557 /// expression From to the type ToType. Standard conversion sequences
1558 /// only consider non-class types; for conversions that involve class
1559 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1560 /// contain the standard conversion sequence required to perform this
1561 /// conversion and this routine will return true. Otherwise, this
1562 /// routine will return false and the value of SCS is unspecified.
1563 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1564 bool InOverloadResolution,
1565 StandardConversionSequence &SCS,
1567 bool AllowObjCWritebackConversion) {
1568 QualType FromType = From->getType();
1570 // Standard conversions (C++ [conv])
1571 SCS.setAsIdentityConversion();
1572 SCS.IncompatibleObjC = false;
1573 SCS.setFromType(FromType);
1574 SCS.CopyConstructor = nullptr;
1576 // There are no standard conversions for class types in C++, so
1577 // abort early. When overloading in C, however, we do permit them.
1578 if (S.getLangOpts().CPlusPlus &&
1579 (FromType->isRecordType() || ToType->isRecordType()))
1582 // The first conversion can be an lvalue-to-rvalue conversion,
1583 // array-to-pointer conversion, or function-to-pointer conversion
1586 if (FromType == S.Context.OverloadTy) {
1587 DeclAccessPair AccessPair;
1588 if (FunctionDecl *Fn
1589 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1591 // We were able to resolve the address of the overloaded function,
1592 // so we can convert to the type of that function.
1593 FromType = Fn->getType();
1594 SCS.setFromType(FromType);
1596 // we can sometimes resolve &foo<int> regardless of ToType, so check
1597 // if the type matches (identity) or we are converting to bool
1598 if (!S.Context.hasSameUnqualifiedType(
1599 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1601 // if the function type matches except for [[noreturn]], it's ok
1602 if (!S.IsFunctionConversion(FromType,
1603 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1604 // otherwise, only a boolean conversion is standard
1605 if (!ToType->isBooleanType())
1609 // Check if the "from" expression is taking the address of an overloaded
1610 // function and recompute the FromType accordingly. Take advantage of the
1611 // fact that non-static member functions *must* have such an address-of
1613 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1614 if (Method && !Method->isStatic()) {
1615 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1616 "Non-unary operator on non-static member address");
1617 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1619 "Non-address-of operator on non-static member address");
1620 const Type *ClassType
1621 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1622 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1623 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1624 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1626 "Non-address-of operator for overloaded function expression");
1627 FromType = S.Context.getPointerType(FromType);
1630 // Check that we've computed the proper type after overload resolution.
1631 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1632 // be calling it from within an NDEBUG block.
1633 assert(S.Context.hasSameType(
1635 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1640 // Lvalue-to-rvalue conversion (C++11 4.1):
1641 // A glvalue (3.10) of a non-function, non-array type T can
1642 // be converted to a prvalue.
1643 bool argIsLValue = From->isGLValue();
1645 !FromType->isFunctionType() && !FromType->isArrayType() &&
1646 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1647 SCS.First = ICK_Lvalue_To_Rvalue;
1650 // ... if the lvalue has atomic type, the value has the non-atomic version
1651 // of the type of the lvalue ...
1652 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1653 FromType = Atomic->getValueType();
1655 // If T is a non-class type, the type of the rvalue is the
1656 // cv-unqualified version of T. Otherwise, the type of the rvalue
1657 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1658 // just strip the qualifiers because they don't matter.
1659 FromType = FromType.getUnqualifiedType();
1660 } else if (FromType->isArrayType()) {
1661 // Array-to-pointer conversion (C++ 4.2)
1662 SCS.First = ICK_Array_To_Pointer;
1664 // An lvalue or rvalue of type "array of N T" or "array of unknown
1665 // bound of T" can be converted to an rvalue of type "pointer to
1667 FromType = S.Context.getArrayDecayedType(FromType);
1669 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1670 // This conversion is deprecated in C++03 (D.4)
1671 SCS.DeprecatedStringLiteralToCharPtr = true;
1673 // For the purpose of ranking in overload resolution
1674 // (13.3.3.1.1), this conversion is considered an
1675 // array-to-pointer conversion followed by a qualification
1676 // conversion (4.4). (C++ 4.2p2)
1677 SCS.Second = ICK_Identity;
1678 SCS.Third = ICK_Qualification;
1679 SCS.QualificationIncludesObjCLifetime = false;
1680 SCS.setAllToTypes(FromType);
1683 } else if (FromType->isFunctionType() && argIsLValue) {
1684 // Function-to-pointer conversion (C++ 4.3).
1685 SCS.First = ICK_Function_To_Pointer;
1687 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1688 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1689 if (!S.checkAddressOfFunctionIsAvailable(FD))
1692 // An lvalue of function type T can be converted to an rvalue of
1693 // type "pointer to T." The result is a pointer to the
1694 // function. (C++ 4.3p1).
1695 FromType = S.Context.getPointerType(FromType);
1697 // We don't require any conversions for the first step.
1698 SCS.First = ICK_Identity;
1700 SCS.setToType(0, FromType);
1702 // The second conversion can be an integral promotion, floating
1703 // point promotion, integral conversion, floating point conversion,
1704 // floating-integral conversion, pointer conversion,
1705 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1706 // For overloading in C, this can also be a "compatible-type"
1708 bool IncompatibleObjC = false;
1709 ImplicitConversionKind SecondICK = ICK_Identity;
1710 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1711 // The unqualified versions of the types are the same: there's no
1712 // conversion to do.
1713 SCS.Second = ICK_Identity;
1714 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1715 // Integral promotion (C++ 4.5).
1716 SCS.Second = ICK_Integral_Promotion;
1717 FromType = ToType.getUnqualifiedType();
1718 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1719 // Floating point promotion (C++ 4.6).
1720 SCS.Second = ICK_Floating_Promotion;
1721 FromType = ToType.getUnqualifiedType();
1722 } else if (S.IsComplexPromotion(FromType, ToType)) {
1723 // Complex promotion (Clang extension)
1724 SCS.Second = ICK_Complex_Promotion;
1725 FromType = ToType.getUnqualifiedType();
1726 } else if (ToType->isBooleanType() &&
1727 (FromType->isArithmeticType() ||
1728 FromType->isAnyPointerType() ||
1729 FromType->isBlockPointerType() ||
1730 FromType->isMemberPointerType() ||
1731 FromType->isNullPtrType())) {
1732 // Boolean conversions (C++ 4.12).
1733 SCS.Second = ICK_Boolean_Conversion;
1734 FromType = S.Context.BoolTy;
1735 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1736 ToType->isIntegralType(S.Context)) {
1737 // Integral conversions (C++ 4.7).
1738 SCS.Second = ICK_Integral_Conversion;
1739 FromType = ToType.getUnqualifiedType();
1740 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1741 // Complex conversions (C99 6.3.1.6)
1742 SCS.Second = ICK_Complex_Conversion;
1743 FromType = ToType.getUnqualifiedType();
1744 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1745 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1746 // Complex-real conversions (C99 6.3.1.7)
1747 SCS.Second = ICK_Complex_Real;
1748 FromType = ToType.getUnqualifiedType();
1749 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1750 // FIXME: disable conversions between long double and __float128 if
1751 // their representation is different until there is back end support
1752 // We of course allow this conversion if long double is really double.
1753 if (&S.Context.getFloatTypeSemantics(FromType) !=
1754 &S.Context.getFloatTypeSemantics(ToType)) {
1755 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1756 ToType == S.Context.LongDoubleTy) ||
1757 (FromType == S.Context.LongDoubleTy &&
1758 ToType == S.Context.Float128Ty));
1759 if (Float128AndLongDouble &&
1760 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1761 &llvm::APFloat::IEEEdouble()))
1764 // Floating point conversions (C++ 4.8).
1765 SCS.Second = ICK_Floating_Conversion;
1766 FromType = ToType.getUnqualifiedType();
1767 } else if ((FromType->isRealFloatingType() &&
1768 ToType->isIntegralType(S.Context)) ||
1769 (FromType->isIntegralOrUnscopedEnumerationType() &&
1770 ToType->isRealFloatingType())) {
1771 // Floating-integral conversions (C++ 4.9).
1772 SCS.Second = ICK_Floating_Integral;
1773 FromType = ToType.getUnqualifiedType();
1774 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1775 SCS.Second = ICK_Block_Pointer_Conversion;
1776 } else if (AllowObjCWritebackConversion &&
1777 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1778 SCS.Second = ICK_Writeback_Conversion;
1779 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1780 FromType, IncompatibleObjC)) {
1781 // Pointer conversions (C++ 4.10).
1782 SCS.Second = ICK_Pointer_Conversion;
1783 SCS.IncompatibleObjC = IncompatibleObjC;
1784 FromType = FromType.getUnqualifiedType();
1785 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1786 InOverloadResolution, FromType)) {
1787 // Pointer to member conversions (4.11).
1788 SCS.Second = ICK_Pointer_Member;
1789 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1790 SCS.Second = SecondICK;
1791 FromType = ToType.getUnqualifiedType();
1792 } else if (!S.getLangOpts().CPlusPlus &&
1793 S.Context.typesAreCompatible(ToType, FromType)) {
1794 // Compatible conversions (Clang extension for C function overloading)
1795 SCS.Second = ICK_Compatible_Conversion;
1796 FromType = ToType.getUnqualifiedType();
1797 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1798 InOverloadResolution,
1800 SCS.Second = ICK_TransparentUnionConversion;
1802 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1804 // tryAtomicConversion has updated the standard conversion sequence
1807 } else if (ToType->isEventT() &&
1808 From->isIntegerConstantExpr(S.getASTContext()) &&
1809 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1810 SCS.Second = ICK_Zero_Event_Conversion;
1812 } else if (ToType->isQueueT() &&
1813 From->isIntegerConstantExpr(S.getASTContext()) &&
1814 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1815 SCS.Second = ICK_Zero_Queue_Conversion;
1818 // No second conversion required.
1819 SCS.Second = ICK_Identity;
1821 SCS.setToType(1, FromType);
1823 // The third conversion can be a function pointer conversion or a
1824 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1825 bool ObjCLifetimeConversion;
1826 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1827 // Function pointer conversions (removing 'noexcept') including removal of
1828 // 'noreturn' (Clang extension).
1829 SCS.Third = ICK_Function_Conversion;
1830 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1831 ObjCLifetimeConversion)) {
1832 SCS.Third = ICK_Qualification;
1833 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1836 // No conversion required
1837 SCS.Third = ICK_Identity;
1840 // C++ [over.best.ics]p6:
1841 // [...] Any difference in top-level cv-qualification is
1842 // subsumed by the initialization itself and does not constitute
1843 // a conversion. [...]
1844 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1845 QualType CanonTo = S.Context.getCanonicalType(ToType);
1846 if (CanonFrom.getLocalUnqualifiedType()
1847 == CanonTo.getLocalUnqualifiedType() &&
1848 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1850 CanonFrom = CanonTo;
1853 SCS.setToType(2, FromType);
1855 if (CanonFrom == CanonTo)
1858 // If we have not converted the argument type to the parameter type,
1859 // this is a bad conversion sequence, unless we're resolving an overload in C.
1860 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1863 ExprResult ER = ExprResult{From};
1864 Sema::AssignConvertType Conv =
1865 S.CheckSingleAssignmentConstraints(ToType, ER,
1867 /*DiagnoseCFAudited=*/false,
1868 /*ConvertRHS=*/false);
1869 ImplicitConversionKind SecondConv;
1871 case Sema::Compatible:
1872 SecondConv = ICK_C_Only_Conversion;
1874 // For our purposes, discarding qualifiers is just as bad as using an
1875 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1876 // qualifiers, as well.
1877 case Sema::CompatiblePointerDiscardsQualifiers:
1878 case Sema::IncompatiblePointer:
1879 case Sema::IncompatiblePointerSign:
1880 SecondConv = ICK_Incompatible_Pointer_Conversion;
1886 // First can only be an lvalue conversion, so we pretend that this was the
1887 // second conversion. First should already be valid from earlier in the
1889 SCS.Second = SecondConv;
1890 SCS.setToType(1, ToType);
1892 // Third is Identity, because Second should rank us worse than any other
1893 // conversion. This could also be ICK_Qualification, but it's simpler to just
1894 // lump everything in with the second conversion, and we don't gain anything
1895 // from making this ICK_Qualification.
1896 SCS.Third = ICK_Identity;
1897 SCS.setToType(2, ToType);
1902 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1904 bool InOverloadResolution,
1905 StandardConversionSequence &SCS,
1908 const RecordType *UT = ToType->getAsUnionType();
1909 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1911 // The field to initialize within the transparent union.
1912 RecordDecl *UD = UT->getDecl();
1913 // It's compatible if the expression matches any of the fields.
1914 for (const auto *it : UD->fields()) {
1915 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1916 CStyle, /*ObjCWritebackConversion=*/false)) {
1917 ToType = it->getType();
1924 /// IsIntegralPromotion - Determines whether the conversion from the
1925 /// expression From (whose potentially-adjusted type is FromType) to
1926 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1927 /// sets PromotedType to the promoted type.
1928 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1929 const BuiltinType *To = ToType->getAs<BuiltinType>();
1930 // All integers are built-in.
1935 // An rvalue of type char, signed char, unsigned char, short int, or
1936 // unsigned short int can be converted to an rvalue of type int if
1937 // int can represent all the values of the source type; otherwise,
1938 // the source rvalue can be converted to an rvalue of type unsigned
1940 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1941 !FromType->isEnumeralType()) {
1942 if (// We can promote any signed, promotable integer type to an int
1943 (FromType->isSignedIntegerType() ||
1944 // We can promote any unsigned integer type whose size is
1945 // less than int to an int.
1946 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1947 return To->getKind() == BuiltinType::Int;
1950 return To->getKind() == BuiltinType::UInt;
1953 // C++11 [conv.prom]p3:
1954 // A prvalue of an unscoped enumeration type whose underlying type is not
1955 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1956 // following types that can represent all the values of the enumeration
1957 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1958 // unsigned int, long int, unsigned long int, long long int, or unsigned
1959 // long long int. If none of the types in that list can represent all the
1960 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1961 // type can be converted to an rvalue a prvalue of the extended integer type
1962 // with lowest integer conversion rank (4.13) greater than the rank of long
1963 // long in which all the values of the enumeration can be represented. If
1964 // there are two such extended types, the signed one is chosen.
1965 // C++11 [conv.prom]p4:
1966 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1967 // can be converted to a prvalue of its underlying type. Moreover, if
1968 // integral promotion can be applied to its underlying type, a prvalue of an
1969 // unscoped enumeration type whose underlying type is fixed can also be
1970 // converted to a prvalue of the promoted underlying type.
1971 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1972 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1973 // provided for a scoped enumeration.
1974 if (FromEnumType->getDecl()->isScoped())
1977 // We can perform an integral promotion to the underlying type of the enum,
1978 // even if that's not the promoted type. Note that the check for promoting
1979 // the underlying type is based on the type alone, and does not consider
1980 // the bitfield-ness of the actual source expression.
1981 if (FromEnumType->getDecl()->isFixed()) {
1982 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1983 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1984 IsIntegralPromotion(nullptr, Underlying, ToType);
1987 // We have already pre-calculated the promotion type, so this is trivial.
1988 if (ToType->isIntegerType() &&
1989 isCompleteType(From->getLocStart(), FromType))
1990 return Context.hasSameUnqualifiedType(
1991 ToType, FromEnumType->getDecl()->getPromotionType());
1994 // C++0x [conv.prom]p2:
1995 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1996 // to an rvalue a prvalue of the first of the following types that can
1997 // represent all the values of its underlying type: int, unsigned int,
1998 // long int, unsigned long int, long long int, or unsigned long long int.
1999 // If none of the types in that list can represent all the values of its
2000 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2001 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2003 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2004 ToType->isIntegerType()) {
2005 // Determine whether the type we're converting from is signed or
2007 bool FromIsSigned = FromType->isSignedIntegerType();
2008 uint64_t FromSize = Context.getTypeSize(FromType);
2010 // The types we'll try to promote to, in the appropriate
2011 // order. Try each of these types.
2012 QualType PromoteTypes[6] = {
2013 Context.IntTy, Context.UnsignedIntTy,
2014 Context.LongTy, Context.UnsignedLongTy ,
2015 Context.LongLongTy, Context.UnsignedLongLongTy
2017 for (int Idx = 0; Idx < 6; ++Idx) {
2018 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2019 if (FromSize < ToSize ||
2020 (FromSize == ToSize &&
2021 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2022 // We found the type that we can promote to. If this is the
2023 // type we wanted, we have a promotion. Otherwise, no
2025 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2030 // An rvalue for an integral bit-field (9.6) can be converted to an
2031 // rvalue of type int if int can represent all the values of the
2032 // bit-field; otherwise, it can be converted to unsigned int if
2033 // unsigned int can represent all the values of the bit-field. If
2034 // the bit-field is larger yet, no integral promotion applies to
2035 // it. If the bit-field has an enumerated type, it is treated as any
2036 // other value of that type for promotion purposes (C++ 4.5p3).
2037 // FIXME: We should delay checking of bit-fields until we actually perform the
2040 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2041 llvm::APSInt BitWidth;
2042 if (FromType->isIntegralType(Context) &&
2043 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2044 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2045 ToSize = Context.getTypeSize(ToType);
2047 // Are we promoting to an int from a bitfield that fits in an int?
2048 if (BitWidth < ToSize ||
2049 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2050 return To->getKind() == BuiltinType::Int;
2053 // Are we promoting to an unsigned int from an unsigned bitfield
2054 // that fits into an unsigned int?
2055 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2056 return To->getKind() == BuiltinType::UInt;
2064 // An rvalue of type bool can be converted to an rvalue of type int,
2065 // with false becoming zero and true becoming one (C++ 4.5p4).
2066 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2073 /// IsFloatingPointPromotion - Determines whether the conversion from
2074 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2075 /// returns true and sets PromotedType to the promoted type.
2076 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2077 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2078 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2079 /// An rvalue of type float can be converted to an rvalue of type
2080 /// double. (C++ 4.6p1).
2081 if (FromBuiltin->getKind() == BuiltinType::Float &&
2082 ToBuiltin->getKind() == BuiltinType::Double)
2086 // When a float is promoted to double or long double, or a
2087 // double is promoted to long double [...].
2088 if (!getLangOpts().CPlusPlus &&
2089 (FromBuiltin->getKind() == BuiltinType::Float ||
2090 FromBuiltin->getKind() == BuiltinType::Double) &&
2091 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2092 ToBuiltin->getKind() == BuiltinType::Float128))
2095 // Half can be promoted to float.
2096 if (!getLangOpts().NativeHalfType &&
2097 FromBuiltin->getKind() == BuiltinType::Half &&
2098 ToBuiltin->getKind() == BuiltinType::Float)
2105 /// \brief Determine if a conversion is a complex promotion.
2107 /// A complex promotion is defined as a complex -> complex conversion
2108 /// where the conversion between the underlying real types is a
2109 /// floating-point or integral promotion.
2110 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2111 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2115 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2119 return IsFloatingPointPromotion(FromComplex->getElementType(),
2120 ToComplex->getElementType()) ||
2121 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2122 ToComplex->getElementType());
2125 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2126 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2127 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2128 /// if non-empty, will be a pointer to ToType that may or may not have
2129 /// the right set of qualifiers on its pointee.
2132 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2133 QualType ToPointee, QualType ToType,
2134 ASTContext &Context,
2135 bool StripObjCLifetime = false) {
2136 assert((FromPtr->getTypeClass() == Type::Pointer ||
2137 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2138 "Invalid similarly-qualified pointer type");
2140 /// Conversions to 'id' subsume cv-qualifier conversions.
2141 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2142 return ToType.getUnqualifiedType();
2144 QualType CanonFromPointee
2145 = Context.getCanonicalType(FromPtr->getPointeeType());
2146 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2147 Qualifiers Quals = CanonFromPointee.getQualifiers();
2149 if (StripObjCLifetime)
2150 Quals.removeObjCLifetime();
2152 // Exact qualifier match -> return the pointer type we're converting to.
2153 if (CanonToPointee.getLocalQualifiers() == Quals) {
2154 // ToType is exactly what we need. Return it.
2155 if (!ToType.isNull())
2156 return ToType.getUnqualifiedType();
2158 // Build a pointer to ToPointee. It has the right qualifiers
2160 if (isa<ObjCObjectPointerType>(ToType))
2161 return Context.getObjCObjectPointerType(ToPointee);
2162 return Context.getPointerType(ToPointee);
2165 // Just build a canonical type that has the right qualifiers.
2166 QualType QualifiedCanonToPointee
2167 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2169 if (isa<ObjCObjectPointerType>(ToType))
2170 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2171 return Context.getPointerType(QualifiedCanonToPointee);
2174 static bool isNullPointerConstantForConversion(Expr *Expr,
2175 bool InOverloadResolution,
2176 ASTContext &Context) {
2177 // Handle value-dependent integral null pointer constants correctly.
2178 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2179 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2180 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2181 return !InOverloadResolution;
2183 return Expr->isNullPointerConstant(Context,
2184 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2185 : Expr::NPC_ValueDependentIsNull);
2188 /// IsPointerConversion - Determines whether the conversion of the
2189 /// expression From, which has the (possibly adjusted) type FromType,
2190 /// can be converted to the type ToType via a pointer conversion (C++
2191 /// 4.10). If so, returns true and places the converted type (that
2192 /// might differ from ToType in its cv-qualifiers at some level) into
2195 /// This routine also supports conversions to and from block pointers
2196 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2197 /// pointers to interfaces. FIXME: Once we've determined the
2198 /// appropriate overloading rules for Objective-C, we may want to
2199 /// split the Objective-C checks into a different routine; however,
2200 /// GCC seems to consider all of these conversions to be pointer
2201 /// conversions, so for now they live here. IncompatibleObjC will be
2202 /// set if the conversion is an allowed Objective-C conversion that
2203 /// should result in a warning.
2204 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2205 bool InOverloadResolution,
2206 QualType& ConvertedType,
2207 bool &IncompatibleObjC) {
2208 IncompatibleObjC = false;
2209 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2213 // Conversion from a null pointer constant to any Objective-C pointer type.
2214 if (ToType->isObjCObjectPointerType() &&
2215 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2216 ConvertedType = ToType;
2220 // Blocks: Block pointers can be converted to void*.
2221 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2222 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2223 ConvertedType = ToType;
2226 // Blocks: A null pointer constant can be converted to a block
2228 if (ToType->isBlockPointerType() &&
2229 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2230 ConvertedType = ToType;
2234 // If the left-hand-side is nullptr_t, the right side can be a null
2235 // pointer constant.
2236 if (ToType->isNullPtrType() &&
2237 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2238 ConvertedType = ToType;
2242 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2246 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2247 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2248 ConvertedType = ToType;
2252 // Beyond this point, both types need to be pointers
2253 // , including objective-c pointers.
2254 QualType ToPointeeType = ToTypePtr->getPointeeType();
2255 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2256 !getLangOpts().ObjCAutoRefCount) {
2257 ConvertedType = BuildSimilarlyQualifiedPointerType(
2258 FromType->getAs<ObjCObjectPointerType>(),
2263 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2267 QualType FromPointeeType = FromTypePtr->getPointeeType();
2269 // If the unqualified pointee types are the same, this can't be a
2270 // pointer conversion, so don't do all of the work below.
2271 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2274 // An rvalue of type "pointer to cv T," where T is an object type,
2275 // can be converted to an rvalue of type "pointer to cv void" (C++
2277 if (FromPointeeType->isIncompleteOrObjectType() &&
2278 ToPointeeType->isVoidType()) {
2279 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2282 /*StripObjCLifetime=*/true);
2286 // MSVC allows implicit function to void* type conversion.
2287 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2288 ToPointeeType->isVoidType()) {
2289 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2295 // When we're overloading in C, we allow a special kind of pointer
2296 // conversion for compatible-but-not-identical pointee types.
2297 if (!getLangOpts().CPlusPlus &&
2298 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2299 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2305 // C++ [conv.ptr]p3:
2307 // An rvalue of type "pointer to cv D," where D is a class type,
2308 // can be converted to an rvalue of type "pointer to cv B," where
2309 // B is a base class (clause 10) of D. If B is an inaccessible
2310 // (clause 11) or ambiguous (10.2) base class of D, a program that
2311 // necessitates this conversion is ill-formed. The result of the
2312 // conversion is a pointer to the base class sub-object of the
2313 // derived class object. The null pointer value is converted to
2314 // the null pointer value of the destination type.
2316 // Note that we do not check for ambiguity or inaccessibility
2317 // here. That is handled by CheckPointerConversion.
2318 if (getLangOpts().CPlusPlus &&
2319 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2320 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2321 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2322 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2328 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2329 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2330 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2339 /// \brief Adopt the given qualifiers for the given type.
2340 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2341 Qualifiers TQs = T.getQualifiers();
2343 // Check whether qualifiers already match.
2347 if (Qs.compatiblyIncludes(TQs))
2348 return Context.getQualifiedType(T, Qs);
2350 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2353 /// isObjCPointerConversion - Determines whether this is an
2354 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2355 /// with the same arguments and return values.
2356 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2357 QualType& ConvertedType,
2358 bool &IncompatibleObjC) {
2359 if (!getLangOpts().ObjC1)
2362 // The set of qualifiers on the type we're converting from.
2363 Qualifiers FromQualifiers = FromType.getQualifiers();
2365 // First, we handle all conversions on ObjC object pointer types.
2366 const ObjCObjectPointerType* ToObjCPtr =
2367 ToType->getAs<ObjCObjectPointerType>();
2368 const ObjCObjectPointerType *FromObjCPtr =
2369 FromType->getAs<ObjCObjectPointerType>();
2371 if (ToObjCPtr && FromObjCPtr) {
2372 // If the pointee types are the same (ignoring qualifications),
2373 // then this is not a pointer conversion.
2374 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2375 FromObjCPtr->getPointeeType()))
2378 // Conversion between Objective-C pointers.
2379 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2380 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2381 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2382 if (getLangOpts().CPlusPlus && LHS && RHS &&
2383 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2384 FromObjCPtr->getPointeeType()))
2386 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2387 ToObjCPtr->getPointeeType(),
2389 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2393 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2394 // Okay: this is some kind of implicit downcast of Objective-C
2395 // interfaces, which is permitted. However, we're going to
2396 // complain about it.
2397 IncompatibleObjC = true;
2398 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2399 ToObjCPtr->getPointeeType(),
2401 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2405 // Beyond this point, both types need to be C pointers or block pointers.
2406 QualType ToPointeeType;
2407 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2408 ToPointeeType = ToCPtr->getPointeeType();
2409 else if (const BlockPointerType *ToBlockPtr =
2410 ToType->getAs<BlockPointerType>()) {
2411 // Objective C++: We're able to convert from a pointer to any object
2412 // to a block pointer type.
2413 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2414 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2417 ToPointeeType = ToBlockPtr->getPointeeType();
2419 else if (FromType->getAs<BlockPointerType>() &&
2420 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2421 // Objective C++: We're able to convert from a block pointer type to a
2422 // pointer to any object.
2423 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2429 QualType FromPointeeType;
2430 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2431 FromPointeeType = FromCPtr->getPointeeType();
2432 else if (const BlockPointerType *FromBlockPtr =
2433 FromType->getAs<BlockPointerType>())
2434 FromPointeeType = FromBlockPtr->getPointeeType();
2438 // If we have pointers to pointers, recursively check whether this
2439 // is an Objective-C conversion.
2440 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2441 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2442 IncompatibleObjC)) {
2443 // We always complain about this conversion.
2444 IncompatibleObjC = true;
2445 ConvertedType = Context.getPointerType(ConvertedType);
2446 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2449 // Allow conversion of pointee being objective-c pointer to another one;
2451 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2452 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2453 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2454 IncompatibleObjC)) {
2456 ConvertedType = Context.getPointerType(ConvertedType);
2457 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2461 // If we have pointers to functions or blocks, check whether the only
2462 // differences in the argument and result types are in Objective-C
2463 // pointer conversions. If so, we permit the conversion (but
2464 // complain about it).
2465 const FunctionProtoType *FromFunctionType
2466 = FromPointeeType->getAs<FunctionProtoType>();
2467 const FunctionProtoType *ToFunctionType
2468 = ToPointeeType->getAs<FunctionProtoType>();
2469 if (FromFunctionType && ToFunctionType) {
2470 // If the function types are exactly the same, this isn't an
2471 // Objective-C pointer conversion.
2472 if (Context.getCanonicalType(FromPointeeType)
2473 == Context.getCanonicalType(ToPointeeType))
2476 // Perform the quick checks that will tell us whether these
2477 // function types are obviously different.
2478 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2479 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2480 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2483 bool HasObjCConversion = false;
2484 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2485 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2486 // Okay, the types match exactly. Nothing to do.
2487 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2488 ToFunctionType->getReturnType(),
2489 ConvertedType, IncompatibleObjC)) {
2490 // Okay, we have an Objective-C pointer conversion.
2491 HasObjCConversion = true;
2493 // Function types are too different. Abort.
2497 // Check argument types.
2498 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2499 ArgIdx != NumArgs; ++ArgIdx) {
2500 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2501 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2502 if (Context.getCanonicalType(FromArgType)
2503 == Context.getCanonicalType(ToArgType)) {
2504 // Okay, the types match exactly. Nothing to do.
2505 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2506 ConvertedType, IncompatibleObjC)) {
2507 // Okay, we have an Objective-C pointer conversion.
2508 HasObjCConversion = true;
2510 // Argument types are too different. Abort.
2515 if (HasObjCConversion) {
2516 // We had an Objective-C conversion. Allow this pointer
2517 // conversion, but complain about it.
2518 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2519 IncompatibleObjC = true;
2527 /// \brief Determine whether this is an Objective-C writeback conversion,
2528 /// used for parameter passing when performing automatic reference counting.
2530 /// \param FromType The type we're converting form.
2532 /// \param ToType The type we're converting to.
2534 /// \param ConvertedType The type that will be produced after applying
2535 /// this conversion.
2536 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2537 QualType &ConvertedType) {
2538 if (!getLangOpts().ObjCAutoRefCount ||
2539 Context.hasSameUnqualifiedType(FromType, ToType))
2542 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2544 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2545 ToPointee = ToPointer->getPointeeType();
2549 Qualifiers ToQuals = ToPointee.getQualifiers();
2550 if (!ToPointee->isObjCLifetimeType() ||
2551 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2552 !ToQuals.withoutObjCLifetime().empty())
2555 // Argument must be a pointer to __strong to __weak.
2556 QualType FromPointee;
2557 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2558 FromPointee = FromPointer->getPointeeType();
2562 Qualifiers FromQuals = FromPointee.getQualifiers();
2563 if (!FromPointee->isObjCLifetimeType() ||
2564 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2565 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2568 // Make sure that we have compatible qualifiers.
2569 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2570 if (!ToQuals.compatiblyIncludes(FromQuals))
2573 // Remove qualifiers from the pointee type we're converting from; they
2574 // aren't used in the compatibility check belong, and we'll be adding back
2575 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2576 FromPointee = FromPointee.getUnqualifiedType();
2578 // The unqualified form of the pointee types must be compatible.
2579 ToPointee = ToPointee.getUnqualifiedType();
2580 bool IncompatibleObjC;
2581 if (Context.typesAreCompatible(FromPointee, ToPointee))
2582 FromPointee = ToPointee;
2583 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2587 /// \brief Construct the type we're converting to, which is a pointer to
2588 /// __autoreleasing pointee.
2589 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2590 ConvertedType = Context.getPointerType(FromPointee);
2594 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2595 QualType& ConvertedType) {
2596 QualType ToPointeeType;
2597 if (const BlockPointerType *ToBlockPtr =
2598 ToType->getAs<BlockPointerType>())
2599 ToPointeeType = ToBlockPtr->getPointeeType();
2603 QualType FromPointeeType;
2604 if (const BlockPointerType *FromBlockPtr =
2605 FromType->getAs<BlockPointerType>())
2606 FromPointeeType = FromBlockPtr->getPointeeType();
2609 // We have pointer to blocks, check whether the only
2610 // differences in the argument and result types are in Objective-C
2611 // pointer conversions. If so, we permit the conversion.
2613 const FunctionProtoType *FromFunctionType
2614 = FromPointeeType->getAs<FunctionProtoType>();
2615 const FunctionProtoType *ToFunctionType
2616 = ToPointeeType->getAs<FunctionProtoType>();
2618 if (!FromFunctionType || !ToFunctionType)
2621 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2624 // Perform the quick checks that will tell us whether these
2625 // function types are obviously different.
2626 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2627 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2630 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2631 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2632 if (FromEInfo != ToEInfo)
2635 bool IncompatibleObjC = false;
2636 if (Context.hasSameType(FromFunctionType->getReturnType(),
2637 ToFunctionType->getReturnType())) {
2638 // Okay, the types match exactly. Nothing to do.
2640 QualType RHS = FromFunctionType->getReturnType();
2641 QualType LHS = ToFunctionType->getReturnType();
2642 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2643 !RHS.hasQualifiers() && LHS.hasQualifiers())
2644 LHS = LHS.getUnqualifiedType();
2646 if (Context.hasSameType(RHS,LHS)) {
2648 } else if (isObjCPointerConversion(RHS, LHS,
2649 ConvertedType, IncompatibleObjC)) {
2650 if (IncompatibleObjC)
2652 // Okay, we have an Objective-C pointer conversion.
2658 // Check argument types.
2659 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2660 ArgIdx != NumArgs; ++ArgIdx) {
2661 IncompatibleObjC = false;
2662 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2663 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2664 if (Context.hasSameType(FromArgType, ToArgType)) {
2665 // Okay, the types match exactly. Nothing to do.
2666 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2667 ConvertedType, IncompatibleObjC)) {
2668 if (IncompatibleObjC)
2670 // Okay, we have an Objective-C pointer conversion.
2672 // Argument types are too different. Abort.
2675 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2679 ConvertedType = ToType;
2687 ft_parameter_mismatch,
2689 ft_qualifer_mismatch,
2693 /// Attempts to get the FunctionProtoType from a Type. Handles
2694 /// MemberFunctionPointers properly.
2695 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2696 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2699 if (auto *MPT = FromType->getAs<MemberPointerType>())
2700 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2705 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2706 /// function types. Catches different number of parameter, mismatch in
2707 /// parameter types, and different return types.
2708 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2709 QualType FromType, QualType ToType) {
2710 // If either type is not valid, include no extra info.
2711 if (FromType.isNull() || ToType.isNull()) {
2712 PDiag << ft_default;
2716 // Get the function type from the pointers.
2717 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2718 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2719 *ToMember = ToType->getAs<MemberPointerType>();
2720 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2721 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2722 << QualType(FromMember->getClass(), 0);
2725 FromType = FromMember->getPointeeType();
2726 ToType = ToMember->getPointeeType();
2729 if (FromType->isPointerType())
2730 FromType = FromType->getPointeeType();
2731 if (ToType->isPointerType())
2732 ToType = ToType->getPointeeType();
2734 // Remove references.
2735 FromType = FromType.getNonReferenceType();
2736 ToType = ToType.getNonReferenceType();
2738 // Don't print extra info for non-specialized template functions.
2739 if (FromType->isInstantiationDependentType() &&
2740 !FromType->getAs<TemplateSpecializationType>()) {
2741 PDiag << ft_default;
2745 // No extra info for same types.
2746 if (Context.hasSameType(FromType, ToType)) {
2747 PDiag << ft_default;
2751 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2752 *ToFunction = tryGetFunctionProtoType(ToType);
2754 // Both types need to be function types.
2755 if (!FromFunction || !ToFunction) {
2756 PDiag << ft_default;
2760 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2761 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2762 << FromFunction->getNumParams();
2766 // Handle different parameter types.
2768 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2769 PDiag << ft_parameter_mismatch << ArgPos + 1
2770 << ToFunction->getParamType(ArgPos)
2771 << FromFunction->getParamType(ArgPos);
2775 // Handle different return type.
2776 if (!Context.hasSameType(FromFunction->getReturnType(),
2777 ToFunction->getReturnType())) {
2778 PDiag << ft_return_type << ToFunction->getReturnType()
2779 << FromFunction->getReturnType();
2783 unsigned FromQuals = FromFunction->getTypeQuals(),
2784 ToQuals = ToFunction->getTypeQuals();
2785 if (FromQuals != ToQuals) {
2786 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2790 // Handle exception specification differences on canonical type (in C++17
2792 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2793 ->isNothrow(Context) !=
2794 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2795 ->isNothrow(Context)) {
2796 PDiag << ft_noexcept;
2800 // Unable to find a difference, so add no extra info.
2801 PDiag << ft_default;
2804 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2805 /// for equality of their argument types. Caller has already checked that
2806 /// they have same number of arguments. If the parameters are different,
2807 /// ArgPos will have the parameter index of the first different parameter.
2808 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2809 const FunctionProtoType *NewType,
2811 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2812 N = NewType->param_type_begin(),
2813 E = OldType->param_type_end();
2814 O && (O != E); ++O, ++N) {
2815 if (!Context.hasSameType(O->getUnqualifiedType(),
2816 N->getUnqualifiedType())) {
2818 *ArgPos = O - OldType->param_type_begin();
2825 /// CheckPointerConversion - Check the pointer conversion from the
2826 /// expression From to the type ToType. This routine checks for
2827 /// ambiguous or inaccessible derived-to-base pointer
2828 /// conversions for which IsPointerConversion has already returned
2829 /// true. It returns true and produces a diagnostic if there was an
2830 /// error, or returns false otherwise.
2831 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2833 CXXCastPath& BasePath,
2834 bool IgnoreBaseAccess,
2836 QualType FromType = From->getType();
2837 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2841 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2842 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2843 Expr::NPCK_ZeroExpression) {
2844 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2845 DiagRuntimeBehavior(From->getExprLoc(), From,
2846 PDiag(diag::warn_impcast_bool_to_null_pointer)
2847 << ToType << From->getSourceRange());
2848 else if (!isUnevaluatedContext())
2849 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2850 << ToType << From->getSourceRange();
2852 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2853 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2854 QualType FromPointeeType = FromPtrType->getPointeeType(),
2855 ToPointeeType = ToPtrType->getPointeeType();
2857 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2858 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2859 // We must have a derived-to-base conversion. Check an
2860 // ambiguous or inaccessible conversion.
2861 unsigned InaccessibleID = 0;
2862 unsigned AmbigiousID = 0;
2864 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2865 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2867 if (CheckDerivedToBaseConversion(
2868 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2869 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2870 &BasePath, IgnoreBaseAccess))
2873 // The conversion was successful.
2874 Kind = CK_DerivedToBase;
2877 if (Diagnose && !IsCStyleOrFunctionalCast &&
2878 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2879 assert(getLangOpts().MSVCCompat &&
2880 "this should only be possible with MSVCCompat!");
2881 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2882 << From->getSourceRange();
2885 } else if (const ObjCObjectPointerType *ToPtrType =
2886 ToType->getAs<ObjCObjectPointerType>()) {
2887 if (const ObjCObjectPointerType *FromPtrType =
2888 FromType->getAs<ObjCObjectPointerType>()) {
2889 // Objective-C++ conversions are always okay.
2890 // FIXME: We should have a different class of conversions for the
2891 // Objective-C++ implicit conversions.
2892 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2894 } else if (FromType->isBlockPointerType()) {
2895 Kind = CK_BlockPointerToObjCPointerCast;
2897 Kind = CK_CPointerToObjCPointerCast;
2899 } else if (ToType->isBlockPointerType()) {
2900 if (!FromType->isBlockPointerType())
2901 Kind = CK_AnyPointerToBlockPointerCast;
2904 // We shouldn't fall into this case unless it's valid for other
2906 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2907 Kind = CK_NullToPointer;
2912 /// IsMemberPointerConversion - Determines whether the conversion of the
2913 /// expression From, which has the (possibly adjusted) type FromType, can be
2914 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2915 /// If so, returns true and places the converted type (that might differ from
2916 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2917 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2919 bool InOverloadResolution,
2920 QualType &ConvertedType) {
2921 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2925 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2926 if (From->isNullPointerConstant(Context,
2927 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2928 : Expr::NPC_ValueDependentIsNull)) {
2929 ConvertedType = ToType;
2933 // Otherwise, both types have to be member pointers.
2934 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2938 // A pointer to member of B can be converted to a pointer to member of D,
2939 // where D is derived from B (C++ 4.11p2).
2940 QualType FromClass(FromTypePtr->getClass(), 0);
2941 QualType ToClass(ToTypePtr->getClass(), 0);
2943 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2944 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2945 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2946 ToClass.getTypePtr());
2953 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2954 /// expression From to the type ToType. This routine checks for ambiguous or
2955 /// virtual or inaccessible base-to-derived member pointer conversions
2956 /// for which IsMemberPointerConversion has already returned true. It returns
2957 /// true and produces a diagnostic if there was an error, or returns false
2959 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2961 CXXCastPath &BasePath,
2962 bool IgnoreBaseAccess) {
2963 QualType FromType = From->getType();
2964 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2966 // This must be a null pointer to member pointer conversion
2967 assert(From->isNullPointerConstant(Context,
2968 Expr::NPC_ValueDependentIsNull) &&
2969 "Expr must be null pointer constant!");
2970 Kind = CK_NullToMemberPointer;
2974 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2975 assert(ToPtrType && "No member pointer cast has a target type "
2976 "that is not a member pointer.");
2978 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2979 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2981 // FIXME: What about dependent types?
2982 assert(FromClass->isRecordType() && "Pointer into non-class.");
2983 assert(ToClass->isRecordType() && "Pointer into non-class.");
2985 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2986 /*DetectVirtual=*/true);
2987 bool DerivationOkay =
2988 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2989 assert(DerivationOkay &&
2990 "Should not have been called if derivation isn't OK.");
2991 (void)DerivationOkay;
2993 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2994 getUnqualifiedType())) {
2995 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2996 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2997 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3001 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3002 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3003 << FromClass << ToClass << QualType(VBase, 0)
3004 << From->getSourceRange();
3008 if (!IgnoreBaseAccess)
3009 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3011 diag::err_downcast_from_inaccessible_base);
3013 // Must be a base to derived member conversion.
3014 BuildBasePathArray(Paths, BasePath);
3015 Kind = CK_BaseToDerivedMemberPointer;
3019 /// Determine whether the lifetime conversion between the two given
3020 /// qualifiers sets is nontrivial.
3021 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3022 Qualifiers ToQuals) {
3023 // Converting anything to const __unsafe_unretained is trivial.
3024 if (ToQuals.hasConst() &&
3025 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3031 /// IsQualificationConversion - Determines whether the conversion from
3032 /// an rvalue of type FromType to ToType is a qualification conversion
3035 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3036 /// when the qualification conversion involves a change in the Objective-C
3037 /// object lifetime.
3039 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3040 bool CStyle, bool &ObjCLifetimeConversion) {
3041 FromType = Context.getCanonicalType(FromType);
3042 ToType = Context.getCanonicalType(ToType);
3043 ObjCLifetimeConversion = false;
3045 // If FromType and ToType are the same type, this is not a
3046 // qualification conversion.
3047 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3051 // A conversion can add cv-qualifiers at levels other than the first
3052 // in multi-level pointers, subject to the following rules: [...]
3053 bool PreviousToQualsIncludeConst = true;
3054 bool UnwrappedAnyPointer = false;
3055 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3056 // Within each iteration of the loop, we check the qualifiers to
3057 // determine if this still looks like a qualification
3058 // conversion. Then, if all is well, we unwrap one more level of
3059 // pointers or pointers-to-members and do it all again
3060 // until there are no more pointers or pointers-to-members left to
3062 UnwrappedAnyPointer = true;
3064 Qualifiers FromQuals = FromType.getQualifiers();
3065 Qualifiers ToQuals = ToType.getQualifiers();
3067 // Ignore __unaligned qualifier if this type is void.
3068 if (ToType.getUnqualifiedType()->isVoidType())
3069 FromQuals.removeUnaligned();
3072 // Check Objective-C lifetime conversions.
3073 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3074 UnwrappedAnyPointer) {
3075 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3076 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3077 ObjCLifetimeConversion = true;
3078 FromQuals.removeObjCLifetime();
3079 ToQuals.removeObjCLifetime();
3081 // Qualification conversions cannot cast between different
3082 // Objective-C lifetime qualifiers.
3087 // Allow addition/removal of GC attributes but not changing GC attributes.
3088 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3089 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3090 FromQuals.removeObjCGCAttr();
3091 ToQuals.removeObjCGCAttr();
3094 // -- for every j > 0, if const is in cv 1,j then const is in cv
3095 // 2,j, and similarly for volatile.
3096 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3099 // -- if the cv 1,j and cv 2,j are different, then const is in
3100 // every cv for 0 < k < j.
3101 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3102 && !PreviousToQualsIncludeConst)
3105 // Keep track of whether all prior cv-qualifiers in the "to" type
3107 PreviousToQualsIncludeConst
3108 = PreviousToQualsIncludeConst && ToQuals.hasConst();
3111 // We are left with FromType and ToType being the pointee types
3112 // after unwrapping the original FromType and ToType the same number
3113 // of types. If we unwrapped any pointers, and if FromType and
3114 // ToType have the same unqualified type (since we checked
3115 // qualifiers above), then this is a qualification conversion.
3116 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3119 /// \brief - Determine whether this is a conversion from a scalar type to an
3122 /// If successful, updates \c SCS's second and third steps in the conversion
3123 /// sequence to finish the conversion.
3124 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3125 bool InOverloadResolution,
3126 StandardConversionSequence &SCS,
3128 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3132 StandardConversionSequence InnerSCS;
3133 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3134 InOverloadResolution, InnerSCS,
3135 CStyle, /*AllowObjCWritebackConversion=*/false))
3138 SCS.Second = InnerSCS.Second;
3139 SCS.setToType(1, InnerSCS.getToType(1));
3140 SCS.Third = InnerSCS.Third;
3141 SCS.QualificationIncludesObjCLifetime
3142 = InnerSCS.QualificationIncludesObjCLifetime;
3143 SCS.setToType(2, InnerSCS.getToType(2));
3147 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3148 CXXConstructorDecl *Constructor,
3150 const FunctionProtoType *CtorType =
3151 Constructor->getType()->getAs<FunctionProtoType>();
3152 if (CtorType->getNumParams() > 0) {
3153 QualType FirstArg = CtorType->getParamType(0);
3154 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3160 static OverloadingResult
3161 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3163 UserDefinedConversionSequence &User,
3164 OverloadCandidateSet &CandidateSet,
3165 bool AllowExplicit) {
3166 for (auto *D : S.LookupConstructors(To)) {
3167 auto Info = getConstructorInfo(D);
3171 bool Usable = !Info.Constructor->isInvalidDecl() &&
3172 S.isInitListConstructor(Info.Constructor) &&
3173 (AllowExplicit || !Info.Constructor->isExplicit());
3175 // If the first argument is (a reference to) the target type,
3176 // suppress conversions.
3177 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3178 S.Context, Info.Constructor, ToType);
3179 if (Info.ConstructorTmpl)
3180 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3181 /*ExplicitArgs*/ nullptr, From,
3182 CandidateSet, SuppressUserConversions);
3184 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3185 CandidateSet, SuppressUserConversions);
3189 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3191 OverloadCandidateSet::iterator Best;
3192 switch (auto Result =
3193 CandidateSet.BestViableFunction(S, From->getLocStart(),
3197 // Record the standard conversion we used and the conversion function.
3198 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3199 QualType ThisType = Constructor->getThisType(S.Context);
3200 // Initializer lists don't have conversions as such.
3201 User.Before.setAsIdentityConversion();
3202 User.HadMultipleCandidates = HadMultipleCandidates;
3203 User.ConversionFunction = Constructor;
3204 User.FoundConversionFunction = Best->FoundDecl;
3205 User.After.setAsIdentityConversion();
3206 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3207 User.After.setAllToTypes(ToType);
3211 case OR_No_Viable_Function:
3212 return OR_No_Viable_Function;
3214 return OR_Ambiguous;
3217 llvm_unreachable("Invalid OverloadResult!");
3220 /// Determines whether there is a user-defined conversion sequence
3221 /// (C++ [over.ics.user]) that converts expression From to the type
3222 /// ToType. If such a conversion exists, User will contain the
3223 /// user-defined conversion sequence that performs such a conversion
3224 /// and this routine will return true. Otherwise, this routine returns
3225 /// false and User is unspecified.
3227 /// \param AllowExplicit true if the conversion should consider C++0x
3228 /// "explicit" conversion functions as well as non-explicit conversion
3229 /// functions (C++0x [class.conv.fct]p2).
3231 /// \param AllowObjCConversionOnExplicit true if the conversion should
3232 /// allow an extra Objective-C pointer conversion on uses of explicit
3233 /// constructors. Requires \c AllowExplicit to also be set.
3234 static OverloadingResult
3235 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3236 UserDefinedConversionSequence &User,
3237 OverloadCandidateSet &CandidateSet,
3239 bool AllowObjCConversionOnExplicit) {
3240 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3242 // Whether we will only visit constructors.
3243 bool ConstructorsOnly = false;
3245 // If the type we are conversion to is a class type, enumerate its
3247 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3248 // C++ [over.match.ctor]p1:
3249 // When objects of class type are direct-initialized (8.5), or
3250 // copy-initialized from an expression of the same or a
3251 // derived class type (8.5), overload resolution selects the
3252 // constructor. [...] For copy-initialization, the candidate
3253 // functions are all the converting constructors (12.3.1) of
3254 // that class. The argument list is the expression-list within
3255 // the parentheses of the initializer.
3256 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3257 (From->getType()->getAs<RecordType>() &&
3258 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3259 ConstructorsOnly = true;
3261 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3262 // We're not going to find any constructors.
3263 } else if (CXXRecordDecl *ToRecordDecl
3264 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3266 Expr **Args = &From;
3267 unsigned NumArgs = 1;
3268 bool ListInitializing = false;
3269 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3270 // But first, see if there is an init-list-constructor that will work.
3271 OverloadingResult Result = IsInitializerListConstructorConversion(
3272 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3273 if (Result != OR_No_Viable_Function)
3276 CandidateSet.clear();
3278 // If we're list-initializing, we pass the individual elements as
3279 // arguments, not the entire list.
3280 Args = InitList->getInits();
3281 NumArgs = InitList->getNumInits();
3282 ListInitializing = true;
3285 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3286 auto Info = getConstructorInfo(D);
3290 bool Usable = !Info.Constructor->isInvalidDecl();
3291 if (ListInitializing)
3292 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3295 Info.Constructor->isConvertingConstructor(AllowExplicit);
3297 bool SuppressUserConversions = !ConstructorsOnly;
3298 if (SuppressUserConversions && ListInitializing) {
3299 SuppressUserConversions = false;
3301 // If the first argument is (a reference to) the target type,
3302 // suppress conversions.
3303 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3304 S.Context, Info.Constructor, ToType);
3307 if (Info.ConstructorTmpl)
3308 S.AddTemplateOverloadCandidate(
3309 Info.ConstructorTmpl, Info.FoundDecl,
3310 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3311 CandidateSet, SuppressUserConversions);
3313 // Allow one user-defined conversion when user specifies a
3314 // From->ToType conversion via an static cast (c-style, etc).
3315 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3316 llvm::makeArrayRef(Args, NumArgs),
3317 CandidateSet, SuppressUserConversions);
3323 // Enumerate conversion functions, if we're allowed to.
3324 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3325 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3326 // No conversion functions from incomplete types.
3327 } else if (const RecordType *FromRecordType
3328 = From->getType()->getAs<RecordType>()) {
3329 if (CXXRecordDecl *FromRecordDecl
3330 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3331 // Add all of the conversion functions as candidates.
3332 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3333 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3334 DeclAccessPair FoundDecl = I.getPair();
3335 NamedDecl *D = FoundDecl.getDecl();
3336 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3337 if (isa<UsingShadowDecl>(D))
3338 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3340 CXXConversionDecl *Conv;
3341 FunctionTemplateDecl *ConvTemplate;
3342 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3343 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3345 Conv = cast<CXXConversionDecl>(D);
3347 if (AllowExplicit || !Conv->isExplicit()) {
3349 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3350 ActingContext, From, ToType,
3352 AllowObjCConversionOnExplicit);
3354 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3355 From, ToType, CandidateSet,
3356 AllowObjCConversionOnExplicit);
3362 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3364 OverloadCandidateSet::iterator Best;
3365 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3369 // Record the standard conversion we used and the conversion function.
3370 if (CXXConstructorDecl *Constructor
3371 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3372 // C++ [over.ics.user]p1:
3373 // If the user-defined conversion is specified by a
3374 // constructor (12.3.1), the initial standard conversion
3375 // sequence converts the source type to the type required by
3376 // the argument of the constructor.
3378 QualType ThisType = Constructor->getThisType(S.Context);
3379 if (isa<InitListExpr>(From)) {
3380 // Initializer lists don't have conversions as such.
3381 User.Before.setAsIdentityConversion();
3383 if (Best->Conversions[0].isEllipsis())
3384 User.EllipsisConversion = true;
3386 User.Before = Best->Conversions[0].Standard;
3387 User.EllipsisConversion = false;
3390 User.HadMultipleCandidates = HadMultipleCandidates;
3391 User.ConversionFunction = Constructor;
3392 User.FoundConversionFunction = Best->FoundDecl;
3393 User.After.setAsIdentityConversion();
3394 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3395 User.After.setAllToTypes(ToType);
3398 if (CXXConversionDecl *Conversion
3399 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3400 // C++ [over.ics.user]p1:
3402 // [...] If the user-defined conversion is specified by a
3403 // conversion function (12.3.2), the initial standard
3404 // conversion sequence converts the source type to the
3405 // implicit object parameter of the conversion function.
3406 User.Before = Best->Conversions[0].Standard;
3407 User.HadMultipleCandidates = HadMultipleCandidates;
3408 User.ConversionFunction = Conversion;
3409 User.FoundConversionFunction = Best->FoundDecl;
3410 User.EllipsisConversion = false;
3412 // C++ [over.ics.user]p2:
3413 // The second standard conversion sequence converts the
3414 // result of the user-defined conversion to the target type
3415 // for the sequence. Since an implicit conversion sequence
3416 // is an initialization, the special rules for
3417 // initialization by user-defined conversion apply when
3418 // selecting the best user-defined conversion for a
3419 // user-defined conversion sequence (see 13.3.3 and
3421 User.After = Best->FinalConversion;
3424 llvm_unreachable("Not a constructor or conversion function?");
3426 case OR_No_Viable_Function:
3427 return OR_No_Viable_Function;
3430 return OR_Ambiguous;
3433 llvm_unreachable("Invalid OverloadResult!");
3437 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3438 ImplicitConversionSequence ICS;
3439 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3440 OverloadCandidateSet::CSK_Normal);
3441 OverloadingResult OvResult =
3442 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3443 CandidateSet, false, false);
3444 if (OvResult == OR_Ambiguous)
3445 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3446 << From->getType() << ToType << From->getSourceRange();
3447 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3448 if (!RequireCompleteType(From->getLocStart(), ToType,
3449 diag::err_typecheck_nonviable_condition_incomplete,
3450 From->getType(), From->getSourceRange()))
3451 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3452 << false << From->getType() << From->getSourceRange() << ToType;
3455 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3459 /// \brief Compare the user-defined conversion functions or constructors
3460 /// of two user-defined conversion sequences to determine whether any ordering
3462 static ImplicitConversionSequence::CompareKind
3463 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3464 FunctionDecl *Function2) {
3465 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3466 return ImplicitConversionSequence::Indistinguishable;
3469 // If both conversion functions are implicitly-declared conversions from
3470 // a lambda closure type to a function pointer and a block pointer,
3471 // respectively, always prefer the conversion to a function pointer,
3472 // because the function pointer is more lightweight and is more likely
3473 // to keep code working.
3474 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3476 return ImplicitConversionSequence::Indistinguishable;
3478 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3480 return ImplicitConversionSequence::Indistinguishable;
3482 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3483 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3484 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3485 if (Block1 != Block2)
3486 return Block1 ? ImplicitConversionSequence::Worse
3487 : ImplicitConversionSequence::Better;
3490 return ImplicitConversionSequence::Indistinguishable;
3493 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3494 const ImplicitConversionSequence &ICS) {
3495 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3496 (ICS.isUserDefined() &&
3497 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3500 /// CompareImplicitConversionSequences - Compare two implicit
3501 /// conversion sequences to determine whether one is better than the
3502 /// other or if they are indistinguishable (C++ 13.3.3.2).
3503 static ImplicitConversionSequence::CompareKind
3504 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3505 const ImplicitConversionSequence& ICS1,
3506 const ImplicitConversionSequence& ICS2)
3508 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3509 // conversion sequences (as defined in 13.3.3.1)
3510 // -- a standard conversion sequence (13.3.3.1.1) is a better
3511 // conversion sequence than a user-defined conversion sequence or
3512 // an ellipsis conversion sequence, and
3513 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3514 // conversion sequence than an ellipsis conversion sequence
3517 // C++0x [over.best.ics]p10:
3518 // For the purpose of ranking implicit conversion sequences as
3519 // described in 13.3.3.2, the ambiguous conversion sequence is
3520 // treated as a user-defined sequence that is indistinguishable
3521 // from any other user-defined conversion sequence.
3523 // String literal to 'char *' conversion has been deprecated in C++03. It has
3524 // been removed from C++11. We still accept this conversion, if it happens at
3525 // the best viable function. Otherwise, this conversion is considered worse
3526 // than ellipsis conversion. Consider this as an extension; this is not in the
3527 // standard. For example:
3529 // int &f(...); // #1
3530 // void f(char*); // #2
3531 // void g() { int &r = f("foo"); }
3533 // In C++03, we pick #2 as the best viable function.
3534 // In C++11, we pick #1 as the best viable function, because ellipsis
3535 // conversion is better than string-literal to char* conversion (since there
3536 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3537 // convert arguments, #2 would be the best viable function in C++11.
3538 // If the best viable function has this conversion, a warning will be issued
3539 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3541 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3542 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3543 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3544 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3545 ? ImplicitConversionSequence::Worse
3546 : ImplicitConversionSequence::Better;
3548 if (ICS1.getKindRank() < ICS2.getKindRank())
3549 return ImplicitConversionSequence::Better;
3550 if (ICS2.getKindRank() < ICS1.getKindRank())
3551 return ImplicitConversionSequence::Worse;
3553 // The following checks require both conversion sequences to be of
3555 if (ICS1.getKind() != ICS2.getKind())
3556 return ImplicitConversionSequence::Indistinguishable;
3558 ImplicitConversionSequence::CompareKind Result =
3559 ImplicitConversionSequence::Indistinguishable;
3561 // Two implicit conversion sequences of the same form are
3562 // indistinguishable conversion sequences unless one of the
3563 // following rules apply: (C++ 13.3.3.2p3):
3565 // List-initialization sequence L1 is a better conversion sequence than
3566 // list-initialization sequence L2 if:
3567 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3569 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3570 // and N1 is smaller than N2.,
3571 // even if one of the other rules in this paragraph would otherwise apply.
3572 if (!ICS1.isBad()) {
3573 if (ICS1.isStdInitializerListElement() &&
3574 !ICS2.isStdInitializerListElement())
3575 return ImplicitConversionSequence::Better;
3576 if (!ICS1.isStdInitializerListElement() &&
3577 ICS2.isStdInitializerListElement())
3578 return ImplicitConversionSequence::Worse;
3581 if (ICS1.isStandard())
3582 // Standard conversion sequence S1 is a better conversion sequence than
3583 // standard conversion sequence S2 if [...]
3584 Result = CompareStandardConversionSequences(S, Loc,
3585 ICS1.Standard, ICS2.Standard);
3586 else if (ICS1.isUserDefined()) {
3587 // User-defined conversion sequence U1 is a better conversion
3588 // sequence than another user-defined conversion sequence U2 if
3589 // they contain the same user-defined conversion function or
3590 // constructor and if the second standard conversion sequence of
3591 // U1 is better than the second standard conversion sequence of
3592 // U2 (C++ 13.3.3.2p3).
3593 if (ICS1.UserDefined.ConversionFunction ==
3594 ICS2.UserDefined.ConversionFunction)
3595 Result = CompareStandardConversionSequences(S, Loc,
3596 ICS1.UserDefined.After,
3597 ICS2.UserDefined.After);
3599 Result = compareConversionFunctions(S,
3600 ICS1.UserDefined.ConversionFunction,
3601 ICS2.UserDefined.ConversionFunction);
3607 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3608 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3610 T1 = Context.getUnqualifiedArrayType(T1, Quals);
3611 T2 = Context.getUnqualifiedArrayType(T2, Quals);
3614 return Context.hasSameUnqualifiedType(T1, T2);
3617 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3618 // determine if one is a proper subset of the other.
3619 static ImplicitConversionSequence::CompareKind
3620 compareStandardConversionSubsets(ASTContext &Context,
3621 const StandardConversionSequence& SCS1,
3622 const StandardConversionSequence& SCS2) {
3623 ImplicitConversionSequence::CompareKind Result
3624 = ImplicitConversionSequence::Indistinguishable;
3626 // the identity conversion sequence is considered to be a subsequence of
3627 // any non-identity conversion sequence
3628 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3629 return ImplicitConversionSequence::Better;
3630 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3631 return ImplicitConversionSequence::Worse;
3633 if (SCS1.Second != SCS2.Second) {
3634 if (SCS1.Second == ICK_Identity)
3635 Result = ImplicitConversionSequence::Better;
3636 else if (SCS2.Second == ICK_Identity)
3637 Result = ImplicitConversionSequence::Worse;
3639 return ImplicitConversionSequence::Indistinguishable;
3640 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3641 return ImplicitConversionSequence::Indistinguishable;
3643 if (SCS1.Third == SCS2.Third) {
3644 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3645 : ImplicitConversionSequence::Indistinguishable;
3648 if (SCS1.Third == ICK_Identity)
3649 return Result == ImplicitConversionSequence::Worse
3650 ? ImplicitConversionSequence::Indistinguishable
3651 : ImplicitConversionSequence::Better;
3653 if (SCS2.Third == ICK_Identity)
3654 return Result == ImplicitConversionSequence::Better
3655 ? ImplicitConversionSequence::Indistinguishable
3656 : ImplicitConversionSequence::Worse;
3658 return ImplicitConversionSequence::Indistinguishable;
3661 /// \brief Determine whether one of the given reference bindings is better
3662 /// than the other based on what kind of bindings they are.
3664 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3665 const StandardConversionSequence &SCS2) {
3666 // C++0x [over.ics.rank]p3b4:
3667 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3668 // implicit object parameter of a non-static member function declared
3669 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3670 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3671 // lvalue reference to a function lvalue and S2 binds an rvalue
3674 // FIXME: Rvalue references. We're going rogue with the above edits,
3675 // because the semantics in the current C++0x working paper (N3225 at the
3676 // time of this writing) break the standard definition of std::forward
3677 // and std::reference_wrapper when dealing with references to functions.
3678 // Proposed wording changes submitted to CWG for consideration.
3679 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3680 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3683 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3684 SCS2.IsLvalueReference) ||
3685 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3686 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3689 /// CompareStandardConversionSequences - Compare two standard
3690 /// conversion sequences to determine whether one is better than the
3691 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3692 static ImplicitConversionSequence::CompareKind
3693 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3694 const StandardConversionSequence& SCS1,
3695 const StandardConversionSequence& SCS2)
3697 // Standard conversion sequence S1 is a better conversion sequence
3698 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3700 // -- S1 is a proper subsequence of S2 (comparing the conversion
3701 // sequences in the canonical form defined by 13.3.3.1.1,
3702 // excluding any Lvalue Transformation; the identity conversion
3703 // sequence is considered to be a subsequence of any
3704 // non-identity conversion sequence) or, if not that,
3705 if (ImplicitConversionSequence::CompareKind CK
3706 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3709 // -- the rank of S1 is better than the rank of S2 (by the rules
3710 // defined below), or, if not that,
3711 ImplicitConversionRank Rank1 = SCS1.getRank();
3712 ImplicitConversionRank Rank2 = SCS2.getRank();
3714 return ImplicitConversionSequence::Better;
3715 else if (Rank2 < Rank1)
3716 return ImplicitConversionSequence::Worse;
3718 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3719 // are indistinguishable unless one of the following rules
3722 // A conversion that is not a conversion of a pointer, or
3723 // pointer to member, to bool is better than another conversion
3724 // that is such a conversion.
3725 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3726 return SCS2.isPointerConversionToBool()
3727 ? ImplicitConversionSequence::Better
3728 : ImplicitConversionSequence::Worse;
3730 // C++ [over.ics.rank]p4b2:
3732 // If class B is derived directly or indirectly from class A,
3733 // conversion of B* to A* is better than conversion of B* to
3734 // void*, and conversion of A* to void* is better than conversion
3736 bool SCS1ConvertsToVoid
3737 = SCS1.isPointerConversionToVoidPointer(S.Context);
3738 bool SCS2ConvertsToVoid
3739 = SCS2.isPointerConversionToVoidPointer(S.Context);
3740 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3741 // Exactly one of the conversion sequences is a conversion to
3742 // a void pointer; it's the worse conversion.
3743 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3744 : ImplicitConversionSequence::Worse;
3745 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3746 // Neither conversion sequence converts to a void pointer; compare
3747 // their derived-to-base conversions.
3748 if (ImplicitConversionSequence::CompareKind DerivedCK
3749 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3751 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3752 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3753 // Both conversion sequences are conversions to void
3754 // pointers. Compare the source types to determine if there's an
3755 // inheritance relationship in their sources.
3756 QualType FromType1 = SCS1.getFromType();
3757 QualType FromType2 = SCS2.getFromType();
3759 // Adjust the types we're converting from via the array-to-pointer
3760 // conversion, if we need to.
3761 if (SCS1.First == ICK_Array_To_Pointer)
3762 FromType1 = S.Context.getArrayDecayedType(FromType1);
3763 if (SCS2.First == ICK_Array_To_Pointer)
3764 FromType2 = S.Context.getArrayDecayedType(FromType2);
3766 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3767 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3769 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3770 return ImplicitConversionSequence::Better;
3771 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3772 return ImplicitConversionSequence::Worse;
3774 // Objective-C++: If one interface is more specific than the
3775 // other, it is the better one.
3776 const ObjCObjectPointerType* FromObjCPtr1
3777 = FromType1->getAs<ObjCObjectPointerType>();
3778 const ObjCObjectPointerType* FromObjCPtr2
3779 = FromType2->getAs<ObjCObjectPointerType>();
3780 if (FromObjCPtr1 && FromObjCPtr2) {
3781 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3783 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3785 if (AssignLeft != AssignRight) {
3786 return AssignLeft? ImplicitConversionSequence::Better
3787 : ImplicitConversionSequence::Worse;
3792 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3794 if (ImplicitConversionSequence::CompareKind QualCK
3795 = CompareQualificationConversions(S, SCS1, SCS2))
3798 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3799 // Check for a better reference binding based on the kind of bindings.
3800 if (isBetterReferenceBindingKind(SCS1, SCS2))
3801 return ImplicitConversionSequence::Better;
3802 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3803 return ImplicitConversionSequence::Worse;
3805 // C++ [over.ics.rank]p3b4:
3806 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3807 // which the references refer are the same type except for
3808 // top-level cv-qualifiers, and the type to which the reference
3809 // initialized by S2 refers is more cv-qualified than the type
3810 // to which the reference initialized by S1 refers.
3811 QualType T1 = SCS1.getToType(2);
3812 QualType T2 = SCS2.getToType(2);
3813 T1 = S.Context.getCanonicalType(T1);
3814 T2 = S.Context.getCanonicalType(T2);
3815 Qualifiers T1Quals, T2Quals;
3816 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3817 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3818 if (UnqualT1 == UnqualT2) {
3819 // Objective-C++ ARC: If the references refer to objects with different
3820 // lifetimes, prefer bindings that don't change lifetime.
3821 if (SCS1.ObjCLifetimeConversionBinding !=
3822 SCS2.ObjCLifetimeConversionBinding) {
3823 return SCS1.ObjCLifetimeConversionBinding
3824 ? ImplicitConversionSequence::Worse
3825 : ImplicitConversionSequence::Better;
3828 // If the type is an array type, promote the element qualifiers to the
3829 // type for comparison.
3830 if (isa<ArrayType>(T1) && T1Quals)
3831 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3832 if (isa<ArrayType>(T2) && T2Quals)
3833 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3834 if (T2.isMoreQualifiedThan(T1))
3835 return ImplicitConversionSequence::Better;
3836 else if (T1.isMoreQualifiedThan(T2))
3837 return ImplicitConversionSequence::Worse;
3841 // In Microsoft mode, prefer an integral conversion to a
3842 // floating-to-integral conversion if the integral conversion
3843 // is between types of the same size.
3851 // Here, MSVC will call f(int) instead of generating a compile error
3852 // as clang will do in standard mode.
3853 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3854 SCS2.Second == ICK_Floating_Integral &&
3855 S.Context.getTypeSize(SCS1.getFromType()) ==
3856 S.Context.getTypeSize(SCS1.getToType(2)))
3857 return ImplicitConversionSequence::Better;
3859 return ImplicitConversionSequence::Indistinguishable;
3862 /// CompareQualificationConversions - Compares two standard conversion
3863 /// sequences to determine whether they can be ranked based on their
3864 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3865 static ImplicitConversionSequence::CompareKind
3866 CompareQualificationConversions(Sema &S,
3867 const StandardConversionSequence& SCS1,
3868 const StandardConversionSequence& SCS2) {
3870 // -- S1 and S2 differ only in their qualification conversion and
3871 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3872 // cv-qualification signature of type T1 is a proper subset of
3873 // the cv-qualification signature of type T2, and S1 is not the
3874 // deprecated string literal array-to-pointer conversion (4.2).
3875 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3876 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3877 return ImplicitConversionSequence::Indistinguishable;
3879 // FIXME: the example in the standard doesn't use a qualification
3881 QualType T1 = SCS1.getToType(2);
3882 QualType T2 = SCS2.getToType(2);
3883 T1 = S.Context.getCanonicalType(T1);
3884 T2 = S.Context.getCanonicalType(T2);
3885 Qualifiers T1Quals, T2Quals;
3886 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3887 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3889 // If the types are the same, we won't learn anything by unwrapped
3891 if (UnqualT1 == UnqualT2)
3892 return ImplicitConversionSequence::Indistinguishable;
3894 // If the type is an array type, promote the element qualifiers to the type
3896 if (isa<ArrayType>(T1) && T1Quals)
3897 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3898 if (isa<ArrayType>(T2) && T2Quals)
3899 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3901 ImplicitConversionSequence::CompareKind Result
3902 = ImplicitConversionSequence::Indistinguishable;
3904 // Objective-C++ ARC:
3905 // Prefer qualification conversions not involving a change in lifetime
3906 // to qualification conversions that do not change lifetime.
3907 if (SCS1.QualificationIncludesObjCLifetime !=
3908 SCS2.QualificationIncludesObjCLifetime) {
3909 Result = SCS1.QualificationIncludesObjCLifetime
3910 ? ImplicitConversionSequence::Worse
3911 : ImplicitConversionSequence::Better;
3914 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3915 // Within each iteration of the loop, we check the qualifiers to
3916 // determine if this still looks like a qualification
3917 // conversion. Then, if all is well, we unwrap one more level of
3918 // pointers or pointers-to-members and do it all again
3919 // until there are no more pointers or pointers-to-members left
3920 // to unwrap. This essentially mimics what
3921 // IsQualificationConversion does, but here we're checking for a
3922 // strict subset of qualifiers.
3923 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3924 // The qualifiers are the same, so this doesn't tell us anything
3925 // about how the sequences rank.
3927 else if (T2.isMoreQualifiedThan(T1)) {
3928 // T1 has fewer qualifiers, so it could be the better sequence.
3929 if (Result == ImplicitConversionSequence::Worse)
3930 // Neither has qualifiers that are a subset of the other's
3932 return ImplicitConversionSequence::Indistinguishable;
3934 Result = ImplicitConversionSequence::Better;
3935 } else if (T1.isMoreQualifiedThan(T2)) {
3936 // T2 has fewer qualifiers, so it could be the better sequence.
3937 if (Result == ImplicitConversionSequence::Better)
3938 // Neither has qualifiers that are a subset of the other's
3940 return ImplicitConversionSequence::Indistinguishable;
3942 Result = ImplicitConversionSequence::Worse;
3944 // Qualifiers are disjoint.
3945 return ImplicitConversionSequence::Indistinguishable;
3948 // If the types after this point are equivalent, we're done.
3949 if (S.Context.hasSameUnqualifiedType(T1, T2))
3953 // Check that the winning standard conversion sequence isn't using
3954 // the deprecated string literal array to pointer conversion.
3956 case ImplicitConversionSequence::Better:
3957 if (SCS1.DeprecatedStringLiteralToCharPtr)
3958 Result = ImplicitConversionSequence::Indistinguishable;
3961 case ImplicitConversionSequence::Indistinguishable:
3964 case ImplicitConversionSequence::Worse:
3965 if (SCS2.DeprecatedStringLiteralToCharPtr)
3966 Result = ImplicitConversionSequence::Indistinguishable;
3973 /// CompareDerivedToBaseConversions - Compares two standard conversion
3974 /// sequences to determine whether they can be ranked based on their
3975 /// various kinds of derived-to-base conversions (C++
3976 /// [over.ics.rank]p4b3). As part of these checks, we also look at
3977 /// conversions between Objective-C interface types.
3978 static ImplicitConversionSequence::CompareKind
3979 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3980 const StandardConversionSequence& SCS1,
3981 const StandardConversionSequence& SCS2) {
3982 QualType FromType1 = SCS1.getFromType();
3983 QualType ToType1 = SCS1.getToType(1);
3984 QualType FromType2 = SCS2.getFromType();
3985 QualType ToType2 = SCS2.getToType(1);
3987 // Adjust the types we're converting from via the array-to-pointer
3988 // conversion, if we need to.
3989 if (SCS1.First == ICK_Array_To_Pointer)
3990 FromType1 = S.Context.getArrayDecayedType(FromType1);
3991 if (SCS2.First == ICK_Array_To_Pointer)
3992 FromType2 = S.Context.getArrayDecayedType(FromType2);
3994 // Canonicalize all of the types.
3995 FromType1 = S.Context.getCanonicalType(FromType1);
3996 ToType1 = S.Context.getCanonicalType(ToType1);
3997 FromType2 = S.Context.getCanonicalType(FromType2);
3998 ToType2 = S.Context.getCanonicalType(ToType2);
4000 // C++ [over.ics.rank]p4b3:
4002 // If class B is derived directly or indirectly from class A and
4003 // class C is derived directly or indirectly from B,
4005 // Compare based on pointer conversions.
4006 if (SCS1.Second == ICK_Pointer_Conversion &&
4007 SCS2.Second == ICK_Pointer_Conversion &&
4008 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4009 FromType1->isPointerType() && FromType2->isPointerType() &&
4010 ToType1->isPointerType() && ToType2->isPointerType()) {
4011 QualType FromPointee1
4012 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4014 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4015 QualType FromPointee2
4016 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4018 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4020 // -- conversion of C* to B* is better than conversion of C* to A*,
4021 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4022 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4023 return ImplicitConversionSequence::Better;
4024 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4025 return ImplicitConversionSequence::Worse;
4028 // -- conversion of B* to A* is better than conversion of C* to A*,
4029 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4030 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4031 return ImplicitConversionSequence::Better;
4032 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4033 return ImplicitConversionSequence::Worse;
4035 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4036 SCS2.Second == ICK_Pointer_Conversion) {
4037 const ObjCObjectPointerType *FromPtr1
4038 = FromType1->getAs<ObjCObjectPointerType>();
4039 const ObjCObjectPointerType *FromPtr2
4040 = FromType2->getAs<ObjCObjectPointerType>();
4041 const ObjCObjectPointerType *ToPtr1
4042 = ToType1->getAs<ObjCObjectPointerType>();
4043 const ObjCObjectPointerType *ToPtr2
4044 = ToType2->getAs<ObjCObjectPointerType>();
4046 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4047 // Apply the same conversion ranking rules for Objective-C pointer types
4048 // that we do for C++ pointers to class types. However, we employ the
4049 // Objective-C pseudo-subtyping relationship used for assignment of
4050 // Objective-C pointer types.
4052 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4053 bool FromAssignRight
4054 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4056 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4058 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4060 // A conversion to an a non-id object pointer type or qualified 'id'
4061 // type is better than a conversion to 'id'.
4062 if (ToPtr1->isObjCIdType() &&
4063 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4064 return ImplicitConversionSequence::Worse;
4065 if (ToPtr2->isObjCIdType() &&
4066 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4067 return ImplicitConversionSequence::Better;
4069 // A conversion to a non-id object pointer type is better than a
4070 // conversion to a qualified 'id' type
4071 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4072 return ImplicitConversionSequence::Worse;
4073 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4074 return ImplicitConversionSequence::Better;
4076 // A conversion to an a non-Class object pointer type or qualified 'Class'
4077 // type is better than a conversion to 'Class'.
4078 if (ToPtr1->isObjCClassType() &&
4079 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4080 return ImplicitConversionSequence::Worse;
4081 if (ToPtr2->isObjCClassType() &&
4082 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4083 return ImplicitConversionSequence::Better;
4085 // A conversion to a non-Class object pointer type is better than a
4086 // conversion to a qualified 'Class' type.
4087 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4088 return ImplicitConversionSequence::Worse;
4089 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4090 return ImplicitConversionSequence::Better;
4092 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4093 if (S.Context.hasSameType(FromType1, FromType2) &&
4094 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4095 (ToAssignLeft != ToAssignRight))
4096 return ToAssignLeft? ImplicitConversionSequence::Worse
4097 : ImplicitConversionSequence::Better;
4099 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4100 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4101 (FromAssignLeft != FromAssignRight))
4102 return FromAssignLeft? ImplicitConversionSequence::Better
4103 : ImplicitConversionSequence::Worse;
4107 // Ranking of member-pointer types.
4108 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4109 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4110 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4111 const MemberPointerType * FromMemPointer1 =
4112 FromType1->getAs<MemberPointerType>();
4113 const MemberPointerType * ToMemPointer1 =
4114 ToType1->getAs<MemberPointerType>();
4115 const MemberPointerType * FromMemPointer2 =
4116 FromType2->getAs<MemberPointerType>();
4117 const MemberPointerType * ToMemPointer2 =
4118 ToType2->getAs<MemberPointerType>();
4119 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4120 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4121 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4122 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4123 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4124 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4125 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4126 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4127 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4128 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4129 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4130 return ImplicitConversionSequence::Worse;
4131 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4132 return ImplicitConversionSequence::Better;
4134 // conversion of B::* to C::* is better than conversion of A::* to C::*
4135 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4136 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4137 return ImplicitConversionSequence::Better;
4138 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4139 return ImplicitConversionSequence::Worse;
4143 if (SCS1.Second == ICK_Derived_To_Base) {
4144 // -- conversion of C to B is better than conversion of C to A,
4145 // -- binding of an expression of type C to a reference of type
4146 // B& is better than binding an expression of type C to a
4147 // reference of type A&,
4148 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4149 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4150 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4151 return ImplicitConversionSequence::Better;
4152 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4153 return ImplicitConversionSequence::Worse;
4156 // -- conversion of B to A is better than conversion of C to A.
4157 // -- binding of an expression of type B to a reference of type
4158 // A& is better than binding an expression of type C to a
4159 // reference of type A&,
4160 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4161 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4162 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4163 return ImplicitConversionSequence::Better;
4164 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4165 return ImplicitConversionSequence::Worse;
4169 return ImplicitConversionSequence::Indistinguishable;
4172 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4174 static bool isTypeValid(QualType T) {
4175 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4176 return !Record->isInvalidDecl();
4181 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4182 /// determine whether they are reference-related,
4183 /// reference-compatible, reference-compatible with added
4184 /// qualification, or incompatible, for use in C++ initialization by
4185 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4186 /// type, and the first type (T1) is the pointee type of the reference
4187 /// type being initialized.
4188 Sema::ReferenceCompareResult
4189 Sema::CompareReferenceRelationship(SourceLocation Loc,
4190 QualType OrigT1, QualType OrigT2,
4191 bool &DerivedToBase,
4192 bool &ObjCConversion,
4193 bool &ObjCLifetimeConversion) {
4194 assert(!OrigT1->isReferenceType() &&
4195 "T1 must be the pointee type of the reference type");
4196 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4198 QualType T1 = Context.getCanonicalType(OrigT1);
4199 QualType T2 = Context.getCanonicalType(OrigT2);
4200 Qualifiers T1Quals, T2Quals;
4201 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4202 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4204 // C++ [dcl.init.ref]p4:
4205 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4206 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4207 // T1 is a base class of T2.
4208 DerivedToBase = false;
4209 ObjCConversion = false;
4210 ObjCLifetimeConversion = false;
4211 QualType ConvertedT2;
4212 if (UnqualT1 == UnqualT2) {
4214 } else if (isCompleteType(Loc, OrigT2) &&
4215 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4216 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4217 DerivedToBase = true;
4218 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4219 UnqualT2->isObjCObjectOrInterfaceType() &&
4220 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4221 ObjCConversion = true;
4222 else if (UnqualT2->isFunctionType() &&
4223 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4224 // C++1z [dcl.init.ref]p4:
4225 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4226 // function" and T1 is "function"
4228 // We extend this to also apply to 'noreturn', so allow any function
4229 // conversion between function types.
4230 return Ref_Compatible;
4232 return Ref_Incompatible;
4234 // At this point, we know that T1 and T2 are reference-related (at
4237 // If the type is an array type, promote the element qualifiers to the type
4239 if (isa<ArrayType>(T1) && T1Quals)
4240 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4241 if (isa<ArrayType>(T2) && T2Quals)
4242 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4244 // C++ [dcl.init.ref]p4:
4245 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4246 // reference-related to T2 and cv1 is the same cv-qualification
4247 // as, or greater cv-qualification than, cv2. For purposes of
4248 // overload resolution, cases for which cv1 is greater
4249 // cv-qualification than cv2 are identified as
4250 // reference-compatible with added qualification (see 13.3.3.2).
4252 // Note that we also require equivalence of Objective-C GC and address-space
4253 // qualifiers when performing these computations, so that e.g., an int in
4254 // address space 1 is not reference-compatible with an int in address
4256 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4257 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4258 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4259 ObjCLifetimeConversion = true;
4261 T1Quals.removeObjCLifetime();
4262 T2Quals.removeObjCLifetime();
4265 // MS compiler ignores __unaligned qualifier for references; do the same.
4266 T1Quals.removeUnaligned();
4267 T2Quals.removeUnaligned();
4269 if (T1Quals.compatiblyIncludes(T2Quals))
4270 return Ref_Compatible;
4275 /// \brief Look for a user-defined conversion to an value reference-compatible
4276 /// with DeclType. Return true if something definite is found.
4278 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4279 QualType DeclType, SourceLocation DeclLoc,
4280 Expr *Init, QualType T2, bool AllowRvalues,
4281 bool AllowExplicit) {
4282 assert(T2->isRecordType() && "Can only find conversions of record types.");
4283 CXXRecordDecl *T2RecordDecl
4284 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4286 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4287 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4288 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4290 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4291 if (isa<UsingShadowDecl>(D))
4292 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4294 FunctionTemplateDecl *ConvTemplate
4295 = dyn_cast<FunctionTemplateDecl>(D);
4296 CXXConversionDecl *Conv;
4298 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4300 Conv = cast<CXXConversionDecl>(D);
4302 // If this is an explicit conversion, and we're not allowed to consider
4303 // explicit conversions, skip it.
4304 if (!AllowExplicit && Conv->isExplicit())
4308 bool DerivedToBase = false;
4309 bool ObjCConversion = false;
4310 bool ObjCLifetimeConversion = false;
4312 // If we are initializing an rvalue reference, don't permit conversion
4313 // functions that return lvalues.
4314 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4315 const ReferenceType *RefType
4316 = Conv->getConversionType()->getAs<LValueReferenceType>();
4317 if (RefType && !RefType->getPointeeType()->isFunctionType())
4321 if (!ConvTemplate &&
4322 S.CompareReferenceRelationship(
4324 Conv->getConversionType().getNonReferenceType()
4325 .getUnqualifiedType(),
4326 DeclType.getNonReferenceType().getUnqualifiedType(),
4327 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4328 Sema::Ref_Incompatible)
4331 // If the conversion function doesn't return a reference type,
4332 // it can't be considered for this conversion. An rvalue reference
4333 // is only acceptable if its referencee is a function type.
4335 const ReferenceType *RefType =
4336 Conv->getConversionType()->getAs<ReferenceType>();
4338 (!RefType->isLValueReferenceType() &&
4339 !RefType->getPointeeType()->isFunctionType()))
4344 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4345 Init, DeclType, CandidateSet,
4346 /*AllowObjCConversionOnExplicit=*/false);
4348 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4349 DeclType, CandidateSet,
4350 /*AllowObjCConversionOnExplicit=*/false);
4353 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4355 OverloadCandidateSet::iterator Best;
4356 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4358 // C++ [over.ics.ref]p1:
4360 // [...] If the parameter binds directly to the result of
4361 // applying a conversion function to the argument
4362 // expression, the implicit conversion sequence is a
4363 // user-defined conversion sequence (13.3.3.1.2), with the
4364 // second standard conversion sequence either an identity
4365 // conversion or, if the conversion function returns an
4366 // entity of a type that is a derived class of the parameter
4367 // type, a derived-to-base Conversion.
4368 if (!Best->FinalConversion.DirectBinding)
4371 ICS.setUserDefined();
4372 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4373 ICS.UserDefined.After = Best->FinalConversion;
4374 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4375 ICS.UserDefined.ConversionFunction = Best->Function;
4376 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4377 ICS.UserDefined.EllipsisConversion = false;
4378 assert(ICS.UserDefined.After.ReferenceBinding &&
4379 ICS.UserDefined.After.DirectBinding &&
4380 "Expected a direct reference binding!");
4385 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4386 Cand != CandidateSet.end(); ++Cand)
4388 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4391 case OR_No_Viable_Function:
4393 // There was no suitable conversion, or we found a deleted
4394 // conversion; continue with other checks.
4398 llvm_unreachable("Invalid OverloadResult!");
4401 /// \brief Compute an implicit conversion sequence for reference
4403 static ImplicitConversionSequence
4404 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4405 SourceLocation DeclLoc,
4406 bool SuppressUserConversions,
4407 bool AllowExplicit) {
4408 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4410 // Most paths end in a failed conversion.
4411 ImplicitConversionSequence ICS;
4412 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4414 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4415 QualType T2 = Init->getType();
4417 // If the initializer is the address of an overloaded function, try
4418 // to resolve the overloaded function. If all goes well, T2 is the
4419 // type of the resulting function.
4420 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4421 DeclAccessPair Found;
4422 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4427 // Compute some basic properties of the types and the initializer.
4428 bool isRValRef = DeclType->isRValueReferenceType();
4429 bool DerivedToBase = false;
4430 bool ObjCConversion = false;
4431 bool ObjCLifetimeConversion = false;
4432 Expr::Classification InitCategory = Init->Classify(S.Context);
4433 Sema::ReferenceCompareResult RefRelationship
4434 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4435 ObjCConversion, ObjCLifetimeConversion);
4438 // C++0x [dcl.init.ref]p5:
4439 // A reference to type "cv1 T1" is initialized by an expression
4440 // of type "cv2 T2" as follows:
4442 // -- If reference is an lvalue reference and the initializer expression
4444 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4445 // reference-compatible with "cv2 T2," or
4447 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4448 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4449 // C++ [over.ics.ref]p1:
4450 // When a parameter of reference type binds directly (8.5.3)
4451 // to an argument expression, the implicit conversion sequence
4452 // is the identity conversion, unless the argument expression
4453 // has a type that is a derived class of the parameter type,
4454 // in which case the implicit conversion sequence is a
4455 // derived-to-base Conversion (13.3.3.1).
4457 ICS.Standard.First = ICK_Identity;
4458 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4459 : ObjCConversion? ICK_Compatible_Conversion
4461 ICS.Standard.Third = ICK_Identity;
4462 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4463 ICS.Standard.setToType(0, T2);
4464 ICS.Standard.setToType(1, T1);
4465 ICS.Standard.setToType(2, T1);
4466 ICS.Standard.ReferenceBinding = true;
4467 ICS.Standard.DirectBinding = true;
4468 ICS.Standard.IsLvalueReference = !isRValRef;
4469 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4470 ICS.Standard.BindsToRvalue = false;
4471 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4472 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4473 ICS.Standard.CopyConstructor = nullptr;
4474 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4476 // Nothing more to do: the inaccessibility/ambiguity check for
4477 // derived-to-base conversions is suppressed when we're
4478 // computing the implicit conversion sequence (C++
4479 // [over.best.ics]p2).
4483 // -- has a class type (i.e., T2 is a class type), where T1 is
4484 // not reference-related to T2, and can be implicitly
4485 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4486 // is reference-compatible with "cv3 T3" 92) (this
4487 // conversion is selected by enumerating the applicable
4488 // conversion functions (13.3.1.6) and choosing the best
4489 // one through overload resolution (13.3)),
4490 if (!SuppressUserConversions && T2->isRecordType() &&
4491 S.isCompleteType(DeclLoc, T2) &&
4492 RefRelationship == Sema::Ref_Incompatible) {
4493 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4494 Init, T2, /*AllowRvalues=*/false,
4500 // -- Otherwise, the reference shall be an lvalue reference to a
4501 // non-volatile const type (i.e., cv1 shall be const), or the reference
4502 // shall be an rvalue reference.
4503 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4506 // -- If the initializer expression
4508 // -- is an xvalue, class prvalue, array prvalue or function
4509 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4510 if (RefRelationship == Sema::Ref_Compatible &&
4511 (InitCategory.isXValue() ||
4512 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4513 (InitCategory.isLValue() && T2->isFunctionType()))) {
4515 ICS.Standard.First = ICK_Identity;
4516 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4517 : ObjCConversion? ICK_Compatible_Conversion
4519 ICS.Standard.Third = ICK_Identity;
4520 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4521 ICS.Standard.setToType(0, T2);
4522 ICS.Standard.setToType(1, T1);
4523 ICS.Standard.setToType(2, T1);
4524 ICS.Standard.ReferenceBinding = true;
4525 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4526 // binding unless we're binding to a class prvalue.
4527 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4528 // allow the use of rvalue references in C++98/03 for the benefit of
4529 // standard library implementors; therefore, we need the xvalue check here.
4530 ICS.Standard.DirectBinding =
4531 S.getLangOpts().CPlusPlus11 ||
4532 !(InitCategory.isPRValue() || T2->isRecordType());
4533 ICS.Standard.IsLvalueReference = !isRValRef;
4534 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4535 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4536 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4537 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4538 ICS.Standard.CopyConstructor = nullptr;
4539 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4543 // -- has a class type (i.e., T2 is a class type), where T1 is not
4544 // reference-related to T2, and can be implicitly converted to
4545 // an xvalue, class prvalue, or function lvalue of type
4546 // "cv3 T3", where "cv1 T1" is reference-compatible with
4549 // then the reference is bound to the value of the initializer
4550 // expression in the first case and to the result of the conversion
4551 // in the second case (or, in either case, to an appropriate base
4552 // class subobject).
4553 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4554 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4555 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4556 Init, T2, /*AllowRvalues=*/true,
4558 // In the second case, if the reference is an rvalue reference
4559 // and the second standard conversion sequence of the
4560 // user-defined conversion sequence includes an lvalue-to-rvalue
4561 // conversion, the program is ill-formed.
4562 if (ICS.isUserDefined() && isRValRef &&
4563 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4564 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4569 // A temporary of function type cannot be created; don't even try.
4570 if (T1->isFunctionType())
4573 // -- Otherwise, a temporary of type "cv1 T1" is created and
4574 // initialized from the initializer expression using the
4575 // rules for a non-reference copy initialization (8.5). The
4576 // reference is then bound to the temporary. If T1 is
4577 // reference-related to T2, cv1 must be the same
4578 // cv-qualification as, or greater cv-qualification than,
4579 // cv2; otherwise, the program is ill-formed.
4580 if (RefRelationship == Sema::Ref_Related) {
4581 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4582 // we would be reference-compatible or reference-compatible with
4583 // added qualification. But that wasn't the case, so the reference
4584 // initialization fails.
4586 // Note that we only want to check address spaces and cvr-qualifiers here.
4587 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4588 Qualifiers T1Quals = T1.getQualifiers();
4589 Qualifiers T2Quals = T2.getQualifiers();
4590 T1Quals.removeObjCGCAttr();
4591 T1Quals.removeObjCLifetime();
4592 T2Quals.removeObjCGCAttr();
4593 T2Quals.removeObjCLifetime();
4594 // MS compiler ignores __unaligned qualifier for references; do the same.
4595 T1Quals.removeUnaligned();
4596 T2Quals.removeUnaligned();
4597 if (!T1Quals.compatiblyIncludes(T2Quals))
4601 // If at least one of the types is a class type, the types are not
4602 // related, and we aren't allowed any user conversions, the
4603 // reference binding fails. This case is important for breaking
4604 // recursion, since TryImplicitConversion below will attempt to
4605 // create a temporary through the use of a copy constructor.
4606 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4607 (T1->isRecordType() || T2->isRecordType()))
4610 // If T1 is reference-related to T2 and the reference is an rvalue
4611 // reference, the initializer expression shall not be an lvalue.
4612 if (RefRelationship >= Sema::Ref_Related &&
4613 isRValRef && Init->Classify(S.Context).isLValue())
4616 // C++ [over.ics.ref]p2:
4617 // When a parameter of reference type is not bound directly to
4618 // an argument expression, the conversion sequence is the one
4619 // required to convert the argument expression to the
4620 // underlying type of the reference according to
4621 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4622 // to copy-initializing a temporary of the underlying type with
4623 // the argument expression. Any difference in top-level
4624 // cv-qualification is subsumed by the initialization itself
4625 // and does not constitute a conversion.
4626 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4627 /*AllowExplicit=*/false,
4628 /*InOverloadResolution=*/false,
4630 /*AllowObjCWritebackConversion=*/false,
4631 /*AllowObjCConversionOnExplicit=*/false);
4633 // Of course, that's still a reference binding.
4634 if (ICS.isStandard()) {
4635 ICS.Standard.ReferenceBinding = true;
4636 ICS.Standard.IsLvalueReference = !isRValRef;
4637 ICS.Standard.BindsToFunctionLvalue = false;
4638 ICS.Standard.BindsToRvalue = true;
4639 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4640 ICS.Standard.ObjCLifetimeConversionBinding = false;
4641 } else if (ICS.isUserDefined()) {
4642 const ReferenceType *LValRefType =
4643 ICS.UserDefined.ConversionFunction->getReturnType()
4644 ->getAs<LValueReferenceType>();
4646 // C++ [over.ics.ref]p3:
4647 // Except for an implicit object parameter, for which see 13.3.1, a
4648 // standard conversion sequence cannot be formed if it requires [...]
4649 // binding an rvalue reference to an lvalue other than a function
4651 // Note that the function case is not possible here.
4652 if (DeclType->isRValueReferenceType() && LValRefType) {
4653 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4654 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4655 // reference to an rvalue!
4656 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4660 ICS.UserDefined.After.ReferenceBinding = true;
4661 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4662 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4663 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4664 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4665 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4671 static ImplicitConversionSequence
4672 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4673 bool SuppressUserConversions,
4674 bool InOverloadResolution,
4675 bool AllowObjCWritebackConversion,
4676 bool AllowExplicit = false);
4678 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4679 /// initializer list From.
4680 static ImplicitConversionSequence
4681 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4682 bool SuppressUserConversions,
4683 bool InOverloadResolution,
4684 bool AllowObjCWritebackConversion) {
4685 // C++11 [over.ics.list]p1:
4686 // When an argument is an initializer list, it is not an expression and
4687 // special rules apply for converting it to a parameter type.
4689 ImplicitConversionSequence Result;
4690 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4692 // We need a complete type for what follows. Incomplete types can never be
4693 // initialized from init lists.
4694 if (!S.isCompleteType(From->getLocStart(), ToType))
4698 // If the parameter type is a class X and the initializer list has a single
4699 // element of type cv U, where U is X or a class derived from X, the
4700 // implicit conversion sequence is the one required to convert the element
4701 // to the parameter type.
4703 // Otherwise, if the parameter type is a character array [... ]
4704 // and the initializer list has a single element that is an
4705 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4706 // implicit conversion sequence is the identity conversion.
4707 if (From->getNumInits() == 1) {
4708 if (ToType->isRecordType()) {
4709 QualType InitType = From->getInit(0)->getType();
4710 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4711 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4712 return TryCopyInitialization(S, From->getInit(0), ToType,
4713 SuppressUserConversions,
4714 InOverloadResolution,
4715 AllowObjCWritebackConversion);
4717 // FIXME: Check the other conditions here: array of character type,
4718 // initializer is a string literal.
4719 if (ToType->isArrayType()) {
4720 InitializedEntity Entity =
4721 InitializedEntity::InitializeParameter(S.Context, ToType,
4722 /*Consumed=*/false);
4723 if (S.CanPerformCopyInitialization(Entity, From)) {
4724 Result.setStandard();
4725 Result.Standard.setAsIdentityConversion();
4726 Result.Standard.setFromType(ToType);
4727 Result.Standard.setAllToTypes(ToType);
4733 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4734 // C++11 [over.ics.list]p2:
4735 // If the parameter type is std::initializer_list<X> or "array of X" and
4736 // all the elements can be implicitly converted to X, the implicit
4737 // conversion sequence is the worst conversion necessary to convert an
4738 // element of the list to X.
4740 // C++14 [over.ics.list]p3:
4741 // Otherwise, if the parameter type is "array of N X", if the initializer
4742 // list has exactly N elements or if it has fewer than N elements and X is
4743 // default-constructible, and if all the elements of the initializer list
4744 // can be implicitly converted to X, the implicit conversion sequence is
4745 // the worst conversion necessary to convert an element of the list to X.
4747 // FIXME: We're missing a lot of these checks.
4748 bool toStdInitializerList = false;
4750 if (ToType->isArrayType())
4751 X = S.Context.getAsArrayType(ToType)->getElementType();
4753 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4755 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4756 Expr *Init = From->getInit(i);
4757 ImplicitConversionSequence ICS =
4758 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4759 InOverloadResolution,
4760 AllowObjCWritebackConversion);
4761 // If a single element isn't convertible, fail.
4766 // Otherwise, look for the worst conversion.
4767 if (Result.isBad() ||
4768 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4770 ImplicitConversionSequence::Worse)
4774 // For an empty list, we won't have computed any conversion sequence.
4775 // Introduce the identity conversion sequence.
4776 if (From->getNumInits() == 0) {
4777 Result.setStandard();
4778 Result.Standard.setAsIdentityConversion();
4779 Result.Standard.setFromType(ToType);
4780 Result.Standard.setAllToTypes(ToType);
4783 Result.setStdInitializerListElement(toStdInitializerList);
4787 // C++14 [over.ics.list]p4:
4788 // C++11 [over.ics.list]p3:
4789 // Otherwise, if the parameter is a non-aggregate class X and overload
4790 // resolution chooses a single best constructor [...] the implicit
4791 // conversion sequence is a user-defined conversion sequence. If multiple
4792 // constructors are viable but none is better than the others, the
4793 // implicit conversion sequence is a user-defined conversion sequence.
4794 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4795 // This function can deal with initializer lists.
4796 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4797 /*AllowExplicit=*/false,
4798 InOverloadResolution, /*CStyle=*/false,
4799 AllowObjCWritebackConversion,
4800 /*AllowObjCConversionOnExplicit=*/false);
4803 // C++14 [over.ics.list]p5:
4804 // C++11 [over.ics.list]p4:
4805 // Otherwise, if the parameter has an aggregate type which can be
4806 // initialized from the initializer list [...] the implicit conversion
4807 // sequence is a user-defined conversion sequence.
4808 if (ToType->isAggregateType()) {
4809 // Type is an aggregate, argument is an init list. At this point it comes
4810 // down to checking whether the initialization works.
4811 // FIXME: Find out whether this parameter is consumed or not.
4812 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4813 // need to call into the initialization code here; overload resolution
4814 // should not be doing that.
4815 InitializedEntity Entity =
4816 InitializedEntity::InitializeParameter(S.Context, ToType,
4817 /*Consumed=*/false);
4818 if (S.CanPerformCopyInitialization(Entity, From)) {
4819 Result.setUserDefined();
4820 Result.UserDefined.Before.setAsIdentityConversion();
4821 // Initializer lists don't have a type.
4822 Result.UserDefined.Before.setFromType(QualType());
4823 Result.UserDefined.Before.setAllToTypes(QualType());
4825 Result.UserDefined.After.setAsIdentityConversion();
4826 Result.UserDefined.After.setFromType(ToType);
4827 Result.UserDefined.After.setAllToTypes(ToType);
4828 Result.UserDefined.ConversionFunction = nullptr;
4833 // C++14 [over.ics.list]p6:
4834 // C++11 [over.ics.list]p5:
4835 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4836 if (ToType->isReferenceType()) {
4837 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4838 // mention initializer lists in any way. So we go by what list-
4839 // initialization would do and try to extrapolate from that.
4841 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4843 // If the initializer list has a single element that is reference-related
4844 // to the parameter type, we initialize the reference from that.
4845 if (From->getNumInits() == 1) {
4846 Expr *Init = From->getInit(0);
4848 QualType T2 = Init->getType();
4850 // If the initializer is the address of an overloaded function, try
4851 // to resolve the overloaded function. If all goes well, T2 is the
4852 // type of the resulting function.
4853 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4854 DeclAccessPair Found;
4855 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4856 Init, ToType, false, Found))
4860 // Compute some basic properties of the types and the initializer.
4861 bool dummy1 = false;
4862 bool dummy2 = false;
4863 bool dummy3 = false;
4864 Sema::ReferenceCompareResult RefRelationship
4865 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4868 if (RefRelationship >= Sema::Ref_Related) {
4869 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4870 SuppressUserConversions,
4871 /*AllowExplicit=*/false);
4875 // Otherwise, we bind the reference to a temporary created from the
4876 // initializer list.
4877 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4878 InOverloadResolution,
4879 AllowObjCWritebackConversion);
4880 if (Result.isFailure())
4882 assert(!Result.isEllipsis() &&
4883 "Sub-initialization cannot result in ellipsis conversion.");
4885 // Can we even bind to a temporary?
4886 if (ToType->isRValueReferenceType() ||
4887 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4888 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4889 Result.UserDefined.After;
4890 SCS.ReferenceBinding = true;
4891 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4892 SCS.BindsToRvalue = true;
4893 SCS.BindsToFunctionLvalue = false;
4894 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4895 SCS.ObjCLifetimeConversionBinding = false;
4897 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4902 // C++14 [over.ics.list]p7:
4903 // C++11 [over.ics.list]p6:
4904 // Otherwise, if the parameter type is not a class:
4905 if (!ToType->isRecordType()) {
4906 // - if the initializer list has one element that is not itself an
4907 // initializer list, the implicit conversion sequence is the one
4908 // required to convert the element to the parameter type.
4909 unsigned NumInits = From->getNumInits();
4910 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4911 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4912 SuppressUserConversions,
4913 InOverloadResolution,
4914 AllowObjCWritebackConversion);
4915 // - if the initializer list has no elements, the implicit conversion
4916 // sequence is the identity conversion.
4917 else if (NumInits == 0) {
4918 Result.setStandard();
4919 Result.Standard.setAsIdentityConversion();
4920 Result.Standard.setFromType(ToType);
4921 Result.Standard.setAllToTypes(ToType);
4926 // C++14 [over.ics.list]p8:
4927 // C++11 [over.ics.list]p7:
4928 // In all cases other than those enumerated above, no conversion is possible
4932 /// TryCopyInitialization - Try to copy-initialize a value of type
4933 /// ToType from the expression From. Return the implicit conversion
4934 /// sequence required to pass this argument, which may be a bad
4935 /// conversion sequence (meaning that the argument cannot be passed to
4936 /// a parameter of this type). If @p SuppressUserConversions, then we
4937 /// do not permit any user-defined conversion sequences.
4938 static ImplicitConversionSequence
4939 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4940 bool SuppressUserConversions,
4941 bool InOverloadResolution,
4942 bool AllowObjCWritebackConversion,
4943 bool AllowExplicit) {
4944 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4945 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4946 InOverloadResolution,AllowObjCWritebackConversion);
4948 if (ToType->isReferenceType())
4949 return TryReferenceInit(S, From, ToType,
4950 /*FIXME:*/From->getLocStart(),
4951 SuppressUserConversions,
4954 return TryImplicitConversion(S, From, ToType,
4955 SuppressUserConversions,
4956 /*AllowExplicit=*/false,
4957 InOverloadResolution,
4959 AllowObjCWritebackConversion,
4960 /*AllowObjCConversionOnExplicit=*/false);
4963 static bool TryCopyInitialization(const CanQualType FromQTy,
4964 const CanQualType ToQTy,
4967 ExprValueKind FromVK) {
4968 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4969 ImplicitConversionSequence ICS =
4970 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4972 return !ICS.isBad();
4975 /// TryObjectArgumentInitialization - Try to initialize the object
4976 /// parameter of the given member function (@c Method) from the
4977 /// expression @p From.
4978 static ImplicitConversionSequence
4979 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4980 Expr::Classification FromClassification,
4981 CXXMethodDecl *Method,
4982 CXXRecordDecl *ActingContext) {
4983 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4984 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4985 // const volatile object.
4986 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4987 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4988 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
4990 // Set up the conversion sequence as a "bad" conversion, to allow us
4992 ImplicitConversionSequence ICS;
4994 // We need to have an object of class type.
4995 if (const PointerType *PT = FromType->getAs<PointerType>()) {
4996 FromType = PT->getPointeeType();
4998 // When we had a pointer, it's implicitly dereferenced, so we
4999 // better have an lvalue.
5000 assert(FromClassification.isLValue());
5003 assert(FromType->isRecordType());
5005 // C++0x [over.match.funcs]p4:
5006 // For non-static member functions, the type of the implicit object
5009 // - "lvalue reference to cv X" for functions declared without a
5010 // ref-qualifier or with the & ref-qualifier
5011 // - "rvalue reference to cv X" for functions declared with the &&
5014 // where X is the class of which the function is a member and cv is the
5015 // cv-qualification on the member function declaration.
5017 // However, when finding an implicit conversion sequence for the argument, we
5018 // are not allowed to perform user-defined conversions
5019 // (C++ [over.match.funcs]p5). We perform a simplified version of
5020 // reference binding here, that allows class rvalues to bind to
5021 // non-constant references.
5023 // First check the qualifiers.
5024 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5025 if (ImplicitParamType.getCVRQualifiers()
5026 != FromTypeCanon.getLocalCVRQualifiers() &&
5027 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5028 ICS.setBad(BadConversionSequence::bad_qualifiers,
5029 FromType, ImplicitParamType);
5033 // Check that we have either the same type or a derived type. It
5034 // affects the conversion rank.
5035 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5036 ImplicitConversionKind SecondKind;
5037 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5038 SecondKind = ICK_Identity;
5039 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5040 SecondKind = ICK_Derived_To_Base;
5042 ICS.setBad(BadConversionSequence::unrelated_class,
5043 FromType, ImplicitParamType);
5047 // Check the ref-qualifier.
5048 switch (Method->getRefQualifier()) {
5050 // Do nothing; we don't care about lvalueness or rvalueness.
5054 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5055 // non-const lvalue reference cannot bind to an rvalue
5056 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5063 if (!FromClassification.isRValue()) {
5064 // rvalue reference cannot bind to an lvalue
5065 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5072 // Success. Mark this as a reference binding.
5074 ICS.Standard.setAsIdentityConversion();
5075 ICS.Standard.Second = SecondKind;
5076 ICS.Standard.setFromType(FromType);
5077 ICS.Standard.setAllToTypes(ImplicitParamType);
5078 ICS.Standard.ReferenceBinding = true;
5079 ICS.Standard.DirectBinding = true;
5080 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5081 ICS.Standard.BindsToFunctionLvalue = false;
5082 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5083 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5084 = (Method->getRefQualifier() == RQ_None);
5088 /// PerformObjectArgumentInitialization - Perform initialization of
5089 /// the implicit object parameter for the given Method with the given
5092 Sema::PerformObjectArgumentInitialization(Expr *From,
5093 NestedNameSpecifier *Qualifier,
5094 NamedDecl *FoundDecl,
5095 CXXMethodDecl *Method) {
5096 QualType FromRecordType, DestType;
5097 QualType ImplicitParamRecordType =
5098 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5100 Expr::Classification FromClassification;
5101 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5102 FromRecordType = PT->getPointeeType();
5103 DestType = Method->getThisType(Context);
5104 FromClassification = Expr::Classification::makeSimpleLValue();
5106 FromRecordType = From->getType();
5107 DestType = ImplicitParamRecordType;
5108 FromClassification = From->Classify(Context);
5111 // Note that we always use the true parent context when performing
5112 // the actual argument initialization.
5113 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5114 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5115 Method->getParent());
5117 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5118 Qualifiers FromQs = FromRecordType.getQualifiers();
5119 Qualifiers ToQs = DestType.getQualifiers();
5120 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5122 Diag(From->getLocStart(),
5123 diag::err_member_function_call_bad_cvr)
5124 << Method->getDeclName() << FromRecordType << (CVR - 1)
5125 << From->getSourceRange();
5126 Diag(Method->getLocation(), diag::note_previous_decl)
5127 << Method->getDeclName();
5132 return Diag(From->getLocStart(),
5133 diag::err_implicit_object_parameter_init)
5134 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5137 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5138 ExprResult FromRes =
5139 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5140 if (FromRes.isInvalid())
5142 From = FromRes.get();
5145 if (!Context.hasSameType(From->getType(), DestType))
5146 From = ImpCastExprToType(From, DestType, CK_NoOp,
5147 From->getValueKind()).get();
5151 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5152 /// expression From to bool (C++0x [conv]p3).
5153 static ImplicitConversionSequence
5154 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5155 return TryImplicitConversion(S, From, S.Context.BoolTy,
5156 /*SuppressUserConversions=*/false,
5157 /*AllowExplicit=*/true,
5158 /*InOverloadResolution=*/false,
5160 /*AllowObjCWritebackConversion=*/false,
5161 /*AllowObjCConversionOnExplicit=*/false);
5164 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5165 /// of the expression From to bool (C++0x [conv]p3).
5166 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5167 if (checkPlaceholderForOverload(*this, From))
5170 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5172 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5174 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5175 return Diag(From->getLocStart(),
5176 diag::err_typecheck_bool_condition)
5177 << From->getType() << From->getSourceRange();
5181 /// Check that the specified conversion is permitted in a converted constant
5182 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5184 static bool CheckConvertedConstantConversions(Sema &S,
5185 StandardConversionSequence &SCS) {
5186 // Since we know that the target type is an integral or unscoped enumeration
5187 // type, most conversion kinds are impossible. All possible First and Third
5188 // conversions are fine.
5189 switch (SCS.Second) {
5191 case ICK_Function_Conversion:
5192 case ICK_Integral_Promotion:
5193 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5194 case ICK_Zero_Queue_Conversion:
5197 case ICK_Boolean_Conversion:
5198 // Conversion from an integral or unscoped enumeration type to bool is
5199 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5200 // conversion, so we allow it in a converted constant expression.
5202 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5203 // a lot of popular code. We should at least add a warning for this
5204 // (non-conforming) extension.
5205 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5206 SCS.getToType(2)->isBooleanType();
5208 case ICK_Pointer_Conversion:
5209 case ICK_Pointer_Member:
5210 // C++1z: null pointer conversions and null member pointer conversions are
5211 // only permitted if the source type is std::nullptr_t.
5212 return SCS.getFromType()->isNullPtrType();
5214 case ICK_Floating_Promotion:
5215 case ICK_Complex_Promotion:
5216 case ICK_Floating_Conversion:
5217 case ICK_Complex_Conversion:
5218 case ICK_Floating_Integral:
5219 case ICK_Compatible_Conversion:
5220 case ICK_Derived_To_Base:
5221 case ICK_Vector_Conversion:
5222 case ICK_Vector_Splat:
5223 case ICK_Complex_Real:
5224 case ICK_Block_Pointer_Conversion:
5225 case ICK_TransparentUnionConversion:
5226 case ICK_Writeback_Conversion:
5227 case ICK_Zero_Event_Conversion:
5228 case ICK_C_Only_Conversion:
5229 case ICK_Incompatible_Pointer_Conversion:
5232 case ICK_Lvalue_To_Rvalue:
5233 case ICK_Array_To_Pointer:
5234 case ICK_Function_To_Pointer:
5235 llvm_unreachable("found a first conversion kind in Second");
5237 case ICK_Qualification:
5238 llvm_unreachable("found a third conversion kind in Second");
5240 case ICK_Num_Conversion_Kinds:
5244 llvm_unreachable("unknown conversion kind");
5247 /// CheckConvertedConstantExpression - Check that the expression From is a
5248 /// converted constant expression of type T, perform the conversion and produce
5249 /// the converted expression, per C++11 [expr.const]p3.
5250 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5251 QualType T, APValue &Value,
5254 assert(S.getLangOpts().CPlusPlus11 &&
5255 "converted constant expression outside C++11");
5257 if (checkPlaceholderForOverload(S, From))
5260 // C++1z [expr.const]p3:
5261 // A converted constant expression of type T is an expression,
5262 // implicitly converted to type T, where the converted
5263 // expression is a constant expression and the implicit conversion
5264 // sequence contains only [... list of conversions ...].
5265 // C++1z [stmt.if]p2:
5266 // If the if statement is of the form if constexpr, the value of the
5267 // condition shall be a contextually converted constant expression of type
5269 ImplicitConversionSequence ICS =
5270 CCE == Sema::CCEK_ConstexprIf
5271 ? TryContextuallyConvertToBool(S, From)
5272 : TryCopyInitialization(S, From, T,
5273 /*SuppressUserConversions=*/false,
5274 /*InOverloadResolution=*/false,
5275 /*AllowObjcWritebackConversion=*/false,
5276 /*AllowExplicit=*/false);
5277 StandardConversionSequence *SCS = nullptr;
5278 switch (ICS.getKind()) {
5279 case ImplicitConversionSequence::StandardConversion:
5280 SCS = &ICS.Standard;
5282 case ImplicitConversionSequence::UserDefinedConversion:
5283 // We are converting to a non-class type, so the Before sequence
5285 SCS = &ICS.UserDefined.After;
5287 case ImplicitConversionSequence::AmbiguousConversion:
5288 case ImplicitConversionSequence::BadConversion:
5289 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5290 return S.Diag(From->getLocStart(),
5291 diag::err_typecheck_converted_constant_expression)
5292 << From->getType() << From->getSourceRange() << T;
5295 case ImplicitConversionSequence::EllipsisConversion:
5296 llvm_unreachable("ellipsis conversion in converted constant expression");
5299 // Check that we would only use permitted conversions.
5300 if (!CheckConvertedConstantConversions(S, *SCS)) {
5301 return S.Diag(From->getLocStart(),
5302 diag::err_typecheck_converted_constant_expression_disallowed)
5303 << From->getType() << From->getSourceRange() << T;
5305 // [...] and where the reference binding (if any) binds directly.
5306 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5307 return S.Diag(From->getLocStart(),
5308 diag::err_typecheck_converted_constant_expression_indirect)
5309 << From->getType() << From->getSourceRange() << T;
5313 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5314 if (Result.isInvalid())
5317 // Check for a narrowing implicit conversion.
5318 APValue PreNarrowingValue;
5319 QualType PreNarrowingType;
5320 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5321 PreNarrowingType)) {
5322 case NK_Dependent_Narrowing:
5323 // Implicit conversion to a narrower type, but the expression is
5324 // value-dependent so we can't tell whether it's actually narrowing.
5325 case NK_Variable_Narrowing:
5326 // Implicit conversion to a narrower type, and the value is not a constant
5327 // expression. We'll diagnose this in a moment.
5328 case NK_Not_Narrowing:
5331 case NK_Constant_Narrowing:
5332 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5333 << CCE << /*Constant*/1
5334 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5337 case NK_Type_Narrowing:
5338 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5339 << CCE << /*Constant*/0 << From->getType() << T;
5343 if (Result.get()->isValueDependent()) {
5348 // Check the expression is a constant expression.
5349 SmallVector<PartialDiagnosticAt, 8> Notes;
5350 Expr::EvalResult Eval;
5353 if ((T->isReferenceType()
5354 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5355 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5356 (RequireInt && !Eval.Val.isInt())) {
5357 // The expression can't be folded, so we can't keep it at this position in
5359 Result = ExprError();
5363 if (Notes.empty()) {
5364 // It's a constant expression.
5369 // It's not a constant expression. Produce an appropriate diagnostic.
5370 if (Notes.size() == 1 &&
5371 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5372 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5374 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5375 << CCE << From->getSourceRange();
5376 for (unsigned I = 0; I < Notes.size(); ++I)
5377 S.Diag(Notes[I].first, Notes[I].second);
5382 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5383 APValue &Value, CCEKind CCE) {
5384 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5387 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5388 llvm::APSInt &Value,
5390 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5393 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5394 if (!R.isInvalid() && !R.get()->isValueDependent())
5400 /// dropPointerConversions - If the given standard conversion sequence
5401 /// involves any pointer conversions, remove them. This may change
5402 /// the result type of the conversion sequence.
5403 static void dropPointerConversion(StandardConversionSequence &SCS) {
5404 if (SCS.Second == ICK_Pointer_Conversion) {
5405 SCS.Second = ICK_Identity;
5406 SCS.Third = ICK_Identity;
5407 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5411 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5412 /// convert the expression From to an Objective-C pointer type.
5413 static ImplicitConversionSequence
5414 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5415 // Do an implicit conversion to 'id'.
5416 QualType Ty = S.Context.getObjCIdType();
5417 ImplicitConversionSequence ICS
5418 = TryImplicitConversion(S, From, Ty,
5419 // FIXME: Are these flags correct?
5420 /*SuppressUserConversions=*/false,
5421 /*AllowExplicit=*/true,
5422 /*InOverloadResolution=*/false,
5424 /*AllowObjCWritebackConversion=*/false,
5425 /*AllowObjCConversionOnExplicit=*/true);
5427 // Strip off any final conversions to 'id'.
5428 switch (ICS.getKind()) {
5429 case ImplicitConversionSequence::BadConversion:
5430 case ImplicitConversionSequence::AmbiguousConversion:
5431 case ImplicitConversionSequence::EllipsisConversion:
5434 case ImplicitConversionSequence::UserDefinedConversion:
5435 dropPointerConversion(ICS.UserDefined.After);
5438 case ImplicitConversionSequence::StandardConversion:
5439 dropPointerConversion(ICS.Standard);
5446 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5447 /// conversion of the expression From to an Objective-C pointer type.
5448 /// Returns a valid but null ExprResult if no conversion sequence exists.
5449 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5450 if (checkPlaceholderForOverload(*this, From))
5453 QualType Ty = Context.getObjCIdType();
5454 ImplicitConversionSequence ICS =
5455 TryContextuallyConvertToObjCPointer(*this, From);
5457 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5458 return ExprResult();
5461 /// Determine whether the provided type is an integral type, or an enumeration
5462 /// type of a permitted flavor.
5463 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5464 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5465 : T->isIntegralOrUnscopedEnumerationType();
5469 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5470 Sema::ContextualImplicitConverter &Converter,
5471 QualType T, UnresolvedSetImpl &ViableConversions) {
5473 if (Converter.Suppress)
5476 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5477 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5478 CXXConversionDecl *Conv =
5479 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5480 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5481 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5487 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5488 Sema::ContextualImplicitConverter &Converter,
5489 QualType T, bool HadMultipleCandidates,
5490 UnresolvedSetImpl &ExplicitConversions) {
5491 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5492 DeclAccessPair Found = ExplicitConversions[0];
5493 CXXConversionDecl *Conversion =
5494 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5496 // The user probably meant to invoke the given explicit
5497 // conversion; use it.
5498 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5499 std::string TypeStr;
5500 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5502 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5503 << FixItHint::CreateInsertion(From->getLocStart(),
5504 "static_cast<" + TypeStr + ">(")
5505 << FixItHint::CreateInsertion(
5506 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5507 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5509 // If we aren't in a SFINAE context, build a call to the
5510 // explicit conversion function.
5511 if (SemaRef.isSFINAEContext())
5514 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5515 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5516 HadMultipleCandidates);
5517 if (Result.isInvalid())
5519 // Record usage of conversion in an implicit cast.
5520 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5521 CK_UserDefinedConversion, Result.get(),
5522 nullptr, Result.get()->getValueKind());
5527 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5528 Sema::ContextualImplicitConverter &Converter,
5529 QualType T, bool HadMultipleCandidates,
5530 DeclAccessPair &Found) {
5531 CXXConversionDecl *Conversion =
5532 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5533 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5535 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5536 if (!Converter.SuppressConversion) {
5537 if (SemaRef.isSFINAEContext())
5540 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5541 << From->getSourceRange();
5544 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5545 HadMultipleCandidates);
5546 if (Result.isInvalid())
5548 // Record usage of conversion in an implicit cast.
5549 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5550 CK_UserDefinedConversion, Result.get(),
5551 nullptr, Result.get()->getValueKind());
5555 static ExprResult finishContextualImplicitConversion(
5556 Sema &SemaRef, SourceLocation Loc, Expr *From,
5557 Sema::ContextualImplicitConverter &Converter) {
5558 if (!Converter.match(From->getType()) && !Converter.Suppress)
5559 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5560 << From->getSourceRange();
5562 return SemaRef.DefaultLvalueConversion(From);
5566 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5567 UnresolvedSetImpl &ViableConversions,
5568 OverloadCandidateSet &CandidateSet) {
5569 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5570 DeclAccessPair FoundDecl = ViableConversions[I];
5571 NamedDecl *D = FoundDecl.getDecl();
5572 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5573 if (isa<UsingShadowDecl>(D))
5574 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5576 CXXConversionDecl *Conv;
5577 FunctionTemplateDecl *ConvTemplate;
5578 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5579 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5581 Conv = cast<CXXConversionDecl>(D);
5584 SemaRef.AddTemplateConversionCandidate(
5585 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5586 /*AllowObjCConversionOnExplicit=*/false);
5588 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5589 ToType, CandidateSet,
5590 /*AllowObjCConversionOnExplicit=*/false);
5594 /// \brief Attempt to convert the given expression to a type which is accepted
5595 /// by the given converter.
5597 /// This routine will attempt to convert an expression of class type to a
5598 /// type accepted by the specified converter. In C++11 and before, the class
5599 /// must have a single non-explicit conversion function converting to a matching
5600 /// type. In C++1y, there can be multiple such conversion functions, but only
5601 /// one target type.
5603 /// \param Loc The source location of the construct that requires the
5606 /// \param From The expression we're converting from.
5608 /// \param Converter Used to control and diagnose the conversion process.
5610 /// \returns The expression, converted to an integral or enumeration type if
5612 ExprResult Sema::PerformContextualImplicitConversion(
5613 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5614 // We can't perform any more checking for type-dependent expressions.
5615 if (From->isTypeDependent())
5618 // Process placeholders immediately.
5619 if (From->hasPlaceholderType()) {
5620 ExprResult result = CheckPlaceholderExpr(From);
5621 if (result.isInvalid())
5623 From = result.get();
5626 // If the expression already has a matching type, we're golden.
5627 QualType T = From->getType();
5628 if (Converter.match(T))
5629 return DefaultLvalueConversion(From);
5631 // FIXME: Check for missing '()' if T is a function type?
5633 // We can only perform contextual implicit conversions on objects of class
5635 const RecordType *RecordTy = T->getAs<RecordType>();
5636 if (!RecordTy || !getLangOpts().CPlusPlus) {
5637 if (!Converter.Suppress)
5638 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5642 // We must have a complete class type.
5643 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5644 ContextualImplicitConverter &Converter;
5647 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5648 : Converter(Converter), From(From) {}
5650 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5651 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5653 } IncompleteDiagnoser(Converter, From);
5655 if (Converter.Suppress ? !isCompleteType(Loc, T)
5656 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5659 // Look for a conversion to an integral or enumeration type.
5661 ViableConversions; // These are *potentially* viable in C++1y.
5662 UnresolvedSet<4> ExplicitConversions;
5663 const auto &Conversions =
5664 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5666 bool HadMultipleCandidates =
5667 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5669 // To check that there is only one target type, in C++1y:
5671 bool HasUniqueTargetType = true;
5673 // Collect explicit or viable (potentially in C++1y) conversions.
5674 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5675 NamedDecl *D = (*I)->getUnderlyingDecl();
5676 CXXConversionDecl *Conversion;
5677 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5679 if (getLangOpts().CPlusPlus14)
5680 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5682 continue; // C++11 does not consider conversion operator templates(?).
5684 Conversion = cast<CXXConversionDecl>(D);
5686 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5687 "Conversion operator templates are considered potentially "
5690 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5691 if (Converter.match(CurToType) || ConvTemplate) {
5693 if (Conversion->isExplicit()) {
5694 // FIXME: For C++1y, do we need this restriction?
5695 // cf. diagnoseNoViableConversion()
5697 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5699 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5700 if (ToType.isNull())
5701 ToType = CurToType.getUnqualifiedType();
5702 else if (HasUniqueTargetType &&
5703 (CurToType.getUnqualifiedType() != ToType))
5704 HasUniqueTargetType = false;
5706 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5711 if (getLangOpts().CPlusPlus14) {
5713 // ... An expression e of class type E appearing in such a context
5714 // is said to be contextually implicitly converted to a specified
5715 // type T and is well-formed if and only if e can be implicitly
5716 // converted to a type T that is determined as follows: E is searched
5717 // for conversion functions whose return type is cv T or reference to
5718 // cv T such that T is allowed by the context. There shall be
5719 // exactly one such T.
5721 // If no unique T is found:
5722 if (ToType.isNull()) {
5723 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5724 HadMultipleCandidates,
5725 ExplicitConversions))
5727 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5730 // If more than one unique Ts are found:
5731 if (!HasUniqueTargetType)
5732 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5735 // If one unique T is found:
5736 // First, build a candidate set from the previously recorded
5737 // potentially viable conversions.
5738 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5739 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5742 // Then, perform overload resolution over the candidate set.
5743 OverloadCandidateSet::iterator Best;
5744 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5746 // Apply this conversion.
5747 DeclAccessPair Found =
5748 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5749 if (recordConversion(*this, Loc, From, Converter, T,
5750 HadMultipleCandidates, Found))
5755 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5757 case OR_No_Viable_Function:
5758 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5759 HadMultipleCandidates,
5760 ExplicitConversions))
5762 // fall through 'OR_Deleted' case.
5764 // We'll complain below about a non-integral condition type.
5768 switch (ViableConversions.size()) {
5770 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5771 HadMultipleCandidates,
5772 ExplicitConversions))
5775 // We'll complain below about a non-integral condition type.
5779 // Apply this conversion.
5780 DeclAccessPair Found = ViableConversions[0];
5781 if (recordConversion(*this, Loc, From, Converter, T,
5782 HadMultipleCandidates, Found))
5787 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5792 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5795 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5796 /// an acceptable non-member overloaded operator for a call whose
5797 /// arguments have types T1 (and, if non-empty, T2). This routine
5798 /// implements the check in C++ [over.match.oper]p3b2 concerning
5799 /// enumeration types.
5800 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5802 ArrayRef<Expr *> Args) {
5803 QualType T1 = Args[0]->getType();
5804 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5806 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5809 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5812 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5813 if (Proto->getNumParams() < 1)
5816 if (T1->isEnumeralType()) {
5817 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5818 if (Context.hasSameUnqualifiedType(T1, ArgType))
5822 if (Proto->getNumParams() < 2)
5825 if (!T2.isNull() && T2->isEnumeralType()) {
5826 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5827 if (Context.hasSameUnqualifiedType(T2, ArgType))
5834 static void initDiagnoseIfComplaint(Sema &S, OverloadCandidateSet &CandidateSet,
5835 OverloadCandidate &Candidate,
5836 FunctionDecl *Function,
5837 ArrayRef<Expr *> Args,
5838 bool MissingImplicitThis = false,
5839 Expr *ExplicitThis = nullptr) {
5840 SmallVector<DiagnoseIfAttr *, 8> Results;
5841 if (DiagnoseIfAttr *DIA = S.checkArgDependentDiagnoseIf(
5842 Function, Args, Results, MissingImplicitThis, ExplicitThis)) {
5844 Results.push_back(DIA);
5847 Candidate.NumTriggeredDiagnoseIfs = Results.size();
5848 if (Results.empty())
5849 Candidate.DiagnoseIfInfo = nullptr;
5850 else if (Results.size() == 1)
5851 Candidate.DiagnoseIfInfo = Results[0];
5853 Candidate.DiagnoseIfInfo = CandidateSet.addDiagnoseIfComplaints(Results);
5856 /// AddOverloadCandidate - Adds the given function to the set of
5857 /// candidate functions, using the given function call arguments. If
5858 /// @p SuppressUserConversions, then don't allow user-defined
5859 /// conversions via constructors or conversion operators.
5861 /// \param PartialOverloading true if we are performing "partial" overloading
5862 /// based on an incomplete set of function arguments. This feature is used by
5863 /// code completion.
5865 Sema::AddOverloadCandidate(FunctionDecl *Function,
5866 DeclAccessPair FoundDecl,
5867 ArrayRef<Expr *> Args,
5868 OverloadCandidateSet &CandidateSet,
5869 bool SuppressUserConversions,
5870 bool PartialOverloading,
5872 ConversionSequenceList EarlyConversions) {
5873 const FunctionProtoType *Proto
5874 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5875 assert(Proto && "Functions without a prototype cannot be overloaded");
5876 assert(!Function->getDescribedFunctionTemplate() &&
5877 "Use AddTemplateOverloadCandidate for function templates");
5879 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5880 if (!isa<CXXConstructorDecl>(Method)) {
5881 // If we get here, it's because we're calling a member function
5882 // that is named without a member access expression (e.g.,
5883 // "this->f") that was either written explicitly or created
5884 // implicitly. This can happen with a qualified call to a member
5885 // function, e.g., X::f(). We use an empty type for the implied
5886 // object argument (C++ [over.call.func]p3), and the acting context
5888 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5889 Expr::Classification::makeSimpleLValue(),
5890 /*ThisArg=*/nullptr, Args, CandidateSet,
5891 SuppressUserConversions, PartialOverloading,
5895 // We treat a constructor like a non-member function, since its object
5896 // argument doesn't participate in overload resolution.
5899 if (!CandidateSet.isNewCandidate(Function))
5902 // C++ [over.match.oper]p3:
5903 // if no operand has a class type, only those non-member functions in the
5904 // lookup set that have a first parameter of type T1 or "reference to
5905 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5906 // is a right operand) a second parameter of type T2 or "reference to
5907 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5908 // candidate functions.
5909 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5910 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5913 // C++11 [class.copy]p11: [DR1402]
5914 // A defaulted move constructor that is defined as deleted is ignored by
5915 // overload resolution.
5916 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5917 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5918 Constructor->isMoveConstructor())
5921 // Overload resolution is always an unevaluated context.
5922 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5924 // Add this candidate
5925 OverloadCandidate &Candidate =
5926 CandidateSet.addCandidate(Args.size(), EarlyConversions);
5927 Candidate.FoundDecl = FoundDecl;
5928 Candidate.Function = Function;
5929 Candidate.Viable = true;
5930 Candidate.IsSurrogate = false;
5931 Candidate.IgnoreObjectArgument = false;
5932 Candidate.ExplicitCallArguments = Args.size();
5935 // C++ [class.copy]p3:
5936 // A member function template is never instantiated to perform the copy
5937 // of a class object to an object of its class type.
5938 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5939 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5940 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5941 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5943 Candidate.Viable = false;
5944 Candidate.FailureKind = ovl_fail_illegal_constructor;
5949 unsigned NumParams = Proto->getNumParams();
5951 // (C++ 13.3.2p2): A candidate function having fewer than m
5952 // parameters is viable only if it has an ellipsis in its parameter
5954 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5955 !Proto->isVariadic()) {
5956 Candidate.Viable = false;
5957 Candidate.FailureKind = ovl_fail_too_many_arguments;
5961 // (C++ 13.3.2p2): A candidate function having more than m parameters
5962 // is viable only if the (m+1)st parameter has a default argument
5963 // (8.3.6). For the purposes of overload resolution, the
5964 // parameter list is truncated on the right, so that there are
5965 // exactly m parameters.
5966 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5967 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5968 // Not enough arguments.
5969 Candidate.Viable = false;
5970 Candidate.FailureKind = ovl_fail_too_few_arguments;
5974 // (CUDA B.1): Check for invalid calls between targets.
5975 if (getLangOpts().CUDA)
5976 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5977 // Skip the check for callers that are implicit members, because in this
5978 // case we may not yet know what the member's target is; the target is
5979 // inferred for the member automatically, based on the bases and fields of
5981 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
5982 Candidate.Viable = false;
5983 Candidate.FailureKind = ovl_fail_bad_target;
5987 // Determine the implicit conversion sequences for each of the
5989 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5990 if (Candidate.Conversions[ArgIdx].isInitialized()) {
5991 // We already formed a conversion sequence for this parameter during
5992 // template argument deduction.
5993 } else if (ArgIdx < NumParams) {
5994 // (C++ 13.3.2p3): for F to be a viable function, there shall
5995 // exist for each argument an implicit conversion sequence
5996 // (13.3.3.1) that converts that argument to the corresponding
5998 QualType ParamType = Proto->getParamType(ArgIdx);
5999 Candidate.Conversions[ArgIdx]
6000 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6001 SuppressUserConversions,
6002 /*InOverloadResolution=*/true,
6003 /*AllowObjCWritebackConversion=*/
6004 getLangOpts().ObjCAutoRefCount,
6006 if (Candidate.Conversions[ArgIdx].isBad()) {
6007 Candidate.Viable = false;
6008 Candidate.FailureKind = ovl_fail_bad_conversion;
6012 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6013 // argument for which there is no corresponding parameter is
6014 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6015 Candidate.Conversions[ArgIdx].setEllipsis();
6019 // C++ [over.best.ics]p4+: (proposed DR resolution)
6020 // If the target is the first parameter of an inherited constructor when
6021 // constructing an object of type C with an argument list that has exactly
6022 // one expression, an implicit conversion sequence cannot be formed if C is
6023 // reference-related to the type that the argument would have after the
6024 // application of the user-defined conversion (if any) and before the final
6025 // standard conversion sequence.
6026 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6027 if (Shadow && Args.size() == 1 && !isa<InitListExpr>(Args.front())) {
6028 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
6029 QualType ConvertedArgumentType = Args.front()->getType();
6030 if (Candidate.Conversions[0].isUserDefined())
6031 ConvertedArgumentType =
6032 Candidate.Conversions[0].UserDefined.After.getFromType();
6033 if (CompareReferenceRelationship(Args.front()->getLocStart(),
6034 Context.getRecordType(Shadow->getParent()),
6035 ConvertedArgumentType, DerivedToBase,
6037 ObjCLifetimeConversion) >= Ref_Related) {
6038 Candidate.Viable = false;
6039 Candidate.FailureKind = ovl_fail_inhctor_slice;
6044 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6045 Candidate.Viable = false;
6046 Candidate.FailureKind = ovl_fail_enable_if;
6047 Candidate.DeductionFailure.Data = FailedAttr;
6051 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6052 Candidate.Viable = false;
6053 Candidate.FailureKind = ovl_fail_ext_disabled;
6057 initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Function, Args);
6061 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6062 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6063 if (Methods.size() <= 1)
6066 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6068 ObjCMethodDecl *Method = Methods[b];
6069 unsigned NumNamedArgs = Sel.getNumArgs();
6070 // Method might have more arguments than selector indicates. This is due
6071 // to addition of c-style arguments in method.
6072 if (Method->param_size() > NumNamedArgs)
6073 NumNamedArgs = Method->param_size();
6074 if (Args.size() < NumNamedArgs)
6077 for (unsigned i = 0; i < NumNamedArgs; i++) {
6078 // We can't do any type-checking on a type-dependent argument.
6079 if (Args[i]->isTypeDependent()) {
6084 ParmVarDecl *param = Method->parameters()[i];
6085 Expr *argExpr = Args[i];
6086 assert(argExpr && "SelectBestMethod(): missing expression");
6088 // Strip the unbridged-cast placeholder expression off unless it's
6089 // a consumed argument.
6090 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6091 !param->hasAttr<CFConsumedAttr>())
6092 argExpr = stripARCUnbridgedCast(argExpr);
6094 // If the parameter is __unknown_anytype, move on to the next method.
6095 if (param->getType() == Context.UnknownAnyTy) {
6100 ImplicitConversionSequence ConversionState
6101 = TryCopyInitialization(*this, argExpr, param->getType(),
6102 /*SuppressUserConversions*/false,
6103 /*InOverloadResolution=*/true,
6104 /*AllowObjCWritebackConversion=*/
6105 getLangOpts().ObjCAutoRefCount,
6106 /*AllowExplicit*/false);
6107 // This function looks for a reasonably-exact match, so we consider
6108 // incompatible pointer conversions to be a failure here.
6109 if (ConversionState.isBad() ||
6110 (ConversionState.isStandard() &&
6111 ConversionState.Standard.Second ==
6112 ICK_Incompatible_Pointer_Conversion)) {
6117 // Promote additional arguments to variadic methods.
6118 if (Match && Method->isVariadic()) {
6119 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6120 if (Args[i]->isTypeDependent()) {
6124 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6126 if (Arg.isInvalid()) {
6132 // Check for extra arguments to non-variadic methods.
6133 if (Args.size() != NumNamedArgs)
6135 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6136 // Special case when selectors have no argument. In this case, select
6137 // one with the most general result type of 'id'.
6138 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6139 QualType ReturnT = Methods[b]->getReturnType();
6140 if (ReturnT->isObjCIdType())
6152 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6153 // enable_if is order-sensitive. As a result, we need to reverse things
6154 // sometimes. Size of 4 elements is arbitrary.
6155 static SmallVector<EnableIfAttr *, 4>
6156 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6157 SmallVector<EnableIfAttr *, 4> Result;
6158 if (!Function->hasAttrs())
6161 const auto &FuncAttrs = Function->getAttrs();
6162 for (Attr *Attr : FuncAttrs)
6163 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6164 Result.push_back(EnableIf);
6166 std::reverse(Result.begin(), Result.end());
6171 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6172 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6173 bool MissingImplicitThis, Expr *&ConvertedThis,
6174 SmallVectorImpl<Expr *> &ConvertedArgs) {
6176 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6177 assert(!isa<CXXConstructorDecl>(Method) &&
6178 "Shouldn't have `this` for ctors!");
6179 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6180 ExprResult R = S.PerformObjectArgumentInitialization(
6181 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6184 ConvertedThis = R.get();
6186 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6188 assert((MissingImplicitThis || MD->isStatic() ||
6189 isa<CXXConstructorDecl>(MD)) &&
6190 "Expected `this` for non-ctor instance methods");
6192 ConvertedThis = nullptr;
6195 // Ignore any variadic arguments. Converting them is pointless, since the
6196 // user can't refer to them in the function condition.
6197 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6199 // Convert the arguments.
6200 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6202 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6203 S.Context, Function->getParamDecl(I)),
6204 SourceLocation(), Args[I]);
6209 ConvertedArgs.push_back(R.get());
6212 if (Trap.hasErrorOccurred())
6215 // Push default arguments if needed.
6216 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6217 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6218 ParmVarDecl *P = Function->getParamDecl(i);
6219 ExprResult R = S.PerformCopyInitialization(
6220 InitializedEntity::InitializeParameter(S.Context,
6221 Function->getParamDecl(i)),
6223 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6224 : P->getDefaultArg());
6227 ConvertedArgs.push_back(R.get());
6230 if (Trap.hasErrorOccurred())
6236 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6237 bool MissingImplicitThis) {
6238 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6239 getOrderedEnableIfAttrs(Function);
6240 if (EnableIfAttrs.empty())
6243 SFINAETrap Trap(*this);
6244 SmallVector<Expr *, 16> ConvertedArgs;
6245 // FIXME: We should look into making enable_if late-parsed.
6246 Expr *DiscardedThis;
6247 if (!convertArgsForAvailabilityChecks(
6248 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6249 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6250 return EnableIfAttrs[0];
6252 for (auto *EIA : EnableIfAttrs) {
6254 // FIXME: This doesn't consider value-dependent cases, because doing so is
6255 // very difficult. Ideally, we should handle them more gracefully.
6256 if (!EIA->getCond()->EvaluateWithSubstitution(
6257 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6260 if (!Result.isInt() || !Result.getInt().getBoolValue())
6266 static bool gatherDiagnoseIfAttrs(FunctionDecl *Function, bool ArgDependent,
6267 SmallVectorImpl<DiagnoseIfAttr *> &Errors,
6268 SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal) {
6269 for (auto *DIA : Function->specific_attrs<DiagnoseIfAttr>())
6270 if (ArgDependent == DIA->getArgDependent()) {
6272 Errors.push_back(DIA);
6274 Nonfatal.push_back(DIA);
6277 return !Errors.empty() || !Nonfatal.empty();
6280 template <typename CheckFn>
6281 static DiagnoseIfAttr *
6282 checkDiagnoseIfAttrsWith(const SmallVectorImpl<DiagnoseIfAttr *> &Errors,
6283 SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal,
6284 CheckFn &&IsSuccessful) {
6285 // Note that diagnose_if attributes are late-parsed, so they appear in the
6286 // correct order (unlike enable_if attributes).
6287 auto ErrAttr = llvm::find_if(Errors, IsSuccessful);
6288 if (ErrAttr != Errors.end())
6291 llvm::erase_if(Nonfatal, [&](DiagnoseIfAttr *A) { return !IsSuccessful(A); });
6296 Sema::checkArgDependentDiagnoseIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6297 SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal,
6298 bool MissingImplicitThis,
6300 SmallVector<DiagnoseIfAttr *, 4> Errors;
6301 if (!gatherDiagnoseIfAttrs(Function, /*ArgDependent=*/true, Errors, Nonfatal))
6304 SFINAETrap Trap(*this);
6305 SmallVector<Expr *, 16> ConvertedArgs;
6306 Expr *ConvertedThis;
6307 if (!convertArgsForAvailabilityChecks(*this, Function, ThisArg, Args, Trap,
6308 MissingImplicitThis, ConvertedThis,
6312 return checkDiagnoseIfAttrsWith(Errors, Nonfatal, [&](DiagnoseIfAttr *DIA) {
6314 // It's sane to use the same ConvertedArgs for any redecl of this function,
6315 // since EvaluateWithSubstitution only cares about the position of each
6316 // argument in the arg list, not the ParmVarDecl* it maps to.
6317 if (!DIA->getCond()->EvaluateWithSubstitution(
6318 Result, Context, DIA->getParent(), ConvertedArgs, ConvertedThis))
6320 return Result.isInt() && Result.getInt().getBoolValue();
6324 DiagnoseIfAttr *Sema::checkArgIndependentDiagnoseIf(
6325 FunctionDecl *Function, SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal) {
6326 SmallVector<DiagnoseIfAttr *, 4> Errors;
6327 if (!gatherDiagnoseIfAttrs(Function, /*ArgDependent=*/false, Errors,
6331 return checkDiagnoseIfAttrsWith(Errors, Nonfatal, [&](DiagnoseIfAttr *DIA) {
6333 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6338 void Sema::emitDiagnoseIfDiagnostic(SourceLocation Loc,
6339 const DiagnoseIfAttr *DIA) {
6340 auto Code = DIA->isError() ? diag::err_diagnose_if_succeeded
6341 : diag::warn_diagnose_if_succeeded;
6342 Diag(Loc, Code) << DIA->getMessage();
6343 Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6344 << DIA->getParent() << DIA->getCond()->getSourceRange();
6347 /// \brief Add all of the function declarations in the given function set to
6348 /// the overload candidate set.
6349 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6350 ArrayRef<Expr *> Args,
6351 OverloadCandidateSet& CandidateSet,
6352 TemplateArgumentListInfo *ExplicitTemplateArgs,
6353 bool SuppressUserConversions,
6354 bool PartialOverloading) {
6355 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6356 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6357 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6358 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6359 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6360 cast<CXXMethodDecl>(FD)->getParent(),
6361 Args[0]->getType(), Args[0]->Classify(Context),
6362 Args[0], Args.slice(1), CandidateSet,
6363 SuppressUserConversions, PartialOverloading);
6365 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6366 SuppressUserConversions, PartialOverloading);
6368 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6369 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6370 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6371 AddMethodTemplateCandidate(
6372 FunTmpl, F.getPair(),
6373 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6374 ExplicitTemplateArgs, Args[0]->getType(),
6375 Args[0]->Classify(Context), Args[0], Args.slice(1), CandidateSet,
6376 SuppressUserConversions, PartialOverloading);
6378 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6379 ExplicitTemplateArgs, Args,
6380 CandidateSet, SuppressUserConversions,
6381 PartialOverloading);
6386 /// AddMethodCandidate - Adds a named decl (which is some kind of
6387 /// method) as a method candidate to the given overload set.
6388 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6389 QualType ObjectType,
6390 Expr::Classification ObjectClassification,
6392 ArrayRef<Expr *> Args,
6393 OverloadCandidateSet& CandidateSet,
6394 bool SuppressUserConversions) {
6395 NamedDecl *Decl = FoundDecl.getDecl();
6396 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6398 if (isa<UsingShadowDecl>(Decl))
6399 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6401 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6402 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6403 "Expected a member function template");
6404 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6405 /*ExplicitArgs*/ nullptr,
6406 ObjectType, ObjectClassification,
6407 ThisArg, Args, CandidateSet,
6408 SuppressUserConversions);
6410 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6411 ObjectType, ObjectClassification,
6413 CandidateSet, SuppressUserConversions);
6417 /// AddMethodCandidate - Adds the given C++ member function to the set
6418 /// of candidate functions, using the given function call arguments
6419 /// and the object argument (@c Object). For example, in a call
6420 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6421 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6422 /// allow user-defined conversions via constructors or conversion
6425 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6426 CXXRecordDecl *ActingContext, QualType ObjectType,
6427 Expr::Classification ObjectClassification,
6428 Expr *ThisArg, ArrayRef<Expr *> Args,
6429 OverloadCandidateSet &CandidateSet,
6430 bool SuppressUserConversions,
6431 bool PartialOverloading,
6432 ConversionSequenceList EarlyConversions) {
6433 const FunctionProtoType *Proto
6434 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6435 assert(Proto && "Methods without a prototype cannot be overloaded");
6436 assert(!isa<CXXConstructorDecl>(Method) &&
6437 "Use AddOverloadCandidate for constructors");
6439 if (!CandidateSet.isNewCandidate(Method))
6442 // C++11 [class.copy]p23: [DR1402]
6443 // A defaulted move assignment operator that is defined as deleted is
6444 // ignored by overload resolution.
6445 if (Method->isDefaulted() && Method->isDeleted() &&
6446 Method->isMoveAssignmentOperator())
6449 // Overload resolution is always an unevaluated context.
6450 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6452 // Add this candidate
6453 OverloadCandidate &Candidate =
6454 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6455 Candidate.FoundDecl = FoundDecl;
6456 Candidate.Function = Method;
6457 Candidate.IsSurrogate = false;
6458 Candidate.IgnoreObjectArgument = false;
6459 Candidate.ExplicitCallArguments = Args.size();
6461 unsigned NumParams = Proto->getNumParams();
6463 // (C++ 13.3.2p2): A candidate function having fewer than m
6464 // parameters is viable only if it has an ellipsis in its parameter
6466 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6467 !Proto->isVariadic()) {
6468 Candidate.Viable = false;
6469 Candidate.FailureKind = ovl_fail_too_many_arguments;
6473 // (C++ 13.3.2p2): A candidate function having more than m parameters
6474 // is viable only if the (m+1)st parameter has a default argument
6475 // (8.3.6). For the purposes of overload resolution, the
6476 // parameter list is truncated on the right, so that there are
6477 // exactly m parameters.
6478 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6479 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6480 // Not enough arguments.
6481 Candidate.Viable = false;
6482 Candidate.FailureKind = ovl_fail_too_few_arguments;
6486 Candidate.Viable = true;
6488 if (Method->isStatic() || ObjectType.isNull())
6489 // The implicit object argument is ignored.
6490 Candidate.IgnoreObjectArgument = true;
6492 // Determine the implicit conversion sequence for the object
6494 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6495 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6496 Method, ActingContext);
6497 if (Candidate.Conversions[0].isBad()) {
6498 Candidate.Viable = false;
6499 Candidate.FailureKind = ovl_fail_bad_conversion;
6504 // (CUDA B.1): Check for invalid calls between targets.
6505 if (getLangOpts().CUDA)
6506 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6507 if (!IsAllowedCUDACall(Caller, Method)) {
6508 Candidate.Viable = false;
6509 Candidate.FailureKind = ovl_fail_bad_target;
6513 // Determine the implicit conversion sequences for each of the
6515 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6516 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6517 // We already formed a conversion sequence for this parameter during
6518 // template argument deduction.
6519 } else if (ArgIdx < NumParams) {
6520 // (C++ 13.3.2p3): for F to be a viable function, there shall
6521 // exist for each argument an implicit conversion sequence
6522 // (13.3.3.1) that converts that argument to the corresponding
6524 QualType ParamType = Proto->getParamType(ArgIdx);
6525 Candidate.Conversions[ArgIdx + 1]
6526 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6527 SuppressUserConversions,
6528 /*InOverloadResolution=*/true,
6529 /*AllowObjCWritebackConversion=*/
6530 getLangOpts().ObjCAutoRefCount);
6531 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6532 Candidate.Viable = false;
6533 Candidate.FailureKind = ovl_fail_bad_conversion;
6537 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6538 // argument for which there is no corresponding parameter is
6539 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6540 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6544 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6545 Candidate.Viable = false;
6546 Candidate.FailureKind = ovl_fail_enable_if;
6547 Candidate.DeductionFailure.Data = FailedAttr;
6551 initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Method, Args,
6552 /*MissingImplicitThis=*/!ThisArg, ThisArg);
6555 /// \brief Add a C++ member function template as a candidate to the candidate
6556 /// set, using template argument deduction to produce an appropriate member
6557 /// function template specialization.
6559 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6560 DeclAccessPair FoundDecl,
6561 CXXRecordDecl *ActingContext,
6562 TemplateArgumentListInfo *ExplicitTemplateArgs,
6563 QualType ObjectType,
6564 Expr::Classification ObjectClassification,
6566 ArrayRef<Expr *> Args,
6567 OverloadCandidateSet& CandidateSet,
6568 bool SuppressUserConversions,
6569 bool PartialOverloading) {
6570 if (!CandidateSet.isNewCandidate(MethodTmpl))
6573 // C++ [over.match.funcs]p7:
6574 // In each case where a candidate is a function template, candidate
6575 // function template specializations are generated using template argument
6576 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6577 // candidate functions in the usual way.113) A given name can refer to one
6578 // or more function templates and also to a set of overloaded non-template
6579 // functions. In such a case, the candidate functions generated from each
6580 // function template are combined with the set of non-template candidate
6582 TemplateDeductionInfo Info(CandidateSet.getLocation());
6583 FunctionDecl *Specialization = nullptr;
6584 ConversionSequenceList Conversions;
6585 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6586 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6587 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6588 return CheckNonDependentConversions(
6589 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6590 SuppressUserConversions, ActingContext, ObjectType,
6591 ObjectClassification);
6593 OverloadCandidate &Candidate =
6594 CandidateSet.addCandidate(Conversions.size(), Conversions);
6595 Candidate.FoundDecl = FoundDecl;
6596 Candidate.Function = MethodTmpl->getTemplatedDecl();
6597 Candidate.Viable = false;
6598 Candidate.IsSurrogate = false;
6599 Candidate.IgnoreObjectArgument =
6600 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6601 ObjectType.isNull();
6602 Candidate.ExplicitCallArguments = Args.size();
6603 if (Result == TDK_NonDependentConversionFailure)
6604 Candidate.FailureKind = ovl_fail_bad_conversion;
6606 Candidate.FailureKind = ovl_fail_bad_deduction;
6607 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6613 // Add the function template specialization produced by template argument
6614 // deduction as a candidate.
6615 assert(Specialization && "Missing member function template specialization?");
6616 assert(isa<CXXMethodDecl>(Specialization) &&
6617 "Specialization is not a member function?");
6618 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6619 ActingContext, ObjectType, ObjectClassification,
6620 /*ThisArg=*/ThisArg, Args, CandidateSet,
6621 SuppressUserConversions, PartialOverloading, Conversions);
6624 /// \brief Add a C++ function template specialization as a candidate
6625 /// in the candidate set, using template argument deduction to produce
6626 /// an appropriate function template specialization.
6628 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6629 DeclAccessPair FoundDecl,
6630 TemplateArgumentListInfo *ExplicitTemplateArgs,
6631 ArrayRef<Expr *> Args,
6632 OverloadCandidateSet& CandidateSet,
6633 bool SuppressUserConversions,
6634 bool PartialOverloading) {
6635 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6638 // C++ [over.match.funcs]p7:
6639 // In each case where a candidate is a function template, candidate
6640 // function template specializations are generated using template argument
6641 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6642 // candidate functions in the usual way.113) A given name can refer to one
6643 // or more function templates and also to a set of overloaded non-template
6644 // functions. In such a case, the candidate functions generated from each
6645 // function template are combined with the set of non-template candidate
6647 TemplateDeductionInfo Info(CandidateSet.getLocation());
6648 FunctionDecl *Specialization = nullptr;
6649 ConversionSequenceList Conversions;
6650 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6651 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6652 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6653 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6654 Args, CandidateSet, Conversions,
6655 SuppressUserConversions);
6657 OverloadCandidate &Candidate =
6658 CandidateSet.addCandidate(Conversions.size(), Conversions);
6659 Candidate.FoundDecl = FoundDecl;
6660 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6661 Candidate.Viable = false;
6662 Candidate.IsSurrogate = false;
6663 // Ignore the object argument if there is one, since we don't have an object
6665 Candidate.IgnoreObjectArgument =
6666 isa<CXXMethodDecl>(Candidate.Function) &&
6667 !isa<CXXConstructorDecl>(Candidate.Function);
6668 Candidate.ExplicitCallArguments = Args.size();
6669 if (Result == TDK_NonDependentConversionFailure)
6670 Candidate.FailureKind = ovl_fail_bad_conversion;
6672 Candidate.FailureKind = ovl_fail_bad_deduction;
6673 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6679 // Add the function template specialization produced by template argument
6680 // deduction as a candidate.
6681 assert(Specialization && "Missing function template specialization?");
6682 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6683 SuppressUserConversions, PartialOverloading,
6684 /*AllowExplicit*/false, Conversions);
6687 /// Check that implicit conversion sequences can be formed for each argument
6688 /// whose corresponding parameter has a non-dependent type, per DR1391's
6689 /// [temp.deduct.call]p10.
6690 bool Sema::CheckNonDependentConversions(
6691 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6692 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6693 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6694 CXXRecordDecl *ActingContext, QualType ObjectType,
6695 Expr::Classification ObjectClassification) {
6696 // FIXME: The cases in which we allow explicit conversions for constructor
6697 // arguments never consider calling a constructor template. It's not clear
6699 const bool AllowExplicit = false;
6701 auto *FD = FunctionTemplate->getTemplatedDecl();
6702 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6703 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6704 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6707 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6709 // Overload resolution is always an unevaluated context.
6710 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6712 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6713 // require that, but this check should never result in a hard error, and
6714 // overload resolution is permitted to sidestep instantiations.
6715 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6716 !ObjectType.isNull()) {
6717 Conversions[0] = TryObjectArgumentInitialization(
6718 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6719 Method, ActingContext);
6720 if (Conversions[0].isBad())
6724 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6726 QualType ParamType = ParamTypes[I];
6727 if (!ParamType->isDependentType()) {
6728 Conversions[ThisConversions + I]
6729 = TryCopyInitialization(*this, Args[I], ParamType,
6730 SuppressUserConversions,
6731 /*InOverloadResolution=*/true,
6732 /*AllowObjCWritebackConversion=*/
6733 getLangOpts().ObjCAutoRefCount,
6735 if (Conversions[ThisConversions + I].isBad())
6743 /// Determine whether this is an allowable conversion from the result
6744 /// of an explicit conversion operator to the expected type, per C++
6745 /// [over.match.conv]p1 and [over.match.ref]p1.
6747 /// \param ConvType The return type of the conversion function.
6749 /// \param ToType The type we are converting to.
6751 /// \param AllowObjCPointerConversion Allow a conversion from one
6752 /// Objective-C pointer to another.
6754 /// \returns true if the conversion is allowable, false otherwise.
6755 static bool isAllowableExplicitConversion(Sema &S,
6756 QualType ConvType, QualType ToType,
6757 bool AllowObjCPointerConversion) {
6758 QualType ToNonRefType = ToType.getNonReferenceType();
6760 // Easy case: the types are the same.
6761 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6764 // Allow qualification conversions.
6765 bool ObjCLifetimeConversion;
6766 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6767 ObjCLifetimeConversion))
6770 // If we're not allowed to consider Objective-C pointer conversions,
6772 if (!AllowObjCPointerConversion)
6775 // Is this an Objective-C pointer conversion?
6776 bool IncompatibleObjC = false;
6777 QualType ConvertedType;
6778 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6782 /// AddConversionCandidate - Add a C++ conversion function as a
6783 /// candidate in the candidate set (C++ [over.match.conv],
6784 /// C++ [over.match.copy]). From is the expression we're converting from,
6785 /// and ToType is the type that we're eventually trying to convert to
6786 /// (which may or may not be the same type as the type that the
6787 /// conversion function produces).
6789 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6790 DeclAccessPair FoundDecl,
6791 CXXRecordDecl *ActingContext,
6792 Expr *From, QualType ToType,
6793 OverloadCandidateSet& CandidateSet,
6794 bool AllowObjCConversionOnExplicit) {
6795 assert(!Conversion->getDescribedFunctionTemplate() &&
6796 "Conversion function templates use AddTemplateConversionCandidate");
6797 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6798 if (!CandidateSet.isNewCandidate(Conversion))
6801 // If the conversion function has an undeduced return type, trigger its
6803 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6804 if (DeduceReturnType(Conversion, From->getExprLoc()))
6806 ConvType = Conversion->getConversionType().getNonReferenceType();
6809 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6810 // operator is only a candidate if its return type is the target type or
6811 // can be converted to the target type with a qualification conversion.
6812 if (Conversion->isExplicit() &&
6813 !isAllowableExplicitConversion(*this, ConvType, ToType,
6814 AllowObjCConversionOnExplicit))
6817 // Overload resolution is always an unevaluated context.
6818 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6820 // Add this candidate
6821 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6822 Candidate.FoundDecl = FoundDecl;
6823 Candidate.Function = Conversion;
6824 Candidate.IsSurrogate = false;
6825 Candidate.IgnoreObjectArgument = false;
6826 Candidate.FinalConversion.setAsIdentityConversion();
6827 Candidate.FinalConversion.setFromType(ConvType);
6828 Candidate.FinalConversion.setAllToTypes(ToType);
6829 Candidate.Viable = true;
6830 Candidate.ExplicitCallArguments = 1;
6832 // C++ [over.match.funcs]p4:
6833 // For conversion functions, the function is considered to be a member of
6834 // the class of the implicit implied object argument for the purpose of
6835 // defining the type of the implicit object parameter.
6837 // Determine the implicit conversion sequence for the implicit
6838 // object parameter.
6839 QualType ImplicitParamType = From->getType();
6840 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6841 ImplicitParamType = FromPtrType->getPointeeType();
6842 CXXRecordDecl *ConversionContext
6843 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6845 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6846 *this, CandidateSet.getLocation(), From->getType(),
6847 From->Classify(Context), Conversion, ConversionContext);
6849 if (Candidate.Conversions[0].isBad()) {
6850 Candidate.Viable = false;
6851 Candidate.FailureKind = ovl_fail_bad_conversion;
6855 // We won't go through a user-defined type conversion function to convert a
6856 // derived to base as such conversions are given Conversion Rank. They only
6857 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6859 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6860 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6861 if (FromCanon == ToCanon ||
6862 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6863 Candidate.Viable = false;
6864 Candidate.FailureKind = ovl_fail_trivial_conversion;
6868 // To determine what the conversion from the result of calling the
6869 // conversion function to the type we're eventually trying to
6870 // convert to (ToType), we need to synthesize a call to the
6871 // conversion function and attempt copy initialization from it. This
6872 // makes sure that we get the right semantics with respect to
6873 // lvalues/rvalues and the type. Fortunately, we can allocate this
6874 // call on the stack and we don't need its arguments to be
6876 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6877 VK_LValue, From->getLocStart());
6878 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6879 Context.getPointerType(Conversion->getType()),
6880 CK_FunctionToPointerDecay,
6881 &ConversionRef, VK_RValue);
6883 QualType ConversionType = Conversion->getConversionType();
6884 if (!isCompleteType(From->getLocStart(), ConversionType)) {
6885 Candidate.Viable = false;
6886 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6890 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6892 // Note that it is safe to allocate CallExpr on the stack here because
6893 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6895 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6896 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6897 From->getLocStart());
6898 ImplicitConversionSequence ICS =
6899 TryCopyInitialization(*this, &Call, ToType,
6900 /*SuppressUserConversions=*/true,
6901 /*InOverloadResolution=*/false,
6902 /*AllowObjCWritebackConversion=*/false);
6904 switch (ICS.getKind()) {
6905 case ImplicitConversionSequence::StandardConversion:
6906 Candidate.FinalConversion = ICS.Standard;
6908 // C++ [over.ics.user]p3:
6909 // If the user-defined conversion is specified by a specialization of a
6910 // conversion function template, the second standard conversion sequence
6911 // shall have exact match rank.
6912 if (Conversion->getPrimaryTemplate() &&
6913 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6914 Candidate.Viable = false;
6915 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6919 // C++0x [dcl.init.ref]p5:
6920 // In the second case, if the reference is an rvalue reference and
6921 // the second standard conversion sequence of the user-defined
6922 // conversion sequence includes an lvalue-to-rvalue conversion, the
6923 // program is ill-formed.
6924 if (ToType->isRValueReferenceType() &&
6925 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6926 Candidate.Viable = false;
6927 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6932 case ImplicitConversionSequence::BadConversion:
6933 Candidate.Viable = false;
6934 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6939 "Can only end up with a standard conversion sequence or failure");
6942 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6943 Candidate.Viable = false;
6944 Candidate.FailureKind = ovl_fail_enable_if;
6945 Candidate.DeductionFailure.Data = FailedAttr;
6949 initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Conversion, None, false, From);
6952 /// \brief Adds a conversion function template specialization
6953 /// candidate to the overload set, using template argument deduction
6954 /// to deduce the template arguments of the conversion function
6955 /// template from the type that we are converting to (C++
6956 /// [temp.deduct.conv]).
6958 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6959 DeclAccessPair FoundDecl,
6960 CXXRecordDecl *ActingDC,
6961 Expr *From, QualType ToType,
6962 OverloadCandidateSet &CandidateSet,
6963 bool AllowObjCConversionOnExplicit) {
6964 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6965 "Only conversion function templates permitted here");
6967 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6970 TemplateDeductionInfo Info(CandidateSet.getLocation());
6971 CXXConversionDecl *Specialization = nullptr;
6972 if (TemplateDeductionResult Result
6973 = DeduceTemplateArguments(FunctionTemplate, ToType,
6974 Specialization, Info)) {
6975 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6976 Candidate.FoundDecl = FoundDecl;
6977 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6978 Candidate.Viable = false;
6979 Candidate.FailureKind = ovl_fail_bad_deduction;
6980 Candidate.IsSurrogate = false;
6981 Candidate.IgnoreObjectArgument = false;
6982 Candidate.ExplicitCallArguments = 1;
6983 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6988 // Add the conversion function template specialization produced by
6989 // template argument deduction as a candidate.
6990 assert(Specialization && "Missing function template specialization?");
6991 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6992 CandidateSet, AllowObjCConversionOnExplicit);
6995 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6996 /// converts the given @c Object to a function pointer via the
6997 /// conversion function @c Conversion, and then attempts to call it
6998 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6999 /// the type of function that we'll eventually be calling.
7000 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7001 DeclAccessPair FoundDecl,
7002 CXXRecordDecl *ActingContext,
7003 const FunctionProtoType *Proto,
7005 ArrayRef<Expr *> Args,
7006 OverloadCandidateSet& CandidateSet) {
7007 if (!CandidateSet.isNewCandidate(Conversion))
7010 // Overload resolution is always an unevaluated context.
7011 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
7013 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7014 Candidate.FoundDecl = FoundDecl;
7015 Candidate.Function = nullptr;
7016 Candidate.Surrogate = Conversion;
7017 Candidate.Viable = true;
7018 Candidate.IsSurrogate = true;
7019 Candidate.IgnoreObjectArgument = false;
7020 Candidate.ExplicitCallArguments = Args.size();
7022 // Determine the implicit conversion sequence for the implicit
7023 // object parameter.
7024 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7025 *this, CandidateSet.getLocation(), Object->getType(),
7026 Object->Classify(Context), Conversion, ActingContext);
7027 if (ObjectInit.isBad()) {
7028 Candidate.Viable = false;
7029 Candidate.FailureKind = ovl_fail_bad_conversion;
7030 Candidate.Conversions[0] = ObjectInit;
7034 // The first conversion is actually a user-defined conversion whose
7035 // first conversion is ObjectInit's standard conversion (which is
7036 // effectively a reference binding). Record it as such.
7037 Candidate.Conversions[0].setUserDefined();
7038 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7039 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7040 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7041 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7042 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7043 Candidate.Conversions[0].UserDefined.After
7044 = Candidate.Conversions[0].UserDefined.Before;
7045 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7048 unsigned NumParams = Proto->getNumParams();
7050 // (C++ 13.3.2p2): A candidate function having fewer than m
7051 // parameters is viable only if it has an ellipsis in its parameter
7053 if (Args.size() > NumParams && !Proto->isVariadic()) {
7054 Candidate.Viable = false;
7055 Candidate.FailureKind = ovl_fail_too_many_arguments;
7059 // Function types don't have any default arguments, so just check if
7060 // we have enough arguments.
7061 if (Args.size() < NumParams) {
7062 // Not enough arguments.
7063 Candidate.Viable = false;
7064 Candidate.FailureKind = ovl_fail_too_few_arguments;
7068 // Determine the implicit conversion sequences for each of the
7070 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7071 if (ArgIdx < NumParams) {
7072 // (C++ 13.3.2p3): for F to be a viable function, there shall
7073 // exist for each argument an implicit conversion sequence
7074 // (13.3.3.1) that converts that argument to the corresponding
7076 QualType ParamType = Proto->getParamType(ArgIdx);
7077 Candidate.Conversions[ArgIdx + 1]
7078 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7079 /*SuppressUserConversions=*/false,
7080 /*InOverloadResolution=*/false,
7081 /*AllowObjCWritebackConversion=*/
7082 getLangOpts().ObjCAutoRefCount);
7083 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7084 Candidate.Viable = false;
7085 Candidate.FailureKind = ovl_fail_bad_conversion;
7089 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7090 // argument for which there is no corresponding parameter is
7091 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7092 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7096 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7097 Candidate.Viable = false;
7098 Candidate.FailureKind = ovl_fail_enable_if;
7099 Candidate.DeductionFailure.Data = FailedAttr;
7103 initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Conversion, None);
7106 /// \brief Add overload candidates for overloaded operators that are
7107 /// member functions.
7109 /// Add the overloaded operator candidates that are member functions
7110 /// for the operator Op that was used in an operator expression such
7111 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7112 /// CandidateSet will store the added overload candidates. (C++
7113 /// [over.match.oper]).
7114 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7115 SourceLocation OpLoc,
7116 ArrayRef<Expr *> Args,
7117 OverloadCandidateSet& CandidateSet,
7118 SourceRange OpRange) {
7119 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7121 // C++ [over.match.oper]p3:
7122 // For a unary operator @ with an operand of a type whose
7123 // cv-unqualified version is T1, and for a binary operator @ with
7124 // a left operand of a type whose cv-unqualified version is T1 and
7125 // a right operand of a type whose cv-unqualified version is T2,
7126 // three sets of candidate functions, designated member
7127 // candidates, non-member candidates and built-in candidates, are
7128 // constructed as follows:
7129 QualType T1 = Args[0]->getType();
7131 // -- If T1 is a complete class type or a class currently being
7132 // defined, the set of member candidates is the result of the
7133 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7134 // the set of member candidates is empty.
7135 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7136 // Complete the type if it can be completed.
7137 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7139 // If the type is neither complete nor being defined, bail out now.
7140 if (!T1Rec->getDecl()->getDefinition())
7143 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7144 LookupQualifiedName(Operators, T1Rec->getDecl());
7145 Operators.suppressDiagnostics();
7147 for (LookupResult::iterator Oper = Operators.begin(),
7148 OperEnd = Operators.end();
7151 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7152 Args[0]->Classify(Context), Args[0], Args.slice(1),
7153 CandidateSet, /*SuppressUserConversions=*/false);
7157 /// AddBuiltinCandidate - Add a candidate for a built-in
7158 /// operator. ResultTy and ParamTys are the result and parameter types
7159 /// of the built-in candidate, respectively. Args and NumArgs are the
7160 /// arguments being passed to the candidate. IsAssignmentOperator
7161 /// should be true when this built-in candidate is an assignment
7162 /// operator. NumContextualBoolArguments is the number of arguments
7163 /// (at the beginning of the argument list) that will be contextually
7164 /// converted to bool.
7165 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
7166 ArrayRef<Expr *> Args,
7167 OverloadCandidateSet& CandidateSet,
7168 bool IsAssignmentOperator,
7169 unsigned NumContextualBoolArguments) {
7170 // Overload resolution is always an unevaluated context.
7171 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
7173 // Add this candidate
7174 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7175 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7176 Candidate.Function = nullptr;
7177 Candidate.IsSurrogate = false;
7178 Candidate.IgnoreObjectArgument = false;
7179 Candidate.BuiltinTypes.ResultTy = ResultTy;
7180 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7181 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
7183 // Determine the implicit conversion sequences for each of the
7185 Candidate.Viable = true;
7186 Candidate.ExplicitCallArguments = Args.size();
7187 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7188 // C++ [over.match.oper]p4:
7189 // For the built-in assignment operators, conversions of the
7190 // left operand are restricted as follows:
7191 // -- no temporaries are introduced to hold the left operand, and
7192 // -- no user-defined conversions are applied to the left
7193 // operand to achieve a type match with the left-most
7194 // parameter of a built-in candidate.
7196 // We block these conversions by turning off user-defined
7197 // conversions, since that is the only way that initialization of
7198 // a reference to a non-class type can occur from something that
7199 // is not of the same type.
7200 if (ArgIdx < NumContextualBoolArguments) {
7201 assert(ParamTys[ArgIdx] == Context.BoolTy &&
7202 "Contextual conversion to bool requires bool type");
7203 Candidate.Conversions[ArgIdx]
7204 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7206 Candidate.Conversions[ArgIdx]
7207 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7208 ArgIdx == 0 && IsAssignmentOperator,
7209 /*InOverloadResolution=*/false,
7210 /*AllowObjCWritebackConversion=*/
7211 getLangOpts().ObjCAutoRefCount);
7213 if (Candidate.Conversions[ArgIdx].isBad()) {
7214 Candidate.Viable = false;
7215 Candidate.FailureKind = ovl_fail_bad_conversion;
7223 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7224 /// candidate operator functions for built-in operators (C++
7225 /// [over.built]). The types are separated into pointer types and
7226 /// enumeration types.
7227 class BuiltinCandidateTypeSet {
7228 /// TypeSet - A set of types.
7229 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7230 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7232 /// PointerTypes - The set of pointer types that will be used in the
7233 /// built-in candidates.
7234 TypeSet PointerTypes;
7236 /// MemberPointerTypes - The set of member pointer types that will be
7237 /// used in the built-in candidates.
7238 TypeSet MemberPointerTypes;
7240 /// EnumerationTypes - The set of enumeration types that will be
7241 /// used in the built-in candidates.
7242 TypeSet EnumerationTypes;
7244 /// \brief The set of vector types that will be used in the built-in
7246 TypeSet VectorTypes;
7248 /// \brief A flag indicating non-record types are viable candidates
7249 bool HasNonRecordTypes;
7251 /// \brief A flag indicating whether either arithmetic or enumeration types
7252 /// were present in the candidate set.
7253 bool HasArithmeticOrEnumeralTypes;
7255 /// \brief A flag indicating whether the nullptr type was present in the
7257 bool HasNullPtrType;
7259 /// Sema - The semantic analysis instance where we are building the
7260 /// candidate type set.
7263 /// Context - The AST context in which we will build the type sets.
7264 ASTContext &Context;
7266 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7267 const Qualifiers &VisibleQuals);
7268 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7271 /// iterator - Iterates through the types that are part of the set.
7272 typedef TypeSet::iterator iterator;
7274 BuiltinCandidateTypeSet(Sema &SemaRef)
7275 : HasNonRecordTypes(false),
7276 HasArithmeticOrEnumeralTypes(false),
7277 HasNullPtrType(false),
7279 Context(SemaRef.Context) { }
7281 void AddTypesConvertedFrom(QualType Ty,
7283 bool AllowUserConversions,
7284 bool AllowExplicitConversions,
7285 const Qualifiers &VisibleTypeConversionsQuals);
7287 /// pointer_begin - First pointer type found;
7288 iterator pointer_begin() { return PointerTypes.begin(); }
7290 /// pointer_end - Past the last pointer type found;
7291 iterator pointer_end() { return PointerTypes.end(); }
7293 /// member_pointer_begin - First member pointer type found;
7294 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7296 /// member_pointer_end - Past the last member pointer type found;
7297 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7299 /// enumeration_begin - First enumeration type found;
7300 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7302 /// enumeration_end - Past the last enumeration type found;
7303 iterator enumeration_end() { return EnumerationTypes.end(); }
7305 iterator vector_begin() { return VectorTypes.begin(); }
7306 iterator vector_end() { return VectorTypes.end(); }
7308 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7309 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7310 bool hasNullPtrType() const { return HasNullPtrType; }
7313 } // end anonymous namespace
7315 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7316 /// the set of pointer types along with any more-qualified variants of
7317 /// that type. For example, if @p Ty is "int const *", this routine
7318 /// will add "int const *", "int const volatile *", "int const
7319 /// restrict *", and "int const volatile restrict *" to the set of
7320 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7321 /// false otherwise.
7323 /// FIXME: what to do about extended qualifiers?
7325 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7326 const Qualifiers &VisibleQuals) {
7328 // Insert this type.
7329 if (!PointerTypes.insert(Ty))
7333 const PointerType *PointerTy = Ty->getAs<PointerType>();
7334 bool buildObjCPtr = false;
7336 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7337 PointeeTy = PTy->getPointeeType();
7338 buildObjCPtr = true;
7340 PointeeTy = PointerTy->getPointeeType();
7343 // Don't add qualified variants of arrays. For one, they're not allowed
7344 // (the qualifier would sink to the element type), and for another, the
7345 // only overload situation where it matters is subscript or pointer +- int,
7346 // and those shouldn't have qualifier variants anyway.
7347 if (PointeeTy->isArrayType())
7350 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7351 bool hasVolatile = VisibleQuals.hasVolatile();
7352 bool hasRestrict = VisibleQuals.hasRestrict();
7354 // Iterate through all strict supersets of BaseCVR.
7355 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7356 if ((CVR | BaseCVR) != CVR) continue;
7357 // Skip over volatile if no volatile found anywhere in the types.
7358 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7360 // Skip over restrict if no restrict found anywhere in the types, or if
7361 // the type cannot be restrict-qualified.
7362 if ((CVR & Qualifiers::Restrict) &&
7364 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7367 // Build qualified pointee type.
7368 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7370 // Build qualified pointer type.
7371 QualType QPointerTy;
7373 QPointerTy = Context.getPointerType(QPointeeTy);
7375 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7377 // Insert qualified pointer type.
7378 PointerTypes.insert(QPointerTy);
7384 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7385 /// to the set of pointer types along with any more-qualified variants of
7386 /// that type. For example, if @p Ty is "int const *", this routine
7387 /// will add "int const *", "int const volatile *", "int const
7388 /// restrict *", and "int const volatile restrict *" to the set of
7389 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7390 /// false otherwise.
7392 /// FIXME: what to do about extended qualifiers?
7394 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7396 // Insert this type.
7397 if (!MemberPointerTypes.insert(Ty))
7400 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7401 assert(PointerTy && "type was not a member pointer type!");
7403 QualType PointeeTy = PointerTy->getPointeeType();
7404 // Don't add qualified variants of arrays. For one, they're not allowed
7405 // (the qualifier would sink to the element type), and for another, the
7406 // only overload situation where it matters is subscript or pointer +- int,
7407 // and those shouldn't have qualifier variants anyway.
7408 if (PointeeTy->isArrayType())
7410 const Type *ClassTy = PointerTy->getClass();
7412 // Iterate through all strict supersets of the pointee type's CVR
7414 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7415 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7416 if ((CVR | BaseCVR) != CVR) continue;
7418 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7419 MemberPointerTypes.insert(
7420 Context.getMemberPointerType(QPointeeTy, ClassTy));
7426 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7427 /// Ty can be implicit converted to the given set of @p Types. We're
7428 /// primarily interested in pointer types and enumeration types. We also
7429 /// take member pointer types, for the conditional operator.
7430 /// AllowUserConversions is true if we should look at the conversion
7431 /// functions of a class type, and AllowExplicitConversions if we
7432 /// should also include the explicit conversion functions of a class
7435 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7437 bool AllowUserConversions,
7438 bool AllowExplicitConversions,
7439 const Qualifiers &VisibleQuals) {
7440 // Only deal with canonical types.
7441 Ty = Context.getCanonicalType(Ty);
7443 // Look through reference types; they aren't part of the type of an
7444 // expression for the purposes of conversions.
7445 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7446 Ty = RefTy->getPointeeType();
7448 // If we're dealing with an array type, decay to the pointer.
7449 if (Ty->isArrayType())
7450 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7452 // Otherwise, we don't care about qualifiers on the type.
7453 Ty = Ty.getLocalUnqualifiedType();
7455 // Flag if we ever add a non-record type.
7456 const RecordType *TyRec = Ty->getAs<RecordType>();
7457 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7459 // Flag if we encounter an arithmetic type.
7460 HasArithmeticOrEnumeralTypes =
7461 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7463 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7464 PointerTypes.insert(Ty);
7465 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7466 // Insert our type, and its more-qualified variants, into the set
7468 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7470 } else if (Ty->isMemberPointerType()) {
7471 // Member pointers are far easier, since the pointee can't be converted.
7472 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7474 } else if (Ty->isEnumeralType()) {
7475 HasArithmeticOrEnumeralTypes = true;
7476 EnumerationTypes.insert(Ty);
7477 } else if (Ty->isVectorType()) {
7478 // We treat vector types as arithmetic types in many contexts as an
7480 HasArithmeticOrEnumeralTypes = true;
7481 VectorTypes.insert(Ty);
7482 } else if (Ty->isNullPtrType()) {
7483 HasNullPtrType = true;
7484 } else if (AllowUserConversions && TyRec) {
7485 // No conversion functions in incomplete types.
7486 if (!SemaRef.isCompleteType(Loc, Ty))
7489 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7490 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7491 if (isa<UsingShadowDecl>(D))
7492 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7494 // Skip conversion function templates; they don't tell us anything
7495 // about which builtin types we can convert to.
7496 if (isa<FunctionTemplateDecl>(D))
7499 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7500 if (AllowExplicitConversions || !Conv->isExplicit()) {
7501 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7508 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7509 /// the volatile- and non-volatile-qualified assignment operators for the
7510 /// given type to the candidate set.
7511 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7513 ArrayRef<Expr *> Args,
7514 OverloadCandidateSet &CandidateSet) {
7515 QualType ParamTypes[2];
7517 // T& operator=(T&, T)
7518 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7520 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7521 /*IsAssignmentOperator=*/true);
7523 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7524 // volatile T& operator=(volatile T&, T)
7526 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7528 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7529 /*IsAssignmentOperator=*/true);
7533 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7534 /// if any, found in visible type conversion functions found in ArgExpr's type.
7535 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7537 const RecordType *TyRec;
7538 if (const MemberPointerType *RHSMPType =
7539 ArgExpr->getType()->getAs<MemberPointerType>())
7540 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7542 TyRec = ArgExpr->getType()->getAs<RecordType>();
7544 // Just to be safe, assume the worst case.
7545 VRQuals.addVolatile();
7546 VRQuals.addRestrict();
7550 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7551 if (!ClassDecl->hasDefinition())
7554 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7555 if (isa<UsingShadowDecl>(D))
7556 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7557 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7558 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7559 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7560 CanTy = ResTypeRef->getPointeeType();
7561 // Need to go down the pointer/mempointer chain and add qualifiers
7565 if (CanTy.isRestrictQualified())
7566 VRQuals.addRestrict();
7567 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7568 CanTy = ResTypePtr->getPointeeType();
7569 else if (const MemberPointerType *ResTypeMPtr =
7570 CanTy->getAs<MemberPointerType>())
7571 CanTy = ResTypeMPtr->getPointeeType();
7574 if (CanTy.isVolatileQualified())
7575 VRQuals.addVolatile();
7576 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7586 /// \brief Helper class to manage the addition of builtin operator overload
7587 /// candidates. It provides shared state and utility methods used throughout
7588 /// the process, as well as a helper method to add each group of builtin
7589 /// operator overloads from the standard to a candidate set.
7590 class BuiltinOperatorOverloadBuilder {
7591 // Common instance state available to all overload candidate addition methods.
7593 ArrayRef<Expr *> Args;
7594 Qualifiers VisibleTypeConversionsQuals;
7595 bool HasArithmeticOrEnumeralCandidateType;
7596 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7597 OverloadCandidateSet &CandidateSet;
7599 // Define some constants used to index and iterate over the arithemetic types
7600 // provided via the getArithmeticType() method below.
7601 // The "promoted arithmetic types" are the arithmetic
7602 // types are that preserved by promotion (C++ [over.built]p2).
7603 static const unsigned FirstIntegralType = 4;
7604 static const unsigned LastIntegralType = 21;
7605 static const unsigned FirstPromotedIntegralType = 4,
7606 LastPromotedIntegralType = 12;
7607 static const unsigned FirstPromotedArithmeticType = 0,
7608 LastPromotedArithmeticType = 12;
7609 static const unsigned NumArithmeticTypes = 21;
7611 /// \brief Get the canonical type for a given arithmetic type index.
7612 CanQualType getArithmeticType(unsigned index) {
7613 assert(index < NumArithmeticTypes);
7614 static CanQualType ASTContext::* const
7615 ArithmeticTypes[NumArithmeticTypes] = {
7616 // Start of promoted types.
7617 &ASTContext::FloatTy,
7618 &ASTContext::DoubleTy,
7619 &ASTContext::LongDoubleTy,
7620 &ASTContext::Float128Ty,
7622 // Start of integral types.
7624 &ASTContext::LongTy,
7625 &ASTContext::LongLongTy,
7626 &ASTContext::Int128Ty,
7627 &ASTContext::UnsignedIntTy,
7628 &ASTContext::UnsignedLongTy,
7629 &ASTContext::UnsignedLongLongTy,
7630 &ASTContext::UnsignedInt128Ty,
7631 // End of promoted types.
7633 &ASTContext::BoolTy,
7634 &ASTContext::CharTy,
7635 &ASTContext::WCharTy,
7636 &ASTContext::Char16Ty,
7637 &ASTContext::Char32Ty,
7638 &ASTContext::SignedCharTy,
7639 &ASTContext::ShortTy,
7640 &ASTContext::UnsignedCharTy,
7641 &ASTContext::UnsignedShortTy,
7642 // End of integral types.
7643 // FIXME: What about complex? What about half?
7645 return S.Context.*ArithmeticTypes[index];
7648 /// \brief Gets the canonical type resulting from the usual arithemetic
7649 /// converions for the given arithmetic types.
7650 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7651 // Accelerator table for performing the usual arithmetic conversions.
7652 // The rules are basically:
7653 // - if either is floating-point, use the wider floating-point
7654 // - if same signedness, use the higher rank
7655 // - if same size, use unsigned of the higher rank
7656 // - use the larger type
7657 // These rules, together with the axiom that higher ranks are
7658 // never smaller, are sufficient to precompute all of these results
7659 // *except* when dealing with signed types of higher rank.
7660 // (we could precompute SLL x UI for all known platforms, but it's
7661 // better not to make any assumptions).
7662 // We assume that int128 has a higher rank than long long on all platforms.
7663 enum PromotedType : int8_t {
7665 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
7667 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7668 [LastPromotedArithmeticType] = {
7669 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7670 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7671 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7672 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7673 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7674 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7675 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7676 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7677 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7678 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7679 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7682 assert(L < LastPromotedArithmeticType);
7683 assert(R < LastPromotedArithmeticType);
7684 int Idx = ConversionsTable[L][R];
7686 // Fast path: the table gives us a concrete answer.
7687 if (Idx != Dep) return getArithmeticType(Idx);
7689 // Slow path: we need to compare widths.
7690 // An invariant is that the signed type has higher rank.
7691 CanQualType LT = getArithmeticType(L),
7692 RT = getArithmeticType(R);
7693 unsigned LW = S.Context.getIntWidth(LT),
7694 RW = S.Context.getIntWidth(RT);
7696 // If they're different widths, use the signed type.
7697 if (LW > RW) return LT;
7698 else if (LW < RW) return RT;
7700 // Otherwise, use the unsigned type of the signed type's rank.
7701 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7702 assert(L == SLL || R == SLL);
7703 return S.Context.UnsignedLongLongTy;
7706 /// \brief Helper method to factor out the common pattern of adding overloads
7707 /// for '++' and '--' builtin operators.
7708 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7711 QualType ParamTypes[2] = {
7712 S.Context.getLValueReferenceType(CandidateTy),
7716 // Non-volatile version.
7717 if (Args.size() == 1)
7718 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7720 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7722 // Use a heuristic to reduce number of builtin candidates in the set:
7723 // add volatile version only if there are conversions to a volatile type.
7726 S.Context.getLValueReferenceType(
7727 S.Context.getVolatileType(CandidateTy));
7728 if (Args.size() == 1)
7729 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7731 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7734 // Add restrict version only if there are conversions to a restrict type
7735 // and our candidate type is a non-restrict-qualified pointer.
7736 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7737 !CandidateTy.isRestrictQualified()) {
7739 = S.Context.getLValueReferenceType(
7740 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7741 if (Args.size() == 1)
7742 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7744 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7748 = S.Context.getLValueReferenceType(
7749 S.Context.getCVRQualifiedType(CandidateTy,
7750 (Qualifiers::Volatile |
7751 Qualifiers::Restrict)));
7752 if (Args.size() == 1)
7753 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7755 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7762 BuiltinOperatorOverloadBuilder(
7763 Sema &S, ArrayRef<Expr *> Args,
7764 Qualifiers VisibleTypeConversionsQuals,
7765 bool HasArithmeticOrEnumeralCandidateType,
7766 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7767 OverloadCandidateSet &CandidateSet)
7769 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7770 HasArithmeticOrEnumeralCandidateType(
7771 HasArithmeticOrEnumeralCandidateType),
7772 CandidateTypes(CandidateTypes),
7773 CandidateSet(CandidateSet) {
7774 // Validate some of our static helper constants in debug builds.
7775 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7776 "Invalid first promoted integral type");
7777 assert(getArithmeticType(LastPromotedIntegralType - 1)
7778 == S.Context.UnsignedInt128Ty &&
7779 "Invalid last promoted integral type");
7780 assert(getArithmeticType(FirstPromotedArithmeticType)
7781 == S.Context.FloatTy &&
7782 "Invalid first promoted arithmetic type");
7783 assert(getArithmeticType(LastPromotedArithmeticType - 1)
7784 == S.Context.UnsignedInt128Ty &&
7785 "Invalid last promoted arithmetic type");
7788 // C++ [over.built]p3:
7790 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7791 // is either volatile or empty, there exist candidate operator
7792 // functions of the form
7794 // VQ T& operator++(VQ T&);
7795 // T operator++(VQ T&, int);
7797 // C++ [over.built]p4:
7799 // For every pair (T, VQ), where T is an arithmetic type other
7800 // than bool, and VQ is either volatile or empty, there exist
7801 // candidate operator functions of the form
7803 // VQ T& operator--(VQ T&);
7804 // T operator--(VQ T&, int);
7805 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7806 if (!HasArithmeticOrEnumeralCandidateType)
7809 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7810 Arith < NumArithmeticTypes; ++Arith) {
7811 addPlusPlusMinusMinusStyleOverloads(
7812 getArithmeticType(Arith),
7813 VisibleTypeConversionsQuals.hasVolatile(),
7814 VisibleTypeConversionsQuals.hasRestrict());
7818 // C++ [over.built]p5:
7820 // For every pair (T, VQ), where T is a cv-qualified or
7821 // cv-unqualified object type, and VQ is either volatile or
7822 // empty, there exist candidate operator functions of the form
7824 // T*VQ& operator++(T*VQ&);
7825 // T*VQ& operator--(T*VQ&);
7826 // T* operator++(T*VQ&, int);
7827 // T* operator--(T*VQ&, int);
7828 void addPlusPlusMinusMinusPointerOverloads() {
7829 for (BuiltinCandidateTypeSet::iterator
7830 Ptr = CandidateTypes[0].pointer_begin(),
7831 PtrEnd = CandidateTypes[0].pointer_end();
7832 Ptr != PtrEnd; ++Ptr) {
7833 // Skip pointer types that aren't pointers to object types.
7834 if (!(*Ptr)->getPointeeType()->isObjectType())
7837 addPlusPlusMinusMinusStyleOverloads(*Ptr,
7838 (!(*Ptr).isVolatileQualified() &&
7839 VisibleTypeConversionsQuals.hasVolatile()),
7840 (!(*Ptr).isRestrictQualified() &&
7841 VisibleTypeConversionsQuals.hasRestrict()));
7845 // C++ [over.built]p6:
7846 // For every cv-qualified or cv-unqualified object type T, there
7847 // exist candidate operator functions of the form
7849 // T& operator*(T*);
7851 // C++ [over.built]p7:
7852 // For every function type T that does not have cv-qualifiers or a
7853 // ref-qualifier, there exist candidate operator functions of the form
7854 // T& operator*(T*);
7855 void addUnaryStarPointerOverloads() {
7856 for (BuiltinCandidateTypeSet::iterator
7857 Ptr = CandidateTypes[0].pointer_begin(),
7858 PtrEnd = CandidateTypes[0].pointer_end();
7859 Ptr != PtrEnd; ++Ptr) {
7860 QualType ParamTy = *Ptr;
7861 QualType PointeeTy = ParamTy->getPointeeType();
7862 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7865 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7866 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7869 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7870 &ParamTy, Args, CandidateSet);
7874 // C++ [over.built]p9:
7875 // For every promoted arithmetic type T, there exist candidate
7876 // operator functions of the form
7880 void addUnaryPlusOrMinusArithmeticOverloads() {
7881 if (!HasArithmeticOrEnumeralCandidateType)
7884 for (unsigned Arith = FirstPromotedArithmeticType;
7885 Arith < LastPromotedArithmeticType; ++Arith) {
7886 QualType ArithTy = getArithmeticType(Arith);
7887 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7890 // Extension: We also add these operators for vector types.
7891 for (BuiltinCandidateTypeSet::iterator
7892 Vec = CandidateTypes[0].vector_begin(),
7893 VecEnd = CandidateTypes[0].vector_end();
7894 Vec != VecEnd; ++Vec) {
7895 QualType VecTy = *Vec;
7896 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7900 // C++ [over.built]p8:
7901 // For every type T, there exist candidate operator functions of
7904 // T* operator+(T*);
7905 void addUnaryPlusPointerOverloads() {
7906 for (BuiltinCandidateTypeSet::iterator
7907 Ptr = CandidateTypes[0].pointer_begin(),
7908 PtrEnd = CandidateTypes[0].pointer_end();
7909 Ptr != PtrEnd; ++Ptr) {
7910 QualType ParamTy = *Ptr;
7911 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7915 // C++ [over.built]p10:
7916 // For every promoted integral type T, there exist candidate
7917 // operator functions of the form
7920 void addUnaryTildePromotedIntegralOverloads() {
7921 if (!HasArithmeticOrEnumeralCandidateType)
7924 for (unsigned Int = FirstPromotedIntegralType;
7925 Int < LastPromotedIntegralType; ++Int) {
7926 QualType IntTy = getArithmeticType(Int);
7927 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7930 // Extension: We also add this operator for vector types.
7931 for (BuiltinCandidateTypeSet::iterator
7932 Vec = CandidateTypes[0].vector_begin(),
7933 VecEnd = CandidateTypes[0].vector_end();
7934 Vec != VecEnd; ++Vec) {
7935 QualType VecTy = *Vec;
7936 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7940 // C++ [over.match.oper]p16:
7941 // For every pointer to member type T or type std::nullptr_t, there
7942 // exist candidate operator functions of the form
7944 // bool operator==(T,T);
7945 // bool operator!=(T,T);
7946 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7947 /// Set of (canonical) types that we've already handled.
7948 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7950 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7951 for (BuiltinCandidateTypeSet::iterator
7952 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7953 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7954 MemPtr != MemPtrEnd;
7956 // Don't add the same builtin candidate twice.
7957 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7960 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7961 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7964 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7965 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7966 if (AddedTypes.insert(NullPtrTy).second) {
7967 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7968 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7975 // C++ [over.built]p15:
7977 // For every T, where T is an enumeration type or a pointer type,
7978 // there exist candidate operator functions of the form
7980 // bool operator<(T, T);
7981 // bool operator>(T, T);
7982 // bool operator<=(T, T);
7983 // bool operator>=(T, T);
7984 // bool operator==(T, T);
7985 // bool operator!=(T, T);
7986 void addRelationalPointerOrEnumeralOverloads() {
7987 // C++ [over.match.oper]p3:
7988 // [...]the built-in candidates include all of the candidate operator
7989 // functions defined in 13.6 that, compared to the given operator, [...]
7990 // do not have the same parameter-type-list as any non-template non-member
7993 // Note that in practice, this only affects enumeration types because there
7994 // aren't any built-in candidates of record type, and a user-defined operator
7995 // must have an operand of record or enumeration type. Also, the only other
7996 // overloaded operator with enumeration arguments, operator=,
7997 // cannot be overloaded for enumeration types, so this is the only place
7998 // where we must suppress candidates like this.
7999 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8000 UserDefinedBinaryOperators;
8002 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8003 if (CandidateTypes[ArgIdx].enumeration_begin() !=
8004 CandidateTypes[ArgIdx].enumeration_end()) {
8005 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8006 CEnd = CandidateSet.end();
8008 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8011 if (C->Function->isFunctionTemplateSpecialization())
8014 QualType FirstParamType =
8015 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8016 QualType SecondParamType =
8017 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8019 // Skip if either parameter isn't of enumeral type.
8020 if (!FirstParamType->isEnumeralType() ||
8021 !SecondParamType->isEnumeralType())
8024 // Add this operator to the set of known user-defined operators.
8025 UserDefinedBinaryOperators.insert(
8026 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8027 S.Context.getCanonicalType(SecondParamType)));
8032 /// Set of (canonical) types that we've already handled.
8033 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8035 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8036 for (BuiltinCandidateTypeSet::iterator
8037 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8038 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8039 Ptr != PtrEnd; ++Ptr) {
8040 // Don't add the same builtin candidate twice.
8041 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8044 QualType ParamTypes[2] = { *Ptr, *Ptr };
8045 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
8047 for (BuiltinCandidateTypeSet::iterator
8048 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8049 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8050 Enum != EnumEnd; ++Enum) {
8051 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8053 // Don't add the same builtin candidate twice, or if a user defined
8054 // candidate exists.
8055 if (!AddedTypes.insert(CanonType).second ||
8056 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8060 QualType ParamTypes[2] = { *Enum, *Enum };
8061 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
8066 // C++ [over.built]p13:
8068 // For every cv-qualified or cv-unqualified object type T
8069 // there exist candidate operator functions of the form
8071 // T* operator+(T*, ptrdiff_t);
8072 // T& operator[](T*, ptrdiff_t); [BELOW]
8073 // T* operator-(T*, ptrdiff_t);
8074 // T* operator+(ptrdiff_t, T*);
8075 // T& operator[](ptrdiff_t, T*); [BELOW]
8077 // C++ [over.built]p14:
8079 // For every T, where T is a pointer to object type, there
8080 // exist candidate operator functions of the form
8082 // ptrdiff_t operator-(T, T);
8083 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8084 /// Set of (canonical) types that we've already handled.
8085 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8087 for (int Arg = 0; Arg < 2; ++Arg) {
8088 QualType AsymmetricParamTypes[2] = {
8089 S.Context.getPointerDiffType(),
8090 S.Context.getPointerDiffType(),
8092 for (BuiltinCandidateTypeSet::iterator
8093 Ptr = CandidateTypes[Arg].pointer_begin(),
8094 PtrEnd = CandidateTypes[Arg].pointer_end();
8095 Ptr != PtrEnd; ++Ptr) {
8096 QualType PointeeTy = (*Ptr)->getPointeeType();
8097 if (!PointeeTy->isObjectType())
8100 AsymmetricParamTypes[Arg] = *Ptr;
8101 if (Arg == 0 || Op == OO_Plus) {
8102 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8103 // T* operator+(ptrdiff_t, T*);
8104 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
8106 if (Op == OO_Minus) {
8107 // ptrdiff_t operator-(T, T);
8108 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8111 QualType ParamTypes[2] = { *Ptr, *Ptr };
8112 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
8113 Args, CandidateSet);
8119 // C++ [over.built]p12:
8121 // For every pair of promoted arithmetic types L and R, there
8122 // exist candidate operator functions of the form
8124 // LR operator*(L, R);
8125 // LR operator/(L, R);
8126 // LR operator+(L, R);
8127 // LR operator-(L, R);
8128 // bool operator<(L, R);
8129 // bool operator>(L, R);
8130 // bool operator<=(L, R);
8131 // bool operator>=(L, R);
8132 // bool operator==(L, R);
8133 // bool operator!=(L, R);
8135 // where LR is the result of the usual arithmetic conversions
8136 // between types L and R.
8138 // C++ [over.built]p24:
8140 // For every pair of promoted arithmetic types L and R, there exist
8141 // candidate operator functions of the form
8143 // LR operator?(bool, L, R);
8145 // where LR is the result of the usual arithmetic conversions
8146 // between types L and R.
8147 // Our candidates ignore the first parameter.
8148 void addGenericBinaryArithmeticOverloads(bool isComparison) {
8149 if (!HasArithmeticOrEnumeralCandidateType)
8152 for (unsigned Left = FirstPromotedArithmeticType;
8153 Left < LastPromotedArithmeticType; ++Left) {
8154 for (unsigned Right = FirstPromotedArithmeticType;
8155 Right < LastPromotedArithmeticType; ++Right) {
8156 QualType LandR[2] = { getArithmeticType(Left),
8157 getArithmeticType(Right) };
8159 isComparison ? S.Context.BoolTy
8160 : getUsualArithmeticConversions(Left, Right);
8161 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8165 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8166 // conditional operator for vector types.
8167 for (BuiltinCandidateTypeSet::iterator
8168 Vec1 = CandidateTypes[0].vector_begin(),
8169 Vec1End = CandidateTypes[0].vector_end();
8170 Vec1 != Vec1End; ++Vec1) {
8171 for (BuiltinCandidateTypeSet::iterator
8172 Vec2 = CandidateTypes[1].vector_begin(),
8173 Vec2End = CandidateTypes[1].vector_end();
8174 Vec2 != Vec2End; ++Vec2) {
8175 QualType LandR[2] = { *Vec1, *Vec2 };
8176 QualType Result = S.Context.BoolTy;
8177 if (!isComparison) {
8178 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
8184 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8189 // C++ [over.built]p17:
8191 // For every pair of promoted integral types L and R, there
8192 // exist candidate operator functions of the form
8194 // LR operator%(L, R);
8195 // LR operator&(L, R);
8196 // LR operator^(L, R);
8197 // LR operator|(L, R);
8198 // L operator<<(L, R);
8199 // L operator>>(L, R);
8201 // where LR is the result of the usual arithmetic conversions
8202 // between types L and R.
8203 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8204 if (!HasArithmeticOrEnumeralCandidateType)
8207 for (unsigned Left = FirstPromotedIntegralType;
8208 Left < LastPromotedIntegralType; ++Left) {
8209 for (unsigned Right = FirstPromotedIntegralType;
8210 Right < LastPromotedIntegralType; ++Right) {
8211 QualType LandR[2] = { getArithmeticType(Left),
8212 getArithmeticType(Right) };
8213 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
8215 : getUsualArithmeticConversions(Left, Right);
8216 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8221 // C++ [over.built]p20:
8223 // For every pair (T, VQ), where T is an enumeration or
8224 // pointer to member type and VQ is either volatile or
8225 // empty, there exist candidate operator functions of the form
8227 // VQ T& operator=(VQ T&, T);
8228 void addAssignmentMemberPointerOrEnumeralOverloads() {
8229 /// Set of (canonical) types that we've already handled.
8230 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8232 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8233 for (BuiltinCandidateTypeSet::iterator
8234 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8235 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8236 Enum != EnumEnd; ++Enum) {
8237 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8240 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8243 for (BuiltinCandidateTypeSet::iterator
8244 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8245 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8246 MemPtr != MemPtrEnd; ++MemPtr) {
8247 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8250 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8255 // C++ [over.built]p19:
8257 // For every pair (T, VQ), where T is any type and VQ is either
8258 // volatile or empty, there exist candidate operator functions
8261 // T*VQ& operator=(T*VQ&, T*);
8263 // C++ [over.built]p21:
8265 // For every pair (T, VQ), where T is a cv-qualified or
8266 // cv-unqualified object type and VQ is either volatile or
8267 // empty, there exist candidate operator functions of the form
8269 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8270 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8271 void addAssignmentPointerOverloads(bool isEqualOp) {
8272 /// Set of (canonical) types that we've already handled.
8273 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8275 for (BuiltinCandidateTypeSet::iterator
8276 Ptr = CandidateTypes[0].pointer_begin(),
8277 PtrEnd = CandidateTypes[0].pointer_end();
8278 Ptr != PtrEnd; ++Ptr) {
8279 // If this is operator=, keep track of the builtin candidates we added.
8281 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8282 else if (!(*Ptr)->getPointeeType()->isObjectType())
8285 // non-volatile version
8286 QualType ParamTypes[2] = {
8287 S.Context.getLValueReferenceType(*Ptr),
8288 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8290 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8291 /*IsAssigmentOperator=*/ isEqualOp);
8293 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8294 VisibleTypeConversionsQuals.hasVolatile();
8298 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8299 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8300 /*IsAssigmentOperator=*/isEqualOp);
8303 if (!(*Ptr).isRestrictQualified() &&
8304 VisibleTypeConversionsQuals.hasRestrict()) {
8307 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8308 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8309 /*IsAssigmentOperator=*/isEqualOp);
8312 // volatile restrict version
8314 = S.Context.getLValueReferenceType(
8315 S.Context.getCVRQualifiedType(*Ptr,
8316 (Qualifiers::Volatile |
8317 Qualifiers::Restrict)));
8318 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8319 /*IsAssigmentOperator=*/isEqualOp);
8325 for (BuiltinCandidateTypeSet::iterator
8326 Ptr = CandidateTypes[1].pointer_begin(),
8327 PtrEnd = CandidateTypes[1].pointer_end();
8328 Ptr != PtrEnd; ++Ptr) {
8329 // Make sure we don't add the same candidate twice.
8330 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8333 QualType ParamTypes[2] = {
8334 S.Context.getLValueReferenceType(*Ptr),
8338 // non-volatile version
8339 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8340 /*IsAssigmentOperator=*/true);
8342 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8343 VisibleTypeConversionsQuals.hasVolatile();
8347 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8348 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8349 /*IsAssigmentOperator=*/true);
8352 if (!(*Ptr).isRestrictQualified() &&
8353 VisibleTypeConversionsQuals.hasRestrict()) {
8356 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8357 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8358 /*IsAssigmentOperator=*/true);
8361 // volatile restrict version
8363 = S.Context.getLValueReferenceType(
8364 S.Context.getCVRQualifiedType(*Ptr,
8365 (Qualifiers::Volatile |
8366 Qualifiers::Restrict)));
8367 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8368 /*IsAssigmentOperator=*/true);
8375 // C++ [over.built]p18:
8377 // For every triple (L, VQ, R), where L is an arithmetic type,
8378 // VQ is either volatile or empty, and R is a promoted
8379 // arithmetic type, there exist candidate operator functions of
8382 // VQ L& operator=(VQ L&, R);
8383 // VQ L& operator*=(VQ L&, R);
8384 // VQ L& operator/=(VQ L&, R);
8385 // VQ L& operator+=(VQ L&, R);
8386 // VQ L& operator-=(VQ L&, R);
8387 void addAssignmentArithmeticOverloads(bool isEqualOp) {
8388 if (!HasArithmeticOrEnumeralCandidateType)
8391 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8392 for (unsigned Right = FirstPromotedArithmeticType;
8393 Right < LastPromotedArithmeticType; ++Right) {
8394 QualType ParamTypes[2];
8395 ParamTypes[1] = getArithmeticType(Right);
8397 // Add this built-in operator as a candidate (VQ is empty).
8399 S.Context.getLValueReferenceType(getArithmeticType(Left));
8400 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8401 /*IsAssigmentOperator=*/isEqualOp);
8403 // Add this built-in operator as a candidate (VQ is 'volatile').
8404 if (VisibleTypeConversionsQuals.hasVolatile()) {
8406 S.Context.getVolatileType(getArithmeticType(Left));
8407 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8408 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8409 /*IsAssigmentOperator=*/isEqualOp);
8414 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8415 for (BuiltinCandidateTypeSet::iterator
8416 Vec1 = CandidateTypes[0].vector_begin(),
8417 Vec1End = CandidateTypes[0].vector_end();
8418 Vec1 != Vec1End; ++Vec1) {
8419 for (BuiltinCandidateTypeSet::iterator
8420 Vec2 = CandidateTypes[1].vector_begin(),
8421 Vec2End = CandidateTypes[1].vector_end();
8422 Vec2 != Vec2End; ++Vec2) {
8423 QualType ParamTypes[2];
8424 ParamTypes[1] = *Vec2;
8425 // Add this built-in operator as a candidate (VQ is empty).
8426 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8427 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8428 /*IsAssigmentOperator=*/isEqualOp);
8430 // Add this built-in operator as a candidate (VQ is 'volatile').
8431 if (VisibleTypeConversionsQuals.hasVolatile()) {
8432 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8433 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8434 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8435 /*IsAssigmentOperator=*/isEqualOp);
8441 // C++ [over.built]p22:
8443 // For every triple (L, VQ, R), where L is an integral type, VQ
8444 // is either volatile or empty, and R is a promoted integral
8445 // type, there exist candidate operator functions of the form
8447 // VQ L& operator%=(VQ L&, R);
8448 // VQ L& operator<<=(VQ L&, R);
8449 // VQ L& operator>>=(VQ L&, R);
8450 // VQ L& operator&=(VQ L&, R);
8451 // VQ L& operator^=(VQ L&, R);
8452 // VQ L& operator|=(VQ L&, R);
8453 void addAssignmentIntegralOverloads() {
8454 if (!HasArithmeticOrEnumeralCandidateType)
8457 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8458 for (unsigned Right = FirstPromotedIntegralType;
8459 Right < LastPromotedIntegralType; ++Right) {
8460 QualType ParamTypes[2];
8461 ParamTypes[1] = getArithmeticType(Right);
8463 // Add this built-in operator as a candidate (VQ is empty).
8465 S.Context.getLValueReferenceType(getArithmeticType(Left));
8466 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8467 if (VisibleTypeConversionsQuals.hasVolatile()) {
8468 // Add this built-in operator as a candidate (VQ is 'volatile').
8469 ParamTypes[0] = getArithmeticType(Left);
8470 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8471 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8472 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8478 // C++ [over.operator]p23:
8480 // There also exist candidate operator functions of the form
8482 // bool operator!(bool);
8483 // bool operator&&(bool, bool);
8484 // bool operator||(bool, bool);
8485 void addExclaimOverload() {
8486 QualType ParamTy = S.Context.BoolTy;
8487 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8488 /*IsAssignmentOperator=*/false,
8489 /*NumContextualBoolArguments=*/1);
8491 void addAmpAmpOrPipePipeOverload() {
8492 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8493 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8494 /*IsAssignmentOperator=*/false,
8495 /*NumContextualBoolArguments=*/2);
8498 // C++ [over.built]p13:
8500 // For every cv-qualified or cv-unqualified object type T there
8501 // exist candidate operator functions of the form
8503 // T* operator+(T*, ptrdiff_t); [ABOVE]
8504 // T& operator[](T*, ptrdiff_t);
8505 // T* operator-(T*, ptrdiff_t); [ABOVE]
8506 // T* operator+(ptrdiff_t, T*); [ABOVE]
8507 // T& operator[](ptrdiff_t, T*);
8508 void addSubscriptOverloads() {
8509 for (BuiltinCandidateTypeSet::iterator
8510 Ptr = CandidateTypes[0].pointer_begin(),
8511 PtrEnd = CandidateTypes[0].pointer_end();
8512 Ptr != PtrEnd; ++Ptr) {
8513 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8514 QualType PointeeType = (*Ptr)->getPointeeType();
8515 if (!PointeeType->isObjectType())
8518 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8520 // T& operator[](T*, ptrdiff_t)
8521 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8524 for (BuiltinCandidateTypeSet::iterator
8525 Ptr = CandidateTypes[1].pointer_begin(),
8526 PtrEnd = CandidateTypes[1].pointer_end();
8527 Ptr != PtrEnd; ++Ptr) {
8528 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8529 QualType PointeeType = (*Ptr)->getPointeeType();
8530 if (!PointeeType->isObjectType())
8533 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8535 // T& operator[](ptrdiff_t, T*)
8536 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8540 // C++ [over.built]p11:
8541 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8542 // C1 is the same type as C2 or is a derived class of C2, T is an object
8543 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8544 // there exist candidate operator functions of the form
8546 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8548 // where CV12 is the union of CV1 and CV2.
8549 void addArrowStarOverloads() {
8550 for (BuiltinCandidateTypeSet::iterator
8551 Ptr = CandidateTypes[0].pointer_begin(),
8552 PtrEnd = CandidateTypes[0].pointer_end();
8553 Ptr != PtrEnd; ++Ptr) {
8554 QualType C1Ty = (*Ptr);
8556 QualifierCollector Q1;
8557 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8558 if (!isa<RecordType>(C1))
8560 // heuristic to reduce number of builtin candidates in the set.
8561 // Add volatile/restrict version only if there are conversions to a
8562 // volatile/restrict type.
8563 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8565 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8567 for (BuiltinCandidateTypeSet::iterator
8568 MemPtr = CandidateTypes[1].member_pointer_begin(),
8569 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8570 MemPtr != MemPtrEnd; ++MemPtr) {
8571 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8572 QualType C2 = QualType(mptr->getClass(), 0);
8573 C2 = C2.getUnqualifiedType();
8574 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8576 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8578 QualType T = mptr->getPointeeType();
8579 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8580 T.isVolatileQualified())
8582 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8583 T.isRestrictQualified())
8585 T = Q1.apply(S.Context, T);
8586 QualType ResultTy = S.Context.getLValueReferenceType(T);
8587 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8592 // Note that we don't consider the first argument, since it has been
8593 // contextually converted to bool long ago. The candidates below are
8594 // therefore added as binary.
8596 // C++ [over.built]p25:
8597 // For every type T, where T is a pointer, pointer-to-member, or scoped
8598 // enumeration type, there exist candidate operator functions of the form
8600 // T operator?(bool, T, T);
8602 void addConditionalOperatorOverloads() {
8603 /// Set of (canonical) types that we've already handled.
8604 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8606 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8607 for (BuiltinCandidateTypeSet::iterator
8608 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8609 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8610 Ptr != PtrEnd; ++Ptr) {
8611 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8614 QualType ParamTypes[2] = { *Ptr, *Ptr };
8615 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8618 for (BuiltinCandidateTypeSet::iterator
8619 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8620 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8621 MemPtr != MemPtrEnd; ++MemPtr) {
8622 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8625 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8626 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8629 if (S.getLangOpts().CPlusPlus11) {
8630 for (BuiltinCandidateTypeSet::iterator
8631 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8632 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8633 Enum != EnumEnd; ++Enum) {
8634 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8637 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8640 QualType ParamTypes[2] = { *Enum, *Enum };
8641 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8648 } // end anonymous namespace
8650 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8651 /// operator overloads to the candidate set (C++ [over.built]), based
8652 /// on the operator @p Op and the arguments given. For example, if the
8653 /// operator is a binary '+', this routine might add "int
8654 /// operator+(int, int)" to cover integer addition.
8655 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8656 SourceLocation OpLoc,
8657 ArrayRef<Expr *> Args,
8658 OverloadCandidateSet &CandidateSet) {
8659 // Find all of the types that the arguments can convert to, but only
8660 // if the operator we're looking at has built-in operator candidates
8661 // that make use of these types. Also record whether we encounter non-record
8662 // candidate types or either arithmetic or enumeral candidate types.
8663 Qualifiers VisibleTypeConversionsQuals;
8664 VisibleTypeConversionsQuals.addConst();
8665 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8666 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8668 bool HasNonRecordCandidateType = false;
8669 bool HasArithmeticOrEnumeralCandidateType = false;
8670 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8671 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8672 CandidateTypes.emplace_back(*this);
8673 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8676 (Op == OO_Exclaim ||
8679 VisibleTypeConversionsQuals);
8680 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8681 CandidateTypes[ArgIdx].hasNonRecordTypes();
8682 HasArithmeticOrEnumeralCandidateType =
8683 HasArithmeticOrEnumeralCandidateType ||
8684 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8687 // Exit early when no non-record types have been added to the candidate set
8688 // for any of the arguments to the operator.
8690 // We can't exit early for !, ||, or &&, since there we have always have
8691 // 'bool' overloads.
8692 if (!HasNonRecordCandidateType &&
8693 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8696 // Setup an object to manage the common state for building overloads.
8697 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8698 VisibleTypeConversionsQuals,
8699 HasArithmeticOrEnumeralCandidateType,
8700 CandidateTypes, CandidateSet);
8702 // Dispatch over the operation to add in only those overloads which apply.
8705 case NUM_OVERLOADED_OPERATORS:
8706 llvm_unreachable("Expected an overloaded operator");
8711 case OO_Array_Delete:
8714 "Special operators don't use AddBuiltinOperatorCandidates");
8719 // C++ [over.match.oper]p3:
8720 // -- For the operator ',', the unary operator '&', the
8721 // operator '->', or the operator 'co_await', the
8722 // built-in candidates set is empty.
8725 case OO_Plus: // '+' is either unary or binary
8726 if (Args.size() == 1)
8727 OpBuilder.addUnaryPlusPointerOverloads();
8730 case OO_Minus: // '-' is either unary or binary
8731 if (Args.size() == 1) {
8732 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8734 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8735 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8739 case OO_Star: // '*' is either unary or binary
8740 if (Args.size() == 1)
8741 OpBuilder.addUnaryStarPointerOverloads();
8743 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8747 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8752 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8753 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8757 case OO_ExclaimEqual:
8758 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8764 case OO_GreaterEqual:
8765 OpBuilder.addRelationalPointerOrEnumeralOverloads();
8766 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8773 case OO_GreaterGreater:
8774 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8777 case OO_Amp: // '&' is either unary or binary
8778 if (Args.size() == 1)
8779 // C++ [over.match.oper]p3:
8780 // -- For the operator ',', the unary operator '&', or the
8781 // operator '->', the built-in candidates set is empty.
8784 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8788 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8792 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8797 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8802 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8805 case OO_PercentEqual:
8806 case OO_LessLessEqual:
8807 case OO_GreaterGreaterEqual:
8811 OpBuilder.addAssignmentIntegralOverloads();
8815 OpBuilder.addExclaimOverload();
8820 OpBuilder.addAmpAmpOrPipePipeOverload();
8824 OpBuilder.addSubscriptOverloads();
8828 OpBuilder.addArrowStarOverloads();
8831 case OO_Conditional:
8832 OpBuilder.addConditionalOperatorOverloads();
8833 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8838 /// \brief Add function candidates found via argument-dependent lookup
8839 /// to the set of overloading candidates.
8841 /// This routine performs argument-dependent name lookup based on the
8842 /// given function name (which may also be an operator name) and adds
8843 /// all of the overload candidates found by ADL to the overload
8844 /// candidate set (C++ [basic.lookup.argdep]).
8846 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8848 ArrayRef<Expr *> Args,
8849 TemplateArgumentListInfo *ExplicitTemplateArgs,
8850 OverloadCandidateSet& CandidateSet,
8851 bool PartialOverloading) {
8854 // FIXME: This approach for uniquing ADL results (and removing
8855 // redundant candidates from the set) relies on pointer-equality,
8856 // which means we need to key off the canonical decl. However,
8857 // always going back to the canonical decl might not get us the
8858 // right set of default arguments. What default arguments are
8859 // we supposed to consider on ADL candidates, anyway?
8861 // FIXME: Pass in the explicit template arguments?
8862 ArgumentDependentLookup(Name, Loc, Args, Fns);
8864 // Erase all of the candidates we already knew about.
8865 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8866 CandEnd = CandidateSet.end();
8867 Cand != CandEnd; ++Cand)
8868 if (Cand->Function) {
8869 Fns.erase(Cand->Function);
8870 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8874 // For each of the ADL candidates we found, add it to the overload
8876 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8877 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8878 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8879 if (ExplicitTemplateArgs)
8882 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8883 PartialOverloading);
8885 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8886 FoundDecl, ExplicitTemplateArgs,
8887 Args, CandidateSet, PartialOverloading);
8892 enum class Comparison { Equal, Better, Worse };
8895 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8896 /// overload resolution.
8898 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8899 /// Cand1's first N enable_if attributes have precisely the same conditions as
8900 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8901 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8903 /// Note that you can have a pair of candidates such that Cand1's enable_if
8904 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8905 /// worse than Cand1's.
8906 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8907 const FunctionDecl *Cand2) {
8908 // Common case: One (or both) decls don't have enable_if attrs.
8909 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8910 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8911 if (!Cand1Attr || !Cand2Attr) {
8912 if (Cand1Attr == Cand2Attr)
8913 return Comparison::Equal;
8914 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8917 // FIXME: The next several lines are just
8918 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8919 // instead of reverse order which is how they're stored in the AST.
8920 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8921 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8923 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8924 // has fewer enable_if attributes than Cand2.
8925 if (Cand1Attrs.size() < Cand2Attrs.size())
8926 return Comparison::Worse;
8928 auto Cand1I = Cand1Attrs.begin();
8929 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8930 for (auto &Cand2A : Cand2Attrs) {
8934 auto &Cand1A = *Cand1I++;
8935 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8936 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8937 if (Cand1ID != Cand2ID)
8938 return Comparison::Worse;
8941 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8944 /// isBetterOverloadCandidate - Determines whether the first overload
8945 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8946 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8947 const OverloadCandidate &Cand2,
8949 bool UserDefinedConversion) {
8950 // Define viable functions to be better candidates than non-viable
8953 return Cand1.Viable;
8954 else if (!Cand1.Viable)
8957 // C++ [over.match.best]p1:
8959 // -- if F is a static member function, ICS1(F) is defined such
8960 // that ICS1(F) is neither better nor worse than ICS1(G) for
8961 // any function G, and, symmetrically, ICS1(G) is neither
8962 // better nor worse than ICS1(F).
8963 unsigned StartArg = 0;
8964 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8967 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8968 // We don't allow incompatible pointer conversions in C++.
8969 if (!S.getLangOpts().CPlusPlus)
8970 return ICS.isStandard() &&
8971 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8973 // The only ill-formed conversion we allow in C++ is the string literal to
8974 // char* conversion, which is only considered ill-formed after C++11.
8975 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8976 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8979 // Define functions that don't require ill-formed conversions for a given
8980 // argument to be better candidates than functions that do.
8981 unsigned NumArgs = Cand1.Conversions.size();
8982 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8983 bool HasBetterConversion = false;
8984 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8985 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8986 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8987 if (Cand1Bad != Cand2Bad) {
8990 HasBetterConversion = true;
8994 if (HasBetterConversion)
8997 // C++ [over.match.best]p1:
8998 // A viable function F1 is defined to be a better function than another
8999 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
9000 // conversion sequence than ICSi(F2), and then...
9001 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9002 switch (CompareImplicitConversionSequences(S, Loc,
9003 Cand1.Conversions[ArgIdx],
9004 Cand2.Conversions[ArgIdx])) {
9005 case ImplicitConversionSequence::Better:
9006 // Cand1 has a better conversion sequence.
9007 HasBetterConversion = true;
9010 case ImplicitConversionSequence::Worse:
9011 // Cand1 can't be better than Cand2.
9014 case ImplicitConversionSequence::Indistinguishable:
9020 // -- for some argument j, ICSj(F1) is a better conversion sequence than
9021 // ICSj(F2), or, if not that,
9022 if (HasBetterConversion)
9025 // -- the context is an initialization by user-defined conversion
9026 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9027 // from the return type of F1 to the destination type (i.e.,
9028 // the type of the entity being initialized) is a better
9029 // conversion sequence than the standard conversion sequence
9030 // from the return type of F2 to the destination type.
9031 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
9032 isa<CXXConversionDecl>(Cand1.Function) &&
9033 isa<CXXConversionDecl>(Cand2.Function)) {
9034 // First check whether we prefer one of the conversion functions over the
9035 // other. This only distinguishes the results in non-standard, extension
9036 // cases such as the conversion from a lambda closure type to a function
9037 // pointer or block.
9038 ImplicitConversionSequence::CompareKind Result =
9039 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9040 if (Result == ImplicitConversionSequence::Indistinguishable)
9041 Result = CompareStandardConversionSequences(S, Loc,
9042 Cand1.FinalConversion,
9043 Cand2.FinalConversion);
9045 if (Result != ImplicitConversionSequence::Indistinguishable)
9046 return Result == ImplicitConversionSequence::Better;
9048 // FIXME: Compare kind of reference binding if conversion functions
9049 // convert to a reference type used in direct reference binding, per
9050 // C++14 [over.match.best]p1 section 2 bullet 3.
9053 // -- F1 is a non-template function and F2 is a function template
9054 // specialization, or, if not that,
9055 bool Cand1IsSpecialization = Cand1.Function &&
9056 Cand1.Function->getPrimaryTemplate();
9057 bool Cand2IsSpecialization = Cand2.Function &&
9058 Cand2.Function->getPrimaryTemplate();
9059 if (Cand1IsSpecialization != Cand2IsSpecialization)
9060 return Cand2IsSpecialization;
9062 // -- F1 and F2 are function template specializations, and the function
9063 // template for F1 is more specialized than the template for F2
9064 // according to the partial ordering rules described in 14.5.5.2, or,
9066 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9067 if (FunctionTemplateDecl *BetterTemplate
9068 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9069 Cand2.Function->getPrimaryTemplate(),
9071 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9073 Cand1.ExplicitCallArguments,
9074 Cand2.ExplicitCallArguments))
9075 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9078 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9079 // A derived-class constructor beats an (inherited) base class constructor.
9080 bool Cand1IsInherited =
9081 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9082 bool Cand2IsInherited =
9083 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9084 if (Cand1IsInherited != Cand2IsInherited)
9085 return Cand2IsInherited;
9086 else if (Cand1IsInherited) {
9087 assert(Cand2IsInherited);
9088 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9089 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9090 if (Cand1Class->isDerivedFrom(Cand2Class))
9092 if (Cand2Class->isDerivedFrom(Cand1Class))
9094 // Inherited from sibling base classes: still ambiguous.
9097 // Check for enable_if value-based overload resolution.
9098 if (Cand1.Function && Cand2.Function) {
9099 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9100 if (Cmp != Comparison::Equal)
9101 return Cmp == Comparison::Better;
9104 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9105 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9106 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9107 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9110 bool HasPS1 = Cand1.Function != nullptr &&
9111 functionHasPassObjectSizeParams(Cand1.Function);
9112 bool HasPS2 = Cand2.Function != nullptr &&
9113 functionHasPassObjectSizeParams(Cand2.Function);
9114 return HasPS1 != HasPS2 && HasPS1;
9117 /// Determine whether two declarations are "equivalent" for the purposes of
9118 /// name lookup and overload resolution. This applies when the same internal/no
9119 /// linkage entity is defined by two modules (probably by textually including
9120 /// the same header). In such a case, we don't consider the declarations to
9121 /// declare the same entity, but we also don't want lookups with both
9122 /// declarations visible to be ambiguous in some cases (this happens when using
9123 /// a modularized libstdc++).
9124 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9125 const NamedDecl *B) {
9126 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9127 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9131 // The declarations must be declaring the same name as an internal linkage
9132 // entity in different modules.
9133 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9134 VB->getDeclContext()->getRedeclContext()) ||
9135 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9136 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9137 VA->isExternallyVisible() || VB->isExternallyVisible())
9140 // Check that the declarations appear to be equivalent.
9142 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9143 // For constants and functions, we should check the initializer or body is
9144 // the same. For non-constant variables, we shouldn't allow it at all.
9145 if (Context.hasSameType(VA->getType(), VB->getType()))
9148 // Enum constants within unnamed enumerations will have different types, but
9149 // may still be similar enough to be interchangeable for our purposes.
9150 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9151 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9152 // Only handle anonymous enums. If the enumerations were named and
9153 // equivalent, they would have been merged to the same type.
9154 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9155 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9156 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9157 !Context.hasSameType(EnumA->getIntegerType(),
9158 EnumB->getIntegerType()))
9160 // Allow this only if the value is the same for both enumerators.
9161 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9165 // Nothing else is sufficiently similar.
9169 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9170 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9171 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9173 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9174 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9175 << !M << (M ? M->getFullModuleName() : "");
9177 for (auto *E : Equiv) {
9178 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9179 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9180 << !M << (M ? M->getFullModuleName() : "");
9184 static bool isCandidateUnavailableDueToDiagnoseIf(const OverloadCandidate &OC) {
9185 ArrayRef<DiagnoseIfAttr *> Info = OC.getDiagnoseIfInfo();
9186 if (!Info.empty() && Info[0]->isError())
9189 assert(llvm::all_of(Info,
9190 [](const DiagnoseIfAttr *A) { return !A->isError(); }) &&
9191 "DiagnoseIf info shouldn't have mixed warnings and errors.");
9195 /// \brief Computes the best viable function (C++ 13.3.3)
9196 /// within an overload candidate set.
9198 /// \param Loc The location of the function name (or operator symbol) for
9199 /// which overload resolution occurs.
9201 /// \param Best If overload resolution was successful or found a deleted
9202 /// function, \p Best points to the candidate function found.
9204 /// \returns The result of overload resolution.
9206 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9208 bool UserDefinedConversion) {
9209 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9210 std::transform(begin(), end(), std::back_inserter(Candidates),
9211 [](OverloadCandidate &Cand) { return &Cand; });
9213 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9214 // are accepted by both clang and NVCC. However, during a particular
9215 // compilation mode only one call variant is viable. We need to
9216 // exclude non-viable overload candidates from consideration based
9217 // only on their host/device attributes. Specifically, if one
9218 // candidate call is WrongSide and the other is SameSide, we ignore
9219 // the WrongSide candidate.
9220 if (S.getLangOpts().CUDA) {
9221 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9222 bool ContainsSameSideCandidate =
9223 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9224 return Cand->Function &&
9225 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9228 if (ContainsSameSideCandidate) {
9229 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9230 return Cand->Function &&
9231 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9232 Sema::CFP_WrongSide;
9234 llvm::erase_if(Candidates, IsWrongSideCandidate);
9238 // Find the best viable function.
9240 for (auto *Cand : Candidates)
9242 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
9243 UserDefinedConversion))
9246 // If we didn't find any viable functions, abort.
9248 return OR_No_Viable_Function;
9250 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9252 // Make sure that this function is better than every other viable
9253 // function. If not, we have an ambiguity.
9254 for (auto *Cand : Candidates) {
9257 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
9258 UserDefinedConversion)) {
9259 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9261 EquivalentCands.push_back(Cand->Function);
9266 return OR_Ambiguous;
9270 // Best is the best viable function.
9271 if (Best->Function &&
9272 (Best->Function->isDeleted() ||
9273 S.isFunctionConsideredUnavailable(Best->Function) ||
9274 isCandidateUnavailableDueToDiagnoseIf(*Best)))
9277 if (!EquivalentCands.empty())
9278 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9281 for (const auto *W : Best->getDiagnoseIfInfo()) {
9282 assert(W->isWarning() && "Errors should've been caught earlier!");
9283 S.emitDiagnoseIfDiagnostic(Loc, W);
9291 enum OverloadCandidateKind {
9295 oc_function_template,
9297 oc_constructor_template,
9298 oc_implicit_default_constructor,
9299 oc_implicit_copy_constructor,
9300 oc_implicit_move_constructor,
9301 oc_implicit_copy_assignment,
9302 oc_implicit_move_assignment,
9303 oc_inherited_constructor,
9304 oc_inherited_constructor_template
9307 static OverloadCandidateKind
9308 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9309 std::string &Description) {
9310 bool isTemplate = false;
9312 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9314 Description = S.getTemplateArgumentBindingsText(
9315 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9318 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9319 if (!Ctor->isImplicit()) {
9320 if (isa<ConstructorUsingShadowDecl>(Found))
9321 return isTemplate ? oc_inherited_constructor_template
9322 : oc_inherited_constructor;
9324 return isTemplate ? oc_constructor_template : oc_constructor;
9327 if (Ctor->isDefaultConstructor())
9328 return oc_implicit_default_constructor;
9330 if (Ctor->isMoveConstructor())
9331 return oc_implicit_move_constructor;
9333 assert(Ctor->isCopyConstructor() &&
9334 "unexpected sort of implicit constructor");
9335 return oc_implicit_copy_constructor;
9338 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9339 // This actually gets spelled 'candidate function' for now, but
9340 // it doesn't hurt to split it out.
9341 if (!Meth->isImplicit())
9342 return isTemplate ? oc_method_template : oc_method;
9344 if (Meth->isMoveAssignmentOperator())
9345 return oc_implicit_move_assignment;
9347 if (Meth->isCopyAssignmentOperator())
9348 return oc_implicit_copy_assignment;
9350 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9354 return isTemplate ? oc_function_template : oc_function;
9357 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9358 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9360 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9361 S.Diag(FoundDecl->getLocation(),
9362 diag::note_ovl_candidate_inherited_constructor)
9363 << Shadow->getNominatedBaseClass();
9366 } // end anonymous namespace
9368 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9369 const FunctionDecl *FD) {
9370 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9372 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9380 /// \brief Returns true if we can take the address of the function.
9382 /// \param Complain - If true, we'll emit a diagnostic
9383 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9384 /// we in overload resolution?
9385 /// \param Loc - The location of the statement we're complaining about. Ignored
9386 /// if we're not complaining, or if we're in overload resolution.
9387 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9389 bool InOverloadResolution,
9390 SourceLocation Loc) {
9391 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9393 if (InOverloadResolution)
9394 S.Diag(FD->getLocStart(),
9395 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9397 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9402 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9403 return P->hasAttr<PassObjectSizeAttr>();
9405 if (I == FD->param_end())
9409 // Add one to ParamNo because it's user-facing
9410 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9411 if (InOverloadResolution)
9412 S.Diag(FD->getLocation(),
9413 diag::note_ovl_candidate_has_pass_object_size_params)
9416 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9422 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9423 const FunctionDecl *FD) {
9424 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9425 /*InOverloadResolution=*/true,
9426 /*Loc=*/SourceLocation());
9429 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9431 SourceLocation Loc) {
9432 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9433 /*InOverloadResolution=*/false,
9437 // Notes the location of an overload candidate.
9438 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9439 QualType DestType, bool TakingAddress) {
9440 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9444 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9445 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9446 << (unsigned) K << Fn << FnDesc;
9448 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9449 Diag(Fn->getLocation(), PD);
9450 MaybeEmitInheritedConstructorNote(*this, Found);
9453 // Notes the location of all overload candidates designated through
9455 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9456 bool TakingAddress) {
9457 assert(OverloadedExpr->getType() == Context.OverloadTy);
9459 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9460 OverloadExpr *OvlExpr = Ovl.Expression;
9462 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9463 IEnd = OvlExpr->decls_end();
9465 if (FunctionTemplateDecl *FunTmpl =
9466 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9467 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9469 } else if (FunctionDecl *Fun
9470 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9471 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9476 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
9477 /// "lead" diagnostic; it will be given two arguments, the source and
9478 /// target types of the conversion.
9479 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9481 SourceLocation CaretLoc,
9482 const PartialDiagnostic &PDiag) const {
9483 S.Diag(CaretLoc, PDiag)
9484 << Ambiguous.getFromType() << Ambiguous.getToType();
9485 // FIXME: The note limiting machinery is borrowed from
9486 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9487 // refactoring here.
9488 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9489 unsigned CandsShown = 0;
9490 AmbiguousConversionSequence::const_iterator I, E;
9491 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9492 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9495 S.NoteOverloadCandidate(I->first, I->second);
9498 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9501 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9502 unsigned I, bool TakingCandidateAddress) {
9503 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9504 assert(Conv.isBad());
9505 assert(Cand->Function && "for now, candidate must be a function");
9506 FunctionDecl *Fn = Cand->Function;
9508 // There's a conversion slot for the object argument if this is a
9509 // non-constructor method. Note that 'I' corresponds the
9510 // conversion-slot index.
9511 bool isObjectArgument = false;
9512 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9514 isObjectArgument = true;
9520 OverloadCandidateKind FnKind =
9521 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9523 Expr *FromExpr = Conv.Bad.FromExpr;
9524 QualType FromTy = Conv.Bad.getFromType();
9525 QualType ToTy = Conv.Bad.getToType();
9527 if (FromTy == S.Context.OverloadTy) {
9528 assert(FromExpr && "overload set argument came from implicit argument?");
9529 Expr *E = FromExpr->IgnoreParens();
9530 if (isa<UnaryOperator>(E))
9531 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9532 DeclarationName Name = cast<OverloadExpr>(E)->getName();
9534 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9535 << (unsigned) FnKind << FnDesc
9536 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9537 << ToTy << Name << I+1;
9538 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9542 // Do some hand-waving analysis to see if the non-viability is due
9543 // to a qualifier mismatch.
9544 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9545 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9546 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9547 CToTy = RT->getPointeeType();
9549 // TODO: detect and diagnose the full richness of const mismatches.
9550 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9551 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9552 CFromTy = FromPT->getPointeeType();
9553 CToTy = ToPT->getPointeeType();
9557 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9558 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9559 Qualifiers FromQs = CFromTy.getQualifiers();
9560 Qualifiers ToQs = CToTy.getQualifiers();
9562 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9563 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9564 << (unsigned) FnKind << FnDesc
9565 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9567 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9568 << (unsigned) isObjectArgument << I+1;
9569 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9573 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9574 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9575 << (unsigned) FnKind << FnDesc
9576 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9578 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9579 << (unsigned) isObjectArgument << I+1;
9580 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9584 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9585 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9586 << (unsigned) FnKind << FnDesc
9587 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9589 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9590 << (unsigned) isObjectArgument << I+1;
9591 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9595 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9596 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9597 << (unsigned) FnKind << FnDesc
9598 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9599 << FromTy << FromQs.hasUnaligned() << I+1;
9600 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9604 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9605 assert(CVR && "unexpected qualifiers mismatch");
9607 if (isObjectArgument) {
9608 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9609 << (unsigned) FnKind << FnDesc
9610 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9611 << FromTy << (CVR - 1);
9613 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9614 << (unsigned) FnKind << FnDesc
9615 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9616 << FromTy << (CVR - 1) << I+1;
9618 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9622 // Special diagnostic for failure to convert an initializer list, since
9623 // telling the user that it has type void is not useful.
9624 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9625 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9626 << (unsigned) FnKind << FnDesc
9627 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9628 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9629 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9633 // Diagnose references or pointers to incomplete types differently,
9634 // since it's far from impossible that the incompleteness triggered
9636 QualType TempFromTy = FromTy.getNonReferenceType();
9637 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9638 TempFromTy = PTy->getPointeeType();
9639 if (TempFromTy->isIncompleteType()) {
9640 // Emit the generic diagnostic and, optionally, add the hints to it.
9641 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9642 << (unsigned) FnKind << FnDesc
9643 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9644 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9645 << (unsigned) (Cand->Fix.Kind);
9647 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9651 // Diagnose base -> derived pointer conversions.
9652 unsigned BaseToDerivedConversion = 0;
9653 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9654 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9655 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9656 FromPtrTy->getPointeeType()) &&
9657 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9658 !ToPtrTy->getPointeeType()->isIncompleteType() &&
9659 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9660 FromPtrTy->getPointeeType()))
9661 BaseToDerivedConversion = 1;
9663 } else if (const ObjCObjectPointerType *FromPtrTy
9664 = FromTy->getAs<ObjCObjectPointerType>()) {
9665 if (const ObjCObjectPointerType *ToPtrTy
9666 = ToTy->getAs<ObjCObjectPointerType>())
9667 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9668 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9669 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9670 FromPtrTy->getPointeeType()) &&
9671 FromIface->isSuperClassOf(ToIface))
9672 BaseToDerivedConversion = 2;
9673 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9674 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9675 !FromTy->isIncompleteType() &&
9676 !ToRefTy->getPointeeType()->isIncompleteType() &&
9677 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9678 BaseToDerivedConversion = 3;
9679 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9680 ToTy.getNonReferenceType().getCanonicalType() ==
9681 FromTy.getNonReferenceType().getCanonicalType()) {
9682 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9683 << (unsigned) FnKind << FnDesc
9684 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9685 << (unsigned) isObjectArgument << I + 1;
9686 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9691 if (BaseToDerivedConversion) {
9692 S.Diag(Fn->getLocation(),
9693 diag::note_ovl_candidate_bad_base_to_derived_conv)
9694 << (unsigned) FnKind << FnDesc
9695 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9696 << (BaseToDerivedConversion - 1)
9697 << FromTy << ToTy << I+1;
9698 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9702 if (isa<ObjCObjectPointerType>(CFromTy) &&
9703 isa<PointerType>(CToTy)) {
9704 Qualifiers FromQs = CFromTy.getQualifiers();
9705 Qualifiers ToQs = CToTy.getQualifiers();
9706 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9707 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9708 << (unsigned) FnKind << FnDesc
9709 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9710 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9711 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9716 if (TakingCandidateAddress &&
9717 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9720 // Emit the generic diagnostic and, optionally, add the hints to it.
9721 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9722 FDiag << (unsigned) FnKind << FnDesc
9723 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9724 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9725 << (unsigned) (Cand->Fix.Kind);
9727 // If we can fix the conversion, suggest the FixIts.
9728 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9729 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9731 S.Diag(Fn->getLocation(), FDiag);
9733 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9736 /// Additional arity mismatch diagnosis specific to a function overload
9737 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9738 /// over a candidate in any candidate set.
9739 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9741 FunctionDecl *Fn = Cand->Function;
9742 unsigned MinParams = Fn->getMinRequiredArguments();
9744 // With invalid overloaded operators, it's possible that we think we
9745 // have an arity mismatch when in fact it looks like we have the
9746 // right number of arguments, because only overloaded operators have
9747 // the weird behavior of overloading member and non-member functions.
9748 // Just don't report anything.
9749 if (Fn->isInvalidDecl() &&
9750 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9753 if (NumArgs < MinParams) {
9754 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9755 (Cand->FailureKind == ovl_fail_bad_deduction &&
9756 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9758 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9759 (Cand->FailureKind == ovl_fail_bad_deduction &&
9760 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9766 /// General arity mismatch diagnosis over a candidate in a candidate set.
9767 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9768 unsigned NumFormalArgs) {
9769 assert(isa<FunctionDecl>(D) &&
9770 "The templated declaration should at least be a function"
9771 " when diagnosing bad template argument deduction due to too many"
9772 " or too few arguments");
9774 FunctionDecl *Fn = cast<FunctionDecl>(D);
9776 // TODO: treat calls to a missing default constructor as a special case
9777 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9778 unsigned MinParams = Fn->getMinRequiredArguments();
9780 // at least / at most / exactly
9781 unsigned mode, modeCount;
9782 if (NumFormalArgs < MinParams) {
9783 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9784 FnTy->isTemplateVariadic())
9785 mode = 0; // "at least"
9787 mode = 2; // "exactly"
9788 modeCount = MinParams;
9790 if (MinParams != FnTy->getNumParams())
9791 mode = 1; // "at most"
9793 mode = 2; // "exactly"
9794 modeCount = FnTy->getNumParams();
9797 std::string Description;
9798 OverloadCandidateKind FnKind =
9799 ClassifyOverloadCandidate(S, Found, Fn, Description);
9801 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9802 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9803 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9804 << mode << Fn->getParamDecl(0) << NumFormalArgs;
9806 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9807 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9808 << mode << modeCount << NumFormalArgs;
9809 MaybeEmitInheritedConstructorNote(S, Found);
9812 /// Arity mismatch diagnosis specific to a function overload candidate.
9813 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9814 unsigned NumFormalArgs) {
9815 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9816 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9819 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9820 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9822 llvm_unreachable("Unsupported: Getting the described template declaration"
9823 " for bad deduction diagnosis");
9826 /// Diagnose a failed template-argument deduction.
9827 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9828 DeductionFailureInfo &DeductionFailure,
9830 bool TakingCandidateAddress) {
9831 TemplateParameter Param = DeductionFailure.getTemplateParameter();
9833 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9834 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9835 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9836 switch (DeductionFailure.Result) {
9837 case Sema::TDK_Success:
9838 llvm_unreachable("TDK_success while diagnosing bad deduction");
9840 case Sema::TDK_Incomplete: {
9841 assert(ParamD && "no parameter found for incomplete deduction result");
9842 S.Diag(Templated->getLocation(),
9843 diag::note_ovl_candidate_incomplete_deduction)
9844 << ParamD->getDeclName();
9845 MaybeEmitInheritedConstructorNote(S, Found);
9849 case Sema::TDK_Underqualified: {
9850 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9851 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9853 QualType Param = DeductionFailure.getFirstArg()->getAsType();
9855 // Param will have been canonicalized, but it should just be a
9856 // qualified version of ParamD, so move the qualifiers to that.
9857 QualifierCollector Qs;
9859 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9860 assert(S.Context.hasSameType(Param, NonCanonParam));
9862 // Arg has also been canonicalized, but there's nothing we can do
9863 // about that. It also doesn't matter as much, because it won't
9864 // have any template parameters in it (because deduction isn't
9865 // done on dependent types).
9866 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9868 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9869 << ParamD->getDeclName() << Arg << NonCanonParam;
9870 MaybeEmitInheritedConstructorNote(S, Found);
9874 case Sema::TDK_Inconsistent: {
9875 assert(ParamD && "no parameter found for inconsistent deduction result");
9877 if (isa<TemplateTypeParmDecl>(ParamD))
9879 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9880 // Deduction might have failed because we deduced arguments of two
9881 // different types for a non-type template parameter.
9882 // FIXME: Use a different TDK value for this.
9884 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9886 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9887 if (!S.Context.hasSameType(T1, T2)) {
9888 S.Diag(Templated->getLocation(),
9889 diag::note_ovl_candidate_inconsistent_deduction_types)
9890 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9891 << *DeductionFailure.getSecondArg() << T2;
9892 MaybeEmitInheritedConstructorNote(S, Found);
9901 S.Diag(Templated->getLocation(),
9902 diag::note_ovl_candidate_inconsistent_deduction)
9903 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9904 << *DeductionFailure.getSecondArg();
9905 MaybeEmitInheritedConstructorNote(S, Found);
9909 case Sema::TDK_InvalidExplicitArguments:
9910 assert(ParamD && "no parameter found for invalid explicit arguments");
9911 if (ParamD->getDeclName())
9912 S.Diag(Templated->getLocation(),
9913 diag::note_ovl_candidate_explicit_arg_mismatch_named)
9914 << ParamD->getDeclName();
9917 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9918 index = TTP->getIndex();
9919 else if (NonTypeTemplateParmDecl *NTTP
9920 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9921 index = NTTP->getIndex();
9923 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9924 S.Diag(Templated->getLocation(),
9925 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9928 MaybeEmitInheritedConstructorNote(S, Found);
9931 case Sema::TDK_TooManyArguments:
9932 case Sema::TDK_TooFewArguments:
9933 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9936 case Sema::TDK_InstantiationDepth:
9937 S.Diag(Templated->getLocation(),
9938 diag::note_ovl_candidate_instantiation_depth);
9939 MaybeEmitInheritedConstructorNote(S, Found);
9942 case Sema::TDK_SubstitutionFailure: {
9943 // Format the template argument list into the argument string.
9944 SmallString<128> TemplateArgString;
9945 if (TemplateArgumentList *Args =
9946 DeductionFailure.getTemplateArgumentList()) {
9947 TemplateArgString = " ";
9948 TemplateArgString += S.getTemplateArgumentBindingsText(
9949 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9952 // If this candidate was disabled by enable_if, say so.
9953 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9954 if (PDiag && PDiag->second.getDiagID() ==
9955 diag::err_typename_nested_not_found_enable_if) {
9956 // FIXME: Use the source range of the condition, and the fully-qualified
9957 // name of the enable_if template. These are both present in PDiag.
9958 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9959 << "'enable_if'" << TemplateArgString;
9963 // Format the SFINAE diagnostic into the argument string.
9964 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9965 // formatted message in another diagnostic.
9966 SmallString<128> SFINAEArgString;
9969 SFINAEArgString = ": ";
9970 R = SourceRange(PDiag->first, PDiag->first);
9971 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9974 S.Diag(Templated->getLocation(),
9975 diag::note_ovl_candidate_substitution_failure)
9976 << TemplateArgString << SFINAEArgString << R;
9977 MaybeEmitInheritedConstructorNote(S, Found);
9981 case Sema::TDK_DeducedMismatch:
9982 case Sema::TDK_DeducedMismatchNested: {
9983 // Format the template argument list into the argument string.
9984 SmallString<128> TemplateArgString;
9985 if (TemplateArgumentList *Args =
9986 DeductionFailure.getTemplateArgumentList()) {
9987 TemplateArgString = " ";
9988 TemplateArgString += S.getTemplateArgumentBindingsText(
9989 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9992 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9993 << (*DeductionFailure.getCallArgIndex() + 1)
9994 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9995 << TemplateArgString
9996 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10000 case Sema::TDK_NonDeducedMismatch: {
10001 // FIXME: Provide a source location to indicate what we couldn't match.
10002 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10003 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10004 if (FirstTA.getKind() == TemplateArgument::Template &&
10005 SecondTA.getKind() == TemplateArgument::Template) {
10006 TemplateName FirstTN = FirstTA.getAsTemplate();
10007 TemplateName SecondTN = SecondTA.getAsTemplate();
10008 if (FirstTN.getKind() == TemplateName::Template &&
10009 SecondTN.getKind() == TemplateName::Template) {
10010 if (FirstTN.getAsTemplateDecl()->getName() ==
10011 SecondTN.getAsTemplateDecl()->getName()) {
10012 // FIXME: This fixes a bad diagnostic where both templates are named
10013 // the same. This particular case is a bit difficult since:
10014 // 1) It is passed as a string to the diagnostic printer.
10015 // 2) The diagnostic printer only attempts to find a better
10016 // name for types, not decls.
10017 // Ideally, this should folded into the diagnostic printer.
10018 S.Diag(Templated->getLocation(),
10019 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10020 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10026 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10027 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10030 // FIXME: For generic lambda parameters, check if the function is a lambda
10031 // call operator, and if so, emit a prettier and more informative
10032 // diagnostic that mentions 'auto' and lambda in addition to
10033 // (or instead of?) the canonical template type parameters.
10034 S.Diag(Templated->getLocation(),
10035 diag::note_ovl_candidate_non_deduced_mismatch)
10036 << FirstTA << SecondTA;
10039 // TODO: diagnose these individually, then kill off
10040 // note_ovl_candidate_bad_deduction, which is uselessly vague.
10041 case Sema::TDK_MiscellaneousDeductionFailure:
10042 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10043 MaybeEmitInheritedConstructorNote(S, Found);
10045 case Sema::TDK_CUDATargetMismatch:
10046 S.Diag(Templated->getLocation(),
10047 diag::note_cuda_ovl_candidate_target_mismatch);
10052 /// Diagnose a failed template-argument deduction, for function calls.
10053 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10055 bool TakingCandidateAddress) {
10056 unsigned TDK = Cand->DeductionFailure.Result;
10057 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10058 if (CheckArityMismatch(S, Cand, NumArgs))
10061 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10062 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10065 /// CUDA: diagnose an invalid call across targets.
10066 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10067 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10068 FunctionDecl *Callee = Cand->Function;
10070 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10071 CalleeTarget = S.IdentifyCUDATarget(Callee);
10073 std::string FnDesc;
10074 OverloadCandidateKind FnKind =
10075 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10077 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10078 << (unsigned)FnKind << CalleeTarget << CallerTarget;
10080 // This could be an implicit constructor for which we could not infer the
10081 // target due to a collsion. Diagnose that case.
10082 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10083 if (Meth != nullptr && Meth->isImplicit()) {
10084 CXXRecordDecl *ParentClass = Meth->getParent();
10085 Sema::CXXSpecialMember CSM;
10090 case oc_implicit_default_constructor:
10091 CSM = Sema::CXXDefaultConstructor;
10093 case oc_implicit_copy_constructor:
10094 CSM = Sema::CXXCopyConstructor;
10096 case oc_implicit_move_constructor:
10097 CSM = Sema::CXXMoveConstructor;
10099 case oc_implicit_copy_assignment:
10100 CSM = Sema::CXXCopyAssignment;
10102 case oc_implicit_move_assignment:
10103 CSM = Sema::CXXMoveAssignment;
10107 bool ConstRHS = false;
10108 if (Meth->getNumParams()) {
10109 if (const ReferenceType *RT =
10110 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10111 ConstRHS = RT->getPointeeType().isConstQualified();
10115 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10116 /* ConstRHS */ ConstRHS,
10117 /* Diagnose */ true);
10121 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10122 FunctionDecl *Callee = Cand->Function;
10123 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10125 S.Diag(Callee->getLocation(),
10126 diag::note_ovl_candidate_disabled_by_function_cond_attr)
10127 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10130 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10131 FunctionDecl *Callee = Cand->Function;
10133 S.Diag(Callee->getLocation(),
10134 diag::note_ovl_candidate_disabled_by_extension);
10137 /// Generates a 'note' diagnostic for an overload candidate. We've
10138 /// already generated a primary error at the call site.
10140 /// It really does need to be a single diagnostic with its caret
10141 /// pointed at the candidate declaration. Yes, this creates some
10142 /// major challenges of technical writing. Yes, this makes pointing
10143 /// out problems with specific arguments quite awkward. It's still
10144 /// better than generating twenty screens of text for every failed
10147 /// It would be great to be able to express per-candidate problems
10148 /// more richly for those diagnostic clients that cared, but we'd
10149 /// still have to be just as careful with the default diagnostics.
10150 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10152 bool TakingCandidateAddress) {
10153 FunctionDecl *Fn = Cand->Function;
10155 // Note deleted candidates, but only if they're viable.
10156 if (Cand->Viable) {
10157 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10158 std::string FnDesc;
10159 OverloadCandidateKind FnKind =
10160 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10162 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10163 << FnKind << FnDesc
10164 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10165 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10168 if (isCandidateUnavailableDueToDiagnoseIf(*Cand)) {
10169 auto *A = Cand->DiagnoseIfInfo.get<DiagnoseIfAttr *>();
10170 assert(A->isError() && "Non-error diagnose_if disables a candidate?");
10171 S.Diag(Cand->Function->getLocation(),
10172 diag::note_ovl_candidate_disabled_by_function_cond_attr)
10173 << A->getCond()->getSourceRange() << A->getMessage();
10177 // We don't really have anything else to say about viable candidates.
10178 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10182 switch (Cand->FailureKind) {
10183 case ovl_fail_too_many_arguments:
10184 case ovl_fail_too_few_arguments:
10185 return DiagnoseArityMismatch(S, Cand, NumArgs);
10187 case ovl_fail_bad_deduction:
10188 return DiagnoseBadDeduction(S, Cand, NumArgs,
10189 TakingCandidateAddress);
10191 case ovl_fail_illegal_constructor: {
10192 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10193 << (Fn->getPrimaryTemplate() ? 1 : 0);
10194 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10198 case ovl_fail_trivial_conversion:
10199 case ovl_fail_bad_final_conversion:
10200 case ovl_fail_final_conversion_not_exact:
10201 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10203 case ovl_fail_bad_conversion: {
10204 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10205 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10206 if (Cand->Conversions[I].isBad())
10207 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10209 // FIXME: this currently happens when we're called from SemaInit
10210 // when user-conversion overload fails. Figure out how to handle
10211 // those conditions and diagnose them well.
10212 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10215 case ovl_fail_bad_target:
10216 return DiagnoseBadTarget(S, Cand);
10218 case ovl_fail_enable_if:
10219 return DiagnoseFailedEnableIfAttr(S, Cand);
10221 case ovl_fail_ext_disabled:
10222 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10224 case ovl_fail_inhctor_slice:
10225 S.Diag(Fn->getLocation(),
10226 diag::note_ovl_candidate_inherited_constructor_slice);
10227 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10230 case ovl_fail_addr_not_available: {
10231 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10233 assert(!Available);
10239 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10240 // Desugar the type of the surrogate down to a function type,
10241 // retaining as many typedefs as possible while still showing
10242 // the function type (and, therefore, its parameter types).
10243 QualType FnType = Cand->Surrogate->getConversionType();
10244 bool isLValueReference = false;
10245 bool isRValueReference = false;
10246 bool isPointer = false;
10247 if (const LValueReferenceType *FnTypeRef =
10248 FnType->getAs<LValueReferenceType>()) {
10249 FnType = FnTypeRef->getPointeeType();
10250 isLValueReference = true;
10251 } else if (const RValueReferenceType *FnTypeRef =
10252 FnType->getAs<RValueReferenceType>()) {
10253 FnType = FnTypeRef->getPointeeType();
10254 isRValueReference = true;
10256 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10257 FnType = FnTypePtr->getPointeeType();
10260 // Desugar down to a function type.
10261 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10262 // Reconstruct the pointer/reference as appropriate.
10263 if (isPointer) FnType = S.Context.getPointerType(FnType);
10264 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10265 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10267 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10271 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10272 SourceLocation OpLoc,
10273 OverloadCandidate *Cand) {
10274 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10275 std::string TypeStr("operator");
10278 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
10279 if (Cand->Conversions.size() == 1) {
10281 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10284 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
10286 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10290 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10291 OverloadCandidate *Cand) {
10292 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10293 if (ICS.isBad()) break; // all meaningless after first invalid
10294 if (!ICS.isAmbiguous()) continue;
10296 ICS.DiagnoseAmbiguousConversion(
10297 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10301 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10302 if (Cand->Function)
10303 return Cand->Function->getLocation();
10304 if (Cand->IsSurrogate)
10305 return Cand->Surrogate->getLocation();
10306 return SourceLocation();
10309 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10310 switch ((Sema::TemplateDeductionResult)DFI.Result) {
10311 case Sema::TDK_Success:
10312 case Sema::TDK_NonDependentConversionFailure:
10313 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10315 case Sema::TDK_Invalid:
10316 case Sema::TDK_Incomplete:
10319 case Sema::TDK_Underqualified:
10320 case Sema::TDK_Inconsistent:
10323 case Sema::TDK_SubstitutionFailure:
10324 case Sema::TDK_DeducedMismatch:
10325 case Sema::TDK_DeducedMismatchNested:
10326 case Sema::TDK_NonDeducedMismatch:
10327 case Sema::TDK_MiscellaneousDeductionFailure:
10328 case Sema::TDK_CUDATargetMismatch:
10331 case Sema::TDK_InstantiationDepth:
10334 case Sema::TDK_InvalidExplicitArguments:
10337 case Sema::TDK_TooManyArguments:
10338 case Sema::TDK_TooFewArguments:
10341 llvm_unreachable("Unhandled deduction result");
10345 struct CompareOverloadCandidatesForDisplay {
10347 SourceLocation Loc;
10350 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
10351 : S(S), NumArgs(nArgs) {}
10353 bool operator()(const OverloadCandidate *L,
10354 const OverloadCandidate *R) {
10355 // Fast-path this check.
10356 if (L == R) return false;
10358 // Order first by viability.
10360 if (!R->Viable) return true;
10362 // TODO: introduce a tri-valued comparison for overload
10363 // candidates. Would be more worthwhile if we had a sort
10364 // that could exploit it.
10365 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10366 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
10367 } else if (R->Viable)
10370 assert(L->Viable == R->Viable);
10372 // Criteria by which we can sort non-viable candidates:
10374 // 1. Arity mismatches come after other candidates.
10375 if (L->FailureKind == ovl_fail_too_many_arguments ||
10376 L->FailureKind == ovl_fail_too_few_arguments) {
10377 if (R->FailureKind == ovl_fail_too_many_arguments ||
10378 R->FailureKind == ovl_fail_too_few_arguments) {
10379 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10380 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10381 if (LDist == RDist) {
10382 if (L->FailureKind == R->FailureKind)
10383 // Sort non-surrogates before surrogates.
10384 return !L->IsSurrogate && R->IsSurrogate;
10385 // Sort candidates requiring fewer parameters than there were
10386 // arguments given after candidates requiring more parameters
10387 // than there were arguments given.
10388 return L->FailureKind == ovl_fail_too_many_arguments;
10390 return LDist < RDist;
10394 if (R->FailureKind == ovl_fail_too_many_arguments ||
10395 R->FailureKind == ovl_fail_too_few_arguments)
10398 // 2. Bad conversions come first and are ordered by the number
10399 // of bad conversions and quality of good conversions.
10400 if (L->FailureKind == ovl_fail_bad_conversion) {
10401 if (R->FailureKind != ovl_fail_bad_conversion)
10404 // The conversion that can be fixed with a smaller number of changes,
10406 unsigned numLFixes = L->Fix.NumConversionsFixed;
10407 unsigned numRFixes = R->Fix.NumConversionsFixed;
10408 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10409 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10410 if (numLFixes != numRFixes) {
10411 return numLFixes < numRFixes;
10414 // If there's any ordering between the defined conversions...
10415 // FIXME: this might not be transitive.
10416 assert(L->Conversions.size() == R->Conversions.size());
10418 int leftBetter = 0;
10419 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10420 for (unsigned E = L->Conversions.size(); I != E; ++I) {
10421 switch (CompareImplicitConversionSequences(S, Loc,
10423 R->Conversions[I])) {
10424 case ImplicitConversionSequence::Better:
10428 case ImplicitConversionSequence::Worse:
10432 case ImplicitConversionSequence::Indistinguishable:
10436 if (leftBetter > 0) return true;
10437 if (leftBetter < 0) return false;
10439 } else if (R->FailureKind == ovl_fail_bad_conversion)
10442 if (L->FailureKind == ovl_fail_bad_deduction) {
10443 if (R->FailureKind != ovl_fail_bad_deduction)
10446 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10447 return RankDeductionFailure(L->DeductionFailure)
10448 < RankDeductionFailure(R->DeductionFailure);
10449 } else if (R->FailureKind == ovl_fail_bad_deduction)
10455 // Sort everything else by location.
10456 SourceLocation LLoc = GetLocationForCandidate(L);
10457 SourceLocation RLoc = GetLocationForCandidate(R);
10459 // Put candidates without locations (e.g. builtins) at the end.
10460 if (LLoc.isInvalid()) return false;
10461 if (RLoc.isInvalid()) return true;
10463 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10468 /// CompleteNonViableCandidate - Normally, overload resolution only
10469 /// computes up to the first bad conversion. Produces the FixIt set if
10471 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10472 ArrayRef<Expr *> Args) {
10473 assert(!Cand->Viable);
10475 // Don't do anything on failures other than bad conversion.
10476 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10478 // We only want the FixIts if all the arguments can be corrected.
10479 bool Unfixable = false;
10480 // Use a implicit copy initialization to check conversion fixes.
10481 Cand->Fix.setConversionChecker(TryCopyInitialization);
10483 // Attempt to fix the bad conversion.
10484 unsigned ConvCount = Cand->Conversions.size();
10485 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10487 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10488 if (Cand->Conversions[ConvIdx].isInitialized() &&
10489 Cand->Conversions[ConvIdx].isBad()) {
10490 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10495 // FIXME: this should probably be preserved from the overload
10496 // operation somehow.
10497 bool SuppressUserConversions = false;
10499 unsigned ConvIdx = 0;
10500 ArrayRef<QualType> ParamTypes;
10502 if (Cand->IsSurrogate) {
10504 = Cand->Surrogate->getConversionType().getNonReferenceType();
10505 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10506 ConvType = ConvPtrType->getPointeeType();
10507 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10508 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10510 } else if (Cand->Function) {
10512 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10513 if (isa<CXXMethodDecl>(Cand->Function) &&
10514 !isa<CXXConstructorDecl>(Cand->Function)) {
10515 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10519 // Builtin operator.
10520 assert(ConvCount <= 3);
10521 ParamTypes = Cand->BuiltinTypes.ParamTypes;
10524 // Fill in the rest of the conversions.
10525 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10526 if (Cand->Conversions[ConvIdx].isInitialized()) {
10527 // We've already checked this conversion.
10528 } else if (ArgIdx < ParamTypes.size()) {
10529 if (ParamTypes[ArgIdx]->isDependentType())
10530 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10531 Args[ArgIdx]->getType());
10533 Cand->Conversions[ConvIdx] =
10534 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10535 SuppressUserConversions,
10536 /*InOverloadResolution=*/true,
10537 /*AllowObjCWritebackConversion=*/
10538 S.getLangOpts().ObjCAutoRefCount);
10539 // Store the FixIt in the candidate if it exists.
10540 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10541 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10544 Cand->Conversions[ConvIdx].setEllipsis();
10548 /// PrintOverloadCandidates - When overload resolution fails, prints
10549 /// diagnostic messages containing the candidates in the candidate
10551 void OverloadCandidateSet::NoteCandidates(
10552 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10553 StringRef Opc, SourceLocation OpLoc,
10554 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10555 // Sort the candidates by viability and position. Sorting directly would
10556 // be prohibitive, so we make a set of pointers and sort those.
10557 SmallVector<OverloadCandidate*, 32> Cands;
10558 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10559 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10560 if (!Filter(*Cand))
10563 Cands.push_back(Cand);
10564 else if (OCD == OCD_AllCandidates) {
10565 CompleteNonViableCandidate(S, Cand, Args);
10566 if (Cand->Function || Cand->IsSurrogate)
10567 Cands.push_back(Cand);
10568 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10569 // want to list every possible builtin candidate.
10573 std::sort(Cands.begin(), Cands.end(),
10574 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10576 bool ReportedAmbiguousConversions = false;
10578 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10579 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10580 unsigned CandsShown = 0;
10581 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10582 OverloadCandidate *Cand = *I;
10584 // Set an arbitrary limit on the number of candidate functions we'll spam
10585 // the user with. FIXME: This limit should depend on details of the
10587 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10592 if (Cand->Function)
10593 NoteFunctionCandidate(S, Cand, Args.size(),
10594 /*TakingCandidateAddress=*/false);
10595 else if (Cand->IsSurrogate)
10596 NoteSurrogateCandidate(S, Cand);
10598 assert(Cand->Viable &&
10599 "Non-viable built-in candidates are not added to Cands.");
10600 // Generally we only see ambiguities including viable builtin
10601 // operators if overload resolution got screwed up by an
10602 // ambiguous user-defined conversion.
10604 // FIXME: It's quite possible for different conversions to see
10605 // different ambiguities, though.
10606 if (!ReportedAmbiguousConversions) {
10607 NoteAmbiguousUserConversions(S, OpLoc, Cand);
10608 ReportedAmbiguousConversions = true;
10611 // If this is a viable builtin, print it.
10612 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10617 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10620 static SourceLocation
10621 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10622 return Cand->Specialization ? Cand->Specialization->getLocation()
10623 : SourceLocation();
10627 struct CompareTemplateSpecCandidatesForDisplay {
10629 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10631 bool operator()(const TemplateSpecCandidate *L,
10632 const TemplateSpecCandidate *R) {
10633 // Fast-path this check.
10637 // Assuming that both candidates are not matches...
10639 // Sort by the ranking of deduction failures.
10640 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10641 return RankDeductionFailure(L->DeductionFailure) <
10642 RankDeductionFailure(R->DeductionFailure);
10644 // Sort everything else by location.
10645 SourceLocation LLoc = GetLocationForCandidate(L);
10646 SourceLocation RLoc = GetLocationForCandidate(R);
10648 // Put candidates without locations (e.g. builtins) at the end.
10649 if (LLoc.isInvalid())
10651 if (RLoc.isInvalid())
10654 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10659 /// Diagnose a template argument deduction failure.
10660 /// We are treating these failures as overload failures due to bad
10662 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10663 bool ForTakingAddress) {
10664 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10665 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10668 void TemplateSpecCandidateSet::destroyCandidates() {
10669 for (iterator i = begin(), e = end(); i != e; ++i) {
10670 i->DeductionFailure.Destroy();
10674 void TemplateSpecCandidateSet::clear() {
10675 destroyCandidates();
10676 Candidates.clear();
10679 /// NoteCandidates - When no template specialization match is found, prints
10680 /// diagnostic messages containing the non-matching specializations that form
10681 /// the candidate set.
10682 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10683 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10684 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10685 // Sort the candidates by position (assuming no candidate is a match).
10686 // Sorting directly would be prohibitive, so we make a set of pointers
10688 SmallVector<TemplateSpecCandidate *, 32> Cands;
10689 Cands.reserve(size());
10690 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10691 if (Cand->Specialization)
10692 Cands.push_back(Cand);
10693 // Otherwise, this is a non-matching builtin candidate. We do not,
10694 // in general, want to list every possible builtin candidate.
10697 std::sort(Cands.begin(), Cands.end(),
10698 CompareTemplateSpecCandidatesForDisplay(S));
10700 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10701 // for generalization purposes (?).
10702 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10704 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10705 unsigned CandsShown = 0;
10706 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10707 TemplateSpecCandidate *Cand = *I;
10709 // Set an arbitrary limit on the number of candidates we'll spam
10710 // the user with. FIXME: This limit should depend on details of the
10712 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10716 assert(Cand->Specialization &&
10717 "Non-matching built-in candidates are not added to Cands.");
10718 Cand->NoteDeductionFailure(S, ForTakingAddress);
10722 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10725 // [PossiblyAFunctionType] --> [Return]
10726 // NonFunctionType --> NonFunctionType
10728 // R (*)(A) --> R (A)
10729 // R (&)(A) --> R (A)
10730 // R (S::*)(A) --> R (A)
10731 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10732 QualType Ret = PossiblyAFunctionType;
10733 if (const PointerType *ToTypePtr =
10734 PossiblyAFunctionType->getAs<PointerType>())
10735 Ret = ToTypePtr->getPointeeType();
10736 else if (const ReferenceType *ToTypeRef =
10737 PossiblyAFunctionType->getAs<ReferenceType>())
10738 Ret = ToTypeRef->getPointeeType();
10739 else if (const MemberPointerType *MemTypePtr =
10740 PossiblyAFunctionType->getAs<MemberPointerType>())
10741 Ret = MemTypePtr->getPointeeType();
10743 Context.getCanonicalType(Ret).getUnqualifiedType();
10747 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10748 bool Complain = true) {
10749 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10750 S.DeduceReturnType(FD, Loc, Complain))
10753 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10754 if (S.getLangOpts().CPlusPlus1z &&
10755 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10756 !S.ResolveExceptionSpec(Loc, FPT))
10763 // A helper class to help with address of function resolution
10764 // - allows us to avoid passing around all those ugly parameters
10765 class AddressOfFunctionResolver {
10768 const QualType& TargetType;
10769 QualType TargetFunctionType; // Extracted function type from target type
10772 //DeclAccessPair& ResultFunctionAccessPair;
10773 ASTContext& Context;
10775 bool TargetTypeIsNonStaticMemberFunction;
10776 bool FoundNonTemplateFunction;
10777 bool StaticMemberFunctionFromBoundPointer;
10778 bool HasComplained;
10780 OverloadExpr::FindResult OvlExprInfo;
10781 OverloadExpr *OvlExpr;
10782 TemplateArgumentListInfo OvlExplicitTemplateArgs;
10783 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10784 TemplateSpecCandidateSet FailedCandidates;
10787 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10788 const QualType &TargetType, bool Complain)
10789 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10790 Complain(Complain), Context(S.getASTContext()),
10791 TargetTypeIsNonStaticMemberFunction(
10792 !!TargetType->getAs<MemberPointerType>()),
10793 FoundNonTemplateFunction(false),
10794 StaticMemberFunctionFromBoundPointer(false),
10795 HasComplained(false),
10796 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10797 OvlExpr(OvlExprInfo.Expression),
10798 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10799 ExtractUnqualifiedFunctionTypeFromTargetType();
10801 if (TargetFunctionType->isFunctionType()) {
10802 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10803 if (!UME->isImplicitAccess() &&
10804 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10805 StaticMemberFunctionFromBoundPointer = true;
10806 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10807 DeclAccessPair dap;
10808 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10809 OvlExpr, false, &dap)) {
10810 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10811 if (!Method->isStatic()) {
10812 // If the target type is a non-function type and the function found
10813 // is a non-static member function, pretend as if that was the
10814 // target, it's the only possible type to end up with.
10815 TargetTypeIsNonStaticMemberFunction = true;
10817 // And skip adding the function if its not in the proper form.
10818 // We'll diagnose this due to an empty set of functions.
10819 if (!OvlExprInfo.HasFormOfMemberPointer)
10823 Matches.push_back(std::make_pair(dap, Fn));
10828 if (OvlExpr->hasExplicitTemplateArgs())
10829 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10831 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10832 // C++ [over.over]p4:
10833 // If more than one function is selected, [...]
10834 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10835 if (FoundNonTemplateFunction)
10836 EliminateAllTemplateMatches();
10838 EliminateAllExceptMostSpecializedTemplate();
10842 if (S.getLangOpts().CUDA && Matches.size() > 1)
10843 EliminateSuboptimalCudaMatches();
10846 bool hasComplained() const { return HasComplained; }
10849 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10851 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10852 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10855 /// \return true if A is considered a better overload candidate for the
10856 /// desired type than B.
10857 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10858 // If A doesn't have exactly the correct type, we don't want to classify it
10859 // as "better" than anything else. This way, the user is required to
10860 // disambiguate for us if there are multiple candidates and no exact match.
10861 return candidateHasExactlyCorrectType(A) &&
10862 (!candidateHasExactlyCorrectType(B) ||
10863 compareEnableIfAttrs(S, A, B) == Comparison::Better);
10866 /// \return true if we were able to eliminate all but one overload candidate,
10867 /// false otherwise.
10868 bool eliminiateSuboptimalOverloadCandidates() {
10869 // Same algorithm as overload resolution -- one pass to pick the "best",
10870 // another pass to be sure that nothing is better than the best.
10871 auto Best = Matches.begin();
10872 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10873 if (isBetterCandidate(I->second, Best->second))
10876 const FunctionDecl *BestFn = Best->second;
10877 auto IsBestOrInferiorToBest = [this, BestFn](
10878 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10879 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10882 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10883 // option, so we can potentially give the user a better error
10884 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10886 Matches[0] = *Best;
10891 bool isTargetTypeAFunction() const {
10892 return TargetFunctionType->isFunctionType();
10895 // [ToType] [Return]
10897 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10898 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10899 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10900 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10901 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10904 // return true if any matching specializations were found
10905 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10906 const DeclAccessPair& CurAccessFunPair) {
10907 if (CXXMethodDecl *Method
10908 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10909 // Skip non-static function templates when converting to pointer, and
10910 // static when converting to member pointer.
10911 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10914 else if (TargetTypeIsNonStaticMemberFunction)
10917 // C++ [over.over]p2:
10918 // If the name is a function template, template argument deduction is
10919 // done (14.8.2.2), and if the argument deduction succeeds, the
10920 // resulting template argument list is used to generate a single
10921 // function template specialization, which is added to the set of
10922 // overloaded functions considered.
10923 FunctionDecl *Specialization = nullptr;
10924 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10925 if (Sema::TemplateDeductionResult Result
10926 = S.DeduceTemplateArguments(FunctionTemplate,
10927 &OvlExplicitTemplateArgs,
10928 TargetFunctionType, Specialization,
10929 Info, /*IsAddressOfFunction*/true)) {
10930 // Make a note of the failed deduction for diagnostics.
10931 FailedCandidates.addCandidate()
10932 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10933 MakeDeductionFailureInfo(Context, Result, Info));
10937 // Template argument deduction ensures that we have an exact match or
10938 // compatible pointer-to-function arguments that would be adjusted by ICS.
10939 // This function template specicalization works.
10940 assert(S.isSameOrCompatibleFunctionType(
10941 Context.getCanonicalType(Specialization->getType()),
10942 Context.getCanonicalType(TargetFunctionType)));
10944 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10947 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10951 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10952 const DeclAccessPair& CurAccessFunPair) {
10953 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10954 // Skip non-static functions when converting to pointer, and static
10955 // when converting to member pointer.
10956 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10959 else if (TargetTypeIsNonStaticMemberFunction)
10962 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10963 if (S.getLangOpts().CUDA)
10964 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10965 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10968 // If any candidate has a placeholder return type, trigger its deduction
10970 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10972 HasComplained |= Complain;
10976 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10979 // If we're in C, we need to support types that aren't exactly identical.
10980 if (!S.getLangOpts().CPlusPlus ||
10981 candidateHasExactlyCorrectType(FunDecl)) {
10982 Matches.push_back(std::make_pair(
10983 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10984 FoundNonTemplateFunction = true;
10992 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10995 // If the overload expression doesn't have the form of a pointer to
10996 // member, don't try to convert it to a pointer-to-member type.
10997 if (IsInvalidFormOfPointerToMemberFunction())
11000 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11001 E = OvlExpr->decls_end();
11003 // Look through any using declarations to find the underlying function.
11004 NamedDecl *Fn = (*I)->getUnderlyingDecl();
11006 // C++ [over.over]p3:
11007 // Non-member functions and static member functions match
11008 // targets of type "pointer-to-function" or "reference-to-function."
11009 // Nonstatic member functions match targets of
11010 // type "pointer-to-member-function."
11011 // Note that according to DR 247, the containing class does not matter.
11012 if (FunctionTemplateDecl *FunctionTemplate
11013 = dyn_cast<FunctionTemplateDecl>(Fn)) {
11014 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11017 // If we have explicit template arguments supplied, skip non-templates.
11018 else if (!OvlExpr->hasExplicitTemplateArgs() &&
11019 AddMatchingNonTemplateFunction(Fn, I.getPair()))
11022 assert(Ret || Matches.empty());
11026 void EliminateAllExceptMostSpecializedTemplate() {
11027 // [...] and any given function template specialization F1 is
11028 // eliminated if the set contains a second function template
11029 // specialization whose function template is more specialized
11030 // than the function template of F1 according to the partial
11031 // ordering rules of 14.5.5.2.
11033 // The algorithm specified above is quadratic. We instead use a
11034 // two-pass algorithm (similar to the one used to identify the
11035 // best viable function in an overload set) that identifies the
11036 // best function template (if it exists).
11038 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11039 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11040 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11042 // TODO: It looks like FailedCandidates does not serve much purpose
11043 // here, since the no_viable diagnostic has index 0.
11044 UnresolvedSetIterator Result = S.getMostSpecialized(
11045 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11046 SourceExpr->getLocStart(), S.PDiag(),
11047 S.PDiag(diag::err_addr_ovl_ambiguous)
11048 << Matches[0].second->getDeclName(),
11049 S.PDiag(diag::note_ovl_candidate)
11050 << (unsigned)oc_function_template,
11051 Complain, TargetFunctionType);
11053 if (Result != MatchesCopy.end()) {
11054 // Make it the first and only element
11055 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11056 Matches[0].second = cast<FunctionDecl>(*Result);
11059 HasComplained |= Complain;
11062 void EliminateAllTemplateMatches() {
11063 // [...] any function template specializations in the set are
11064 // eliminated if the set also contains a non-template function, [...]
11065 for (unsigned I = 0, N = Matches.size(); I != N; ) {
11066 if (Matches[I].second->getPrimaryTemplate() == nullptr)
11069 Matches[I] = Matches[--N];
11075 void EliminateSuboptimalCudaMatches() {
11076 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11080 void ComplainNoMatchesFound() const {
11081 assert(Matches.empty());
11082 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11083 << OvlExpr->getName() << TargetFunctionType
11084 << OvlExpr->getSourceRange();
11085 if (FailedCandidates.empty())
11086 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11087 /*TakingAddress=*/true);
11089 // We have some deduction failure messages. Use them to diagnose
11090 // the function templates, and diagnose the non-template candidates
11092 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11093 IEnd = OvlExpr->decls_end();
11095 if (FunctionDecl *Fun =
11096 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11097 if (!functionHasPassObjectSizeParams(Fun))
11098 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11099 /*TakingAddress=*/true);
11100 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11104 bool IsInvalidFormOfPointerToMemberFunction() const {
11105 return TargetTypeIsNonStaticMemberFunction &&
11106 !OvlExprInfo.HasFormOfMemberPointer;
11109 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11110 // TODO: Should we condition this on whether any functions might
11111 // have matched, or is it more appropriate to do that in callers?
11112 // TODO: a fixit wouldn't hurt.
11113 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11114 << TargetType << OvlExpr->getSourceRange();
11117 bool IsStaticMemberFunctionFromBoundPointer() const {
11118 return StaticMemberFunctionFromBoundPointer;
11121 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11122 S.Diag(OvlExpr->getLocStart(),
11123 diag::err_invalid_form_pointer_member_function)
11124 << OvlExpr->getSourceRange();
11127 void ComplainOfInvalidConversion() const {
11128 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11129 << OvlExpr->getName() << TargetType;
11132 void ComplainMultipleMatchesFound() const {
11133 assert(Matches.size() > 1);
11134 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11135 << OvlExpr->getName()
11136 << OvlExpr->getSourceRange();
11137 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11138 /*TakingAddress=*/true);
11141 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11143 int getNumMatches() const { return Matches.size(); }
11145 FunctionDecl* getMatchingFunctionDecl() const {
11146 if (Matches.size() != 1) return nullptr;
11147 return Matches[0].second;
11150 const DeclAccessPair* getMatchingFunctionAccessPair() const {
11151 if (Matches.size() != 1) return nullptr;
11152 return &Matches[0].first;
11157 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11158 /// an overloaded function (C++ [over.over]), where @p From is an
11159 /// expression with overloaded function type and @p ToType is the type
11160 /// we're trying to resolve to. For example:
11166 /// int (*pfd)(double) = f; // selects f(double)
11169 /// This routine returns the resulting FunctionDecl if it could be
11170 /// resolved, and NULL otherwise. When @p Complain is true, this
11171 /// routine will emit diagnostics if there is an error.
11173 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11174 QualType TargetType,
11176 DeclAccessPair &FoundResult,
11177 bool *pHadMultipleCandidates) {
11178 assert(AddressOfExpr->getType() == Context.OverloadTy);
11180 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11182 int NumMatches = Resolver.getNumMatches();
11183 FunctionDecl *Fn = nullptr;
11184 bool ShouldComplain = Complain && !Resolver.hasComplained();
11185 if (NumMatches == 0 && ShouldComplain) {
11186 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11187 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11189 Resolver.ComplainNoMatchesFound();
11191 else if (NumMatches > 1 && ShouldComplain)
11192 Resolver.ComplainMultipleMatchesFound();
11193 else if (NumMatches == 1) {
11194 Fn = Resolver.getMatchingFunctionDecl();
11196 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11197 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11198 FoundResult = *Resolver.getMatchingFunctionAccessPair();
11200 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11201 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11203 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11207 if (pHadMultipleCandidates)
11208 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11212 /// \brief Given an expression that refers to an overloaded function, try to
11213 /// resolve that function to a single function that can have its address taken.
11214 /// This will modify `Pair` iff it returns non-null.
11216 /// This routine can only realistically succeed if all but one candidates in the
11217 /// overload set for SrcExpr cannot have their addresses taken.
11219 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11220 DeclAccessPair &Pair) {
11221 OverloadExpr::FindResult R = OverloadExpr::find(E);
11222 OverloadExpr *Ovl = R.Expression;
11223 FunctionDecl *Result = nullptr;
11224 DeclAccessPair DAP;
11225 // Don't use the AddressOfResolver because we're specifically looking for
11226 // cases where we have one overload candidate that lacks
11227 // enable_if/pass_object_size/...
11228 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11229 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11233 if (!checkAddressOfFunctionIsAvailable(FD))
11236 // We have more than one result; quit.
11248 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11249 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11250 /// will perform access checks, diagnose the use of the resultant decl, and, if
11251 /// necessary, perform a function-to-pointer decay.
11253 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11254 /// Otherwise, returns true. This may emit diagnostics and return true.
11255 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11256 ExprResult &SrcExpr) {
11257 Expr *E = SrcExpr.get();
11258 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11260 DeclAccessPair DAP;
11261 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11265 // Emitting multiple diagnostics for a function that is both inaccessible and
11266 // unavailable is consistent with our behavior elsewhere. So, always check
11268 DiagnoseUseOfDecl(Found, E->getExprLoc());
11269 CheckAddressOfMemberAccess(E, DAP);
11270 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11271 if (Fixed->getType()->isFunctionType())
11272 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11278 /// \brief Given an expression that refers to an overloaded function, try to
11279 /// resolve that overloaded function expression down to a single function.
11281 /// This routine can only resolve template-ids that refer to a single function
11282 /// template, where that template-id refers to a single template whose template
11283 /// arguments are either provided by the template-id or have defaults,
11284 /// as described in C++0x [temp.arg.explicit]p3.
11286 /// If no template-ids are found, no diagnostics are emitted and NULL is
11289 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11291 DeclAccessPair *FoundResult) {
11292 // C++ [over.over]p1:
11293 // [...] [Note: any redundant set of parentheses surrounding the
11294 // overloaded function name is ignored (5.1). ]
11295 // C++ [over.over]p1:
11296 // [...] The overloaded function name can be preceded by the &
11299 // If we didn't actually find any template-ids, we're done.
11300 if (!ovl->hasExplicitTemplateArgs())
11303 TemplateArgumentListInfo ExplicitTemplateArgs;
11304 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11305 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11307 // Look through all of the overloaded functions, searching for one
11308 // whose type matches exactly.
11309 FunctionDecl *Matched = nullptr;
11310 for (UnresolvedSetIterator I = ovl->decls_begin(),
11311 E = ovl->decls_end(); I != E; ++I) {
11312 // C++0x [temp.arg.explicit]p3:
11313 // [...] In contexts where deduction is done and fails, or in contexts
11314 // where deduction is not done, if a template argument list is
11315 // specified and it, along with any default template arguments,
11316 // identifies a single function template specialization, then the
11317 // template-id is an lvalue for the function template specialization.
11318 FunctionTemplateDecl *FunctionTemplate
11319 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11321 // C++ [over.over]p2:
11322 // If the name is a function template, template argument deduction is
11323 // done (14.8.2.2), and if the argument deduction succeeds, the
11324 // resulting template argument list is used to generate a single
11325 // function template specialization, which is added to the set of
11326 // overloaded functions considered.
11327 FunctionDecl *Specialization = nullptr;
11328 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11329 if (TemplateDeductionResult Result
11330 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11331 Specialization, Info,
11332 /*IsAddressOfFunction*/true)) {
11333 // Make a note of the failed deduction for diagnostics.
11334 // TODO: Actually use the failed-deduction info?
11335 FailedCandidates.addCandidate()
11336 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11337 MakeDeductionFailureInfo(Context, Result, Info));
11341 assert(Specialization && "no specialization and no error?");
11343 // Multiple matches; we can't resolve to a single declaration.
11346 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11348 NoteAllOverloadCandidates(ovl);
11353 Matched = Specialization;
11354 if (FoundResult) *FoundResult = I.getPair();
11358 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11367 // Resolve and fix an overloaded expression that can be resolved
11368 // because it identifies a single function template specialization.
11370 // Last three arguments should only be supplied if Complain = true
11372 // Return true if it was logically possible to so resolve the
11373 // expression, regardless of whether or not it succeeded. Always
11374 // returns true if 'complain' is set.
11375 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11376 ExprResult &SrcExpr, bool doFunctionPointerConverion,
11377 bool complain, SourceRange OpRangeForComplaining,
11378 QualType DestTypeForComplaining,
11379 unsigned DiagIDForComplaining) {
11380 assert(SrcExpr.get()->getType() == Context.OverloadTy);
11382 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11384 DeclAccessPair found;
11385 ExprResult SingleFunctionExpression;
11386 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11387 ovl.Expression, /*complain*/ false, &found)) {
11388 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11389 SrcExpr = ExprError();
11393 // It is only correct to resolve to an instance method if we're
11394 // resolving a form that's permitted to be a pointer to member.
11395 // Otherwise we'll end up making a bound member expression, which
11396 // is illegal in all the contexts we resolve like this.
11397 if (!ovl.HasFormOfMemberPointer &&
11398 isa<CXXMethodDecl>(fn) &&
11399 cast<CXXMethodDecl>(fn)->isInstance()) {
11400 if (!complain) return false;
11402 Diag(ovl.Expression->getExprLoc(),
11403 diag::err_bound_member_function)
11404 << 0 << ovl.Expression->getSourceRange();
11406 // TODO: I believe we only end up here if there's a mix of
11407 // static and non-static candidates (otherwise the expression
11408 // would have 'bound member' type, not 'overload' type).
11409 // Ideally we would note which candidate was chosen and why
11410 // the static candidates were rejected.
11411 SrcExpr = ExprError();
11415 // Fix the expression to refer to 'fn'.
11416 SingleFunctionExpression =
11417 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11419 // If desired, do function-to-pointer decay.
11420 if (doFunctionPointerConverion) {
11421 SingleFunctionExpression =
11422 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11423 if (SingleFunctionExpression.isInvalid()) {
11424 SrcExpr = ExprError();
11430 if (!SingleFunctionExpression.isUsable()) {
11432 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11433 << ovl.Expression->getName()
11434 << DestTypeForComplaining
11435 << OpRangeForComplaining
11436 << ovl.Expression->getQualifierLoc().getSourceRange();
11437 NoteAllOverloadCandidates(SrcExpr.get());
11439 SrcExpr = ExprError();
11446 SrcExpr = SingleFunctionExpression;
11450 /// \brief Add a single candidate to the overload set.
11451 static void AddOverloadedCallCandidate(Sema &S,
11452 DeclAccessPair FoundDecl,
11453 TemplateArgumentListInfo *ExplicitTemplateArgs,
11454 ArrayRef<Expr *> Args,
11455 OverloadCandidateSet &CandidateSet,
11456 bool PartialOverloading,
11458 NamedDecl *Callee = FoundDecl.getDecl();
11459 if (isa<UsingShadowDecl>(Callee))
11460 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11462 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11463 if (ExplicitTemplateArgs) {
11464 assert(!KnownValid && "Explicit template arguments?");
11467 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11468 /*SuppressUsedConversions=*/false,
11469 PartialOverloading);
11473 if (FunctionTemplateDecl *FuncTemplate
11474 = dyn_cast<FunctionTemplateDecl>(Callee)) {
11475 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11476 ExplicitTemplateArgs, Args, CandidateSet,
11477 /*SuppressUsedConversions=*/false,
11478 PartialOverloading);
11482 assert(!KnownValid && "unhandled case in overloaded call candidate");
11485 /// \brief Add the overload candidates named by callee and/or found by argument
11486 /// dependent lookup to the given overload set.
11487 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11488 ArrayRef<Expr *> Args,
11489 OverloadCandidateSet &CandidateSet,
11490 bool PartialOverloading) {
11493 // Verify that ArgumentDependentLookup is consistent with the rules
11494 // in C++0x [basic.lookup.argdep]p3:
11496 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11497 // and let Y be the lookup set produced by argument dependent
11498 // lookup (defined as follows). If X contains
11500 // -- a declaration of a class member, or
11502 // -- a block-scope function declaration that is not a
11503 // using-declaration, or
11505 // -- a declaration that is neither a function or a function
11508 // then Y is empty.
11510 if (ULE->requiresADL()) {
11511 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11512 E = ULE->decls_end(); I != E; ++I) {
11513 assert(!(*I)->getDeclContext()->isRecord());
11514 assert(isa<UsingShadowDecl>(*I) ||
11515 !(*I)->getDeclContext()->isFunctionOrMethod());
11516 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11521 // It would be nice to avoid this copy.
11522 TemplateArgumentListInfo TABuffer;
11523 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11524 if (ULE->hasExplicitTemplateArgs()) {
11525 ULE->copyTemplateArgumentsInto(TABuffer);
11526 ExplicitTemplateArgs = &TABuffer;
11529 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11530 E = ULE->decls_end(); I != E; ++I)
11531 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11532 CandidateSet, PartialOverloading,
11533 /*KnownValid*/ true);
11535 if (ULE->requiresADL())
11536 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11537 Args, ExplicitTemplateArgs,
11538 CandidateSet, PartialOverloading);
11541 /// Determine whether a declaration with the specified name could be moved into
11542 /// a different namespace.
11543 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11544 switch (Name.getCXXOverloadedOperator()) {
11545 case OO_New: case OO_Array_New:
11546 case OO_Delete: case OO_Array_Delete:
11554 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11555 /// template, where the non-dependent name was declared after the template
11556 /// was defined. This is common in code written for a compilers which do not
11557 /// correctly implement two-stage name lookup.
11559 /// Returns true if a viable candidate was found and a diagnostic was issued.
11561 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11562 const CXXScopeSpec &SS, LookupResult &R,
11563 OverloadCandidateSet::CandidateSetKind CSK,
11564 TemplateArgumentListInfo *ExplicitTemplateArgs,
11565 ArrayRef<Expr *> Args,
11566 bool *DoDiagnoseEmptyLookup = nullptr) {
11567 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11570 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11571 if (DC->isTransparentContext())
11574 SemaRef.LookupQualifiedName(R, DC);
11577 R.suppressDiagnostics();
11579 if (isa<CXXRecordDecl>(DC)) {
11580 // Don't diagnose names we find in classes; we get much better
11581 // diagnostics for these from DiagnoseEmptyLookup.
11583 if (DoDiagnoseEmptyLookup)
11584 *DoDiagnoseEmptyLookup = true;
11588 OverloadCandidateSet Candidates(FnLoc, CSK);
11589 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11590 AddOverloadedCallCandidate(SemaRef, I.getPair(),
11591 ExplicitTemplateArgs, Args,
11592 Candidates, false, /*KnownValid*/ false);
11594 OverloadCandidateSet::iterator Best;
11595 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11596 // No viable functions. Don't bother the user with notes for functions
11597 // which don't work and shouldn't be found anyway.
11602 // Find the namespaces where ADL would have looked, and suggest
11603 // declaring the function there instead.
11604 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11605 Sema::AssociatedClassSet AssociatedClasses;
11606 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11607 AssociatedNamespaces,
11608 AssociatedClasses);
11609 Sema::AssociatedNamespaceSet SuggestedNamespaces;
11610 if (canBeDeclaredInNamespace(R.getLookupName())) {
11611 DeclContext *Std = SemaRef.getStdNamespace();
11612 for (Sema::AssociatedNamespaceSet::iterator
11613 it = AssociatedNamespaces.begin(),
11614 end = AssociatedNamespaces.end(); it != end; ++it) {
11615 // Never suggest declaring a function within namespace 'std'.
11616 if (Std && Std->Encloses(*it))
11619 // Never suggest declaring a function within a namespace with a
11620 // reserved name, like __gnu_cxx.
11621 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11623 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11626 SuggestedNamespaces.insert(*it);
11630 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11631 << R.getLookupName();
11632 if (SuggestedNamespaces.empty()) {
11633 SemaRef.Diag(Best->Function->getLocation(),
11634 diag::note_not_found_by_two_phase_lookup)
11635 << R.getLookupName() << 0;
11636 } else if (SuggestedNamespaces.size() == 1) {
11637 SemaRef.Diag(Best->Function->getLocation(),
11638 diag::note_not_found_by_two_phase_lookup)
11639 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11641 // FIXME: It would be useful to list the associated namespaces here,
11642 // but the diagnostics infrastructure doesn't provide a way to produce
11643 // a localized representation of a list of items.
11644 SemaRef.Diag(Best->Function->getLocation(),
11645 diag::note_not_found_by_two_phase_lookup)
11646 << R.getLookupName() << 2;
11649 // Try to recover by calling this function.
11659 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11660 /// template, where the non-dependent operator was declared after the template
11663 /// Returns true if a viable candidate was found and a diagnostic was issued.
11665 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11666 SourceLocation OpLoc,
11667 ArrayRef<Expr *> Args) {
11668 DeclarationName OpName =
11669 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11670 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11671 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11672 OverloadCandidateSet::CSK_Operator,
11673 /*ExplicitTemplateArgs=*/nullptr, Args);
11677 class BuildRecoveryCallExprRAII {
11680 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11681 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11682 SemaRef.IsBuildingRecoveryCallExpr = true;
11685 ~BuildRecoveryCallExprRAII() {
11686 SemaRef.IsBuildingRecoveryCallExpr = false;
11692 static std::unique_ptr<CorrectionCandidateCallback>
11693 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11694 bool HasTemplateArgs, bool AllowTypoCorrection) {
11695 if (!AllowTypoCorrection)
11696 return llvm::make_unique<NoTypoCorrectionCCC>();
11697 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11698 HasTemplateArgs, ME);
11701 /// Attempts to recover from a call where no functions were found.
11703 /// Returns true if new candidates were found.
11705 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11706 UnresolvedLookupExpr *ULE,
11707 SourceLocation LParenLoc,
11708 MutableArrayRef<Expr *> Args,
11709 SourceLocation RParenLoc,
11710 bool EmptyLookup, bool AllowTypoCorrection) {
11711 // Do not try to recover if it is already building a recovery call.
11712 // This stops infinite loops for template instantiations like
11714 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11715 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11717 if (SemaRef.IsBuildingRecoveryCallExpr)
11718 return ExprError();
11719 BuildRecoveryCallExprRAII RCE(SemaRef);
11722 SS.Adopt(ULE->getQualifierLoc());
11723 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11725 TemplateArgumentListInfo TABuffer;
11726 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11727 if (ULE->hasExplicitTemplateArgs()) {
11728 ULE->copyTemplateArgumentsInto(TABuffer);
11729 ExplicitTemplateArgs = &TABuffer;
11732 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11733 Sema::LookupOrdinaryName);
11734 bool DoDiagnoseEmptyLookup = EmptyLookup;
11735 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11736 OverloadCandidateSet::CSK_Normal,
11737 ExplicitTemplateArgs, Args,
11738 &DoDiagnoseEmptyLookup) &&
11739 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11741 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11742 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11743 ExplicitTemplateArgs, Args)))
11744 return ExprError();
11746 assert(!R.empty() && "lookup results empty despite recovery");
11748 // If recovery created an ambiguity, just bail out.
11749 if (R.isAmbiguous()) {
11750 R.suppressDiagnostics();
11751 return ExprError();
11754 // Build an implicit member call if appropriate. Just drop the
11755 // casts and such from the call, we don't really care.
11756 ExprResult NewFn = ExprError();
11757 if ((*R.begin())->isCXXClassMember())
11758 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11759 ExplicitTemplateArgs, S);
11760 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11761 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11762 ExplicitTemplateArgs);
11764 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11766 if (NewFn.isInvalid())
11767 return ExprError();
11769 // This shouldn't cause an infinite loop because we're giving it
11770 // an expression with viable lookup results, which should never
11772 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11773 MultiExprArg(Args.data(), Args.size()),
11777 /// \brief Constructs and populates an OverloadedCandidateSet from
11778 /// the given function.
11779 /// \returns true when an the ExprResult output parameter has been set.
11780 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11781 UnresolvedLookupExpr *ULE,
11783 SourceLocation RParenLoc,
11784 OverloadCandidateSet *CandidateSet,
11785 ExprResult *Result) {
11787 if (ULE->requiresADL()) {
11788 // To do ADL, we must have found an unqualified name.
11789 assert(!ULE->getQualifier() && "qualified name with ADL");
11791 // We don't perform ADL for implicit declarations of builtins.
11792 // Verify that this was correctly set up.
11794 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11795 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11796 F->getBuiltinID() && F->isImplicit())
11797 llvm_unreachable("performing ADL for builtin");
11799 // We don't perform ADL in C.
11800 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11804 UnbridgedCastsSet UnbridgedCasts;
11805 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11806 *Result = ExprError();
11810 // Add the functions denoted by the callee to the set of candidate
11811 // functions, including those from argument-dependent lookup.
11812 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11814 if (getLangOpts().MSVCCompat &&
11815 CurContext->isDependentContext() && !isSFINAEContext() &&
11816 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11818 OverloadCandidateSet::iterator Best;
11819 if (CandidateSet->empty() ||
11820 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11821 OR_No_Viable_Function) {
11822 // In Microsoft mode, if we are inside a template class member function then
11823 // create a type dependent CallExpr. The goal is to postpone name lookup
11824 // to instantiation time to be able to search into type dependent base
11826 CallExpr *CE = new (Context) CallExpr(
11827 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11828 CE->setTypeDependent(true);
11829 CE->setValueDependent(true);
11830 CE->setInstantiationDependent(true);
11836 if (CandidateSet->empty())
11839 UnbridgedCasts.restore();
11843 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11844 /// the completed call expression. If overload resolution fails, emits
11845 /// diagnostics and returns ExprError()
11846 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11847 UnresolvedLookupExpr *ULE,
11848 SourceLocation LParenLoc,
11850 SourceLocation RParenLoc,
11852 OverloadCandidateSet *CandidateSet,
11853 OverloadCandidateSet::iterator *Best,
11854 OverloadingResult OverloadResult,
11855 bool AllowTypoCorrection) {
11856 if (CandidateSet->empty())
11857 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11858 RParenLoc, /*EmptyLookup=*/true,
11859 AllowTypoCorrection);
11861 switch (OverloadResult) {
11863 FunctionDecl *FDecl = (*Best)->Function;
11864 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11865 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11866 return ExprError();
11867 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11868 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11872 case OR_No_Viable_Function: {
11873 // Try to recover by looking for viable functions which the user might
11874 // have meant to call.
11875 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11877 /*EmptyLookup=*/false,
11878 AllowTypoCorrection);
11879 if (!Recovery.isInvalid())
11882 // If the user passes in a function that we can't take the address of, we
11883 // generally end up emitting really bad error messages. Here, we attempt to
11884 // emit better ones.
11885 for (const Expr *Arg : Args) {
11886 if (!Arg->getType()->isFunctionType())
11888 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11889 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11891 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11892 Arg->getExprLoc()))
11893 return ExprError();
11897 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11898 << ULE->getName() << Fn->getSourceRange();
11899 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11904 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11905 << ULE->getName() << Fn->getSourceRange();
11906 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11910 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11911 << (*Best)->Function->isDeleted()
11913 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11914 << Fn->getSourceRange();
11915 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11917 // We emitted an error for the unvailable/deleted function call but keep
11918 // the call in the AST.
11919 FunctionDecl *FDecl = (*Best)->Function;
11920 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11921 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11926 // Overload resolution failed.
11927 return ExprError();
11930 static void markUnaddressableCandidatesUnviable(Sema &S,
11931 OverloadCandidateSet &CS) {
11932 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11934 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11936 I->FailureKind = ovl_fail_addr_not_available;
11941 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11942 /// (which eventually refers to the declaration Func) and the call
11943 /// arguments Args/NumArgs, attempt to resolve the function call down
11944 /// to a specific function. If overload resolution succeeds, returns
11945 /// the call expression produced by overload resolution.
11946 /// Otherwise, emits diagnostics and returns ExprError.
11947 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11948 UnresolvedLookupExpr *ULE,
11949 SourceLocation LParenLoc,
11951 SourceLocation RParenLoc,
11953 bool AllowTypoCorrection,
11954 bool CalleesAddressIsTaken) {
11955 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11956 OverloadCandidateSet::CSK_Normal);
11959 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11963 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11964 // functions that aren't addressible are considered unviable.
11965 if (CalleesAddressIsTaken)
11966 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11968 OverloadCandidateSet::iterator Best;
11969 OverloadingResult OverloadResult =
11970 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11972 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11973 RParenLoc, ExecConfig, &CandidateSet,
11974 &Best, OverloadResult,
11975 AllowTypoCorrection);
11978 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11979 return Functions.size() > 1 ||
11980 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11983 /// \brief Create a unary operation that may resolve to an overloaded
11986 /// \param OpLoc The location of the operator itself (e.g., '*').
11988 /// \param Opc The UnaryOperatorKind that describes this operator.
11990 /// \param Fns The set of non-member functions that will be
11991 /// considered by overload resolution. The caller needs to build this
11992 /// set based on the context using, e.g.,
11993 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11994 /// set should not contain any member functions; those will be added
11995 /// by CreateOverloadedUnaryOp().
11997 /// \param Input The input argument.
11999 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12000 const UnresolvedSetImpl &Fns,
12002 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12003 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12004 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12005 // TODO: provide better source location info.
12006 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12008 if (checkPlaceholderForOverload(*this, Input))
12009 return ExprError();
12011 Expr *Args[2] = { Input, nullptr };
12012 unsigned NumArgs = 1;
12014 // For post-increment and post-decrement, add the implicit '0' as
12015 // the second argument, so that we know this is a post-increment or
12017 if (Opc == UO_PostInc || Opc == UO_PostDec) {
12018 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12019 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12024 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12026 if (Input->isTypeDependent()) {
12028 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12029 VK_RValue, OK_Ordinary, OpLoc);
12031 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12032 UnresolvedLookupExpr *Fn
12033 = UnresolvedLookupExpr::Create(Context, NamingClass,
12034 NestedNameSpecifierLoc(), OpNameInfo,
12035 /*ADL*/ true, IsOverloaded(Fns),
12036 Fns.begin(), Fns.end());
12037 return new (Context)
12038 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12039 VK_RValue, OpLoc, false);
12042 // Build an empty overload set.
12043 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12045 // Add the candidates from the given function set.
12046 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12048 // Add operator candidates that are member functions.
12049 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12051 // Add candidates from ADL.
12052 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12053 /*ExplicitTemplateArgs*/nullptr,
12056 // Add builtin operator candidates.
12057 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12059 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12061 // Perform overload resolution.
12062 OverloadCandidateSet::iterator Best;
12063 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12065 // We found a built-in operator or an overloaded operator.
12066 FunctionDecl *FnDecl = Best->Function;
12069 // We matched an overloaded operator. Build a call to that
12072 // Convert the arguments.
12073 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12074 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12076 ExprResult InputRes =
12077 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12078 Best->FoundDecl, Method);
12079 if (InputRes.isInvalid())
12080 return ExprError();
12081 Input = InputRes.get();
12083 // Convert the arguments.
12084 ExprResult InputInit
12085 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12087 FnDecl->getParamDecl(0)),
12090 if (InputInit.isInvalid())
12091 return ExprError();
12092 Input = InputInit.get();
12095 // Build the actual expression node.
12096 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12097 HadMultipleCandidates, OpLoc);
12098 if (FnExpr.isInvalid())
12099 return ExprError();
12101 // Determine the result type.
12102 QualType ResultTy = FnDecl->getReturnType();
12103 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12104 ResultTy = ResultTy.getNonLValueExprType(Context);
12107 CallExpr *TheCall =
12108 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12109 ResultTy, VK, OpLoc, false);
12111 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12112 return ExprError();
12114 return MaybeBindToTemporary(TheCall);
12116 // We matched a built-in operator. Convert the arguments, then
12117 // break out so that we will build the appropriate built-in
12119 ExprResult InputRes =
12120 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
12121 Best->Conversions[0], AA_Passing);
12122 if (InputRes.isInvalid())
12123 return ExprError();
12124 Input = InputRes.get();
12129 case OR_No_Viable_Function:
12130 // This is an erroneous use of an operator which can be overloaded by
12131 // a non-member function. Check for non-member operators which were
12132 // defined too late to be candidates.
12133 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12134 // FIXME: Recover by calling the found function.
12135 return ExprError();
12137 // No viable function; fall through to handling this as a
12138 // built-in operator, which will produce an error message for us.
12142 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12143 << UnaryOperator::getOpcodeStr(Opc)
12144 << Input->getType()
12145 << Input->getSourceRange();
12146 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12147 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12148 return ExprError();
12151 Diag(OpLoc, diag::err_ovl_deleted_oper)
12152 << Best->Function->isDeleted()
12153 << UnaryOperator::getOpcodeStr(Opc)
12154 << getDeletedOrUnavailableSuffix(Best->Function)
12155 << Input->getSourceRange();
12156 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12157 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12158 return ExprError();
12161 // Either we found no viable overloaded operator or we matched a
12162 // built-in operator. In either case, fall through to trying to
12163 // build a built-in operation.
12164 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12167 /// \brief Create a binary operation that may resolve to an overloaded
12170 /// \param OpLoc The location of the operator itself (e.g., '+').
12172 /// \param Opc The BinaryOperatorKind that describes this operator.
12174 /// \param Fns The set of non-member functions that will be
12175 /// considered by overload resolution. The caller needs to build this
12176 /// set based on the context using, e.g.,
12177 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12178 /// set should not contain any member functions; those will be added
12179 /// by CreateOverloadedBinOp().
12181 /// \param LHS Left-hand argument.
12182 /// \param RHS Right-hand argument.
12184 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12185 BinaryOperatorKind Opc,
12186 const UnresolvedSetImpl &Fns,
12187 Expr *LHS, Expr *RHS) {
12188 Expr *Args[2] = { LHS, RHS };
12189 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12191 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12192 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12194 // If either side is type-dependent, create an appropriate dependent
12196 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12198 // If there are no functions to store, just build a dependent
12199 // BinaryOperator or CompoundAssignment.
12200 if (Opc <= BO_Assign || Opc > BO_OrAssign)
12201 return new (Context) BinaryOperator(
12202 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12203 OpLoc, FPFeatures.fp_contract);
12205 return new (Context) CompoundAssignOperator(
12206 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12207 Context.DependentTy, Context.DependentTy, OpLoc,
12208 FPFeatures.fp_contract);
12211 // FIXME: save results of ADL from here?
12212 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12213 // TODO: provide better source location info in DNLoc component.
12214 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12215 UnresolvedLookupExpr *Fn
12216 = UnresolvedLookupExpr::Create(Context, NamingClass,
12217 NestedNameSpecifierLoc(), OpNameInfo,
12218 /*ADL*/ true, IsOverloaded(Fns),
12219 Fns.begin(), Fns.end());
12220 return new (Context)
12221 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12222 VK_RValue, OpLoc, FPFeatures.fp_contract);
12225 // Always do placeholder-like conversions on the RHS.
12226 if (checkPlaceholderForOverload(*this, Args[1]))
12227 return ExprError();
12229 // Do placeholder-like conversion on the LHS; note that we should
12230 // not get here with a PseudoObject LHS.
12231 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12232 if (checkPlaceholderForOverload(*this, Args[0]))
12233 return ExprError();
12235 // If this is the assignment operator, we only perform overload resolution
12236 // if the left-hand side is a class or enumeration type. This is actually
12237 // a hack. The standard requires that we do overload resolution between the
12238 // various built-in candidates, but as DR507 points out, this can lead to
12239 // problems. So we do it this way, which pretty much follows what GCC does.
12240 // Note that we go the traditional code path for compound assignment forms.
12241 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12242 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12244 // If this is the .* operator, which is not overloadable, just
12245 // create a built-in binary operator.
12246 if (Opc == BO_PtrMemD)
12247 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12249 // Build an empty overload set.
12250 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12252 // Add the candidates from the given function set.
12253 AddFunctionCandidates(Fns, Args, CandidateSet);
12255 // Add operator candidates that are member functions.
12256 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12258 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12259 // performed for an assignment operator (nor for operator[] nor operator->,
12260 // which don't get here).
12261 if (Opc != BO_Assign)
12262 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12263 /*ExplicitTemplateArgs*/ nullptr,
12266 // Add builtin operator candidates.
12267 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12269 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12271 // Perform overload resolution.
12272 OverloadCandidateSet::iterator Best;
12273 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12275 // We found a built-in operator or an overloaded operator.
12276 FunctionDecl *FnDecl = Best->Function;
12279 // We matched an overloaded operator. Build a call to that
12282 // Convert the arguments.
12283 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12284 // Best->Access is only meaningful for class members.
12285 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12288 PerformCopyInitialization(
12289 InitializedEntity::InitializeParameter(Context,
12290 FnDecl->getParamDecl(0)),
12291 SourceLocation(), Args[1]);
12292 if (Arg1.isInvalid())
12293 return ExprError();
12296 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12297 Best->FoundDecl, Method);
12298 if (Arg0.isInvalid())
12299 return ExprError();
12300 Args[0] = Arg0.getAs<Expr>();
12301 Args[1] = RHS = Arg1.getAs<Expr>();
12303 // Convert the arguments.
12304 ExprResult Arg0 = PerformCopyInitialization(
12305 InitializedEntity::InitializeParameter(Context,
12306 FnDecl->getParamDecl(0)),
12307 SourceLocation(), Args[0]);
12308 if (Arg0.isInvalid())
12309 return ExprError();
12312 PerformCopyInitialization(
12313 InitializedEntity::InitializeParameter(Context,
12314 FnDecl->getParamDecl(1)),
12315 SourceLocation(), Args[1]);
12316 if (Arg1.isInvalid())
12317 return ExprError();
12318 Args[0] = LHS = Arg0.getAs<Expr>();
12319 Args[1] = RHS = Arg1.getAs<Expr>();
12322 // Build the actual expression node.
12323 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12325 HadMultipleCandidates, OpLoc);
12326 if (FnExpr.isInvalid())
12327 return ExprError();
12329 // Determine the result type.
12330 QualType ResultTy = FnDecl->getReturnType();
12331 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12332 ResultTy = ResultTy.getNonLValueExprType(Context);
12334 CXXOperatorCallExpr *TheCall =
12335 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12336 Args, ResultTy, VK, OpLoc,
12337 FPFeatures.fp_contract);
12339 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12341 return ExprError();
12343 ArrayRef<const Expr *> ArgsArray(Args, 2);
12344 // Cut off the implicit 'this'.
12345 if (isa<CXXMethodDecl>(FnDecl))
12346 ArgsArray = ArgsArray.slice(1);
12348 // Check for a self move.
12349 if (Op == OO_Equal)
12350 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12352 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
12353 TheCall->getSourceRange(), VariadicDoesNotApply);
12355 return MaybeBindToTemporary(TheCall);
12357 // We matched a built-in operator. Convert the arguments, then
12358 // break out so that we will build the appropriate built-in
12360 ExprResult ArgsRes0 =
12361 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12362 Best->Conversions[0], AA_Passing);
12363 if (ArgsRes0.isInvalid())
12364 return ExprError();
12365 Args[0] = ArgsRes0.get();
12367 ExprResult ArgsRes1 =
12368 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12369 Best->Conversions[1], AA_Passing);
12370 if (ArgsRes1.isInvalid())
12371 return ExprError();
12372 Args[1] = ArgsRes1.get();
12377 case OR_No_Viable_Function: {
12378 // C++ [over.match.oper]p9:
12379 // If the operator is the operator , [...] and there are no
12380 // viable functions, then the operator is assumed to be the
12381 // built-in operator and interpreted according to clause 5.
12382 if (Opc == BO_Comma)
12385 // For class as left operand for assignment or compound assigment
12386 // operator do not fall through to handling in built-in, but report that
12387 // no overloaded assignment operator found
12388 ExprResult Result = ExprError();
12389 if (Args[0]->getType()->isRecordType() &&
12390 Opc >= BO_Assign && Opc <= BO_OrAssign) {
12391 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12392 << BinaryOperator::getOpcodeStr(Opc)
12393 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12394 if (Args[0]->getType()->isIncompleteType()) {
12395 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12396 << Args[0]->getType()
12397 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12400 // This is an erroneous use of an operator which can be overloaded by
12401 // a non-member function. Check for non-member operators which were
12402 // defined too late to be candidates.
12403 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12404 // FIXME: Recover by calling the found function.
12405 return ExprError();
12407 // No viable function; try to create a built-in operation, which will
12408 // produce an error. Then, show the non-viable candidates.
12409 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12411 assert(Result.isInvalid() &&
12412 "C++ binary operator overloading is missing candidates!");
12413 if (Result.isInvalid())
12414 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12415 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12420 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
12421 << BinaryOperator::getOpcodeStr(Opc)
12422 << Args[0]->getType() << Args[1]->getType()
12423 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12424 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12425 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12426 return ExprError();
12429 if (isImplicitlyDeleted(Best->Function)) {
12430 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12431 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12432 << Context.getRecordType(Method->getParent())
12433 << getSpecialMember(Method);
12435 // The user probably meant to call this special member. Just
12436 // explain why it's deleted.
12437 NoteDeletedFunction(Method);
12438 return ExprError();
12440 Diag(OpLoc, diag::err_ovl_deleted_oper)
12441 << Best->Function->isDeleted()
12442 << BinaryOperator::getOpcodeStr(Opc)
12443 << getDeletedOrUnavailableSuffix(Best->Function)
12444 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12446 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12447 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12448 return ExprError();
12451 // We matched a built-in operator; build it.
12452 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12456 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12457 SourceLocation RLoc,
12458 Expr *Base, Expr *Idx) {
12459 Expr *Args[2] = { Base, Idx };
12460 DeclarationName OpName =
12461 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12463 // If either side is type-dependent, create an appropriate dependent
12465 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12467 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12468 // CHECKME: no 'operator' keyword?
12469 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12470 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12471 UnresolvedLookupExpr *Fn
12472 = UnresolvedLookupExpr::Create(Context, NamingClass,
12473 NestedNameSpecifierLoc(), OpNameInfo,
12474 /*ADL*/ true, /*Overloaded*/ false,
12475 UnresolvedSetIterator(),
12476 UnresolvedSetIterator());
12477 // Can't add any actual overloads yet
12479 return new (Context)
12480 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12481 Context.DependentTy, VK_RValue, RLoc, false);
12484 // Handle placeholders on both operands.
12485 if (checkPlaceholderForOverload(*this, Args[0]))
12486 return ExprError();
12487 if (checkPlaceholderForOverload(*this, Args[1]))
12488 return ExprError();
12490 // Build an empty overload set.
12491 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12493 // Subscript can only be overloaded as a member function.
12495 // Add operator candidates that are member functions.
12496 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12498 // Add builtin operator candidates.
12499 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12501 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12503 // Perform overload resolution.
12504 OverloadCandidateSet::iterator Best;
12505 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12507 // We found a built-in operator or an overloaded operator.
12508 FunctionDecl *FnDecl = Best->Function;
12511 // We matched an overloaded operator. Build a call to that
12514 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12516 // Convert the arguments.
12517 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12519 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12520 Best->FoundDecl, Method);
12521 if (Arg0.isInvalid())
12522 return ExprError();
12523 Args[0] = Arg0.get();
12525 // Convert the arguments.
12526 ExprResult InputInit
12527 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12529 FnDecl->getParamDecl(0)),
12532 if (InputInit.isInvalid())
12533 return ExprError();
12535 Args[1] = InputInit.getAs<Expr>();
12537 // Build the actual expression node.
12538 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12539 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12540 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12542 HadMultipleCandidates,
12543 OpLocInfo.getLoc(),
12544 OpLocInfo.getInfo());
12545 if (FnExpr.isInvalid())
12546 return ExprError();
12548 // Determine the result type
12549 QualType ResultTy = FnDecl->getReturnType();
12550 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12551 ResultTy = ResultTy.getNonLValueExprType(Context);
12553 CXXOperatorCallExpr *TheCall =
12554 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12555 FnExpr.get(), Args,
12556 ResultTy, VK, RLoc,
12559 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12560 return ExprError();
12562 return MaybeBindToTemporary(TheCall);
12564 // We matched a built-in operator. Convert the arguments, then
12565 // break out so that we will build the appropriate built-in
12567 ExprResult ArgsRes0 =
12568 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12569 Best->Conversions[0], AA_Passing);
12570 if (ArgsRes0.isInvalid())
12571 return ExprError();
12572 Args[0] = ArgsRes0.get();
12574 ExprResult ArgsRes1 =
12575 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12576 Best->Conversions[1], AA_Passing);
12577 if (ArgsRes1.isInvalid())
12578 return ExprError();
12579 Args[1] = ArgsRes1.get();
12585 case OR_No_Viable_Function: {
12586 if (CandidateSet.empty())
12587 Diag(LLoc, diag::err_ovl_no_oper)
12588 << Args[0]->getType() << /*subscript*/ 0
12589 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12591 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12592 << Args[0]->getType()
12593 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12594 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12596 return ExprError();
12600 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
12602 << Args[0]->getType() << Args[1]->getType()
12603 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12604 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12606 return ExprError();
12609 Diag(LLoc, diag::err_ovl_deleted_oper)
12610 << Best->Function->isDeleted() << "[]"
12611 << getDeletedOrUnavailableSuffix(Best->Function)
12612 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12613 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12615 return ExprError();
12618 // We matched a built-in operator; build it.
12619 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12622 /// BuildCallToMemberFunction - Build a call to a member
12623 /// function. MemExpr is the expression that refers to the member
12624 /// function (and includes the object parameter), Args/NumArgs are the
12625 /// arguments to the function call (not including the object
12626 /// parameter). The caller needs to validate that the member
12627 /// expression refers to a non-static member function or an overloaded
12628 /// member function.
12630 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12631 SourceLocation LParenLoc,
12633 SourceLocation RParenLoc) {
12634 assert(MemExprE->getType() == Context.BoundMemberTy ||
12635 MemExprE->getType() == Context.OverloadTy);
12637 // Dig out the member expression. This holds both the object
12638 // argument and the member function we're referring to.
12639 Expr *NakedMemExpr = MemExprE->IgnoreParens();
12641 // Determine whether this is a call to a pointer-to-member function.
12642 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12643 assert(op->getType() == Context.BoundMemberTy);
12644 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12647 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12649 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12650 QualType resultType = proto->getCallResultType(Context);
12651 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12653 // Check that the object type isn't more qualified than the
12654 // member function we're calling.
12655 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12657 QualType objectType = op->getLHS()->getType();
12658 if (op->getOpcode() == BO_PtrMemI)
12659 objectType = objectType->castAs<PointerType>()->getPointeeType();
12660 Qualifiers objectQuals = objectType.getQualifiers();
12662 Qualifiers difference = objectQuals - funcQuals;
12663 difference.removeObjCGCAttr();
12664 difference.removeAddressSpace();
12666 std::string qualsString = difference.getAsString();
12667 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12668 << fnType.getUnqualifiedType()
12670 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12673 CXXMemberCallExpr *call
12674 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12675 resultType, valueKind, RParenLoc);
12677 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12679 return ExprError();
12681 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12682 return ExprError();
12684 if (CheckOtherCall(call, proto))
12685 return ExprError();
12687 return MaybeBindToTemporary(call);
12690 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12691 return new (Context)
12692 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12694 UnbridgedCastsSet UnbridgedCasts;
12695 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12696 return ExprError();
12698 MemberExpr *MemExpr;
12699 CXXMethodDecl *Method = nullptr;
12700 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12701 NestedNameSpecifier *Qualifier = nullptr;
12702 if (isa<MemberExpr>(NakedMemExpr)) {
12703 MemExpr = cast<MemberExpr>(NakedMemExpr);
12704 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12705 FoundDecl = MemExpr->getFoundDecl();
12706 Qualifier = MemExpr->getQualifier();
12707 UnbridgedCasts.restore();
12709 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12710 Qualifier = UnresExpr->getQualifier();
12712 QualType ObjectType = UnresExpr->getBaseType();
12713 Expr::Classification ObjectClassification
12714 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12715 : UnresExpr->getBase()->Classify(Context);
12717 // Add overload candidates
12718 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12719 OverloadCandidateSet::CSK_Normal);
12721 // FIXME: avoid copy.
12722 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12723 if (UnresExpr->hasExplicitTemplateArgs()) {
12724 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12725 TemplateArgs = &TemplateArgsBuffer;
12728 // Poor-programmer's Lazy<Expr *>; isImplicitAccess requires stripping
12729 // parens/casts, which would be nice to avoid potentially doing multiple
12731 llvm::Optional<Expr *> UnresolvedBase;
12732 auto GetUnresolvedBase = [&] {
12733 if (!UnresolvedBase.hasValue())
12735 UnresExpr->isImplicitAccess() ? nullptr : UnresExpr->getBase();
12736 return *UnresolvedBase;
12738 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12739 E = UnresExpr->decls_end(); I != E; ++I) {
12741 NamedDecl *Func = *I;
12742 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12743 if (isa<UsingShadowDecl>(Func))
12744 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12747 // Microsoft supports direct constructor calls.
12748 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12749 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12750 Args, CandidateSet);
12751 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12752 // If explicit template arguments were provided, we can't call a
12753 // non-template member function.
12757 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12758 ObjectClassification,
12759 /*ThisArg=*/GetUnresolvedBase(), Args, CandidateSet,
12760 /*SuppressUserConversions=*/false);
12762 AddMethodTemplateCandidate(
12763 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12764 TemplateArgs, ObjectType, ObjectClassification,
12765 /*ThisArg=*/GetUnresolvedBase(), Args, CandidateSet,
12766 /*SuppressUsedConversions=*/false);
12770 DeclarationName DeclName = UnresExpr->getMemberName();
12772 UnbridgedCasts.restore();
12774 OverloadCandidateSet::iterator Best;
12775 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12778 Method = cast<CXXMethodDecl>(Best->Function);
12779 FoundDecl = Best->FoundDecl;
12780 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12781 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12782 return ExprError();
12783 // If FoundDecl is different from Method (such as if one is a template
12784 // and the other a specialization), make sure DiagnoseUseOfDecl is
12786 // FIXME: This would be more comprehensively addressed by modifying
12787 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12789 if (Method != FoundDecl.getDecl() &&
12790 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12791 return ExprError();
12794 case OR_No_Viable_Function:
12795 Diag(UnresExpr->getMemberLoc(),
12796 diag::err_ovl_no_viable_member_function_in_call)
12797 << DeclName << MemExprE->getSourceRange();
12798 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12799 // FIXME: Leaking incoming expressions!
12800 return ExprError();
12803 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12804 << DeclName << MemExprE->getSourceRange();
12805 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12806 // FIXME: Leaking incoming expressions!
12807 return ExprError();
12810 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12811 << Best->Function->isDeleted()
12813 << getDeletedOrUnavailableSuffix(Best->Function)
12814 << MemExprE->getSourceRange();
12815 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12816 // FIXME: Leaking incoming expressions!
12817 return ExprError();
12820 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12822 // If overload resolution picked a static member, build a
12823 // non-member call based on that function.
12824 if (Method->isStatic()) {
12825 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12829 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12832 QualType ResultType = Method->getReturnType();
12833 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12834 ResultType = ResultType.getNonLValueExprType(Context);
12836 assert(Method && "Member call to something that isn't a method?");
12837 CXXMemberCallExpr *TheCall =
12838 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12839 ResultType, VK, RParenLoc);
12841 // Check for a valid return type.
12842 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12844 return ExprError();
12846 // Convert the object argument (for a non-static member function call).
12847 // We only need to do this if there was actually an overload; otherwise
12848 // it was done at lookup.
12849 if (!Method->isStatic()) {
12850 ExprResult ObjectArg =
12851 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12852 FoundDecl, Method);
12853 if (ObjectArg.isInvalid())
12854 return ExprError();
12855 MemExpr->setBase(ObjectArg.get());
12858 // Convert the rest of the arguments
12859 const FunctionProtoType *Proto =
12860 Method->getType()->getAs<FunctionProtoType>();
12861 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12863 return ExprError();
12865 DiagnoseSentinelCalls(Method, LParenLoc, Args);
12867 if (CheckFunctionCall(Method, TheCall, Proto))
12868 return ExprError();
12870 // In the case the method to call was not selected by the overloading
12871 // resolution process, we still need to handle the enable_if attribute. Do
12872 // that here, so it will not hide previous -- and more relevant -- errors.
12873 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12874 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12875 Diag(MemE->getMemberLoc(),
12876 diag::err_ovl_no_viable_member_function_in_call)
12877 << Method << Method->getSourceRange();
12878 Diag(Method->getLocation(),
12879 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12880 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12881 return ExprError();
12884 SmallVector<DiagnoseIfAttr *, 4> Nonfatal;
12885 if (const DiagnoseIfAttr *Attr = checkArgDependentDiagnoseIf(
12886 Method, Args, Nonfatal, false, MemE->getBase())) {
12887 emitDiagnoseIfDiagnostic(MemE->getMemberLoc(), Attr);
12888 return ExprError();
12891 for (const auto *Attr : Nonfatal)
12892 emitDiagnoseIfDiagnostic(MemE->getMemberLoc(), Attr);
12895 if ((isa<CXXConstructorDecl>(CurContext) ||
12896 isa<CXXDestructorDecl>(CurContext)) &&
12897 TheCall->getMethodDecl()->isPure()) {
12898 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12900 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12901 MemExpr->performsVirtualDispatch(getLangOpts())) {
12902 Diag(MemExpr->getLocStart(),
12903 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12904 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12905 << MD->getParent()->getDeclName();
12907 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12908 if (getLangOpts().AppleKext)
12909 Diag(MemExpr->getLocStart(),
12910 diag::note_pure_qualified_call_kext)
12911 << MD->getParent()->getDeclName()
12912 << MD->getDeclName();
12916 if (CXXDestructorDecl *DD =
12917 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12918 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12919 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12920 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12921 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12922 MemExpr->getMemberLoc());
12925 return MaybeBindToTemporary(TheCall);
12928 /// BuildCallToObjectOfClassType - Build a call to an object of class
12929 /// type (C++ [over.call.object]), which can end up invoking an
12930 /// overloaded function call operator (@c operator()) or performing a
12931 /// user-defined conversion on the object argument.
12933 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12934 SourceLocation LParenLoc,
12936 SourceLocation RParenLoc) {
12937 if (checkPlaceholderForOverload(*this, Obj))
12938 return ExprError();
12939 ExprResult Object = Obj;
12941 UnbridgedCastsSet UnbridgedCasts;
12942 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12943 return ExprError();
12945 assert(Object.get()->getType()->isRecordType() &&
12946 "Requires object type argument");
12947 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12949 // C++ [over.call.object]p1:
12950 // If the primary-expression E in the function call syntax
12951 // evaluates to a class object of type "cv T", then the set of
12952 // candidate functions includes at least the function call
12953 // operators of T. The function call operators of T are obtained by
12954 // ordinary lookup of the name operator() in the context of
12956 OverloadCandidateSet CandidateSet(LParenLoc,
12957 OverloadCandidateSet::CSK_Operator);
12958 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12960 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12961 diag::err_incomplete_object_call, Object.get()))
12964 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12965 LookupQualifiedName(R, Record->getDecl());
12966 R.suppressDiagnostics();
12968 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12969 Oper != OperEnd; ++Oper) {
12970 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12971 Object.get()->Classify(Context),
12972 Object.get(), Args, CandidateSet,
12973 /*SuppressUserConversions=*/ false);
12976 // C++ [over.call.object]p2:
12977 // In addition, for each (non-explicit in C++0x) conversion function
12978 // declared in T of the form
12980 // operator conversion-type-id () cv-qualifier;
12982 // where cv-qualifier is the same cv-qualification as, or a
12983 // greater cv-qualification than, cv, and where conversion-type-id
12984 // denotes the type "pointer to function of (P1,...,Pn) returning
12985 // R", or the type "reference to pointer to function of
12986 // (P1,...,Pn) returning R", or the type "reference to function
12987 // of (P1,...,Pn) returning R", a surrogate call function [...]
12988 // is also considered as a candidate function. Similarly,
12989 // surrogate call functions are added to the set of candidate
12990 // functions for each conversion function declared in an
12991 // accessible base class provided the function is not hidden
12992 // within T by another intervening declaration.
12993 const auto &Conversions =
12994 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12995 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12997 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12998 if (isa<UsingShadowDecl>(D))
12999 D = cast<UsingShadowDecl>(D)->getTargetDecl();
13001 // Skip over templated conversion functions; they aren't
13003 if (isa<FunctionTemplateDecl>(D))
13006 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13007 if (!Conv->isExplicit()) {
13008 // Strip the reference type (if any) and then the pointer type (if
13009 // any) to get down to what might be a function type.
13010 QualType ConvType = Conv->getConversionType().getNonReferenceType();
13011 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13012 ConvType = ConvPtrType->getPointeeType();
13014 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13016 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13017 Object.get(), Args, CandidateSet);
13022 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13024 // Perform overload resolution.
13025 OverloadCandidateSet::iterator Best;
13026 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13029 // Overload resolution succeeded; we'll build the appropriate call
13033 case OR_No_Viable_Function:
13034 if (CandidateSet.empty())
13035 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13036 << Object.get()->getType() << /*call*/ 1
13037 << Object.get()->getSourceRange();
13039 Diag(Object.get()->getLocStart(),
13040 diag::err_ovl_no_viable_object_call)
13041 << Object.get()->getType() << Object.get()->getSourceRange();
13042 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13046 Diag(Object.get()->getLocStart(),
13047 diag::err_ovl_ambiguous_object_call)
13048 << Object.get()->getType() << Object.get()->getSourceRange();
13049 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13053 Diag(Object.get()->getLocStart(),
13054 diag::err_ovl_deleted_object_call)
13055 << Best->Function->isDeleted()
13056 << Object.get()->getType()
13057 << getDeletedOrUnavailableSuffix(Best->Function)
13058 << Object.get()->getSourceRange();
13059 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13063 if (Best == CandidateSet.end())
13066 UnbridgedCasts.restore();
13068 if (Best->Function == nullptr) {
13069 // Since there is no function declaration, this is one of the
13070 // surrogate candidates. Dig out the conversion function.
13071 CXXConversionDecl *Conv
13072 = cast<CXXConversionDecl>(
13073 Best->Conversions[0].UserDefined.ConversionFunction);
13075 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13077 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13078 return ExprError();
13079 assert(Conv == Best->FoundDecl.getDecl() &&
13080 "Found Decl & conversion-to-functionptr should be same, right?!");
13081 // We selected one of the surrogate functions that converts the
13082 // object parameter to a function pointer. Perform the conversion
13083 // on the object argument, then let ActOnCallExpr finish the job.
13085 // Create an implicit member expr to refer to the conversion operator.
13086 // and then call it.
13087 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13088 Conv, HadMultipleCandidates);
13089 if (Call.isInvalid())
13090 return ExprError();
13091 // Record usage of conversion in an implicit cast.
13092 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13093 CK_UserDefinedConversion, Call.get(),
13094 nullptr, VK_RValue);
13096 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13099 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13101 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13102 // that calls this method, using Object for the implicit object
13103 // parameter and passing along the remaining arguments.
13104 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13106 // An error diagnostic has already been printed when parsing the declaration.
13107 if (Method->isInvalidDecl())
13108 return ExprError();
13110 const FunctionProtoType *Proto =
13111 Method->getType()->getAs<FunctionProtoType>();
13113 unsigned NumParams = Proto->getNumParams();
13115 DeclarationNameInfo OpLocInfo(
13116 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13117 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13118 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13119 HadMultipleCandidates,
13120 OpLocInfo.getLoc(),
13121 OpLocInfo.getInfo());
13122 if (NewFn.isInvalid())
13125 // Build the full argument list for the method call (the implicit object
13126 // parameter is placed at the beginning of the list).
13127 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13128 MethodArgs[0] = Object.get();
13129 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13131 // Once we've built TheCall, all of the expressions are properly
13133 QualType ResultTy = Method->getReturnType();
13134 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13135 ResultTy = ResultTy.getNonLValueExprType(Context);
13137 CXXOperatorCallExpr *TheCall = new (Context)
13138 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13139 VK, RParenLoc, false);
13141 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13144 // We may have default arguments. If so, we need to allocate more
13145 // slots in the call for them.
13146 if (Args.size() < NumParams)
13147 TheCall->setNumArgs(Context, NumParams + 1);
13149 bool IsError = false;
13151 // Initialize the implicit object parameter.
13152 ExprResult ObjRes =
13153 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13154 Best->FoundDecl, Method);
13155 if (ObjRes.isInvalid())
13159 TheCall->setArg(0, Object.get());
13161 // Check the argument types.
13162 for (unsigned i = 0; i != NumParams; i++) {
13164 if (i < Args.size()) {
13167 // Pass the argument.
13169 ExprResult InputInit
13170 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13172 Method->getParamDecl(i)),
13173 SourceLocation(), Arg);
13175 IsError |= InputInit.isInvalid();
13176 Arg = InputInit.getAs<Expr>();
13179 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13180 if (DefArg.isInvalid()) {
13185 Arg = DefArg.getAs<Expr>();
13188 TheCall->setArg(i + 1, Arg);
13191 // If this is a variadic call, handle args passed through "...".
13192 if (Proto->isVariadic()) {
13193 // Promote the arguments (C99 6.5.2.2p7).
13194 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13195 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13197 IsError |= Arg.isInvalid();
13198 TheCall->setArg(i + 1, Arg.get());
13202 if (IsError) return true;
13204 DiagnoseSentinelCalls(Method, LParenLoc, Args);
13206 if (CheckFunctionCall(Method, TheCall, Proto))
13209 return MaybeBindToTemporary(TheCall);
13212 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13213 /// (if one exists), where @c Base is an expression of class type and
13214 /// @c Member is the name of the member we're trying to find.
13216 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13217 bool *NoArrowOperatorFound) {
13218 assert(Base->getType()->isRecordType() &&
13219 "left-hand side must have class type");
13221 if (checkPlaceholderForOverload(*this, Base))
13222 return ExprError();
13224 SourceLocation Loc = Base->getExprLoc();
13226 // C++ [over.ref]p1:
13228 // [...] An expression x->m is interpreted as (x.operator->())->m
13229 // for a class object x of type T if T::operator->() exists and if
13230 // the operator is selected as the best match function by the
13231 // overload resolution mechanism (13.3).
13232 DeclarationName OpName =
13233 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13234 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13235 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13237 if (RequireCompleteType(Loc, Base->getType(),
13238 diag::err_typecheck_incomplete_tag, Base))
13239 return ExprError();
13241 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13242 LookupQualifiedName(R, BaseRecord->getDecl());
13243 R.suppressDiagnostics();
13245 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13246 Oper != OperEnd; ++Oper) {
13247 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13248 Base, None, CandidateSet,
13249 /*SuppressUserConversions=*/false);
13252 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13254 // Perform overload resolution.
13255 OverloadCandidateSet::iterator Best;
13256 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13258 // Overload resolution succeeded; we'll build the call below.
13261 case OR_No_Viable_Function:
13262 if (CandidateSet.empty()) {
13263 QualType BaseType = Base->getType();
13264 if (NoArrowOperatorFound) {
13265 // Report this specific error to the caller instead of emitting a
13266 // diagnostic, as requested.
13267 *NoArrowOperatorFound = true;
13268 return ExprError();
13270 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13271 << BaseType << Base->getSourceRange();
13272 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13273 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13274 << FixItHint::CreateReplacement(OpLoc, ".");
13277 Diag(OpLoc, diag::err_ovl_no_viable_oper)
13278 << "operator->" << Base->getSourceRange();
13279 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13280 return ExprError();
13283 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13284 << "->" << Base->getType() << Base->getSourceRange();
13285 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13286 return ExprError();
13289 Diag(OpLoc, diag::err_ovl_deleted_oper)
13290 << Best->Function->isDeleted()
13292 << getDeletedOrUnavailableSuffix(Best->Function)
13293 << Base->getSourceRange();
13294 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13295 return ExprError();
13298 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13300 // Convert the object parameter.
13301 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13302 ExprResult BaseResult =
13303 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13304 Best->FoundDecl, Method);
13305 if (BaseResult.isInvalid())
13306 return ExprError();
13307 Base = BaseResult.get();
13309 // Build the operator call.
13310 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13311 HadMultipleCandidates, OpLoc);
13312 if (FnExpr.isInvalid())
13313 return ExprError();
13315 QualType ResultTy = Method->getReturnType();
13316 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13317 ResultTy = ResultTy.getNonLValueExprType(Context);
13318 CXXOperatorCallExpr *TheCall =
13319 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13320 Base, ResultTy, VK, OpLoc, false);
13322 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13323 return ExprError();
13325 return MaybeBindToTemporary(TheCall);
13328 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13329 /// a literal operator described by the provided lookup results.
13330 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13331 DeclarationNameInfo &SuffixInfo,
13332 ArrayRef<Expr*> Args,
13333 SourceLocation LitEndLoc,
13334 TemplateArgumentListInfo *TemplateArgs) {
13335 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13337 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13338 OverloadCandidateSet::CSK_Normal);
13339 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13340 /*SuppressUserConversions=*/true);
13342 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13344 // Perform overload resolution. This will usually be trivial, but might need
13345 // to perform substitutions for a literal operator template.
13346 OverloadCandidateSet::iterator Best;
13347 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13352 case OR_No_Viable_Function:
13353 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13354 << R.getLookupName();
13355 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13356 return ExprError();
13359 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13360 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13361 return ExprError();
13364 FunctionDecl *FD = Best->Function;
13365 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13366 HadMultipleCandidates,
13367 SuffixInfo.getLoc(),
13368 SuffixInfo.getInfo());
13369 if (Fn.isInvalid())
13372 // Check the argument types. This should almost always be a no-op, except
13373 // that array-to-pointer decay is applied to string literals.
13375 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13376 ExprResult InputInit = PerformCopyInitialization(
13377 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13378 SourceLocation(), Args[ArgIdx]);
13379 if (InputInit.isInvalid())
13381 ConvArgs[ArgIdx] = InputInit.get();
13384 QualType ResultTy = FD->getReturnType();
13385 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13386 ResultTy = ResultTy.getNonLValueExprType(Context);
13388 UserDefinedLiteral *UDL =
13389 new (Context) UserDefinedLiteral(Context, Fn.get(),
13390 llvm::makeArrayRef(ConvArgs, Args.size()),
13391 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13393 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13394 return ExprError();
13396 if (CheckFunctionCall(FD, UDL, nullptr))
13397 return ExprError();
13399 return MaybeBindToTemporary(UDL);
13402 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13403 /// given LookupResult is non-empty, it is assumed to describe a member which
13404 /// will be invoked. Otherwise, the function will be found via argument
13405 /// dependent lookup.
13406 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13407 /// otherwise CallExpr is set to ExprError() and some non-success value
13409 Sema::ForRangeStatus
13410 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13411 SourceLocation RangeLoc,
13412 const DeclarationNameInfo &NameInfo,
13413 LookupResult &MemberLookup,
13414 OverloadCandidateSet *CandidateSet,
13415 Expr *Range, ExprResult *CallExpr) {
13416 Scope *S = nullptr;
13418 CandidateSet->clear();
13419 if (!MemberLookup.empty()) {
13420 ExprResult MemberRef =
13421 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13422 /*IsPtr=*/false, CXXScopeSpec(),
13423 /*TemplateKWLoc=*/SourceLocation(),
13424 /*FirstQualifierInScope=*/nullptr,
13426 /*TemplateArgs=*/nullptr, S);
13427 if (MemberRef.isInvalid()) {
13428 *CallExpr = ExprError();
13429 return FRS_DiagnosticIssued;
13431 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13432 if (CallExpr->isInvalid()) {
13433 *CallExpr = ExprError();
13434 return FRS_DiagnosticIssued;
13437 UnresolvedSet<0> FoundNames;
13438 UnresolvedLookupExpr *Fn =
13439 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13440 NestedNameSpecifierLoc(), NameInfo,
13441 /*NeedsADL=*/true, /*Overloaded=*/false,
13442 FoundNames.begin(), FoundNames.end());
13444 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13445 CandidateSet, CallExpr);
13446 if (CandidateSet->empty() || CandidateSetError) {
13447 *CallExpr = ExprError();
13448 return FRS_NoViableFunction;
13450 OverloadCandidateSet::iterator Best;
13451 OverloadingResult OverloadResult =
13452 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13454 if (OverloadResult == OR_No_Viable_Function) {
13455 *CallExpr = ExprError();
13456 return FRS_NoViableFunction;
13458 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13459 Loc, nullptr, CandidateSet, &Best,
13461 /*AllowTypoCorrection=*/false);
13462 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13463 *CallExpr = ExprError();
13464 return FRS_DiagnosticIssued;
13467 return FRS_Success;
13471 /// FixOverloadedFunctionReference - E is an expression that refers to
13472 /// a C++ overloaded function (possibly with some parentheses and
13473 /// perhaps a '&' around it). We have resolved the overloaded function
13474 /// to the function declaration Fn, so patch up the expression E to
13475 /// refer (possibly indirectly) to Fn. Returns the new expr.
13476 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13477 FunctionDecl *Fn) {
13478 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13479 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13481 if (SubExpr == PE->getSubExpr())
13484 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13487 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13488 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13490 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13491 SubExpr->getType()) &&
13492 "Implicit cast type cannot be determined from overload");
13493 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13494 if (SubExpr == ICE->getSubExpr())
13497 return ImplicitCastExpr::Create(Context, ICE->getType(),
13498 ICE->getCastKind(),
13500 ICE->getValueKind());
13503 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13504 if (!GSE->isResultDependent()) {
13506 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13507 if (SubExpr == GSE->getResultExpr())
13510 // Replace the resulting type information before rebuilding the generic
13511 // selection expression.
13512 ArrayRef<Expr *> A = GSE->getAssocExprs();
13513 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13514 unsigned ResultIdx = GSE->getResultIndex();
13515 AssocExprs[ResultIdx] = SubExpr;
13517 return new (Context) GenericSelectionExpr(
13518 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13519 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13520 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13523 // Rather than fall through to the unreachable, return the original generic
13524 // selection expression.
13528 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13529 assert(UnOp->getOpcode() == UO_AddrOf &&
13530 "Can only take the address of an overloaded function");
13531 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13532 if (Method->isStatic()) {
13533 // Do nothing: static member functions aren't any different
13534 // from non-member functions.
13536 // Fix the subexpression, which really has to be an
13537 // UnresolvedLookupExpr holding an overloaded member function
13539 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13541 if (SubExpr == UnOp->getSubExpr())
13544 assert(isa<DeclRefExpr>(SubExpr)
13545 && "fixed to something other than a decl ref");
13546 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13547 && "fixed to a member ref with no nested name qualifier");
13549 // We have taken the address of a pointer to member
13550 // function. Perform the computation here so that we get the
13551 // appropriate pointer to member type.
13553 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13554 QualType MemPtrType
13555 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13556 // Under the MS ABI, lock down the inheritance model now.
13557 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13558 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13560 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13561 VK_RValue, OK_Ordinary,
13562 UnOp->getOperatorLoc());
13565 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13567 if (SubExpr == UnOp->getSubExpr())
13570 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13571 Context.getPointerType(SubExpr->getType()),
13572 VK_RValue, OK_Ordinary,
13573 UnOp->getOperatorLoc());
13576 // C++ [except.spec]p17:
13577 // An exception-specification is considered to be needed when:
13578 // - in an expression the function is the unique lookup result or the
13579 // selected member of a set of overloaded functions
13580 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13581 ResolveExceptionSpec(E->getExprLoc(), FPT);
13583 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13584 // FIXME: avoid copy.
13585 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13586 if (ULE->hasExplicitTemplateArgs()) {
13587 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13588 TemplateArgs = &TemplateArgsBuffer;
13591 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13592 ULE->getQualifierLoc(),
13593 ULE->getTemplateKeywordLoc(),
13595 /*enclosing*/ false, // FIXME?
13601 MarkDeclRefReferenced(DRE);
13602 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13606 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13607 // FIXME: avoid copy.
13608 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13609 if (MemExpr->hasExplicitTemplateArgs()) {
13610 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13611 TemplateArgs = &TemplateArgsBuffer;
13616 // If we're filling in a static method where we used to have an
13617 // implicit member access, rewrite to a simple decl ref.
13618 if (MemExpr->isImplicitAccess()) {
13619 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13620 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13621 MemExpr->getQualifierLoc(),
13622 MemExpr->getTemplateKeywordLoc(),
13624 /*enclosing*/ false,
13625 MemExpr->getMemberLoc(),
13630 MarkDeclRefReferenced(DRE);
13631 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13634 SourceLocation Loc = MemExpr->getMemberLoc();
13635 if (MemExpr->getQualifier())
13636 Loc = MemExpr->getQualifierLoc().getBeginLoc();
13637 CheckCXXThisCapture(Loc);
13638 Base = new (Context) CXXThisExpr(Loc,
13639 MemExpr->getBaseType(),
13640 /*isImplicit=*/true);
13643 Base = MemExpr->getBase();
13645 ExprValueKind valueKind;
13647 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13648 valueKind = VK_LValue;
13649 type = Fn->getType();
13651 valueKind = VK_RValue;
13652 type = Context.BoundMemberTy;
13655 MemberExpr *ME = MemberExpr::Create(
13656 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13657 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13658 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13660 ME->setHadMultipleCandidates(true);
13661 MarkMemberReferenced(ME);
13665 llvm_unreachable("Invalid reference to overloaded function");
13668 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13669 DeclAccessPair Found,
13670 FunctionDecl *Fn) {
13671 return FixOverloadedFunctionReference(E.get(), Found, Fn);