clang  15.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Overload.h"
30 #include "clang/Sema/Template.h"
32 #include "llvm/ADT/DenseSet.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include <algorithm>
38 #include <cstdlib>
39 
40 using namespace clang;
41 using namespace sema;
42 
44 
46  return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
47  return P->hasAttr<PassObjectSizeAttr>();
48  });
49 }
50 
51 /// A convenience routine for creating a decayed reference to a function.
53  Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
54  bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
55  const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
56  if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
57  return ExprError();
58  // If FoundDecl is different from Fn (such as if one is a template
59  // and the other a specialization), make sure DiagnoseUseOfDecl is
60  // called on both.
61  // FIXME: This would be more comprehensively addressed by modifying
62  // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
63  // being used.
64  if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
65  return ExprError();
66  DeclRefExpr *DRE = new (S.Context)
67  DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
68  if (HadMultipleCandidates)
69  DRE->setHadMultipleCandidates(true);
70 
72  if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
73  if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
74  S.ResolveExceptionSpec(Loc, FPT);
75  DRE->setType(Fn->getType());
76  }
77  }
78  return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
79  CK_FunctionToPointerDecay);
80 }
81 
82 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
83  bool InOverloadResolution,
85  bool CStyle,
86  bool AllowObjCWritebackConversion);
87 
88 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
89  QualType &ToType,
90  bool InOverloadResolution,
92  bool CStyle);
93 static OverloadingResult
94 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
96  OverloadCandidateSet& Conversions,
97  AllowedExplicit AllowExplicit,
98  bool AllowObjCConversionOnExplicit);
99 
102  const StandardConversionSequence& SCS1,
103  const StandardConversionSequence& SCS2);
104 
107  const StandardConversionSequence& SCS1,
108  const StandardConversionSequence& SCS2);
109 
112  const StandardConversionSequence& SCS1,
113  const StandardConversionSequence& SCS2);
114 
115 /// GetConversionRank - Retrieve the implicit conversion rank
116 /// corresponding to the given implicit conversion kind.
118  static const ImplicitConversionRank
119  Rank[(int)ICK_Num_Conversion_Kinds] = {
145  ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
146  // it was omitted by the patch that added
147  // ICK_Zero_Event_Conversion
150  };
151  return Rank[(int)Kind];
152 }
153 
154 /// GetImplicitConversionName - Return the name of this kind of
155 /// implicit conversion.
157  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
158  "No conversion",
159  "Lvalue-to-rvalue",
160  "Array-to-pointer",
161  "Function-to-pointer",
162  "Function pointer conversion",
163  "Qualification",
164  "Integral promotion",
165  "Floating point promotion",
166  "Complex promotion",
167  "Integral conversion",
168  "Floating conversion",
169  "Complex conversion",
170  "Floating-integral conversion",
171  "Pointer conversion",
172  "Pointer-to-member conversion",
173  "Boolean conversion",
174  "Compatible-types conversion",
175  "Derived-to-base conversion",
176  "Vector conversion",
177  "SVE Vector conversion",
178  "Vector splat",
179  "Complex-real conversion",
180  "Block Pointer conversion",
181  "Transparent Union Conversion",
182  "Writeback conversion",
183  "OpenCL Zero Event Conversion",
184  "C specific type conversion",
185  "Incompatible pointer conversion"
186  };
187  return Name[Kind];
188 }
189 
190 /// StandardConversionSequence - Set the standard conversion
191 /// sequence to the identity conversion.
194  Second = ICK_Identity;
195  Third = ICK_Identity;
196  DeprecatedStringLiteralToCharPtr = false;
197  QualificationIncludesObjCLifetime = false;
198  ReferenceBinding = false;
199  DirectBinding = false;
200  IsLvalueReference = true;
201  BindsToFunctionLvalue = false;
202  BindsToRvalue = false;
203  BindsImplicitObjectArgumentWithoutRefQualifier = false;
204  ObjCLifetimeConversionBinding = false;
205  CopyConstructor = nullptr;
206 }
207 
208 /// getRank - Retrieve the rank of this standard conversion sequence
209 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
210 /// implicit conversions.
213  if (GetConversionRank(First) > Rank)
214  Rank = GetConversionRank(First);
215  if (GetConversionRank(Second) > Rank)
216  Rank = GetConversionRank(Second);
217  if (GetConversionRank(Third) > Rank)
218  Rank = GetConversionRank(Third);
219  return Rank;
220 }
221 
222 /// isPointerConversionToBool - Determines whether this conversion is
223 /// a conversion of a pointer or pointer-to-member to bool. This is
224 /// used as part of the ranking of standard conversion sequences
225 /// (C++ 13.3.3.2p4).
227  // Note that FromType has not necessarily been transformed by the
228  // array-to-pointer or function-to-pointer implicit conversions, so
229  // check for their presence as well as checking whether FromType is
230  // a pointer.
231  if (getToType(1)->isBooleanType() &&
232  (getFromType()->isPointerType() ||
233  getFromType()->isMemberPointerType() ||
234  getFromType()->isObjCObjectPointerType() ||
235  getFromType()->isBlockPointerType() ||
237  return true;
238 
239  return false;
240 }
241 
242 /// isPointerConversionToVoidPointer - Determines whether this
243 /// conversion is a conversion of a pointer to a void pointer. This is
244 /// used as part of the ranking of standard conversion sequences (C++
245 /// 13.3.3.2p4).
246 bool
249  QualType FromType = getFromType();
250  QualType ToType = getToType(1);
251 
252  // Note that FromType has not necessarily been transformed by the
253  // array-to-pointer implicit conversion, so check for its presence
254  // and redo the conversion to get a pointer.
256  FromType = Context.getArrayDecayedType(FromType);
257 
258  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
259  if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
260  return ToPtrType->getPointeeType()->isVoidType();
261 
262  return false;
263 }
264 
265 /// Skip any implicit casts which could be either part of a narrowing conversion
266 /// or after one in an implicit conversion.
268  const Expr *Converted) {
269  // We can have cleanups wrapping the converted expression; these need to be
270  // preserved so that destructors run if necessary.
271  if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
272  Expr *Inner =
273  const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
274  return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
275  EWC->getObjects());
276  }
277 
278  while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
279  switch (ICE->getCastKind()) {
280  case CK_NoOp:
281  case CK_IntegralCast:
282  case CK_IntegralToBoolean:
283  case CK_IntegralToFloating:
284  case CK_BooleanToSignedIntegral:
285  case CK_FloatingToIntegral:
286  case CK_FloatingToBoolean:
287  case CK_FloatingCast:
288  Converted = ICE->getSubExpr();
289  continue;
290 
291  default:
292  return Converted;
293  }
294  }
295 
296  return Converted;
297 }
298 
299 /// Check if this standard conversion sequence represents a narrowing
300 /// conversion, according to C++11 [dcl.init.list]p7.
301 ///
302 /// \param Ctx The AST context.
303 /// \param Converted The result of applying this standard conversion sequence.
304 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
305 /// value of the expression prior to the narrowing conversion.
306 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
307 /// type of the expression prior to the narrowing conversion.
308 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
309 /// from floating point types to integral types should be ignored.
311  ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
312  QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
313  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
314 
315  // C++11 [dcl.init.list]p7:
316  // A narrowing conversion is an implicit conversion ...
317  QualType FromType = getToType(0);
318  QualType ToType = getToType(1);
319 
320  // A conversion to an enumeration type is narrowing if the conversion to
321  // the underlying type is narrowing. This only arises for expressions of
322  // the form 'Enum{init}'.
323  if (auto *ET = ToType->getAs<EnumType>())
324  ToType = ET->getDecl()->getIntegerType();
325 
326  switch (Second) {
327  // 'bool' is an integral type; dispatch to the right place to handle it.
329  if (FromType->isRealFloatingType())
330  goto FloatingIntegralConversion;
331  if (FromType->isIntegralOrUnscopedEnumerationType())
332  goto IntegralConversion;
333  // -- from a pointer type or pointer-to-member type to bool, or
334  return NK_Type_Narrowing;
335 
336  // -- from a floating-point type to an integer type, or
337  //
338  // -- from an integer type or unscoped enumeration type to a floating-point
339  // type, except where the source is a constant expression and the actual
340  // value after conversion will fit into the target type and will produce
341  // the original value when converted back to the original type, or
343  FloatingIntegralConversion:
344  if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
345  return NK_Type_Narrowing;
346  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
347  ToType->isRealFloatingType()) {
348  if (IgnoreFloatToIntegralConversion)
349  return NK_Not_Narrowing;
350  const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
351  assert(Initializer && "Unknown conversion expression");
352 
353  // If it's value-dependent, we can't tell whether it's narrowing.
354  if (Initializer->isValueDependent())
355  return NK_Dependent_Narrowing;
356 
357  if (Optional<llvm::APSInt> IntConstantValue =
358  Initializer->getIntegerConstantExpr(Ctx)) {
359  // Convert the integer to the floating type.
360  llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
361  Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
362  llvm::APFloat::rmNearestTiesToEven);
363  // And back.
364  llvm::APSInt ConvertedValue = *IntConstantValue;
365  bool ignored;
366  Result.convertToInteger(ConvertedValue,
367  llvm::APFloat::rmTowardZero, &ignored);
368  // If the resulting value is different, this was a narrowing conversion.
369  if (*IntConstantValue != ConvertedValue) {
370  ConstantValue = APValue(*IntConstantValue);
371  ConstantType = Initializer->getType();
372  return NK_Constant_Narrowing;
373  }
374  } else {
375  // Variables are always narrowings.
376  return NK_Variable_Narrowing;
377  }
378  }
379  return NK_Not_Narrowing;
380 
381  // -- from long double to double or float, or from double to float, except
382  // where the source is a constant expression and the actual value after
383  // conversion is within the range of values that can be represented (even
384  // if it cannot be represented exactly), or
386  if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
387  Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
388  // FromType is larger than ToType.
389  const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
390 
391  // If it's value-dependent, we can't tell whether it's narrowing.
392  if (Initializer->isValueDependent())
393  return NK_Dependent_Narrowing;
394 
395  if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
396  // Constant!
397  assert(ConstantValue.isFloat());
398  llvm::APFloat FloatVal = ConstantValue.getFloat();
399  // Convert the source value into the target type.
400  bool ignored;
401  llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
402  Ctx.getFloatTypeSemantics(ToType),
403  llvm::APFloat::rmNearestTiesToEven, &ignored);
404  // If there was no overflow, the source value is within the range of
405  // values that can be represented.
406  if (ConvertStatus & llvm::APFloat::opOverflow) {
407  ConstantType = Initializer->getType();
408  return NK_Constant_Narrowing;
409  }
410  } else {
411  return NK_Variable_Narrowing;
412  }
413  }
414  return NK_Not_Narrowing;
415 
416  // -- from an integer type or unscoped enumeration type to an integer type
417  // that cannot represent all the values of the original type, except where
418  // the source is a constant expression and the actual value after
419  // conversion will fit into the target type and will produce the original
420  // value when converted back to the original type.
422  IntegralConversion: {
423  assert(FromType->isIntegralOrUnscopedEnumerationType());
424  assert(ToType->isIntegralOrUnscopedEnumerationType());
425  const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
426  const unsigned FromWidth = Ctx.getIntWidth(FromType);
427  const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
428  const unsigned ToWidth = Ctx.getIntWidth(ToType);
429 
430  if (FromWidth > ToWidth ||
431  (FromWidth == ToWidth && FromSigned != ToSigned) ||
432  (FromSigned && !ToSigned)) {
433  // Not all values of FromType can be represented in ToType.
434  const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
435 
436  // If it's value-dependent, we can't tell whether it's narrowing.
437  if (Initializer->isValueDependent())
438  return NK_Dependent_Narrowing;
439 
440  Optional<llvm::APSInt> OptInitializerValue;
441  if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
442  // Such conversions on variables are always narrowing.
443  return NK_Variable_Narrowing;
444  }
445  llvm::APSInt &InitializerValue = *OptInitializerValue;
446  bool Narrowing = false;
447  if (FromWidth < ToWidth) {
448  // Negative -> unsigned is narrowing. Otherwise, more bits is never
449  // narrowing.
450  if (InitializerValue.isSigned() && InitializerValue.isNegative())
451  Narrowing = true;
452  } else {
453  // Add a bit to the InitializerValue so we don't have to worry about
454  // signed vs. unsigned comparisons.
455  InitializerValue = InitializerValue.extend(
456  InitializerValue.getBitWidth() + 1);
457  // Convert the initializer to and from the target width and signed-ness.
458  llvm::APSInt ConvertedValue = InitializerValue;
459  ConvertedValue = ConvertedValue.trunc(ToWidth);
460  ConvertedValue.setIsSigned(ToSigned);
461  ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
462  ConvertedValue.setIsSigned(InitializerValue.isSigned());
463  // If the result is different, this was a narrowing conversion.
464  if (ConvertedValue != InitializerValue)
465  Narrowing = true;
466  }
467  if (Narrowing) {
468  ConstantType = Initializer->getType();
469  ConstantValue = APValue(InitializerValue);
470  return NK_Constant_Narrowing;
471  }
472  }
473  return NK_Not_Narrowing;
474  }
475 
476  default:
477  // Other kinds of conversions are not narrowings.
478  return NK_Not_Narrowing;
479  }
480 }
481 
482 /// dump - Print this standard conversion sequence to standard
483 /// error. Useful for debugging overloading issues.
484 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
485  raw_ostream &OS = llvm::errs();
486  bool PrintedSomething = false;
487  if (First != ICK_Identity) {
489  PrintedSomething = true;
490  }
491 
492  if (Second != ICK_Identity) {
493  if (PrintedSomething) {
494  OS << " -> ";
495  }
496  OS << GetImplicitConversionName(Second);
497 
498  if (CopyConstructor) {
499  OS << " (by copy constructor)";
500  } else if (DirectBinding) {
501  OS << " (direct reference binding)";
502  } else if (ReferenceBinding) {
503  OS << " (reference binding)";
504  }
505  PrintedSomething = true;
506  }
507 
508  if (Third != ICK_Identity) {
509  if (PrintedSomething) {
510  OS << " -> ";
511  }
512  OS << GetImplicitConversionName(Third);
513  PrintedSomething = true;
514  }
515 
516  if (!PrintedSomething) {
517  OS << "No conversions required";
518  }
519 }
520 
521 /// dump - Print this user-defined conversion sequence to standard
522 /// error. Useful for debugging overloading issues.
524  raw_ostream &OS = llvm::errs();
525  if (Before.First || Before.Second || Before.Third) {
526  Before.dump();
527  OS << " -> ";
528  }
529  if (ConversionFunction)
530  OS << '\'' << *ConversionFunction << '\'';
531  else
532  OS << "aggregate initialization";
533  if (After.First || After.Second || After.Third) {
534  OS << " -> ";
535  After.dump();
536  }
537 }
538 
539 /// dump - Print this implicit conversion sequence to standard
540 /// error. Useful for debugging overloading issues.
542  raw_ostream &OS = llvm::errs();
543  if (hasInitializerListContainerType())
544  OS << "Worst list element conversion: ";
545  switch (ConversionKind) {
546  case StandardConversion:
547  OS << "Standard conversion: ";
548  Standard.dump();
549  break;
550  case UserDefinedConversion:
551  OS << "User-defined conversion: ";
552  UserDefined.dump();
553  break;
554  case EllipsisConversion:
555  OS << "Ellipsis conversion";
556  break;
557  case AmbiguousConversion:
558  OS << "Ambiguous conversion";
559  break;
560  case BadConversion:
561  OS << "Bad conversion";
562  break;
563  }
564 
565  OS << "\n";
566 }
567 
569  new (&conversions()) ConversionSet();
570 }
571 
573  conversions().~ConversionSet();
574 }
575 
576 void
578  FromTypePtr = O.FromTypePtr;
579  ToTypePtr = O.ToTypePtr;
580  new (&conversions()) ConversionSet(O.conversions());
581 }
582 
583 namespace {
584  // Structure used by DeductionFailureInfo to store
585  // template argument information.
586  struct DFIArguments {
587  TemplateArgument FirstArg;
588  TemplateArgument SecondArg;
589  };
590  // Structure used by DeductionFailureInfo to store
591  // template parameter and template argument information.
592  struct DFIParamWithArguments : DFIArguments {
593  TemplateParameter Param;
594  };
595  // Structure used by DeductionFailureInfo to store template argument
596  // information and the index of the problematic call argument.
597  struct DFIDeducedMismatchArgs : DFIArguments {
598  TemplateArgumentList *TemplateArgs;
599  unsigned CallArgIndex;
600  };
601  // Structure used by DeductionFailureInfo to store information about
602  // unsatisfied constraints.
603  struct CNSInfo {
604  TemplateArgumentList *TemplateArgs;
605  ConstraintSatisfaction Satisfaction;
606  };
607 }
608 
609 /// Convert from Sema's representation of template deduction information
610 /// to the form used in overload-candidate information.
614  TemplateDeductionInfo &Info) {
615  DeductionFailureInfo Result;
616  Result.Result = static_cast<unsigned>(TDK);
617  Result.HasDiagnostic = false;
618  switch (TDK) {
619  case Sema::TDK_Invalid:
625  Result.Data = nullptr;
626  break;
627 
630  Result.Data = Info.Param.getOpaqueValue();
631  break;
632 
635  // FIXME: Should allocate from normal heap so that we can free this later.
636  auto *Saved = new (Context) DFIDeducedMismatchArgs;
637  Saved->FirstArg = Info.FirstArg;
638  Saved->SecondArg = Info.SecondArg;
639  Saved->TemplateArgs = Info.take();
640  Saved->CallArgIndex = Info.CallArgIndex;
641  Result.Data = Saved;
642  break;
643  }
644 
646  // FIXME: Should allocate from normal heap so that we can free this later.
647  DFIArguments *Saved = new (Context) DFIArguments;
648  Saved->FirstArg = Info.FirstArg;
649  Saved->SecondArg = Info.SecondArg;
650  Result.Data = Saved;
651  break;
652  }
653 
655  // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
658  // FIXME: Should allocate from normal heap so that we can free this later.
659  DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
660  Saved->Param = Info.Param;
661  Saved->FirstArg = Info.FirstArg;
662  Saved->SecondArg = Info.SecondArg;
663  Result.Data = Saved;
664  break;
665  }
666 
668  Result.Data = Info.take();
669  if (Info.hasSFINAEDiagnostic()) {
670  PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
672  Info.takeSFINAEDiagnostic(*Diag);
673  Result.HasDiagnostic = true;
674  }
675  break;
676 
678  CNSInfo *Saved = new (Context) CNSInfo;
679  Saved->TemplateArgs = Info.take();
680  Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
681  Result.Data = Saved;
682  break;
683  }
684 
685  case Sema::TDK_Success:
687  llvm_unreachable("not a deduction failure");
688  }
689 
690  return Result;
691 }
692 
694  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695  case Sema::TDK_Success:
696  case Sema::TDK_Invalid:
704  break;
705 
712  // FIXME: Destroy the data?
713  Data = nullptr;
714  break;
715 
717  // FIXME: Destroy the template argument list?
718  Data = nullptr;
719  if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
720  Diag->~PartialDiagnosticAt();
721  HasDiagnostic = false;
722  }
723  break;
724 
726  // FIXME: Destroy the template argument list?
727  Data = nullptr;
728  if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
729  Diag->~PartialDiagnosticAt();
730  HasDiagnostic = false;
731  }
732  break;
733 
734  // Unhandled
736  break;
737  }
738 }
739 
741  if (HasDiagnostic)
742  return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
743  return nullptr;
744 }
745 
747  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
748  case Sema::TDK_Success:
749  case Sema::TDK_Invalid:
760  return TemplateParameter();
761 
764  return TemplateParameter::getFromOpaqueValue(Data);
765 
769  return static_cast<DFIParamWithArguments*>(Data)->Param;
770 
771  // Unhandled
773  break;
774  }
775 
776  return TemplateParameter();
777 }
778 
780  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
781  case Sema::TDK_Success:
782  case Sema::TDK_Invalid:
794  return nullptr;
795 
798  return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
799 
801  return static_cast<TemplateArgumentList*>(Data);
802 
804  return static_cast<CNSInfo*>(Data)->TemplateArgs;
805 
806  // Unhandled
808  break;
809  }
810 
811  return nullptr;
812 }
813 
815  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
816  case Sema::TDK_Success:
817  case Sema::TDK_Invalid:
827  return nullptr;
828 
835  return &static_cast<DFIArguments*>(Data)->FirstArg;
836 
837  // Unhandled
839  break;
840  }
841 
842  return nullptr;
843 }
844 
846  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
847  case Sema::TDK_Success:
848  case Sema::TDK_Invalid:
859  return nullptr;
860 
866  return &static_cast<DFIArguments*>(Data)->SecondArg;
867 
868  // Unhandled
870  break;
871  }
872 
873  return nullptr;
874 }
875 
877  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
880  return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
881 
882  default:
883  return llvm::None;
884  }
885 }
886 
889  if (!AllowRewrittenCandidates)
890  return false;
891  return Op == OO_EqualEqual || Op == OO_Spaceship;
892 }
893 
895  ASTContext &Ctx, const FunctionDecl *FD) {
896  if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
897  return false;
898  // Don't bother adding a reversed candidate that can never be a better
899  // match than the non-reversed version.
900  return FD->getNumParams() != 2 ||
902  FD->getParamDecl(1)->getType()) ||
903  FD->hasAttr<EnableIfAttr>();
904 }
905 
906 void OverloadCandidateSet::destroyCandidates() {
907  for (iterator i = begin(), e = end(); i != e; ++i) {
908  for (auto &C : i->Conversions)
909  C.~ImplicitConversionSequence();
910  if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
911  i->DeductionFailure.Destroy();
912  }
913 }
914 
916  destroyCandidates();
917  SlabAllocator.Reset();
918  NumInlineBytesUsed = 0;
919  Candidates.clear();
920  Functions.clear();
921  Kind = CSK;
922 }
923 
924 namespace {
925  class UnbridgedCastsSet {
926  struct Entry {
927  Expr **Addr;
928  Expr *Saved;
929  };
930  SmallVector<Entry, 2> Entries;
931 
932  public:
933  void save(Sema &S, Expr *&E) {
934  assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
935  Entry entry = { &E, E };
936  Entries.push_back(entry);
937  E = S.stripARCUnbridgedCast(E);
938  }
939 
940  void restore() {
942  i = Entries.begin(), e = Entries.end(); i != e; ++i)
943  *i->Addr = i->Saved;
944  }
945  };
946 }
947 
948 /// checkPlaceholderForOverload - Do any interesting placeholder-like
949 /// preprocessing on the given expression.
950 ///
951 /// \param unbridgedCasts a collection to which to add unbridged casts;
952 /// without this, they will be immediately diagnosed as errors
953 ///
954 /// Return true on unrecoverable error.
955 static bool
957  UnbridgedCastsSet *unbridgedCasts = nullptr) {
958  if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
959  // We can't handle overloaded expressions here because overload
960  // resolution might reasonably tweak them.
961  if (placeholder->getKind() == BuiltinType::Overload) return false;
962 
963  // If the context potentially accepts unbridged ARC casts, strip
964  // the unbridged cast and add it to the collection for later restoration.
965  if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
966  unbridgedCasts) {
967  unbridgedCasts->save(S, E);
968  return false;
969  }
970 
971  // Go ahead and check everything else.
972  ExprResult result = S.CheckPlaceholderExpr(E);
973  if (result.isInvalid())
974  return true;
975 
976  E = result.get();
977  return false;
978  }
979 
980  // Nothing to do.
981  return false;
982 }
983 
984 /// checkArgPlaceholdersForOverload - Check a set of call operands for
985 /// placeholders.
987  UnbridgedCastsSet &unbridged) {
988  for (unsigned i = 0, e = Args.size(); i != e; ++i)
989  if (checkPlaceholderForOverload(S, Args[i], &unbridged))
990  return true;
991 
992  return false;
993 }
994 
995 /// Determine whether the given New declaration is an overload of the
996 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
997 /// New and Old cannot be overloaded, e.g., if New has the same signature as
998 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
999 /// functions (or function templates) at all. When it does return Ovl_Match or
1000 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1001 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1002 /// declaration.
1003 ///
1004 /// Example: Given the following input:
1005 ///
1006 /// void f(int, float); // #1
1007 /// void f(int, int); // #2
1008 /// int f(int, int); // #3
1009 ///
1010 /// When we process #1, there is no previous declaration of "f", so IsOverload
1011 /// will not be used.
1012 ///
1013 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1014 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1015 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1016 /// unchanged.
1017 ///
1018 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1019 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1020 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1021 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1022 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1023 ///
1024 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1025 /// by a using declaration. The rules for whether to hide shadow declarations
1026 /// ignore some properties which otherwise figure into a function template's
1027 /// signature.
1030  NamedDecl *&Match, bool NewIsUsingDecl) {
1031  for (LookupResult::iterator I = Old.begin(), E = Old.end();
1032  I != E; ++I) {
1033  NamedDecl *OldD = *I;
1034 
1035  bool OldIsUsingDecl = false;
1036  if (isa<UsingShadowDecl>(OldD)) {
1037  OldIsUsingDecl = true;
1038 
1039  // We can always introduce two using declarations into the same
1040  // context, even if they have identical signatures.
1041  if (NewIsUsingDecl) continue;
1042 
1043  OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1044  }
1045 
1046  // A using-declaration does not conflict with another declaration
1047  // if one of them is hidden.
1048  if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1049  continue;
1050 
1051  // If either declaration was introduced by a using declaration,
1052  // we'll need to use slightly different rules for matching.
1053  // Essentially, these rules are the normal rules, except that
1054  // function templates hide function templates with different
1055  // return types or template parameter lists.
1056  bool UseMemberUsingDeclRules =
1057  (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1058  !New->getFriendObjectKind();
1059 
1060  if (FunctionDecl *OldF = OldD->getAsFunction()) {
1061  if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1062  if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1063  HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1064  continue;
1065  }
1066 
1067  if (!isa<FunctionTemplateDecl>(OldD) &&
1068  !shouldLinkPossiblyHiddenDecl(*I, New))
1069  continue;
1070 
1071  Match = *I;
1072  return Ovl_Match;
1073  }
1074 
1075  // Builtins that have custom typechecking or have a reference should
1076  // not be overloadable or redeclarable.
1077  if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1078  Match = *I;
1079  return Ovl_NonFunction;
1080  }
1081  } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1082  // We can overload with these, which can show up when doing
1083  // redeclaration checks for UsingDecls.
1084  assert(Old.getLookupKind() == LookupUsingDeclName);
1085  } else if (isa<TagDecl>(OldD)) {
1086  // We can always overload with tags by hiding them.
1087  } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1088  // Optimistically assume that an unresolved using decl will
1089  // overload; if it doesn't, we'll have to diagnose during
1090  // template instantiation.
1091  //
1092  // Exception: if the scope is dependent and this is not a class
1093  // member, the using declaration can only introduce an enumerator.
1094  if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1095  Match = *I;
1096  return Ovl_NonFunction;
1097  }
1098  } else {
1099  // (C++ 13p1):
1100  // Only function declarations can be overloaded; object and type
1101  // declarations cannot be overloaded.
1102  Match = *I;
1103  return Ovl_NonFunction;
1104  }
1105  }
1106 
1107  // C++ [temp.friend]p1:
1108  // For a friend function declaration that is not a template declaration:
1109  // -- if the name of the friend is a qualified or unqualified template-id,
1110  // [...], otherwise
1111  // -- if the name of the friend is a qualified-id and a matching
1112  // non-template function is found in the specified class or namespace,
1113  // the friend declaration refers to that function, otherwise,
1114  // -- if the name of the friend is a qualified-id and a matching function
1115  // template is found in the specified class or namespace, the friend
1116  // declaration refers to the deduced specialization of that function
1117  // template, otherwise
1118  // -- the name shall be an unqualified-id [...]
1119  // If we get here for a qualified friend declaration, we've just reached the
1120  // third bullet. If the type of the friend is dependent, skip this lookup
1121  // until instantiation.
1122  if (New->getFriendObjectKind() && New->getQualifier() &&
1123  !New->getDescribedFunctionTemplate() &&
1125  !New->getType()->isDependentType()) {
1126  LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1127  TemplateSpecResult.addAllDecls(Old);
1128  if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1129  /*QualifiedFriend*/true)) {
1130  New->setInvalidDecl();
1131  return Ovl_Overload;
1132  }
1133 
1134  Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1135  return Ovl_Match;
1136  }
1137 
1138  return Ovl_Overload;
1139 }
1140 
1142  bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1143  bool ConsiderRequiresClauses) {
1144  // C++ [basic.start.main]p2: This function shall not be overloaded.
1145  if (New->isMain())
1146  return false;
1147 
1148  // MSVCRT user defined entry points cannot be overloaded.
1149  if (New->isMSVCRTEntryPoint())
1150  return false;
1151 
1152  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1153  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1154 
1155  // C++ [temp.fct]p2:
1156  // A function template can be overloaded with other function templates
1157  // and with normal (non-template) functions.
1158  if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1159  return true;
1160 
1161  // Is the function New an overload of the function Old?
1162  QualType OldQType = Context.getCanonicalType(Old->getType());
1163  QualType NewQType = Context.getCanonicalType(New->getType());
1164 
1165  // Compare the signatures (C++ 1.3.10) of the two functions to
1166  // determine whether they are overloads. If we find any mismatch
1167  // in the signature, they are overloads.
1168 
1169  // If either of these functions is a K&R-style function (no
1170  // prototype), then we consider them to have matching signatures.
1171  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1172  isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1173  return false;
1174 
1175  const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1176  const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1177 
1178  // The signature of a function includes the types of its
1179  // parameters (C++ 1.3.10), which includes the presence or absence
1180  // of the ellipsis; see C++ DR 357).
1181  if (OldQType != NewQType &&
1182  (OldType->getNumParams() != NewType->getNumParams() ||
1183  OldType->isVariadic() != NewType->isVariadic() ||
1184  !FunctionParamTypesAreEqual(OldType, NewType)))
1185  return true;
1186 
1187  // C++ [temp.over.link]p4:
1188  // The signature of a function template consists of its function
1189  // signature, its return type and its template parameter list. The names
1190  // of the template parameters are significant only for establishing the
1191  // relationship between the template parameters and the rest of the
1192  // signature.
1193  //
1194  // We check the return type and template parameter lists for function
1195  // templates first; the remaining checks follow.
1196  //
1197  // However, we don't consider either of these when deciding whether
1198  // a member introduced by a shadow declaration is hidden.
1199  if (!UseMemberUsingDeclRules && NewTemplate &&
1200  (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1201  OldTemplate->getTemplateParameters(),
1202  false, TPL_TemplateMatch) ||
1203  !Context.hasSameType(Old->getDeclaredReturnType(),
1204  New->getDeclaredReturnType())))
1205  return true;
1206 
1207  // If the function is a class member, its signature includes the
1208  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1209  //
1210  // As part of this, also check whether one of the member functions
1211  // is static, in which case they are not overloads (C++
1212  // 13.1p2). While not part of the definition of the signature,
1213  // this check is important to determine whether these functions
1214  // can be overloaded.
1215  CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1216  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1217  if (OldMethod && NewMethod &&
1218  !OldMethod->isStatic() && !NewMethod->isStatic()) {
1219  if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1220  if (!UseMemberUsingDeclRules &&
1221  (OldMethod->getRefQualifier() == RQ_None ||
1222  NewMethod->getRefQualifier() == RQ_None)) {
1223  // C++0x [over.load]p2:
1224  // - Member function declarations with the same name and the same
1225  // parameter-type-list as well as member function template
1226  // declarations with the same name, the same parameter-type-list, and
1227  // the same template parameter lists cannot be overloaded if any of
1228  // them, but not all, have a ref-qualifier (8.3.5).
1229  Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1230  << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1231  Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1232  }
1233  return true;
1234  }
1235 
1236  // We may not have applied the implicit const for a constexpr member
1237  // function yet (because we haven't yet resolved whether this is a static
1238  // or non-static member function). Add it now, on the assumption that this
1239  // is a redeclaration of OldMethod.
1240  auto OldQuals = OldMethod->getMethodQualifiers();
1241  auto NewQuals = NewMethod->getMethodQualifiers();
1242  if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1243  !isa<CXXConstructorDecl>(NewMethod))
1244  NewQuals.addConst();
1245  // We do not allow overloading based off of '__restrict'.
1246  OldQuals.removeRestrict();
1247  NewQuals.removeRestrict();
1248  if (OldQuals != NewQuals)
1249  return true;
1250  }
1251 
1252  // Though pass_object_size is placed on parameters and takes an argument, we
1253  // consider it to be a function-level modifier for the sake of function
1254  // identity. Either the function has one or more parameters with
1255  // pass_object_size or it doesn't.
1258  return true;
1259 
1260  // enable_if attributes are an order-sensitive part of the signature.
1262  NewI = New->specific_attr_begin<EnableIfAttr>(),
1263  NewE = New->specific_attr_end<EnableIfAttr>(),
1264  OldI = Old->specific_attr_begin<EnableIfAttr>(),
1265  OldE = Old->specific_attr_end<EnableIfAttr>();
1266  NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1267  if (NewI == NewE || OldI == OldE)
1268  return true;
1269  llvm::FoldingSetNodeID NewID, OldID;
1270  NewI->getCond()->Profile(NewID, Context, true);
1271  OldI->getCond()->Profile(OldID, Context, true);
1272  if (NewID != OldID)
1273  return true;
1274  }
1275 
1276  if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1277  // Don't allow overloading of destructors. (In theory we could, but it
1278  // would be a giant change to clang.)
1279  if (!isa<CXXDestructorDecl>(New)) {
1280  CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1281  OldTarget = IdentifyCUDATarget(Old);
1282  if (NewTarget != CFT_InvalidTarget) {
1283  assert((OldTarget != CFT_InvalidTarget) &&
1284  "Unexpected invalid target.");
1285 
1286  // Allow overloading of functions with same signature and different CUDA
1287  // target attributes.
1288  if (NewTarget != OldTarget)
1289  return true;
1290  }
1291  }
1292  }
1293 
1294  if (ConsiderRequiresClauses) {
1295  Expr *NewRC = New->getTrailingRequiresClause(),
1296  *OldRC = Old->getTrailingRequiresClause();
1297  if ((NewRC != nullptr) != (OldRC != nullptr))
1298  // RC are most certainly different - these are overloads.
1299  return true;
1300 
1301  if (NewRC) {
1302  llvm::FoldingSetNodeID NewID, OldID;
1303  NewRC->Profile(NewID, Context, /*Canonical=*/true);
1304  OldRC->Profile(OldID, Context, /*Canonical=*/true);
1305  if (NewID != OldID)
1306  // RCs are not equivalent - these are overloads.
1307  return true;
1308  }
1309  }
1310 
1311  // The signatures match; this is not an overload.
1312  return false;
1313 }
1314 
1315 /// Tries a user-defined conversion from From to ToType.
1316 ///
1317 /// Produces an implicit conversion sequence for when a standard conversion
1318 /// is not an option. See TryImplicitConversion for more information.
1321  bool SuppressUserConversions,
1322  AllowedExplicit AllowExplicit,
1323  bool InOverloadResolution,
1324  bool CStyle,
1325  bool AllowObjCWritebackConversion,
1326  bool AllowObjCConversionOnExplicit) {
1328 
1329  if (SuppressUserConversions) {
1330  // We're not in the case above, so there is no conversion that
1331  // we can perform.
1332  ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1333  return ICS;
1334  }
1335 
1336  // Attempt user-defined conversion.
1337  OverloadCandidateSet Conversions(From->getExprLoc(),
1339  switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1340  Conversions, AllowExplicit,
1341  AllowObjCConversionOnExplicit)) {
1342  case OR_Success:
1343  case OR_Deleted:
1344  ICS.setUserDefined();
1345  // C++ [over.ics.user]p4:
1346  // A conversion of an expression of class type to the same class
1347  // type is given Exact Match rank, and a conversion of an
1348  // expression of class type to a base class of that type is
1349  // given Conversion rank, in spite of the fact that a copy
1350  // constructor (i.e., a user-defined conversion function) is
1351  // called for those cases.
1352  if (CXXConstructorDecl *Constructor
1353  = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1354  QualType FromCanon
1356  QualType ToCanon
1358  if (Constructor->isCopyConstructor() &&
1359  (FromCanon == ToCanon ||
1360  S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1361  // Turn this into a "standard" conversion sequence, so that it
1362  // gets ranked with standard conversion sequences.
1364  ICS.setStandard();
1366  ICS.Standard.setFromType(From->getType());
1367  ICS.Standard.setAllToTypes(ToType);
1368  ICS.Standard.CopyConstructor = Constructor;
1369  ICS.Standard.FoundCopyConstructor = Found;
1370  if (ToCanon != FromCanon)
1372  }
1373  }
1374  break;
1375 
1376  case OR_Ambiguous:
1377  ICS.setAmbiguous();
1378  ICS.Ambiguous.setFromType(From->getType());
1379  ICS.Ambiguous.setToType(ToType);
1380  for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1381  Cand != Conversions.end(); ++Cand)
1382  if (Cand->Best)
1383  ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1384  break;
1385 
1386  // Fall through.
1387  case OR_No_Viable_Function:
1388  ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1389  break;
1390  }
1391 
1392  return ICS;
1393 }
1394 
1395 /// TryImplicitConversion - Attempt to perform an implicit conversion
1396 /// from the given expression (Expr) to the given type (ToType). This
1397 /// function returns an implicit conversion sequence that can be used
1398 /// to perform the initialization. Given
1399 ///
1400 /// void f(float f);
1401 /// void g(int i) { f(i); }
1402 ///
1403 /// this routine would produce an implicit conversion sequence to
1404 /// describe the initialization of f from i, which will be a standard
1405 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1406 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1407 //
1408 /// Note that this routine only determines how the conversion can be
1409 /// performed; it does not actually perform the conversion. As such,
1410 /// it will not produce any diagnostics if no conversion is available,
1411 /// but will instead return an implicit conversion sequence of kind
1412 /// "BadConversion".
1413 ///
1414 /// If @p SuppressUserConversions, then user-defined conversions are
1415 /// not permitted.
1416 /// If @p AllowExplicit, then explicit user-defined conversions are
1417 /// permitted.
1418 ///
1419 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1420 /// writeback conversion, which allows __autoreleasing id* parameters to
1421 /// be initialized with __strong id* or __weak id* arguments.
1424  bool SuppressUserConversions,
1425  AllowedExplicit AllowExplicit,
1426  bool InOverloadResolution,
1427  bool CStyle,
1428  bool AllowObjCWritebackConversion,
1429  bool AllowObjCConversionOnExplicit) {
1431  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1432  ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1433  ICS.setStandard();
1434  return ICS;
1435  }
1436 
1437  if (!S.getLangOpts().CPlusPlus) {
1438  ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1439  return ICS;
1440  }
1441 
1442  // C++ [over.ics.user]p4:
1443  // A conversion of an expression of class type to the same class
1444  // type is given Exact Match rank, and a conversion of an
1445  // expression of class type to a base class of that type is
1446  // given Conversion rank, in spite of the fact that a copy/move
1447  // constructor (i.e., a user-defined conversion function) is
1448  // called for those cases.
1449  QualType FromType = From->getType();
1450  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1451  (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1452  S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1453  ICS.setStandard();
1455  ICS.Standard.setFromType(FromType);
1456  ICS.Standard.setAllToTypes(ToType);
1457 
1458  // We don't actually check at this point whether there is a valid
1459  // copy/move constructor, since overloading just assumes that it
1460  // exists. When we actually perform initialization, we'll find the
1461  // appropriate constructor to copy the returned object, if needed.
1462  ICS.Standard.CopyConstructor = nullptr;
1463 
1464  // Determine whether this is considered a derived-to-base conversion.
1465  if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1467 
1468  return ICS;
1469  }
1470 
1471  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1472  AllowExplicit, InOverloadResolution, CStyle,
1473  AllowObjCWritebackConversion,
1474  AllowObjCConversionOnExplicit);
1475 }
1476 
1479  bool SuppressUserConversions,
1480  AllowedExplicit AllowExplicit,
1481  bool InOverloadResolution,
1482  bool CStyle,
1483  bool AllowObjCWritebackConversion) {
1484  return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1485  AllowExplicit, InOverloadResolution, CStyle,
1486  AllowObjCWritebackConversion,
1487  /*AllowObjCConversionOnExplicit=*/false);
1488 }
1489 
1490 /// PerformImplicitConversion - Perform an implicit conversion of the
1491 /// expression From to the type ToType. Returns the
1492 /// converted expression. Flavor is the kind of conversion we're
1493 /// performing, used in the error message. If @p AllowExplicit,
1494 /// explicit user-defined conversions are permitted.
1496  AssignmentAction Action,
1497  bool AllowExplicit) {
1498  if (checkPlaceholderForOverload(*this, From))
1499  return ExprError();
1500 
1501  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1502  bool AllowObjCWritebackConversion
1503  = getLangOpts().ObjCAutoRefCount &&
1504  (Action == AA_Passing || Action == AA_Sending);
1505  if (getLangOpts().ObjC)
1506  CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1507  From->getType(), From);
1509  *this, From, ToType,
1510  /*SuppressUserConversions=*/false,
1511  AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1512  /*InOverloadResolution=*/false,
1513  /*CStyle=*/false, AllowObjCWritebackConversion,
1514  /*AllowObjCConversionOnExplicit=*/false);
1515  return PerformImplicitConversion(From, ToType, ICS, Action);
1516 }
1517 
1518 /// Determine whether the conversion from FromType to ToType is a valid
1519 /// conversion that strips "noexcept" or "noreturn" off the nested function
1520 /// type.
1522  QualType &ResultTy) {
1523  if (Context.hasSameUnqualifiedType(FromType, ToType))
1524  return false;
1525 
1526  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1527  // or F(t noexcept) -> F(t)
1528  // where F adds one of the following at most once:
1529  // - a pointer
1530  // - a member pointer
1531  // - a block pointer
1532  // Changes here need matching changes in FindCompositePointerType.
1533  CanQualType CanTo = Context.getCanonicalType(ToType);
1534  CanQualType CanFrom = Context.getCanonicalType(FromType);
1535  Type::TypeClass TyClass = CanTo->getTypeClass();
1536  if (TyClass != CanFrom->getTypeClass()) return false;
1537  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1538  if (TyClass == Type::Pointer) {
1539  CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1540  CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1541  } else if (TyClass == Type::BlockPointer) {
1542  CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1543  CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1544  } else if (TyClass == Type::MemberPointer) {
1545  auto ToMPT = CanTo.castAs<MemberPointerType>();
1546  auto FromMPT = CanFrom.castAs<MemberPointerType>();
1547  // A function pointer conversion cannot change the class of the function.
1548  if (ToMPT->getClass() != FromMPT->getClass())
1549  return false;
1550  CanTo = ToMPT->getPointeeType();
1551  CanFrom = FromMPT->getPointeeType();
1552  } else {
1553  return false;
1554  }
1555 
1556  TyClass = CanTo->getTypeClass();
1557  if (TyClass != CanFrom->getTypeClass()) return false;
1558  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1559  return false;
1560  }
1561 
1562  const auto *FromFn = cast<FunctionType>(CanFrom);
1563  FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1564 
1565  const auto *ToFn = cast<FunctionType>(CanTo);
1566  FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1567 
1568  bool Changed = false;
1569 
1570  // Drop 'noreturn' if not present in target type.
1571  if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1572  FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1573  Changed = true;
1574  }
1575 
1576  // Drop 'noexcept' if not present in target type.
1577  if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1578  const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1579  if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1580  FromFn = cast<FunctionType>(
1581  Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1582  EST_None)
1583  .getTypePtr());
1584  Changed = true;
1585  }
1586 
1587  // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1588  // only if the ExtParameterInfo lists of the two function prototypes can be
1589  // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1591  bool CanUseToFPT, CanUseFromFPT;
1592  if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1593  CanUseFromFPT, NewParamInfos) &&
1594  CanUseToFPT && !CanUseFromFPT) {
1595  FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1596  ExtInfo.ExtParameterInfos =
1597  NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1598  QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1599  FromFPT->getParamTypes(), ExtInfo);
1600  FromFn = QT->getAs<FunctionType>();
1601  Changed = true;
1602  }
1603  }
1604 
1605  if (!Changed)
1606  return false;
1607 
1608  assert(QualType(FromFn, 0).isCanonical());
1609  if (QualType(FromFn, 0) != CanTo) return false;
1610 
1611  ResultTy = ToType;
1612  return true;
1613 }
1614 
1615 /// Determine whether the conversion from FromType to ToType is a valid
1616 /// vector conversion.
1617 ///
1618 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1619 /// conversion.
1620 static bool IsVectorConversion(Sema &S, QualType FromType,
1621  QualType ToType, ImplicitConversionKind &ICK) {
1622  // We need at least one of these types to be a vector type to have a vector
1623  // conversion.
1624  if (!ToType->isVectorType() && !FromType->isVectorType())
1625  return false;
1626 
1627  // Identical types require no conversions.
1628  if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1629  return false;
1630 
1631  // There are no conversions between extended vector types, only identity.
1632  if (ToType->isExtVectorType()) {
1633  // There are no conversions between extended vector types other than the
1634  // identity conversion.
1635  if (FromType->isExtVectorType())
1636  return false;
1637 
1638  // Vector splat from any arithmetic type to a vector.
1639  if (FromType->isArithmeticType()) {
1640  ICK = ICK_Vector_Splat;
1641  return true;
1642  }
1643  }
1644 
1645  if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType())
1646  if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1647  S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1649  return true;
1650  }
1651 
1652  // We can perform the conversion between vector types in the following cases:
1653  // 1)vector types are equivalent AltiVec and GCC vector types
1654  // 2)lax vector conversions are permitted and the vector types are of the
1655  // same size
1656  // 3)the destination type does not have the ARM MVE strict-polymorphism
1657  // attribute, which inhibits lax vector conversion for overload resolution
1658  // only
1659  if (ToType->isVectorType() && FromType->isVectorType()) {
1660  if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1661  (S.isLaxVectorConversion(FromType, ToType) &&
1662  !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1663  ICK = ICK_Vector_Conversion;
1664  return true;
1665  }
1666  }
1667 
1668  return false;
1669 }
1670 
1671 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1672  bool InOverloadResolution,
1674  bool CStyle);
1675 
1676 /// IsStandardConversion - Determines whether there is a standard
1677 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1678 /// expression From to the type ToType. Standard conversion sequences
1679 /// only consider non-class types; for conversions that involve class
1680 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1681 /// contain the standard conversion sequence required to perform this
1682 /// conversion and this routine will return true. Otherwise, this
1683 /// routine will return false and the value of SCS is unspecified.
1684 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1685  bool InOverloadResolution,
1687  bool CStyle,
1688  bool AllowObjCWritebackConversion) {
1689  QualType FromType = From->getType();
1690 
1691  // Standard conversions (C++ [conv])
1693  SCS.IncompatibleObjC = false;
1694  SCS.setFromType(FromType);
1695  SCS.CopyConstructor = nullptr;
1696 
1697  // There are no standard conversions for class types in C++, so
1698  // abort early. When overloading in C, however, we do permit them.
1699  if (S.getLangOpts().CPlusPlus &&
1700  (FromType->isRecordType() || ToType->isRecordType()))
1701  return false;
1702 
1703  // The first conversion can be an lvalue-to-rvalue conversion,
1704  // array-to-pointer conversion, or function-to-pointer conversion
1705  // (C++ 4p1).
1706 
1707  if (FromType == S.Context.OverloadTy) {
1708  DeclAccessPair AccessPair;
1709  if (FunctionDecl *Fn
1710  = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1711  AccessPair)) {
1712  // We were able to resolve the address of the overloaded function,
1713  // so we can convert to the type of that function.
1714  FromType = Fn->getType();
1715  SCS.setFromType(FromType);
1716 
1717  // we can sometimes resolve &foo<int> regardless of ToType, so check
1718  // if the type matches (identity) or we are converting to bool
1720  S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1721  QualType resultTy;
1722  // if the function type matches except for [[noreturn]], it's ok
1723  if (!S.IsFunctionConversion(FromType,
1724  S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1725  // otherwise, only a boolean conversion is standard
1726  if (!ToType->isBooleanType())
1727  return false;
1728  }
1729 
1730  // Check if the "from" expression is taking the address of an overloaded
1731  // function and recompute the FromType accordingly. Take advantage of the
1732  // fact that non-static member functions *must* have such an address-of
1733  // expression.
1734  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1735  if (Method && !Method->isStatic()) {
1736  assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1737  "Non-unary operator on non-static member address");
1738  assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1739  == UO_AddrOf &&
1740  "Non-address-of operator on non-static member address");
1741  const Type *ClassType
1742  = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1743  FromType = S.Context.getMemberPointerType(FromType, ClassType);
1744  } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1745  assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1746  UO_AddrOf &&
1747  "Non-address-of operator for overloaded function expression");
1748  FromType = S.Context.getPointerType(FromType);
1749  }
1750  } else {
1751  return false;
1752  }
1753  }
1754  // Lvalue-to-rvalue conversion (C++11 4.1):
1755  // A glvalue (3.10) of a non-function, non-array type T can
1756  // be converted to a prvalue.
1757  bool argIsLValue = From->isGLValue();
1758  if (argIsLValue &&
1759  !FromType->isFunctionType() && !FromType->isArrayType() &&
1760  S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1762 
1763  // C11 6.3.2.1p2:
1764  // ... if the lvalue has atomic type, the value has the non-atomic version
1765  // of the type of the lvalue ...
1766  if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1767  FromType = Atomic->getValueType();
1768 
1769  // If T is a non-class type, the type of the rvalue is the
1770  // cv-unqualified version of T. Otherwise, the type of the rvalue
1771  // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1772  // just strip the qualifiers because they don't matter.
1773  FromType = FromType.getUnqualifiedType();
1774  } else if (FromType->isArrayType()) {
1775  // Array-to-pointer conversion (C++ 4.2)
1777 
1778  // An lvalue or rvalue of type "array of N T" or "array of unknown
1779  // bound of T" can be converted to an rvalue of type "pointer to
1780  // T" (C++ 4.2p1).
1781  FromType = S.Context.getArrayDecayedType(FromType);
1782 
1783  if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1784  // This conversion is deprecated in C++03 (D.4)
1786 
1787  // For the purpose of ranking in overload resolution
1788  // (13.3.3.1.1), this conversion is considered an
1789  // array-to-pointer conversion followed by a qualification
1790  // conversion (4.4). (C++ 4.2p2)
1791  SCS.Second = ICK_Identity;
1792  SCS.Third = ICK_Qualification;
1794  SCS.setAllToTypes(FromType);
1795  return true;
1796  }
1797  } else if (FromType->isFunctionType() && argIsLValue) {
1798  // Function-to-pointer conversion (C++ 4.3).
1800 
1801  if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1802  if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1804  return false;
1805 
1806  // An lvalue of function type T can be converted to an rvalue of
1807  // type "pointer to T." The result is a pointer to the
1808  // function. (C++ 4.3p1).
1809  FromType = S.Context.getPointerType(FromType);
1810  } else {
1811  // We don't require any conversions for the first step.
1812  SCS.First = ICK_Identity;
1813  }
1814  SCS.setToType(0, FromType);
1815 
1816  // The second conversion can be an integral promotion, floating
1817  // point promotion, integral conversion, floating point conversion,
1818  // floating-integral conversion, pointer conversion,
1819  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1820  // For overloading in C, this can also be a "compatible-type"
1821  // conversion.
1822  bool IncompatibleObjC = false;
1824  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1825  // The unqualified versions of the types are the same: there's no
1826  // conversion to do.
1827  SCS.Second = ICK_Identity;
1828  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1829  // Integral promotion (C++ 4.5).
1831  FromType = ToType.getUnqualifiedType();
1832  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1833  // Floating point promotion (C++ 4.6).
1835  FromType = ToType.getUnqualifiedType();
1836  } else if (S.IsComplexPromotion(FromType, ToType)) {
1837  // Complex promotion (Clang extension)
1839  FromType = ToType.getUnqualifiedType();
1840  } else if (ToType->isBooleanType() &&
1841  (FromType->isArithmeticType() ||
1842  FromType->isAnyPointerType() ||
1843  FromType->isBlockPointerType() ||
1844  FromType->isMemberPointerType())) {
1845  // Boolean conversions (C++ 4.12).
1847  FromType = S.Context.BoolTy;
1848  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1849  ToType->isIntegralType(S.Context)) {
1850  // Integral conversions (C++ 4.7).
1852  FromType = ToType.getUnqualifiedType();
1853  } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1854  // Complex conversions (C99 6.3.1.6)
1856  FromType = ToType.getUnqualifiedType();
1857  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1858  (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1859  // Complex-real conversions (C99 6.3.1.7)
1860  SCS.Second = ICK_Complex_Real;
1861  FromType = ToType.getUnqualifiedType();
1862  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1863  // FIXME: disable conversions between long double, __ibm128 and __float128
1864  // if their representation is different until there is back end support
1865  // We of course allow this conversion if long double is really double.
1866 
1867  // Conversions between bfloat and other floats are not permitted.
1868  if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1869  return false;
1870 
1871  // Conversions between IEEE-quad and IBM-extended semantics are not
1872  // permitted.
1873  const llvm::fltSemantics &FromSem =
1874  S.Context.getFloatTypeSemantics(FromType);
1875  const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1876  if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1877  &ToSem == &llvm::APFloat::IEEEquad()) ||
1878  (&FromSem == &llvm::APFloat::IEEEquad() &&
1879  &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1880  return false;
1881 
1882  // Floating point conversions (C++ 4.8).
1884  FromType = ToType.getUnqualifiedType();
1885  } else if ((FromType->isRealFloatingType() &&
1886  ToType->isIntegralType(S.Context)) ||
1887  (FromType->isIntegralOrUnscopedEnumerationType() &&
1888  ToType->isRealFloatingType())) {
1889  // Conversions between bfloat and int are not permitted.
1890  if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1891  return false;
1892 
1893  // Floating-integral conversions (C++ 4.9).
1895  FromType = ToType.getUnqualifiedType();
1896  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1898  } else if (AllowObjCWritebackConversion &&
1899  S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1901  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1902  FromType, IncompatibleObjC)) {
1903  // Pointer conversions (C++ 4.10).
1905  SCS.IncompatibleObjC = IncompatibleObjC;
1906  FromType = FromType.getUnqualifiedType();
1907  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1908  InOverloadResolution, FromType)) {
1909  // Pointer to member conversions (4.11).
1910  SCS.Second = ICK_Pointer_Member;
1911  } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1912  SCS.Second = SecondICK;
1913  FromType = ToType.getUnqualifiedType();
1914  } else if (!S.getLangOpts().CPlusPlus &&
1915  S.Context.typesAreCompatible(ToType, FromType)) {
1916  // Compatible conversions (Clang extension for C function overloading)
1918  FromType = ToType.getUnqualifiedType();
1919  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1920  InOverloadResolution,
1921  SCS, CStyle)) {
1923  FromType = ToType;
1924  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1925  CStyle)) {
1926  // tryAtomicConversion has updated the standard conversion sequence
1927  // appropriately.
1928  return true;
1929  } else if (ToType->isEventT() &&
1930  From->isIntegerConstantExpr(S.getASTContext()) &&
1931  From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1933  FromType = ToType;
1934  } else if (ToType->isQueueT() &&
1935  From->isIntegerConstantExpr(S.getASTContext()) &&
1936  (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1938  FromType = ToType;
1939  } else if (ToType->isSamplerT() &&
1940  From->isIntegerConstantExpr(S.getASTContext())) {
1942  FromType = ToType;
1943  } else {
1944  // No second conversion required.
1945  SCS.Second = ICK_Identity;
1946  }
1947  SCS.setToType(1, FromType);
1948 
1949  // The third conversion can be a function pointer conversion or a
1950  // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1951  bool ObjCLifetimeConversion;
1952  if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1953  // Function pointer conversions (removing 'noexcept') including removal of
1954  // 'noreturn' (Clang extension).
1956  } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1957  ObjCLifetimeConversion)) {
1958  SCS.Third = ICK_Qualification;
1959  SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1960  FromType = ToType;
1961  } else {
1962  // No conversion required
1963  SCS.Third = ICK_Identity;
1964  }
1965 
1966  // C++ [over.best.ics]p6:
1967  // [...] Any difference in top-level cv-qualification is
1968  // subsumed by the initialization itself and does not constitute
1969  // a conversion. [...]
1970  QualType CanonFrom = S.Context.getCanonicalType(FromType);
1971  QualType CanonTo = S.Context.getCanonicalType(ToType);
1972  if (CanonFrom.getLocalUnqualifiedType()
1973  == CanonTo.getLocalUnqualifiedType() &&
1974  CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1975  FromType = ToType;
1976  CanonFrom = CanonTo;
1977  }
1978 
1979  SCS.setToType(2, FromType);
1980 
1981  if (CanonFrom == CanonTo)
1982  return true;
1983 
1984  // If we have not converted the argument type to the parameter type,
1985  // this is a bad conversion sequence, unless we're resolving an overload in C.
1986  if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1987  return false;
1988 
1989  ExprResult ER = ExprResult{From};
1991  S.CheckSingleAssignmentConstraints(ToType, ER,
1992  /*Diagnose=*/false,
1993  /*DiagnoseCFAudited=*/false,
1994  /*ConvertRHS=*/false);
1995  ImplicitConversionKind SecondConv;
1996  switch (Conv) {
1997  case Sema::Compatible:
1998  SecondConv = ICK_C_Only_Conversion;
1999  break;
2000  // For our purposes, discarding qualifiers is just as bad as using an
2001  // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2002  // qualifiers, as well.
2007  break;
2008  default:
2009  return false;
2010  }
2011 
2012  // First can only be an lvalue conversion, so we pretend that this was the
2013  // second conversion. First should already be valid from earlier in the
2014  // function.
2015  SCS.Second = SecondConv;
2016  SCS.setToType(1, ToType);
2017 
2018  // Third is Identity, because Second should rank us worse than any other
2019  // conversion. This could also be ICK_Qualification, but it's simpler to just
2020  // lump everything in with the second conversion, and we don't gain anything
2021  // from making this ICK_Qualification.
2022  SCS.Third = ICK_Identity;
2023  SCS.setToType(2, ToType);
2024  return true;
2025 }
2026 
2027 static bool
2029  QualType &ToType,
2030  bool InOverloadResolution,
2032  bool CStyle) {
2033 
2034  const RecordType *UT = ToType->getAsUnionType();
2035  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2036  return false;
2037  // The field to initialize within the transparent union.
2038  RecordDecl *UD = UT->getDecl();
2039  // It's compatible if the expression matches any of the fields.
2040  for (const auto *it : UD->fields()) {
2041  if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2042  CStyle, /*AllowObjCWritebackConversion=*/false)) {
2043  ToType = it->getType();
2044  return true;
2045  }
2046  }
2047  return false;
2048 }
2049 
2050 /// IsIntegralPromotion - Determines whether the conversion from the
2051 /// expression From (whose potentially-adjusted type is FromType) to
2052 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2053 /// sets PromotedType to the promoted type.
2054 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2055  const BuiltinType *To = ToType->getAs<BuiltinType>();
2056  // All integers are built-in.
2057  if (!To) {
2058  return false;
2059  }
2060 
2061  // An rvalue of type char, signed char, unsigned char, short int, or
2062  // unsigned short int can be converted to an rvalue of type int if
2063  // int can represent all the values of the source type; otherwise,
2064  // the source rvalue can be converted to an rvalue of type unsigned
2065  // int (C++ 4.5p1).
2066  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2067  !FromType->isEnumeralType()) {
2068  if (// We can promote any signed, promotable integer type to an int
2069  (FromType->isSignedIntegerType() ||
2070  // We can promote any unsigned integer type whose size is
2071  // less than int to an int.
2072  Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2073  return To->getKind() == BuiltinType::Int;
2074  }
2075 
2076  return To->getKind() == BuiltinType::UInt;
2077  }
2078 
2079  // C++11 [conv.prom]p3:
2080  // A prvalue of an unscoped enumeration type whose underlying type is not
2081  // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2082  // following types that can represent all the values of the enumeration
2083  // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2084  // unsigned int, long int, unsigned long int, long long int, or unsigned
2085  // long long int. If none of the types in that list can represent all the
2086  // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2087  // type can be converted to an rvalue a prvalue of the extended integer type
2088  // with lowest integer conversion rank (4.13) greater than the rank of long
2089  // long in which all the values of the enumeration can be represented. If
2090  // there are two such extended types, the signed one is chosen.
2091  // C++11 [conv.prom]p4:
2092  // A prvalue of an unscoped enumeration type whose underlying type is fixed
2093  // can be converted to a prvalue of its underlying type. Moreover, if
2094  // integral promotion can be applied to its underlying type, a prvalue of an
2095  // unscoped enumeration type whose underlying type is fixed can also be
2096  // converted to a prvalue of the promoted underlying type.
2097  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2098  // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2099  // provided for a scoped enumeration.
2100  if (FromEnumType->getDecl()->isScoped())
2101  return false;
2102 
2103  // We can perform an integral promotion to the underlying type of the enum,
2104  // even if that's not the promoted type. Note that the check for promoting
2105  // the underlying type is based on the type alone, and does not consider
2106  // the bitfield-ness of the actual source expression.
2107  if (FromEnumType->getDecl()->isFixed()) {
2108  QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2109  return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2110  IsIntegralPromotion(nullptr, Underlying, ToType);
2111  }
2112 
2113  // We have already pre-calculated the promotion type, so this is trivial.
2114  if (ToType->isIntegerType() &&
2115  isCompleteType(From->getBeginLoc(), FromType))
2116  return Context.hasSameUnqualifiedType(
2117  ToType, FromEnumType->getDecl()->getPromotionType());
2118 
2119  // C++ [conv.prom]p5:
2120  // If the bit-field has an enumerated type, it is treated as any other
2121  // value of that type for promotion purposes.
2122  //
2123  // ... so do not fall through into the bit-field checks below in C++.
2124  if (getLangOpts().CPlusPlus)
2125  return false;
2126  }
2127 
2128  // C++0x [conv.prom]p2:
2129  // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2130  // to an rvalue a prvalue of the first of the following types that can
2131  // represent all the values of its underlying type: int, unsigned int,
2132  // long int, unsigned long int, long long int, or unsigned long long int.
2133  // If none of the types in that list can represent all the values of its
2134  // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2135  // or wchar_t can be converted to an rvalue a prvalue of its underlying
2136  // type.
2137  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2138  ToType->isIntegerType()) {
2139  // Determine whether the type we're converting from is signed or
2140  // unsigned.
2141  bool FromIsSigned = FromType->isSignedIntegerType();
2142  uint64_t FromSize = Context.getTypeSize(FromType);
2143 
2144  // The types we'll try to promote to, in the appropriate
2145  // order. Try each of these types.
2146  QualType PromoteTypes[6] = {
2147  Context.IntTy, Context.UnsignedIntTy,
2148  Context.LongTy, Context.UnsignedLongTy ,
2149  Context.LongLongTy, Context.UnsignedLongLongTy
2150  };
2151  for (int Idx = 0; Idx < 6; ++Idx) {
2152  uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2153  if (FromSize < ToSize ||
2154  (FromSize == ToSize &&
2155  FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2156  // We found the type that we can promote to. If this is the
2157  // type we wanted, we have a promotion. Otherwise, no
2158  // promotion.
2159  return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2160  }
2161  }
2162  }
2163 
2164  // An rvalue for an integral bit-field (9.6) can be converted to an
2165  // rvalue of type int if int can represent all the values of the
2166  // bit-field; otherwise, it can be converted to unsigned int if
2167  // unsigned int can represent all the values of the bit-field. If
2168  // the bit-field is larger yet, no integral promotion applies to
2169  // it. If the bit-field has an enumerated type, it is treated as any
2170  // other value of that type for promotion purposes (C++ 4.5p3).
2171  // FIXME: We should delay checking of bit-fields until we actually perform the
2172  // conversion.
2173  //
2174  // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2175  // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2176  // bit-fields and those whose underlying type is larger than int) for GCC
2177  // compatibility.
2178  if (From) {
2179  if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2180  Optional<llvm::APSInt> BitWidth;
2181  if (FromType->isIntegralType(Context) &&
2182  (BitWidth =
2183  MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2184  llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2185  ToSize = Context.getTypeSize(ToType);
2186 
2187  // Are we promoting to an int from a bitfield that fits in an int?
2188  if (*BitWidth < ToSize ||
2189  (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2190  return To->getKind() == BuiltinType::Int;
2191  }
2192 
2193  // Are we promoting to an unsigned int from an unsigned bitfield
2194  // that fits into an unsigned int?
2195  if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2196  return To->getKind() == BuiltinType::UInt;
2197  }
2198 
2199  return false;
2200  }
2201  }
2202  }
2203 
2204  // An rvalue of type bool can be converted to an rvalue of type int,
2205  // with false becoming zero and true becoming one (C++ 4.5p4).
2206  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2207  return true;
2208  }
2209 
2210  return false;
2211 }
2212 
2213 /// IsFloatingPointPromotion - Determines whether the conversion from
2214 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2215 /// returns true and sets PromotedType to the promoted type.
2217  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2218  if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2219  /// An rvalue of type float can be converted to an rvalue of type
2220  /// double. (C++ 4.6p1).
2221  if (FromBuiltin->getKind() == BuiltinType::Float &&
2222  ToBuiltin->getKind() == BuiltinType::Double)
2223  return true;
2224 
2225  // C99 6.3.1.5p1:
2226  // When a float is promoted to double or long double, or a
2227  // double is promoted to long double [...].
2228  if (!getLangOpts().CPlusPlus &&
2229  (FromBuiltin->getKind() == BuiltinType::Float ||
2230  FromBuiltin->getKind() == BuiltinType::Double) &&
2231  (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2232  ToBuiltin->getKind() == BuiltinType::Float128 ||
2233  ToBuiltin->getKind() == BuiltinType::Ibm128))
2234  return true;
2235 
2236  // Half can be promoted to float.
2237  if (!getLangOpts().NativeHalfType &&
2238  FromBuiltin->getKind() == BuiltinType::Half &&
2239  ToBuiltin->getKind() == BuiltinType::Float)
2240  return true;
2241  }
2242 
2243  return false;
2244 }
2245 
2246 /// Determine if a conversion is a complex promotion.
2247 ///
2248 /// A complex promotion is defined as a complex -> complex conversion
2249 /// where the conversion between the underlying real types is a
2250 /// floating-point or integral promotion.
2252  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2253  if (!FromComplex)
2254  return false;
2255 
2256  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2257  if (!ToComplex)
2258  return false;
2259 
2260  return IsFloatingPointPromotion(FromComplex->getElementType(),
2261  ToComplex->getElementType()) ||
2262  IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2263  ToComplex->getElementType());
2264 }
2265 
2266 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2267 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2268 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2269 /// if non-empty, will be a pointer to ToType that may or may not have
2270 /// the right set of qualifiers on its pointee.
2271 ///
2272 static QualType
2274  QualType ToPointee, QualType ToType,
2275  ASTContext &Context,
2276  bool StripObjCLifetime = false) {
2277  assert((FromPtr->getTypeClass() == Type::Pointer ||
2278  FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2279  "Invalid similarly-qualified pointer type");
2280 
2281  /// Conversions to 'id' subsume cv-qualifier conversions.
2282  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2283  return ToType.getUnqualifiedType();
2284 
2285  QualType CanonFromPointee
2286  = Context.getCanonicalType(FromPtr->getPointeeType());
2287  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2288  Qualifiers Quals = CanonFromPointee.getQualifiers();
2289 
2290  if (StripObjCLifetime)
2291  Quals.removeObjCLifetime();
2292 
2293  // Exact qualifier match -> return the pointer type we're converting to.
2294  if (CanonToPointee.getLocalQualifiers() == Quals) {
2295  // ToType is exactly what we need. Return it.
2296  if (!ToType.isNull())
2297  return ToType.getUnqualifiedType();
2298 
2299  // Build a pointer to ToPointee. It has the right qualifiers
2300  // already.
2301  if (isa<ObjCObjectPointerType>(ToType))
2302  return Context.getObjCObjectPointerType(ToPointee);
2303  return Context.getPointerType(ToPointee);
2304  }
2305 
2306  // Just build a canonical type that has the right qualifiers.
2307  QualType QualifiedCanonToPointee
2308  = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2309 
2310  if (isa<ObjCObjectPointerType>(ToType))
2311  return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2312  return Context.getPointerType(QualifiedCanonToPointee);
2313 }
2314 
2316  bool InOverloadResolution,
2317  ASTContext &Context) {
2318  // Handle value-dependent integral null pointer constants correctly.
2319  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2320  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2322  return !InOverloadResolution;
2323 
2324  return Expr->isNullPointerConstant(Context,
2325  InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2327 }
2328 
2329 /// IsPointerConversion - Determines whether the conversion of the
2330 /// expression From, which has the (possibly adjusted) type FromType,
2331 /// can be converted to the type ToType via a pointer conversion (C++
2332 /// 4.10). If so, returns true and places the converted type (that
2333 /// might differ from ToType in its cv-qualifiers at some level) into
2334 /// ConvertedType.
2335 ///
2336 /// This routine also supports conversions to and from block pointers
2337 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2338 /// pointers to interfaces. FIXME: Once we've determined the
2339 /// appropriate overloading rules for Objective-C, we may want to
2340 /// split the Objective-C checks into a different routine; however,
2341 /// GCC seems to consider all of these conversions to be pointer
2342 /// conversions, so for now they live here. IncompatibleObjC will be
2343 /// set if the conversion is an allowed Objective-C conversion that
2344 /// should result in a warning.
2345 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2346  bool InOverloadResolution,
2347  QualType& ConvertedType,
2348  bool &IncompatibleObjC) {
2349  IncompatibleObjC = false;
2350  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2351  IncompatibleObjC))
2352  return true;
2353 
2354  // Conversion from a null pointer constant to any Objective-C pointer type.
2355  if (ToType->isObjCObjectPointerType() &&
2356  isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2357  ConvertedType = ToType;
2358  return true;
2359  }
2360 
2361  // Blocks: Block pointers can be converted to void*.
2362  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2363  ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2364  ConvertedType = ToType;
2365  return true;
2366  }
2367  // Blocks: A null pointer constant can be converted to a block
2368  // pointer type.
2369  if (ToType->isBlockPointerType() &&
2370  isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2371  ConvertedType = ToType;
2372  return true;
2373  }
2374 
2375  // If the left-hand-side is nullptr_t, the right side can be a null
2376  // pointer constant.
2377  if (ToType->isNullPtrType() &&
2378  isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2379  ConvertedType = ToType;
2380  return true;
2381  }
2382 
2383  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2384  if (!ToTypePtr)
2385  return false;
2386 
2387  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2388  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2389  ConvertedType = ToType;
2390  return true;
2391  }
2392 
2393  // Beyond this point, both types need to be pointers
2394  // , including objective-c pointers.
2395  QualType ToPointeeType = ToTypePtr->getPointeeType();
2396  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2397  !getLangOpts().ObjCAutoRefCount) {
2398  ConvertedType = BuildSimilarlyQualifiedPointerType(
2399  FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2400  Context);
2401  return true;
2402  }
2403  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2404  if (!FromTypePtr)
2405  return false;
2406 
2407  QualType FromPointeeType = FromTypePtr->getPointeeType();
2408 
2409  // If the unqualified pointee types are the same, this can't be a
2410  // pointer conversion, so don't do all of the work below.
2411  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2412  return false;
2413 
2414  // An rvalue of type "pointer to cv T," where T is an object type,
2415  // can be converted to an rvalue of type "pointer to cv void" (C++
2416  // 4.10p2).
2417  if (FromPointeeType->isIncompleteOrObjectType() &&
2418  ToPointeeType->isVoidType()) {
2419  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2420  ToPointeeType,
2421  ToType, Context,
2422  /*StripObjCLifetime=*/true);
2423  return true;
2424  }
2425 
2426  // MSVC allows implicit function to void* type conversion.
2427  if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2428  ToPointeeType->isVoidType()) {
2429  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2430  ToPointeeType,
2431  ToType, Context);
2432  return true;
2433  }
2434 
2435  // When we're overloading in C, we allow a special kind of pointer
2436  // conversion for compatible-but-not-identical pointee types.
2437  if (!getLangOpts().CPlusPlus &&
2438  Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2439  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2440  ToPointeeType,
2441  ToType, Context);
2442  return true;
2443  }
2444 
2445  // C++ [conv.ptr]p3:
2446  //
2447  // An rvalue of type "pointer to cv D," where D is a class type,
2448  // can be converted to an rvalue of type "pointer to cv B," where
2449  // B is a base class (clause 10) of D. If B is an inaccessible
2450  // (clause 11) or ambiguous (10.2) base class of D, a program that
2451  // necessitates this conversion is ill-formed. The result of the
2452  // conversion is a pointer to the base class sub-object of the
2453  // derived class object. The null pointer value is converted to
2454  // the null pointer value of the destination type.
2455  //
2456  // Note that we do not check for ambiguity or inaccessibility
2457  // here. That is handled by CheckPointerConversion.
2458  if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2459  ToPointeeType->isRecordType() &&
2460  !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2461  IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2462  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2463  ToPointeeType,
2464  ToType, Context);
2465  return true;
2466  }
2467 
2468  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2469  Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2470  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2471  ToPointeeType,
2472  ToType, Context);
2473  return true;
2474  }
2475 
2476  return false;
2477 }
2478 
2479 /// Adopt the given qualifiers for the given type.
2481  Qualifiers TQs = T.getQualifiers();
2482 
2483  // Check whether qualifiers already match.
2484  if (TQs == Qs)
2485  return T;
2486 
2487  if (Qs.compatiblyIncludes(TQs))
2488  return Context.getQualifiedType(T, Qs);
2489 
2490  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2491 }
2492 
2493 /// isObjCPointerConversion - Determines whether this is an
2494 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2495 /// with the same arguments and return values.
2497  QualType& ConvertedType,
2498  bool &IncompatibleObjC) {
2499  if (!getLangOpts().ObjC)
2500  return false;
2501 
2502  // The set of qualifiers on the type we're converting from.
2503  Qualifiers FromQualifiers = FromType.getQualifiers();
2504 
2505  // First, we handle all conversions on ObjC object pointer types.
2506  const ObjCObjectPointerType* ToObjCPtr =
2507  ToType->getAs<ObjCObjectPointerType>();
2508  const ObjCObjectPointerType *FromObjCPtr =
2509  FromType->getAs<ObjCObjectPointerType>();
2510 
2511  if (ToObjCPtr && FromObjCPtr) {
2512  // If the pointee types are the same (ignoring qualifications),
2513  // then this is not a pointer conversion.
2514  if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2515  FromObjCPtr->getPointeeType()))
2516  return false;
2517 
2518  // Conversion between Objective-C pointers.
2519  if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2520  const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2521  const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2522  if (getLangOpts().CPlusPlus && LHS && RHS &&
2523  !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2524  FromObjCPtr->getPointeeType()))
2525  return false;
2526  ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2527  ToObjCPtr->getPointeeType(),
2528  ToType, Context);
2529  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2530  return true;
2531  }
2532 
2533  if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2534  // Okay: this is some kind of implicit downcast of Objective-C
2535  // interfaces, which is permitted. However, we're going to
2536  // complain about it.
2537  IncompatibleObjC = true;
2538  ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2539  ToObjCPtr->getPointeeType(),
2540  ToType, Context);
2541  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2542  return true;
2543  }
2544  }
2545  // Beyond this point, both types need to be C pointers or block pointers.
2546  QualType ToPointeeType;
2547  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2548  ToPointeeType = ToCPtr->getPointeeType();
2549  else if (const BlockPointerType *ToBlockPtr =
2550  ToType->getAs<BlockPointerType>()) {
2551  // Objective C++: We're able to convert from a pointer to any object
2552  // to a block pointer type.
2553  if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2554  ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2555  return true;
2556  }
2557  ToPointeeType = ToBlockPtr->getPointeeType();
2558  }
2559  else if (FromType->getAs<BlockPointerType>() &&
2560  ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2561  // Objective C++: We're able to convert from a block pointer type to a
2562  // pointer to any object.
2563  ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2564  return true;
2565  }
2566  else
2567  return false;
2568 
2569  QualType FromPointeeType;
2570  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2571  FromPointeeType = FromCPtr->getPointeeType();
2572  else if (const BlockPointerType *FromBlockPtr =
2573  FromType->getAs<BlockPointerType>())
2574  FromPointeeType = FromBlockPtr->getPointeeType();
2575  else
2576  return false;
2577 
2578  // If we have pointers to pointers, recursively check whether this
2579  // is an Objective-C conversion.
2580  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2581  isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2582  IncompatibleObjC)) {
2583  // We always complain about this conversion.
2584  IncompatibleObjC = true;
2585  ConvertedType = Context.getPointerType(ConvertedType);
2586  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2587  return true;
2588  }
2589  // Allow conversion of pointee being objective-c pointer to another one;
2590  // as in I* to id.
2591  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2592  ToPointeeType->getAs<ObjCObjectPointerType>() &&
2593  isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2594  IncompatibleObjC)) {
2595 
2596  ConvertedType = Context.getPointerType(ConvertedType);
2597  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2598  return true;
2599  }
2600 
2601  // If we have pointers to functions or blocks, check whether the only
2602  // differences in the argument and result types are in Objective-C
2603  // pointer conversions. If so, we permit the conversion (but
2604  // complain about it).
2605  const FunctionProtoType *FromFunctionType
2606  = FromPointeeType->getAs<FunctionProtoType>();
2607  const FunctionProtoType *ToFunctionType
2608  = ToPointeeType->getAs<FunctionProtoType>();
2609  if (FromFunctionType && ToFunctionType) {
2610  // If the function types are exactly the same, this isn't an
2611  // Objective-C pointer conversion.
2612  if (Context.getCanonicalType(FromPointeeType)
2613  == Context.getCanonicalType(ToPointeeType))
2614  return false;
2615 
2616  // Perform the quick checks that will tell us whether these
2617  // function types are obviously different.
2618  if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2619  FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2620  FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2621  return false;
2622 
2623  bool HasObjCConversion = false;
2624  if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2625  Context.getCanonicalType(ToFunctionType->getReturnType())) {
2626  // Okay, the types match exactly. Nothing to do.
2627  } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2628  ToFunctionType->getReturnType(),
2629  ConvertedType, IncompatibleObjC)) {
2630  // Okay, we have an Objective-C pointer conversion.
2631  HasObjCConversion = true;
2632  } else {
2633  // Function types are too different. Abort.
2634  return false;
2635  }
2636 
2637  // Check argument types.
2638  for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2639  ArgIdx != NumArgs; ++ArgIdx) {
2640  QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2641  QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2642  if (Context.getCanonicalType(FromArgType)
2643  == Context.getCanonicalType(ToArgType)) {
2644  // Okay, the types match exactly. Nothing to do.
2645  } else if (isObjCPointerConversion(FromArgType, ToArgType,
2646  ConvertedType, IncompatibleObjC)) {
2647  // Okay, we have an Objective-C pointer conversion.
2648  HasObjCConversion = true;
2649  } else {
2650  // Argument types are too different. Abort.
2651  return false;
2652  }
2653  }
2654 
2655  if (HasObjCConversion) {
2656  // We had an Objective-C conversion. Allow this pointer
2657  // conversion, but complain about it.
2658  ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2659  IncompatibleObjC = true;
2660  return true;
2661  }
2662  }
2663 
2664  return false;
2665 }
2666 
2667 /// Determine whether this is an Objective-C writeback conversion,
2668 /// used for parameter passing when performing automatic reference counting.
2669 ///
2670 /// \param FromType The type we're converting form.
2671 ///
2672 /// \param ToType The type we're converting to.
2673 ///
2674 /// \param ConvertedType The type that will be produced after applying
2675 /// this conversion.
2677  QualType &ConvertedType) {
2678  if (!getLangOpts().ObjCAutoRefCount ||
2679  Context.hasSameUnqualifiedType(FromType, ToType))
2680  return false;
2681 
2682  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2683  QualType ToPointee;
2684  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2685  ToPointee = ToPointer->getPointeeType();
2686  else
2687  return false;
2688 
2689  Qualifiers ToQuals = ToPointee.getQualifiers();
2690  if (!ToPointee->isObjCLifetimeType() ||
2692  !ToQuals.withoutObjCLifetime().empty())
2693  return false;
2694 
2695  // Argument must be a pointer to __strong to __weak.
2696  QualType FromPointee;
2697  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2698  FromPointee = FromPointer->getPointeeType();
2699  else
2700  return false;
2701 
2702  Qualifiers FromQuals = FromPointee.getQualifiers();
2703  if (!FromPointee->isObjCLifetimeType() ||
2704  (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2705  FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2706  return false;
2707 
2708  // Make sure that we have compatible qualifiers.
2710  if (!ToQuals.compatiblyIncludes(FromQuals))
2711  return false;
2712 
2713  // Remove qualifiers from the pointee type we're converting from; they
2714  // aren't used in the compatibility check belong, and we'll be adding back
2715  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2716  FromPointee = FromPointee.getUnqualifiedType();
2717 
2718  // The unqualified form of the pointee types must be compatible.
2719  ToPointee = ToPointee.getUnqualifiedType();
2720  bool IncompatibleObjC;
2721  if (Context.typesAreCompatible(FromPointee, ToPointee))
2722  FromPointee = ToPointee;
2723  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2724  IncompatibleObjC))
2725  return false;
2726 
2727  /// Construct the type we're converting to, which is a pointer to
2728  /// __autoreleasing pointee.
2729  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2730  ConvertedType = Context.getPointerType(FromPointee);
2731  return true;
2732 }
2733 
2735  QualType& ConvertedType) {
2736  QualType ToPointeeType;
2737  if (const BlockPointerType *ToBlockPtr =
2738  ToType->getAs<BlockPointerType>())
2739  ToPointeeType = ToBlockPtr->getPointeeType();
2740  else
2741  return false;
2742 
2743  QualType FromPointeeType;
2744  if (const BlockPointerType *FromBlockPtr =
2745  FromType->getAs<BlockPointerType>())
2746  FromPointeeType = FromBlockPtr->getPointeeType();
2747  else
2748  return false;
2749  // We have pointer to blocks, check whether the only
2750  // differences in the argument and result types are in Objective-C
2751  // pointer conversions. If so, we permit the conversion.
2752 
2753  const FunctionProtoType *FromFunctionType
2754  = FromPointeeType->getAs<FunctionProtoType>();
2755  const FunctionProtoType *ToFunctionType
2756  = ToPointeeType->getAs<FunctionProtoType>();
2757 
2758  if (!FromFunctionType || !ToFunctionType)
2759  return false;
2760 
2761  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2762  return true;
2763 
2764  // Perform the quick checks that will tell us whether these
2765  // function types are obviously different.
2766  if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2767  FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2768  return false;
2769 
2770  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2771  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2772  if (FromEInfo != ToEInfo)
2773  return false;
2774 
2775  bool IncompatibleObjC = false;
2776  if (Context.hasSameType(FromFunctionType->getReturnType(),
2777  ToFunctionType->getReturnType())) {
2778  // Okay, the types match exactly. Nothing to do.
2779  } else {
2780  QualType RHS = FromFunctionType->getReturnType();
2781  QualType LHS = ToFunctionType->getReturnType();
2782  if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2783  !RHS.hasQualifiers() && LHS.hasQualifiers())
2784  LHS = LHS.getUnqualifiedType();
2785 
2786  if (Context.hasSameType(RHS,LHS)) {
2787  // OK exact match.
2788  } else if (isObjCPointerConversion(RHS, LHS,
2789  ConvertedType, IncompatibleObjC)) {
2790  if (IncompatibleObjC)
2791  return false;
2792  // Okay, we have an Objective-C pointer conversion.
2793  }
2794  else
2795  return false;
2796  }
2797 
2798  // Check argument types.
2799  for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2800  ArgIdx != NumArgs; ++ArgIdx) {
2801  IncompatibleObjC = false;
2802  QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2803  QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2804  if (Context.hasSameType(FromArgType, ToArgType)) {
2805  // Okay, the types match exactly. Nothing to do.
2806  } else if (isObjCPointerConversion(ToArgType, FromArgType,
2807  ConvertedType, IncompatibleObjC)) {
2808  if (IncompatibleObjC)
2809  return false;
2810  // Okay, we have an Objective-C pointer conversion.
2811  } else
2812  // Argument types are too different. Abort.
2813  return false;
2814  }
2815 
2817  bool CanUseToFPT, CanUseFromFPT;
2818  if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2819  CanUseToFPT, CanUseFromFPT,
2820  NewParamInfos))
2821  return false;
2822 
2823  ConvertedType = ToType;
2824  return true;
2825 }
2826 
2827 enum {
2835 };
2836 
2837 /// Attempts to get the FunctionProtoType from a Type. Handles
2838 /// MemberFunctionPointers properly.
2840  if (auto *FPT = FromType->getAs<FunctionProtoType>())
2841  return FPT;
2842 
2843  if (auto *MPT = FromType->getAs<MemberPointerType>())
2844  return MPT->getPointeeType()->getAs<FunctionProtoType>();
2845 
2846  return nullptr;
2847 }
2848 
2849 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2850 /// function types. Catches different number of parameter, mismatch in
2851 /// parameter types, and different return types.
2853  QualType FromType, QualType ToType) {
2854  // If either type is not valid, include no extra info.
2855  if (FromType.isNull() || ToType.isNull()) {
2856  PDiag << ft_default;
2857  return;
2858  }
2859 
2860  // Get the function type from the pointers.
2861  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2862  const auto *FromMember = FromType->castAs<MemberPointerType>(),
2863  *ToMember = ToType->castAs<MemberPointerType>();
2864  if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2865  PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2866  << QualType(FromMember->getClass(), 0);
2867  return;
2868  }
2869  FromType = FromMember->getPointeeType();
2870  ToType = ToMember->getPointeeType();
2871  }
2872 
2873  if (FromType->isPointerType())
2874  FromType = FromType->getPointeeType();
2875  if (ToType->isPointerType())
2876  ToType = ToType->getPointeeType();
2877 
2878  // Remove references.
2879  FromType = FromType.getNonReferenceType();
2880  ToType = ToType.getNonReferenceType();
2881 
2882  // Don't print extra info for non-specialized template functions.
2883  if (FromType->isInstantiationDependentType() &&
2884  !FromType->getAs<TemplateSpecializationType>()) {
2885  PDiag << ft_default;
2886  return;
2887  }
2888 
2889  // No extra info for same types.
2890  if (Context.hasSameType(FromType, ToType)) {
2891  PDiag << ft_default;
2892  return;
2893  }
2894 
2895  const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2896  *ToFunction = tryGetFunctionProtoType(ToType);
2897 
2898  // Both types need to be function types.
2899  if (!FromFunction || !ToFunction) {
2900  PDiag << ft_default;
2901  return;
2902  }
2903 
2904  if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2905  PDiag << ft_parameter_arity << ToFunction->getNumParams()
2906  << FromFunction->getNumParams();
2907  return;
2908  }
2909 
2910  // Handle different parameter types.
2911  unsigned ArgPos;
2912  if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2913  PDiag << ft_parameter_mismatch << ArgPos + 1
2914  << ToFunction->getParamType(ArgPos)
2915  << FromFunction->getParamType(ArgPos);
2916  return;
2917  }
2918 
2919  // Handle different return type.
2920  if (!Context.hasSameType(FromFunction->getReturnType(),
2921  ToFunction->getReturnType())) {
2922  PDiag << ft_return_type << ToFunction->getReturnType()
2923  << FromFunction->getReturnType();
2924  return;
2925  }
2926 
2927  if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2928  PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2929  << FromFunction->getMethodQuals();
2930  return;
2931  }
2932 
2933  // Handle exception specification differences on canonical type (in C++17
2934  // onwards).
2935  if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2936  ->isNothrow() !=
2937  cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2938  ->isNothrow()) {
2939  PDiag << ft_noexcept;
2940  return;
2941  }
2942 
2943  // Unable to find a difference, so add no extra info.
2944  PDiag << ft_default;
2945 }
2946 
2947 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2948 /// for equality of their parameter types. Caller has already checked that
2949 /// they have same number of parameters. If the parameters are different,
2950 /// ArgPos will have the parameter index of the first different parameter.
2951 /// If `Reversed` is true, the parameters of `NewType` will be compared in
2952 /// reverse order. That's useful if one of the functions is being used as a C++20
2953 /// synthesized operator overload with a reversed parameter order.
2955  const FunctionProtoType *NewType,
2956  unsigned *ArgPos, bool Reversed) {
2957  assert(OldType->getNumParams() == NewType->getNumParams() &&
2958  "Can't compare parameters of functions with different number of "
2959  "parameters!");
2960  for (size_t I = 0; I < OldType->getNumParams(); I++) {
2961  // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
2962  size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I;
2963 
2964  // Ignore address spaces in pointee type. This is to disallow overloading
2965  // on __ptr32/__ptr64 address spaces.
2966  QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType());
2967  QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType());
2968 
2969  if (!Context.hasSameType(Old, New)) {
2970  if (ArgPos)
2971  *ArgPos = I;
2972  return false;
2973  }
2974  }
2975  return true;
2976 }
2977 
2978 /// CheckPointerConversion - Check the pointer conversion from the
2979 /// expression From to the type ToType. This routine checks for
2980 /// ambiguous or inaccessible derived-to-base pointer
2981 /// conversions for which IsPointerConversion has already returned
2982 /// true. It returns true and produces a diagnostic if there was an
2983 /// error, or returns false otherwise.
2985  CastKind &Kind,
2986  CXXCastPath& BasePath,
2987  bool IgnoreBaseAccess,
2988  bool Diagnose) {
2989  QualType FromType = From->getType();
2990  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2991 
2992  Kind = CK_BitCast;
2993 
2994  if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2997  if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2998  DiagRuntimeBehavior(From->getExprLoc(), From,
2999  PDiag(diag::warn_impcast_bool_to_null_pointer)
3000  << ToType << From->getSourceRange());
3001  else if (!isUnevaluatedContext())
3002  Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3003  << ToType << From->getSourceRange();
3004  }
3005  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3006  if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3007  QualType FromPointeeType = FromPtrType->getPointeeType(),
3008  ToPointeeType = ToPtrType->getPointeeType();
3009 
3010  if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3011  !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3012  // We must have a derived-to-base conversion. Check an
3013  // ambiguous or inaccessible conversion.
3014  unsigned InaccessibleID = 0;
3015  unsigned AmbiguousID = 0;
3016  if (Diagnose) {
3017  InaccessibleID = diag::err_upcast_to_inaccessible_base;
3018  AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3019  }
3020  if (CheckDerivedToBaseConversion(
3021  FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3022  From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3023  &BasePath, IgnoreBaseAccess))
3024  return true;
3025 
3026  // The conversion was successful.
3027  Kind = CK_DerivedToBase;
3028  }
3029 
3030  if (Diagnose && !IsCStyleOrFunctionalCast &&
3031  FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3032  assert(getLangOpts().MSVCCompat &&
3033  "this should only be possible with MSVCCompat!");
3034  Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3035  << From->getSourceRange();
3036  }
3037  }
3038  } else if (const ObjCObjectPointerType *ToPtrType =
3039  ToType->getAs<ObjCObjectPointerType>()) {
3040  if (const ObjCObjectPointerType *FromPtrType =
3041  FromType->getAs<ObjCObjectPointerType>()) {
3042  // Objective-C++ conversions are always okay.
3043  // FIXME: We should have a different class of conversions for the
3044  // Objective-C++ implicit conversions.
3045  if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3046  return false;
3047  } else if (FromType->isBlockPointerType()) {
3048  Kind = CK_BlockPointerToObjCPointerCast;
3049  } else {
3050  Kind = CK_CPointerToObjCPointerCast;
3051  }
3052  } else if (ToType->isBlockPointerType()) {
3053  if (!FromType->isBlockPointerType())
3054  Kind = CK_AnyPointerToBlockPointerCast;
3055  }
3056 
3057  // We shouldn't fall into this case unless it's valid for other
3058  // reasons.
3060  Kind = CK_NullToPointer;
3061 
3062  return false;
3063 }
3064 
3065 /// IsMemberPointerConversion - Determines whether the conversion of the
3066 /// expression From, which has the (possibly adjusted) type FromType, can be
3067 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3068 /// If so, returns true and places the converted type (that might differ from
3069 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3071  QualType ToType,
3072  bool InOverloadResolution,
3073  QualType &ConvertedType) {
3074  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3075  if (!ToTypePtr)
3076  return false;
3077 
3078  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3079  if (From->isNullPointerConstant(Context,
3080  InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3082  ConvertedType = ToType;
3083  return true;
3084  }
3085 
3086  // Otherwise, both types have to be member pointers.
3087  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3088  if (!FromTypePtr)
3089  return false;
3090 
3091  // A pointer to member of B can be converted to a pointer to member of D,
3092  // where D is derived from B (C++ 4.11p2).
3093  QualType FromClass(FromTypePtr->getClass(), 0);
3094  QualType ToClass(ToTypePtr->getClass(), 0);
3095 
3096  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3097  IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3098  ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3099  ToClass.getTypePtr());
3100  return true;
3101  }
3102 
3103  return false;
3104 }
3105 
3106 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3107 /// expression From to the type ToType. This routine checks for ambiguous or
3108 /// virtual or inaccessible base-to-derived member pointer conversions
3109 /// for which IsMemberPointerConversion has already returned true. It returns
3110 /// true and produces a diagnostic if there was an error, or returns false
3111 /// otherwise.
3113  CastKind &Kind,
3114  CXXCastPath &BasePath,
3115  bool IgnoreBaseAccess) {
3116  QualType FromType = From->getType();
3117  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3118  if (!FromPtrType) {
3119  // This must be a null pointer to member pointer conversion
3120  assert(From->isNullPointerConstant(Context,
3122  "Expr must be null pointer constant!");
3123  Kind = CK_NullToMemberPointer;
3124  return false;
3125  }
3126 
3127  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3128  assert(ToPtrType && "No member pointer cast has a target type "
3129  "that is not a member pointer.");
3130 
3131  QualType FromClass = QualType(FromPtrType->getClass(), 0);
3132  QualType ToClass = QualType(ToPtrType->getClass(), 0);
3133 
3134  // FIXME: What about dependent types?
3135  assert(FromClass->isRecordType() && "Pointer into non-class.");
3136  assert(ToClass->isRecordType() && "Pointer into non-class.");
3137 
3138  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3139  /*DetectVirtual=*/true);
3140  bool DerivationOkay =
3141  IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3142  assert(DerivationOkay &&
3143  "Should not have been called if derivation isn't OK.");
3144  (void)DerivationOkay;
3145 
3146  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3147  getUnqualifiedType())) {
3148  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3149  Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3150  << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3151  return true;
3152  }
3153 
3154  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3155  Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3156  << FromClass << ToClass << QualType(VBase, 0)
3157  << From->getSourceRange();
3158  return true;
3159  }
3160 
3161  if (!IgnoreBaseAccess)
3162  CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3163  Paths.front(),
3164  diag::err_downcast_from_inaccessible_base);
3165 
3166  // Must be a base to derived member conversion.
3167  BuildBasePathArray(Paths, BasePath);
3168  Kind = CK_BaseToDerivedMemberPointer;
3169  return false;
3170 }
3171 
3172 /// Determine whether the lifetime conversion between the two given
3173 /// qualifiers sets is nontrivial.
3175  Qualifiers ToQuals) {
3176  // Converting anything to const __unsafe_unretained is trivial.
3177  if (ToQuals.hasConst() &&
3179  return false;
3180 
3181  return true;
3182 }
3183 
3184 /// Perform a single iteration of the loop for checking if a qualification
3185 /// conversion is valid.
3186 ///
3187 /// Specifically, check whether any change between the qualifiers of \p
3188 /// FromType and \p ToType is permissible, given knowledge about whether every
3189 /// outer layer is const-qualified.
3190 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3191  bool CStyle, bool IsTopLevel,
3192  bool &PreviousToQualsIncludeConst,
3193  bool &ObjCLifetimeConversion) {
3194  Qualifiers FromQuals = FromType.getQualifiers();
3195  Qualifiers ToQuals = ToType.getQualifiers();
3196 
3197  // Ignore __unaligned qualifier.
3198  FromQuals.removeUnaligned();
3199 
3200  // Objective-C ARC:
3201  // Check Objective-C lifetime conversions.
3202  if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3203  if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3204  if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3205  ObjCLifetimeConversion = true;
3206  FromQuals.removeObjCLifetime();
3207  ToQuals.removeObjCLifetime();
3208  } else {
3209  // Qualification conversions cannot cast between different
3210  // Objective-C lifetime qualifiers.
3211  return false;
3212  }
3213  }
3214 
3215  // Allow addition/removal of GC attributes but not changing GC attributes.
3216  if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3217  (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3218  FromQuals.removeObjCGCAttr();
3219  ToQuals.removeObjCGCAttr();
3220  }
3221 
3222  // -- for every j > 0, if const is in cv 1,j then const is in cv
3223  // 2,j, and similarly for volatile.
3224  if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3225  return false;
3226 
3227  // If address spaces mismatch:
3228  // - in top level it is only valid to convert to addr space that is a
3229  // superset in all cases apart from C-style casts where we allow
3230  // conversions between overlapping address spaces.
3231  // - in non-top levels it is not a valid conversion.
3232  if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3233  (!IsTopLevel ||
3234  !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3235  (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3236  return false;
3237 
3238  // -- if the cv 1,j and cv 2,j are different, then const is in
3239  // every cv for 0 < k < j.
3240  if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3241  !PreviousToQualsIncludeConst)
3242  return false;
3243 
3244  // The following wording is from C++20, where the result of the conversion
3245  // is T3, not T2.
3246  // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3247  // "array of unknown bound of"
3248  if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3249  return false;
3250 
3251  // -- if the resulting P3,i is different from P1,i [...], then const is
3252  // added to every cv 3_k for 0 < k < i.
3253  if (!CStyle && FromType->isConstantArrayType() &&
3254  ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3255  return false;
3256 
3257  // Keep track of whether all prior cv-qualifiers in the "to" type
3258  // include const.
3259  PreviousToQualsIncludeConst =
3260  PreviousToQualsIncludeConst && ToQuals.hasConst();
3261  return true;
3262 }
3263 
3264 /// IsQualificationConversion - Determines whether the conversion from
3265 /// an rvalue of type FromType to ToType is a qualification conversion
3266 /// (C++ 4.4).
3267 ///
3268 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3269 /// when the qualification conversion involves a change in the Objective-C
3270 /// object lifetime.
3271 bool
3273  bool CStyle, bool &ObjCLifetimeConversion) {
3274  FromType = Context.getCanonicalType(FromType);
3275  ToType = Context.getCanonicalType(ToType);
3276  ObjCLifetimeConversion = false;
3277 
3278  // If FromType and ToType are the same type, this is not a
3279  // qualification conversion.
3280  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3281  return false;
3282 
3283  // (C++ 4.4p4):
3284  // A conversion can add cv-qualifiers at levels other than the first
3285  // in multi-level pointers, subject to the following rules: [...]
3286  bool PreviousToQualsIncludeConst = true;
3287  bool UnwrappedAnyPointer = false;
3288  while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3290  FromType, ToType, CStyle, !UnwrappedAnyPointer,
3291  PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3292  return false;
3293  UnwrappedAnyPointer = true;
3294  }
3295 
3296  // We are left with FromType and ToType being the pointee types
3297  // after unwrapping the original FromType and ToType the same number
3298  // of times. If we unwrapped any pointers, and if FromType and
3299  // ToType have the same unqualified type (since we checked
3300  // qualifiers above), then this is a qualification conversion.
3301  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3302 }
3303 
3304 /// - Determine whether this is a conversion from a scalar type to an
3305 /// atomic type.
3306 ///
3307 /// If successful, updates \c SCS's second and third steps in the conversion
3308 /// sequence to finish the conversion.
3309 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3310  bool InOverloadResolution,
3312  bool CStyle) {
3313  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3314  if (!ToAtomic)
3315  return false;
3316 
3317  StandardConversionSequence InnerSCS;
3318  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3319  InOverloadResolution, InnerSCS,
3320  CStyle, /*AllowObjCWritebackConversion=*/false))
3321  return false;
3322 
3323  SCS.Second = InnerSCS.Second;
3324  SCS.setToType(1, InnerSCS.getToType(1));
3325  SCS.Third = InnerSCS.Third;
3328  SCS.setToType(2, InnerSCS.getToType(2));
3329  return true;
3330 }
3331 
3333  CXXConstructorDecl *Constructor,
3334  QualType Type) {
3335  const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3336  if (CtorType->getNumParams() > 0) {
3337  QualType FirstArg = CtorType->getParamType(0);
3338  if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3339  return true;
3340  }
3341  return false;
3342 }
3343 
3344 static OverloadingResult
3346  CXXRecordDecl *To,
3348  OverloadCandidateSet &CandidateSet,
3349  bool AllowExplicit) {
3351  for (auto *D : S.LookupConstructors(To)) {
3352  auto Info = getConstructorInfo(D);
3353  if (!Info)
3354  continue;
3355 
3356  bool Usable = !Info.Constructor->isInvalidDecl() &&
3357  S.isInitListConstructor(Info.Constructor);
3358  if (Usable) {
3359  bool SuppressUserConversions = false;
3360  if (Info.ConstructorTmpl)
3361  S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3362  /*ExplicitArgs*/ nullptr, From,
3363  CandidateSet, SuppressUserConversions,
3364  /*PartialOverloading*/ false,
3365  AllowExplicit);
3366  else
3367  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3368  CandidateSet, SuppressUserConversions,
3369  /*PartialOverloading*/ false, AllowExplicit);
3370  }
3371  }
3372 
3373  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3374 
3376  switch (auto Result =
3377  CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3378  case OR_Deleted:
3379  case OR_Success: {
3380  // Record the standard conversion we used and the conversion function.
3381  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3382  QualType ThisType = Constructor->getThisType();
3383  // Initializer lists don't have conversions as such.
3385  User.HadMultipleCandidates = HadMultipleCandidates;
3386  User.ConversionFunction = Constructor;
3387  User.FoundConversionFunction = Best->FoundDecl;
3389  User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3390  User.After.setAllToTypes(ToType);
3391  return Result;
3392  }
3393 
3394  case OR_No_Viable_Function:
3395  return OR_No_Viable_Function;
3396  case OR_Ambiguous:
3397  return OR_Ambiguous;
3398  }
3399 
3400  llvm_unreachable("Invalid OverloadResult!");
3401 }
3402 
3403 /// Determines whether there is a user-defined conversion sequence
3404 /// (C++ [over.ics.user]) that converts expression From to the type
3405 /// ToType. If such a conversion exists, User will contain the
3406 /// user-defined conversion sequence that performs such a conversion
3407 /// and this routine will return true. Otherwise, this routine returns
3408 /// false and User is unspecified.
3409 ///
3410 /// \param AllowExplicit true if the conversion should consider C++0x
3411 /// "explicit" conversion functions as well as non-explicit conversion
3412 /// functions (C++0x [class.conv.fct]p2).
3413 ///
3414 /// \param AllowObjCConversionOnExplicit true if the conversion should
3415 /// allow an extra Objective-C pointer conversion on uses of explicit
3416 /// constructors. Requires \c AllowExplicit to also be set.
3417 static OverloadingResult
3420  OverloadCandidateSet &CandidateSet,
3421  AllowedExplicit AllowExplicit,
3422  bool AllowObjCConversionOnExplicit) {
3423  assert(AllowExplicit != AllowedExplicit::None ||
3424  !AllowObjCConversionOnExplicit);
3426 
3427  // Whether we will only visit constructors.
3428  bool ConstructorsOnly = false;
3429 
3430  // If the type we are conversion to is a class type, enumerate its
3431  // constructors.
3432  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3433  // C++ [over.match.ctor]p1:
3434  // When objects of class type are direct-initialized (8.5), or
3435  // copy-initialized from an expression of the same or a
3436  // derived class type (8.5), overload resolution selects the
3437  // constructor. [...] For copy-initialization, the candidate
3438  // functions are all the converting constructors (12.3.1) of
3439  // that class. The argument list is the expression-list within
3440  // the parentheses of the initializer.
3441  if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3442  (From->getType()->getAs<RecordType>() &&
3443  S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3444  ConstructorsOnly = true;
3445 
3446  if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3447  // We're not going to find any constructors.
3448  } else if (CXXRecordDecl *ToRecordDecl
3449  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3450 
3451  Expr **Args = &From;
3452  unsigned NumArgs = 1;
3453  bool ListInitializing = false;
3454  if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3455  // But first, see if there is an init-list-constructor that will work.
3457  S, From, ToType, ToRecordDecl, User, CandidateSet,
3458  AllowExplicit == AllowedExplicit::All);
3459  if (Result != OR_No_Viable_Function)
3460  return Result;
3461  // Never mind.
3462  CandidateSet.clear(
3464 
3465  // If we're list-initializing, we pass the individual elements as
3466  // arguments, not the entire list.
3467  Args = InitList->getInits();
3468  NumArgs = InitList->getNumInits();
3469  ListInitializing = true;
3470  }
3471 
3472  for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3473  auto Info = getConstructorInfo(D);
3474  if (!Info)
3475  continue;
3476 
3477  bool Usable = !Info.Constructor->isInvalidDecl();
3478  if (!ListInitializing)
3479  Usable = Usable && Info.Constructor->isConvertingConstructor(
3480  /*AllowExplicit*/ true);
3481  if (Usable) {
3482  bool SuppressUserConversions = !ConstructorsOnly;
3483  // C++20 [over.best.ics.general]/4.5:
3484  // if the target is the first parameter of a constructor [of class
3485  // X] and the constructor [...] is a candidate by [...] the second
3486  // phase of [over.match.list] when the initializer list has exactly
3487  // one element that is itself an initializer list, [...] and the
3488  // conversion is to X or reference to cv X, user-defined conversion
3489  // sequences are not cnosidered.
3490  if (SuppressUserConversions && ListInitializing) {
3491  SuppressUserConversions =
3492  NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3493  isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3494  ToType);
3495  }
3496  if (Info.ConstructorTmpl)
3498  Info.ConstructorTmpl, Info.FoundDecl,
3499  /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3500  CandidateSet, SuppressUserConversions,
3501  /*PartialOverloading*/ false,
3502  AllowExplicit == AllowedExplicit::All);
3503  else
3504  // Allow one user-defined conversion when user specifies a
3505  // From->ToType conversion via an static cast (c-style, etc).
3506  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3507  llvm::makeArrayRef(Args, NumArgs),
3508  CandidateSet, SuppressUserConversions,
3509  /*PartialOverloading*/ false,
3510  AllowExplicit == AllowedExplicit::All);
3511  }
3512  }
3513  }
3514  }
3515 
3516  // Enumerate conversion functions, if we're allowed to.
3517  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3518  } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3519  // No conversion functions from incomplete types.
3520  } else if (const RecordType *FromRecordType =
3521  From->getType()->getAs<RecordType>()) {
3522  if (CXXRecordDecl *FromRecordDecl
3523  = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3524  // Add all of the conversion functions as candidates.
3525  const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3526  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3527  DeclAccessPair FoundDecl = I.getPair();
3528  NamedDecl *D = FoundDecl.getDecl();
3529  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3530  if (isa<UsingShadowDecl>(D))
3531  D = cast<UsingShadowDecl>(D)->getTargetDecl();
3532 
3533  CXXConversionDecl *Conv;
3534  FunctionTemplateDecl *ConvTemplate;
3535  if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3536  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3537  else
3538  Conv = cast<CXXConversionDecl>(D);
3539 
3540  if (ConvTemplate)
3542  ConvTemplate, FoundDecl, ActingContext, From, ToType,
3543  CandidateSet, AllowObjCConversionOnExplicit,
3544  AllowExplicit != AllowedExplicit::None);
3545  else
3546  S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3547  CandidateSet, AllowObjCConversionOnExplicit,
3548  AllowExplicit != AllowedExplicit::None);
3549  }
3550  }
3551  }
3552 
3553  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3554 
3556  switch (auto Result =
3557  CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3558  case OR_Success:
3559  case OR_Deleted:
3560  // Record the standard conversion we used and the conversion function.
3561  if (CXXConstructorDecl *Constructor
3562  = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3563  // C++ [over.ics.user]p1:
3564  // If the user-defined conversion is specified by a
3565  // constructor (12.3.1), the initial standard conversion
3566  // sequence converts the source type to the type required by
3567  // the argument of the constructor.
3568  //
3569  QualType ThisType = Constructor->getThisType();
3570  if (isa<InitListExpr>(From)) {
3571  // Initializer lists don't have conversions as such.
3573  } else {
3574  if (Best->Conversions[0].isEllipsis())
3575  User.EllipsisConversion = true;
3576  else {
3577  User.Before = Best->Conversions[0].Standard;
3578  User.EllipsisConversion = false;
3579  }
3580  }
3581  User.HadMultipleCandidates = HadMultipleCandidates;
3582  User.ConversionFunction = Constructor;
3583  User.FoundConversionFunction = Best->FoundDecl;
3585  User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3586  User.After.setAllToTypes(ToType);
3587  return Result;
3588  }
3589  if (CXXConversionDecl *Conversion
3590  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3591  // C++ [over.ics.user]p1:
3592  //
3593  // [...] If the user-defined conversion is specified by a
3594  // conversion function (12.3.2), the initial standard
3595  // conversion sequence converts the source type to the
3596  // implicit object parameter of the conversion function.
3597  User.Before = Best->Conversions[0].Standard;
3598  User.HadMultipleCandidates = HadMultipleCandidates;
3599  User.ConversionFunction = Conversion;
3600  User.FoundConversionFunction = Best->FoundDecl;
3601  User.EllipsisConversion = false;
3602 
3603  // C++ [over.ics.user]p2:
3604  // The second standard conversion sequence converts the
3605  // result of the user-defined conversion to the target type
3606  // for the sequence. Since an implicit conversion sequence
3607  // is an initialization, the special rules for
3608  // initialization by user-defined conversion apply when
3609  // selecting the best user-defined conversion for a
3610  // user-defined conversion sequence (see 13.3.3 and
3611  // 13.3.3.1).
3612  User.After = Best->FinalConversion;
3613  return Result;
3614  }
3615  llvm_unreachable("Not a constructor or conversion function?");
3616 
3617  case OR_No_Viable_Function:
3618  return OR_No_Viable_Function;
3619 
3620  case OR_Ambiguous:
3621  return OR_Ambiguous;
3622  }
3623 
3624  llvm_unreachable("Invalid OverloadResult!");
3625 }
3626 
3627 bool
3630  OverloadCandidateSet CandidateSet(From->getExprLoc(),
3632  OverloadingResult OvResult =
3633  IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3634  CandidateSet, AllowedExplicit::None, false);
3635 
3636  if (!(OvResult == OR_Ambiguous ||
3637  (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3638  return false;
3639 
3640  auto Cands = CandidateSet.CompleteCandidates(
3641  *this,
3643  From);
3644  if (OvResult == OR_Ambiguous)
3645  Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3646  << From->getType() << ToType << From->getSourceRange();
3647  else { // OR_No_Viable_Function && !CandidateSet.empty()
3648  if (!RequireCompleteType(From->getBeginLoc(), ToType,
3649  diag::err_typecheck_nonviable_condition_incomplete,
3650  From->getType(), From->getSourceRange()))
3651  Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3652  << false << From->getType() << From->getSourceRange() << ToType;
3653  }
3654 
3655  CandidateSet.NoteCandidates(
3656  *this, From, Cands);
3657  return true;
3658 }
3659 
3660 // Helper for compareConversionFunctions that gets the FunctionType that the
3661 // conversion-operator return value 'points' to, or nullptr.
3662 static const FunctionType *
3664  const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3665  const PointerType *RetPtrTy =
3666  ConvFuncTy->getReturnType()->getAs<PointerType>();
3667 
3668  if (!RetPtrTy)
3669  return nullptr;
3670 
3671  return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3672 }
3673 
3674 /// Compare the user-defined conversion functions or constructors
3675 /// of two user-defined conversion sequences to determine whether any ordering
3676 /// is possible.
3679  FunctionDecl *Function2) {
3680  CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3681  CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3682  if (!Conv1 || !Conv2)
3684 
3685  if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3687 
3688  // Objective-C++:
3689  // If both conversion functions are implicitly-declared conversions from
3690  // a lambda closure type to a function pointer and a block pointer,
3691  // respectively, always prefer the conversion to a function pointer,
3692  // because the function pointer is more lightweight and is more likely
3693  // to keep code working.
3694  if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3695  bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3696  bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3697  if (Block1 != Block2)
3698  return Block1 ? ImplicitConversionSequence::Worse
3700  }
3701 
3702  // In order to support multiple calling conventions for the lambda conversion
3703  // operator (such as when the free and member function calling convention is
3704  // different), prefer the 'free' mechanism, followed by the calling-convention
3705  // of operator(). The latter is in place to support the MSVC-like solution of
3706  // defining ALL of the possible conversions in regards to calling-convention.
3707  const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3708  const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3709 
3710  if (Conv1FuncRet && Conv2FuncRet &&
3711  Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3712  CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3713  CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3714 
3715  CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3716  const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3717 
3718  CallingConv CallOpCC =
3719  CallOp->getType()->castAs<FunctionType>()->getCallConv();
3721  CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3723  CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3724 
3725  CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3726  for (CallingConv CC : PrefOrder) {
3727  if (Conv1CC == CC)
3729  if (Conv2CC == CC)
3731  }
3732  }
3733 
3735 }
3736 
3738  const ImplicitConversionSequence &ICS) {
3739  return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3740  (ICS.isUserDefined() &&
3742 }
3743 
3744 /// CompareImplicitConversionSequences - Compare two implicit
3745 /// conversion sequences to determine whether one is better than the
3746 /// other or if they are indistinguishable (C++ 13.3.3.2).
3749  const ImplicitConversionSequence& ICS1,
3750  const ImplicitConversionSequence& ICS2)
3751 {
3752  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3753  // conversion sequences (as defined in 13.3.3.1)
3754  // -- a standard conversion sequence (13.3.3.1.1) is a better
3755  // conversion sequence than a user-defined conversion sequence or
3756  // an ellipsis conversion sequence, and
3757  // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3758  // conversion sequence than an ellipsis conversion sequence
3759  // (13.3.3.1.3).
3760  //
3761  // C++0x [over.best.ics]p10:
3762  // For the purpose of ranking implicit conversion sequences as
3763  // described in 13.3.3.2, the ambiguous conversion sequence is
3764  // treated as a user-defined sequence that is indistinguishable
3765  // from any other user-defined conversion sequence.
3766 
3767  // String literal to 'char *' conversion has been deprecated in C++03. It has
3768  // been removed from C++11. We still accept this conversion, if it happens at
3769  // the best viable function. Otherwise, this conversion is considered worse
3770  // than ellipsis conversion. Consider this as an extension; this is not in the
3771  // standard. For example:
3772  //
3773  // int &f(...); // #1
3774  // void f(char*); // #2
3775  // void g() { int &r = f("foo"); }
3776  //
3777  // In C++03, we pick #2 as the best viable function.
3778  // In C++11, we pick #1 as the best viable function, because ellipsis
3779  // conversion is better than string-literal to char* conversion (since there
3780  // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3781  // convert arguments, #2 would be the best viable function in C++11.
3782  // If the best viable function has this conversion, a warning will be issued
3783  // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3784 
3785  if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3788  // Ill-formedness must not differ
3789  ICS1.isBad() == ICS2.isBad())
3793 
3794  if (ICS1.getKindRank() < ICS2.getKindRank())
3796  if (ICS2.getKindRank() < ICS1.getKindRank())
3798 
3799  // The following checks require both conversion sequences to be of
3800  // the same kind.
3801  if (ICS1.getKind() != ICS2.getKind())
3803 
3806 
3807  // Two implicit conversion sequences of the same form are
3808  // indistinguishable conversion sequences unless one of the
3809  // following rules apply: (C++ 13.3.3.2p3):
3810 
3811  // List-initialization sequence L1 is a better conversion sequence than
3812  // list-initialization sequence L2 if:
3813  // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3814  // if not that,
3815  // — L1 and L2 convert to arrays of the same element type, and either the
3816  // number of elements n_1 initialized by L1 is less than the number of
3817  // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3818  // an array of unknown bound and L1 does not,
3819  // even if one of the other rules in this paragraph would otherwise apply.
3820  if (!ICS1.isBad()) {
3821  bool StdInit1 = false, StdInit2 = false;
3824  nullptr);
3827  nullptr);
3828  if (StdInit1 != StdInit2)
3829  return StdInit1 ? ImplicitConversionSequence::Better
3831 
3832  if (ICS1.hasInitializerListContainerType() &&
3834  if (auto *CAT1 = S.Context.getAsConstantArrayType(
3836  if (auto *CAT2 = S.Context.getAsConstantArrayType(
3838  if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3839  CAT2->getElementType())) {
3840  // Both to arrays of the same element type
3841  if (CAT1->getSize() != CAT2->getSize())
3842  // Different sized, the smaller wins
3843  return CAT1->getSize().ult(CAT2->getSize())
3848  // One is incomplete, it loses
3852  }
3853  }
3854  }
3855 
3856  if (ICS1.isStandard())
3857  // Standard conversion sequence S1 is a better conversion sequence than
3858  // standard conversion sequence S2 if [...]
3859  Result = CompareStandardConversionSequences(S, Loc,
3860  ICS1.Standard, ICS2.Standard);
3861  else if (ICS1.isUserDefined()) {
3862  // User-defined conversion sequence U1 is a better conversion
3863  // sequence than another user-defined conversion sequence U2 if
3864  // they contain the same user-defined conversion function or
3865  // constructor and if the second standard conversion sequence of
3866  // U1 is better than the second standard conversion sequence of
3867  // U2 (C++ 13.3.3.2p3).
3868  if (ICS1.UserDefined.ConversionFunction ==
3870  Result = CompareStandardConversionSequences(S, Loc,
3871  ICS1.UserDefined.After,
3872  ICS2.UserDefined.After);
3873  else
3874  Result = compareConversionFunctions(S,
3877  }
3878 
3879  return Result;
3880 }
3881 
3882 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3883 // determine if one is a proper subset of the other.
3886  const StandardConversionSequence& SCS1,
3887  const StandardConversionSequence& SCS2) {
3890 
3891  // the identity conversion sequence is considered to be a subsequence of
3892  // any non-identity conversion sequence
3893  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3895  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3897 
3898  if (SCS1.Second != SCS2.Second) {
3899  if (SCS1.Second == ICK_Identity)
3901  else if (SCS2.Second == ICK_Identity)
3903  else
3905  } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3907 
3908  if (SCS1.Third == SCS2.Third) {
3909  return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3911  }
3912 
3913  if (SCS1.Third == ICK_Identity)
3914  return Result == ImplicitConversionSequence::Worse
3917 
3918  if (SCS2.Third == ICK_Identity)
3919  return Result == ImplicitConversionSequence::Better
3922 
3924 }
3925 
3926 /// Determine whether one of the given reference bindings is better
3927 /// than the other based on what kind of bindings they are.
3928 static bool
3930  const StandardConversionSequence &SCS2) {
3931  // C++0x [over.ics.rank]p3b4:
3932  // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3933  // implicit object parameter of a non-static member function declared
3934  // without a ref-qualifier, and *either* S1 binds an rvalue reference
3935  // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3936  // lvalue reference to a function lvalue and S2 binds an rvalue
3937  // reference*.
3938  //
3939  // FIXME: Rvalue references. We're going rogue with the above edits,
3940  // because the semantics in the current C++0x working paper (N3225 at the
3941  // time of this writing) break the standard definition of std::forward
3942  // and std::reference_wrapper when dealing with references to functions.
3943  // Proposed wording changes submitted to CWG for consideration.
3946  return false;
3947 
3948  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3949  SCS2.IsLvalueReference) ||
3950  (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3952 }
3953 
3955  None,
3958 };
3959 
3960 /// Returns kind of fixed enum promotion the \a SCS uses.
3961 static FixedEnumPromotion
3963 
3964  if (SCS.Second != ICK_Integral_Promotion)
3965  return FixedEnumPromotion::None;
3966 
3967  QualType FromType = SCS.getFromType();
3968  if (!FromType->isEnumeralType())
3969  return FixedEnumPromotion::None;
3970 
3971  EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
3972  if (!Enum->isFixed())
3973  return FixedEnumPromotion::None;
3974 
3975  QualType UnderlyingType = Enum->getIntegerType();
3976  if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3978 
3980 }
3981 
3982 /// CompareStandardConversionSequences - Compare two standard
3983 /// conversion sequences to determine whether one is better than the
3984 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3987  const StandardConversionSequence& SCS1,
3988  const StandardConversionSequence& SCS2)
3989 {
3990  // Standard conversion sequence S1 is a better conversion sequence
3991  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3992 
3993  // -- S1 is a proper subsequence of S2 (comparing the conversion
3994  // sequences in the canonical form defined by 13.3.3.1.1,
3995  // excluding any Lvalue Transformation; the identity conversion
3996  // sequence is considered to be a subsequence of any
3997  // non-identity conversion sequence) or, if not that,
3999  = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4000  return CK;
4001 
4002  // -- the rank of S1 is better than the rank of S2 (by the rules
4003  // defined below), or, if not that,
4004  ImplicitConversionRank Rank1 = SCS1.getRank();
4005  ImplicitConversionRank Rank2 = SCS2.getRank();
4006  if (Rank1 < Rank2)
4008  else if (Rank2 < Rank1)
4010 
4011  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4012  // are indistinguishable unless one of the following rules
4013  // applies:
4014 
4015  // A conversion that is not a conversion of a pointer, or
4016  // pointer to member, to bool is better than another conversion
4017  // that is such a conversion.
4019  return SCS2.isPointerConversionToBool()
4022 
4023  // C++14 [over.ics.rank]p4b2:
4024  // This is retroactively applied to C++11 by CWG 1601.
4025  //
4026  // A conversion that promotes an enumeration whose underlying type is fixed
4027  // to its underlying type is better than one that promotes to the promoted
4028  // underlying type, if the two are different.
4029  FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4030  FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4031  if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4032  FEP1 != FEP2)
4036 
4037  // C++ [over.ics.rank]p4b2:
4038  //
4039  // If class B is derived directly or indirectly from class A,
4040  // conversion of B* to A* is better than conversion of B* to
4041  // void*, and conversion of A* to void* is better than conversion
4042  // of B* to void*.
4043  bool SCS1ConvertsToVoid
4045  bool SCS2ConvertsToVoid
4047  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4048  // Exactly one of the conversion sequences is a conversion to
4049  // a void pointer; it's the worse conversion.
4050  return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4052  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4053  // Neither conversion sequence converts to a void pointer; compare
4054  // their derived-to-base conversions.
4056  = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4057  return DerivedCK;
4058  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4059  !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4060  // Both conversion sequences are conversions to void
4061  // pointers. Compare the source types to determine if there's an
4062  // inheritance relationship in their sources.
4063  QualType FromType1 = SCS1.getFromType();
4064  QualType FromType2 = SCS2.getFromType();
4065 
4066  // Adjust the types we're converting from via the array-to-pointer
4067  // conversion, if we need to.
4068  if (SCS1.First == ICK_Array_To_Pointer)
4069  FromType1 = S.Context.getArrayDecayedType(FromType1);
4070  if (SCS2.First == ICK_Array_To_Pointer)
4071  FromType2 = S.Context.getArrayDecayedType(FromType2);
4072 
4073  QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4074  QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4075 
4076  if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4078  else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4080 
4081  // Objective-C++: If one interface is more specific than the
4082  // other, it is the better one.
4083  const ObjCObjectPointerType* FromObjCPtr1
4084  = FromType1->getAs<ObjCObjectPointerType>();
4085  const ObjCObjectPointerType* FromObjCPtr2
4086  = FromType2->getAs<ObjCObjectPointerType>();
4087  if (FromObjCPtr1 && FromObjCPtr2) {
4088  bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4089  FromObjCPtr2);
4090  bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4091  FromObjCPtr1);
4092  if (AssignLeft != AssignRight) {
4093  return AssignLeft? ImplicitConversionSequence::Better
4095  }
4096  }
4097  }
4098 
4099  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4100  // Check for a better reference binding based on the kind of bindings.
4101  if (isBetterReferenceBindingKind(SCS1, SCS2))
4103  else if (isBetterReferenceBindingKind(SCS2, SCS1))
4105  }
4106 
4107  // Compare based on qualification conversions (C++ 13.3.3.2p3,
4108  // bullet 3).
4110  = CompareQualificationConversions(S, SCS1, SCS2))
4111  return QualCK;
4112 
4113  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4114  // C++ [over.ics.rank]p3b4:
4115  // -- S1 and S2 are reference bindings (8.5.3), and the types to
4116  // which the references refer are the same type except for
4117  // top-level cv-qualifiers, and the type to which the reference
4118  // initialized by S2 refers is more cv-qualified than the type
4119  // to which the reference initialized by S1 refers.
4120  QualType T1 = SCS1.getToType(2);
4121  QualType T2 = SCS2.getToType(2);
4122  T1 = S.Context.getCanonicalType(T1);
4123  T2 = S.Context.getCanonicalType(T2);
4124  Qualifiers T1Quals, T2Quals;
4125  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4126  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4127  if (UnqualT1 == UnqualT2) {
4128  // Objective-C++ ARC: If the references refer to objects with different
4129  // lifetimes, prefer bindings that don't change lifetime.
4130  if (SCS1.ObjCLifetimeConversionBinding !=
4132  return SCS1.ObjCLifetimeConversionBinding
4135  }
4136 
4137  // If the type is an array type, promote the element qualifiers to the
4138  // type for comparison.
4139  if (isa<ArrayType>(T1) && T1Quals)
4140  T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4141  if (isa<ArrayType>(T2) && T2Quals)
4142  T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4143  if (T2.isMoreQualifiedThan(T1))
4145  if (T1.isMoreQualifiedThan(T2))
4147  }
4148  }
4149 
4150  // In Microsoft mode (below 19.28), prefer an integral conversion to a
4151  // floating-to-integral conversion if the integral conversion
4152  // is between types of the same size.
4153  // For example:
4154  // void f(float);
4155  // void f(int);
4156  // int main {
4157  // long a;
4158  // f(a);
4159  // }
4160  // Here, MSVC will call f(int) instead of generating a compile error
4161  // as clang will do in standard mode.
4162  if (S.getLangOpts().MSVCCompat &&
4164  SCS1.Second == ICK_Integral_Conversion &&
4165  SCS2.Second == ICK_Floating_Integral &&
4166  S.Context.getTypeSize(SCS1.getFromType()) ==
4167  S.Context.getTypeSize(SCS1.getToType(2)))
4169 
4170  // Prefer a compatible vector conversion over a lax vector conversion
4171  // For example:
4172  //
4173  // typedef float __v4sf __attribute__((__vector_size__(16)));
4174  // void f(vector float);
4175  // void f(vector signed int);
4176  // int main() {
4177  // __v4sf a;
4178  // f(a);
4179  // }
4180  // Here, we'd like to choose f(vector float) and not
4181  // report an ambiguous call error
4182  if (SCS1.Second == ICK_Vector_Conversion &&
4183  SCS2.Second == ICK_Vector_Conversion) {
4184  bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4185  SCS1.getFromType(), SCS1.getToType(2));
4186  bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4187  SCS2.getFromType(), SCS2.getToType(2));
4188 
4189  if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4190  return SCS1IsCompatibleVectorConversion
4193  }
4194 
4195  if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4197  bool SCS1IsCompatibleSVEVectorConversion =
4199  bool SCS2IsCompatibleSVEVectorConversion =
4201 
4202  if (SCS1IsCompatibleSVEVectorConversion !=
4203  SCS2IsCompatibleSVEVectorConversion)
4204  return SCS1IsCompatibleSVEVectorConversion
4207  }
4208 
4210 }
4211 
4212 /// CompareQualificationConversions - Compares two standard conversion
4213 /// sequences to determine whether they can be ranked based on their
4214 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4217  const StandardConversionSequence& SCS1,
4218  const StandardConversionSequence& SCS2) {
4219  // C++ [over.ics.rank]p3:
4220  // -- S1 and S2 differ only in their qualification conversion and
4221  // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4222  // [C++98]
4223  // [...] and the cv-qualification signature of type T1 is a proper subset
4224  // of the cv-qualification signature of type T2, and S1 is not the
4225  // deprecated string literal array-to-pointer conversion (4.2).
4226  // [C++2a]
4227  // [...] where T1 can be converted to T2 by a qualification conversion.
4228  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4229  SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4231 
4232  // FIXME: the example in the standard doesn't use a qualification
4233  // conversion (!)
4234  QualType T1 = SCS1.getToType(2);
4235  QualType T2 = SCS2.getToType(2);
4236  T1 = S.Context.getCanonicalType(T1);
4237  T2 = S.Context.getCanonicalType(T2);
4238  assert(!T1->isReferenceType() && !T2->isReferenceType());
4239  Qualifiers T1Quals, T2Quals;
4240  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4241  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4242 
4243  // If the types are the same, we won't learn anything by unwrapping
4244  // them.
4245  if (UnqualT1 == UnqualT2)
4247 
4248  // Don't ever prefer a standard conversion sequence that uses the deprecated
4249  // string literal array to pointer conversion.
4250  bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4251  bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4252 
4253  // Objective-C++ ARC:
4254  // Prefer qualification conversions not involving a change in lifetime
4255  // to qualification conversions that do change lifetime.
4258  CanPick1 = false;
4261  CanPick2 = false;
4262 
4263  bool ObjCLifetimeConversion;
4264  if (CanPick1 &&
4265  !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4266  CanPick1 = false;
4267  // FIXME: In Objective-C ARC, we can have qualification conversions in both
4268  // directions, so we can't short-cut this second check in general.
4269  if (CanPick2 &&
4270  !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4271  CanPick2 = false;
4272 
4273  if (CanPick1 != CanPick2)
4274  return CanPick1 ? ImplicitConversionSequence::Better
4277 }
4278 
4279 /// CompareDerivedToBaseConversions - Compares two standard conversion
4280 /// sequences to determine whether they can be ranked based on their
4281 /// various kinds of derived-to-base conversions (C++
4282 /// [over.ics.rank]p4b3). As part of these checks, we also look at
4283 /// conversions between Objective-C interface types.
4286  const StandardConversionSequence& SCS1,
4287  const StandardConversionSequence& SCS2) {
4288  QualType FromType1 = SCS1.getFromType();
4289  QualType ToType1 = SCS1.getToType(1);
4290  QualType FromType2 = SCS2.getFromType();
4291  QualType ToType2 = SCS2.getToType(1);
4292 
4293  // Adjust the types we're converting from via the array-to-pointer
4294  // conversion, if we need to.
4295  if (SCS1.First == ICK_Array_To_Pointer)
4296  FromType1 = S.Context.getArrayDecayedType(FromType1);
4297  if (SCS2.First == ICK_Array_To_Pointer)
4298  FromType2 = S.Context.getArrayDecayedType(FromType2);
4299 
4300  // Canonicalize all of the types.
4301  FromType1 = S.Context.getCanonicalType(FromType1);
4302  ToType1 = S.Context.getCanonicalType(ToType1);
4303  FromType2 = S.Context.getCanonicalType(FromType2);
4304  ToType2 = S.Context.getCanonicalType(ToType2);
4305 
4306  // C++ [over.ics.rank]p4b3:
4307  //
4308  // If class B is derived directly or indirectly from class A and
4309  // class C is derived directly or indirectly from B,
4310  //
4311  // Compare based on pointer conversions.
4312  if (SCS1.Second == ICK_Pointer_Conversion &&
4313  SCS2.Second == ICK_Pointer_Conversion &&
4314  /*FIXME: Remove if Objective-C id conversions get their own rank*/
4315  FromType1->isPointerType() && FromType2->isPointerType() &&
4316  ToType1->isPointerType() && ToType2->isPointerType()) {
4317  QualType FromPointee1 =
4318  FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4319  QualType ToPointee1 =
4320  ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4321  QualType FromPointee2 =
4322  FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4323  QualType ToPointee2 =
4324  ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4325 
4326  // -- conversion of C* to B* is better than conversion of C* to A*,
4327  if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4328  if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4330  else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4332  }
4333 
4334  // -- conversion of B* to A* is better than conversion of C* to A*,
4335  if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4336  if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4338  else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4340  }
4341  } else if (SCS1.Second == ICK_Pointer_Conversion &&
4342  SCS2.Second == ICK_Pointer_Conversion) {
4343  const ObjCObjectPointerType *FromPtr1
4344  = FromType1->getAs<ObjCObjectPointerType>();
4345  const ObjCObjectPointerType *FromPtr2
4346  = FromType2->getAs<ObjCObjectPointerType>();
4347  const ObjCObjectPointerType *ToPtr1
4348  = ToType1->getAs<ObjCObjectPointerType>();
4349  const ObjCObjectPointerType *ToPtr2
4350  = ToType2->getAs<ObjCObjectPointerType>();
4351 
4352  if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4353  // Apply the same conversion ranking rules for Objective-C pointer types
4354  // that we do for C++ pointers to class types. However, we employ the
4355  // Objective-C pseudo-subtyping relationship used for assignment of
4356  // Objective-C pointer types.
4357  bool FromAssignLeft
4358  = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4359  bool FromAssignRight
4360  = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4361  bool ToAssignLeft
4362  = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4363  bool ToAssignRight
4364  = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4365 
4366  // A conversion to an a non-id object pointer type or qualified 'id'
4367  // type is better than a conversion to 'id'.
4368  if (ToPtr1->isObjCIdType() &&
4369  (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4371  if (ToPtr2->isObjCIdType() &&
4372  (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4374 
4375  // A conversion to a non-id object pointer type is better than a
4376  // conversion to a qualified 'id' type
4377  if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4379  if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4381 
4382  // A conversion to an a non-Class object pointer type or qualified 'Class'
4383  // type is better than a conversion to 'Class'.
4384  if (ToPtr1->isObjCClassType() &&
4385  (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4387  if (ToPtr2->isObjCClassType() &&
4388  (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4390 
4391  // A conversion to a non-Class object pointer type is better than a
4392  // conversion to a qualified 'Class' type.
4393  if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4395  if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4397 
4398  // -- "conversion of C* to B* is better than conversion of C* to A*,"
4399  if (S.Context.hasSameType(FromType1, FromType2) &&
4400  !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4401  (ToAssignLeft != ToAssignRight)) {
4402  if (FromPtr1->isSpecialized()) {
4403  // "conversion of B<A> * to B * is better than conversion of B * to
4404  // C *.
4405  bool IsFirstSame =
4406  FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4407  bool IsSecondSame =
4408  FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4409  if (IsFirstSame) {
4410  if (!IsSecondSame)
4412  } else if (IsSecondSame)
4414  }
4415  return ToAssignLeft? ImplicitConversionSequence::Worse
4417  }
4418 
4419  // -- "conversion of B* to A* is better than conversion of C* to A*,"
4420  if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4421  (FromAssignLeft != FromAssignRight))
4422  return FromAssignLeft? ImplicitConversionSequence::Better
4424  }
4425  }
4426 
4427  // Ranking of member-pointer types.
4428  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4429  FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4430  ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4431  const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4432  const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4433  const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4434  const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4435  const Type *FromPointeeType1 = FromMemPointer1->getClass();
4436  const Type *ToPointeeType1 = ToMemPointer1->getClass();
4437  const Type *FromPointeeType2 = FromMemPointer2->getClass();
4438  const Type *ToPointeeType2 = ToMemPointer2->getClass();
4439  QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4440  QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4441  QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4442  QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4443  // conversion of A::* to B::* is better than conversion of A::* to C::*,
4444  if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4445  if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4447  else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4449  }
4450  // conversion of B::* to C::* is better than conversion of A::* to C::*
4451  if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4452  if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4454  else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4456  }
4457  }
4458 
4459  if (SCS1.Second == ICK_Derived_To_Base) {
4460  // -- conversion of C to B is better than conversion of C to A,
4461  // -- binding of an expression of type C to a reference of type
4462  // B& is better than binding an expression of type C to a
4463  // reference of type A&,
4464  if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4465  !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4466  if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4468  else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4470  }
4471 
4472  // -- conversion of B to A is better than conversion of C to A.
4473  // -- binding of an expression of type B to a reference of type
4474  // A& is better than binding an expression of type C to a
4475  // reference of type A&,
4476  if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4477  S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4478  if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4480  else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4482  }
4483  }
4484 
4486 }
4487 
4488 /// Determine whether the given type is valid, e.g., it is not an invalid
4489 /// C++ class.
4490 static bool isTypeValid(QualType T) {
4491  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4492  return !Record->isInvalidDecl();
4493 
4494  return true;
4495 }
4496 
4498  if (!T.getQualifiers().hasUnaligned())
4499  return T;
4500 
4501  Qualifiers Q;
4502  T = Ctx.getUnqualifiedArrayType(T, Q);
4503  Q.removeUnaligned();
4504  return Ctx.getQualifiedType(T, Q);
4505 }
4506 
4507 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4508 /// determine whether they are reference-compatible,
4509 /// reference-related, or incompatible, for use in C++ initialization by
4510 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4511 /// type, and the first type (T1) is the pointee type of the reference
4512 /// type being initialized.
4515  QualType OrigT1, QualType OrigT2,
4516  ReferenceConversions *ConvOut) {
4517  assert(!OrigT1->isReferenceType() &&
4518  "T1 must be the pointee type of the reference type");
4519  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4520 
4521  QualType T1 = Context.getCanonicalType(OrigT1);
4522  QualType T2 = Context.getCanonicalType(OrigT2);
4523  Qualifiers T1Quals, T2Quals;
4524  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4525  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4526 
4527  ReferenceConversions ConvTmp;
4528  ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4529  Conv = ReferenceConversions();
4530 
4531  // C++2a [dcl.init.ref]p4:
4532  // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4533  // reference-related to "cv2 T2" if T1 is similar to T2, or
4534  // T1 is a base class of T2.
4535  // "cv1 T1" is reference-compatible with "cv2 T2" if
4536  // a prvalue of type "pointer to cv2 T2" can be converted to the type
4537  // "pointer to cv1 T1" via a standard conversion sequence.
4538 
4539  // Check for standard conversions we can apply to pointers: derived-to-base
4540  // conversions, ObjC pointer conversions, and function pointer conversions.
4541  // (Qualification conversions are checked last.)
4542  QualType ConvertedT2;
4543  if (UnqualT1 == UnqualT2) {
4544  // Nothing to do.
4545  } else if (isCompleteType(Loc, OrigT2) &&
4546  isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4547  IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4548  Conv |= ReferenceConversions::DerivedToBase;
4549  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4550  UnqualT2->isObjCObjectOrInterfaceType() &&
4551  Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4553  else if (UnqualT2->isFunctionType() &&
4554  IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4555  Conv |= ReferenceConversions::Function;
4556  // No need to check qualifiers; function types don't have them.
4557  return Ref_Compatible;
4558  }
4559  bool ConvertedReferent = Conv != 0;
4560 
4561  // We can have a qualification conversion. Compute whether the types are
4562  // similar at the same time.
4563  bool PreviousToQualsIncludeConst = true;
4564  bool TopLevel = true;
4565  do {
4566  if (T1 == T2)
4567  break;
4568 
4569  // We will need a qualification conversion.
4570  Conv |= ReferenceConversions::Qualification;
4571 
4572  // Track whether we performed a qualification conversion anywhere other
4573  // than the top level. This matters for ranking reference bindings in
4574  // overload resolution.
4575  if (!TopLevel)
4576  Conv |= ReferenceConversions::NestedQualification;
4577 
4578  // MS compiler ignores __unaligned qualifier for references; do the same.
4579  T1 = withoutUnaligned(Context, T1);
4580  T2 = withoutUnaligned(Context, T2);
4581 
4582  // If we find a qualifier mismatch, the types are not reference-compatible,
4583  // but are still be reference-related if they're similar.
4584  bool ObjCLifetimeConversion = false;
4585  if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4586  PreviousToQualsIncludeConst,
4587  ObjCLifetimeConversion))
4588  return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4589  ? Ref_Related
4590  : Ref_Incompatible;
4591 
4592  // FIXME: Should we track this for any level other than the first?
4593  if (ObjCLifetimeConversion)
4594  Conv |= ReferenceConversions::ObjCLifetime;
4595 
4596  TopLevel = false;
4597  } while (Context.UnwrapSimilarTypes(T1, T2));
4598 
4599  // At this point, if the types are reference-related, we must either have the
4600  // same inner type (ignoring qualifiers), or must have already worked out how
4601  // to convert the referent.
4602  return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4603  ? Ref_Compatible
4604  : Ref_Incompatible;
4605 }
4606 
4607 /// Look for a user-defined conversion to a value reference-compatible
4608 /// with DeclType. Return true if something definite is found.
4609 static bool
4611  QualType DeclType, SourceLocation DeclLoc,
4612  Expr *Init, QualType T2, bool AllowRvalues,
4613  bool AllowExplicit) {
4614  assert(T2->isRecordType() && "Can only find conversions of record types.");
4615  auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4616 
4617  OverloadCandidateSet CandidateSet(
4619  const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4620  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4621  NamedDecl *D = *I;
4622  CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4623  if (isa<UsingShadowDecl>(D))
4624  D = cast<UsingShadowDecl>(D)->getTargetDecl();
4625 
4626  FunctionTemplateDecl *ConvTemplate
4627  = dyn_cast<FunctionTemplateDecl>(D);
4628  CXXConversionDecl *Conv;
4629  if (ConvTemplate)
4630  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4631  else
4632  Conv = cast<CXXConversionDecl>(D);
4633 
4634  if (AllowRvalues) {
4635  // If we are initializing an rvalue reference, don't permit conversion
4636  // functions that return lvalues.
4637  if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4638  const ReferenceType *RefType
4640  if (RefType && !RefType->getPointeeType()->isFunctionType())
4641  continue;
4642  }
4643 
4644  if (!ConvTemplate &&
4646  DeclLoc,
4647  Conv->getConversionType()
4649  .getUnqualifiedType(),
4650  DeclType.getNonReferenceType().getUnqualifiedType()) ==
4652  continue;
4653  } else {
4654  // If the conversion function doesn't return a reference type,
4655  // it can't be considered for this conversion. An rvalue reference
4656  // is only acceptable if its referencee is a function type.
4657 
4658  const ReferenceType *RefType =
4660  if (!RefType ||
4661  (!RefType->isLValueReferenceType() &&
4662  !RefType->getPointeeType()->isFunctionType()))
4663  continue;
4664  }
4665 
4666  if (ConvTemplate)
4668  ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4669  /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4670  else
4672  Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4673  /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4674  }
4675 
4676  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4677 
4679  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4680  case OR_Success:
4681  // C++ [over.ics.ref]p1:
4682  //
4683  // [...] If the parameter binds directly to the result of
4684  // applying a conversion function to the argument
4685  // expression, the implicit conversion sequence is a
4686  // user-defined conversion sequence (13.3.3.1.2), with the
4687  // second standard conversion sequence either an identity
4688  // conversion or, if the conversion function returns an
4689  // entity of a type that is a derived class of the parameter
4690  // type, a derived-to-base Conversion.
4691  if (!Best->FinalConversion.DirectBinding)
4692  return false;
4693 
4694  ICS.setUserDefined();
4695  ICS.UserDefined.Before = Best->Conversions[0].Standard;
4696  ICS.UserDefined.After = Best->FinalConversion;
4697  ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4698  ICS.UserDefined.ConversionFunction = Best->Function;
4699  ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4700  ICS.UserDefined.EllipsisConversion = false;
4701  assert(ICS.UserDefined.After.ReferenceBinding &&
4703  "Expected a direct reference binding!");
4704  return true;
4705 
4706  case OR_Ambiguous:
4707  ICS.setAmbiguous();
4708  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4709  Cand != CandidateSet.end(); ++Cand)
4710  if (Cand->Best)
4711  ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4712  return true;
4713 
4714  case OR_No_Viable_Function:
4715  case OR_Deleted:
4716  // There was no suitable conversion, or we found a deleted
4717  // conversion; continue with other checks.
4718  return false;
4719  }
4720 
4721  llvm_unreachable("Invalid OverloadResult!");
4722 }
4723 
4724 /// Compute an implicit conversion sequence for reference
4725 /// initialization.
4727 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4728  SourceLocation DeclLoc,
4729  bool SuppressUserConversions,
4730  bool AllowExplicit) {
4731  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4732 
4733  // Most paths end in a failed conversion.
4735  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4736 
4737  QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4738  QualType T2 = Init->getType();
4739 
4740  // If the initializer is the address of an overloaded function, try
4741  // to resolve the overloaded function. If all goes well, T2 is the
4742  // type of the resulting function.
4743  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4744  DeclAccessPair Found;
4745  if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4746  false, Found))
4747  T2 = Fn->getType();
4748  }
4749 
4750  // Compute some basic properties of the types and the initializer.
4751  bool isRValRef = DeclType->isRValueReferenceType();
4752  Expr::Classification InitCategory = Init->Classify(S.Context);
4753 
4755  Sema::ReferenceCompareResult RefRelationship =
4756  S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4757 
4758  auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4759  ICS.setStandard();
4760  ICS.Standard.First = ICK_Identity;
4761  // FIXME: A reference binding can be a function conversion too. We should
4762  // consider that when ordering reference-to-function bindings.
4763  ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4765  : (RefConv & Sema::ReferenceConversions::ObjC)
4767  : ICK_Identity;
4768  // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4769  // a reference binding that performs a non-top-level qualification
4770  // conversion as a qualification conversion, not as an identity conversion.
4771  ICS.Standard.Third = (RefConv &
4772  Sema::ReferenceConversions::NestedQualification)
4774  : ICK_Identity;
4775  ICS.Standard.setFromType(T2);
4776  ICS.Standard.setToType(0, T2);
4777  ICS.Standard.setToType(1, T1);
4778  ICS.Standard.setToType(2, T1);
4779  ICS.Standard.ReferenceBinding = true;
4780  ICS.Standard.DirectBinding = BindsDirectly;
4781  ICS.Standard.IsLvalueReference = !isRValRef;
4783  ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4786  (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4787  ICS.Standard.CopyConstructor = nullptr;
4789  };
4790 
4791  // C++0x [dcl.init.ref]p5:
4792  // A reference to type "cv1 T1" is initialized by an expression
4793  // of type "cv2 T2" as follows:
4794 
4795  // -- If reference is an lvalue reference and the initializer expression
4796  if (!isRValRef) {
4797  // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4798  // reference-compatible with "cv2 T2," or
4799  //
4800  // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4801  if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4802  // C++ [over.ics.ref]p1:
4803  // When a parameter of reference type binds directly (8.5.3)
4804  // to an argument expression, the implicit conversion sequence
4805  // is the identity conversion, unless the argument expression
4806  // has a type that is a derived class of the parameter type,
4807  // in which case the implicit conversion sequence is a
4808  // derived-to-base Conversion (13.3.3.1).
4809  SetAsReferenceBinding(/*BindsDirectly=*/true);
4810 
4811  // Nothing more to do: the inaccessibility/ambiguity check for
4812  // derived-to-base conversions is suppressed when we're
4813  // computing the implicit conversion sequence (C++
4814  // [over.best.ics]p2).
4815  return ICS;
4816  }
4817 
4818  // -- has a class type (i.e., T2 is a class type), where T1 is
4819  // not reference-related to T2, and can be implicitly
4820  // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4821  // is reference-compatible with "cv3 T3" 92) (this
4822  // conversion is selected by enumerating the applicable
4823  // conversion functions (13.3.1.6) and choosing the best
4824  // one through overload resolution (13.3)),
4825  if (!SuppressUserConversions && T2->isRecordType() &&
4826  S.isCompleteType(DeclLoc, T2) &&
4827  RefRelationship == Sema::Ref_Incompatible) {
4828  if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4829  Init, T2, /*AllowRvalues=*/false,
4830  AllowExplicit))
4831  return ICS;
4832  }
4833  }
4834 
4835  // -- Otherwise, the reference shall be an lvalue reference to a
4836  // non-volatile const type (i.e., cv1 shall be const), or the reference
4837  // shall be an rvalue reference.
4838  if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4839  if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4841  return ICS;
4842  }
4843 
4844  // -- If the initializer expression
4845  //
4846  // -- is an xvalue, class prvalue, array prvalue or function
4847  // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4848  if (RefRelationship == Sema::Ref_Compatible &&
4849  (InitCategory.isXValue() ||
4850  (InitCategory.isPRValue() &&
4851  (T2->isRecordType() || T2->isArrayType())) ||
4852  (InitCategory.isLValue() && T2->isFunctionType()))) {
4853  // In C++11, this is always a direct binding. In C++98/03, it's a direct
4854  // binding unless we're binding to a class prvalue.
4855  // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4856  // allow the use of rvalue references in C++98/03 for the benefit of
4857  // standard library implementors; therefore, we need the xvalue check here.
4858  SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4859  !(InitCategory.isPRValue() || T2->isRecordType()));
4860  return ICS;
4861  }
4862 
4863  // -- has a class type (i.e., T2 is a class type), where T1 is not
4864  // reference-related to T2, and can be implicitly converted to
4865  // an xvalue, class prvalue, or function lvalue of type
4866  // "cv3 T3", where "cv1 T1" is reference-compatible with
4867  // "cv3 T3",
4868  //
4869  // then the reference is bound to the value of the initializer
4870  // expression in the first case and to the result of the conversion
4871  // in the second case (or, in either case, to an appropriate base
4872  // class subobject).
4873  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4874  T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4875  FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4876  Init, T2, /*AllowRvalues=*/true,
4877  AllowExplicit)) {
4878  // In the second case, if the reference is an rvalue reference
4879  // and the second standard conversion sequence of the
4880  // user-defined conversion sequence includes an lvalue-to-rvalue
4881  // conversion, the program is ill-formed.
4882  if (ICS.isUserDefined() && isRValRef &&
4884  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4885 
4886  return ICS;
4887  }
4888 
4889  // A temporary of function type cannot be created; don't even try.
4890  if (T1->isFunctionType())
4891  return ICS;
4892 
4893  // -- Otherwise, a temporary of type "cv1 T1" is created and
4894  // initialized from the initializer expression using the
4895  // rules for a non-reference copy initialization (8.5). The
4896  // reference is then bound to the temporary. If T1 is
4897  // reference-related to T2, cv1 must be the same
4898  // cv-qualification as, or greater cv-qualification than,
4899  // cv2; otherwise, the program is ill-formed.
4900  if (RefRelationship == Sema::Ref_Related) {
4901  // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4902  // we would be reference-compatible or reference-compatible with
4903  // added qualification. But that wasn't the case, so the reference
4904  // initialization fails.
4905  //
4906  // Note that we only want to check address spaces and cvr-qualifiers here.
4907  // ObjC GC, lifetime and unaligned qualifiers aren't important.
4908  Qualifiers T1Quals = T1.getQualifiers();
4909  Qualifiers T2Quals = T2.getQualifiers();
4910  T1Quals.removeObjCGCAttr();
4911  T1Quals.removeObjCLifetime();
4912  T2Quals.removeObjCGCAttr();
4913  T2Quals.removeObjCLifetime();
4914  // MS compiler ignores __unaligned qualifier for references; do the same.
4915  T1Quals.removeUnaligned();
4916  T2Quals.removeUnaligned();
4917  if (!T1Quals.compatiblyIncludes(T2Quals))
4918  return ICS;
4919  }
4920 
4921  // If at least one of the types is a class type, the types are not
4922  // related, and we aren't allowed any user conversions, the
4923  // reference binding fails. This case is important for breaking
4924  // recursion, since TryImplicitConversion below will attempt to
4925  // create a temporary through the use of a copy constructor.
4926  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4927  (T1->isRecordType() || T2->isRecordType()))
4928  return ICS;
4929 
4930  // If T1 is reference-related to T2 and the reference is an rvalue
4931  // reference, the initializer expression shall not be an lvalue.
4932  if (RefRelationship >= Sema::Ref_Related && isRValRef &&
4933  Init->Classify(S.Context).isLValue()) {
4935  return ICS;
4936  }
4937 
4938  // C++ [over.ics.ref]p2:
4939  // When a parameter of reference type is not bound directly to
4940  // an argument expression, the conversion sequence is the one
4941  // required to convert the argument expression to the
4942  // underlying type of the reference according to
4943  // 13.3.3.1. Conceptually, this conversion sequence corresponds
4944  // to copy-initializing a temporary of the underlying type with
4945  // the argument expression. Any difference in top-level
4946  // cv-qualification is subsumed by the initialization itself
4947  // and does not constitute a conversion.
4948  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4949  AllowedExplicit::None,
4950  /*InOverloadResolution=*/false,
4951  /*CStyle=*/false,
4952  /*AllowObjCWritebackConversion=*/false,
4953  /*AllowObjCConversionOnExplicit=*/false);
4954 
4955  // Of course, that's still a reference binding.
4956  if (ICS.isStandard()) {
4957  ICS.Standard.ReferenceBinding = true;
4958  ICS.Standard.IsLvalueReference = !isRValRef;
4959  ICS.Standard.BindsToFunctionLvalue = false;
4960  ICS.Standard.BindsToRvalue = true;
4963  } else if (ICS.isUserDefined()) {
4964  const ReferenceType *LValRefType =
4967 
4968  // C++ [over.ics.ref]p3:
4969  // Except for an implicit object parameter, for which see 13.3.1, a
4970  // standard conversion sequence cannot be formed if it requires [...]
4971  // binding an rvalue reference to an lvalue other than a function
4972  // lvalue.
4973  // Note that the function case is not possible here.
4974  if (isRValRef && LValRefType) {
4975  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4976  return ICS;
4977  }
4978 
4979  ICS.UserDefined.After.ReferenceBinding = true;
4980  ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4982  ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4985  }
4986 
4987  return ICS;
4988 }
4989 
4991 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4992  bool SuppressUserConversions,
4993  bool InOverloadResolution,
4994  bool AllowObjCWritebackConversion,
4995  bool AllowExplicit = false);
4996 
4997 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4998 /// initializer list From.
5001  bool SuppressUserConversions,
5002  bool InOverloadResolution,
5003  bool AllowObjCWritebackConversion) {
5004  // C++11 [over.ics.list]p1:
5005  // When an argument is an initializer list, it is not an expression and
5006  // special rules apply for converting it to a parameter type.
5007 
5009  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5010 
5011  // We need a complete type for what follows. With one C++20 exception,
5012  // incomplete types can never be initialized from init lists.
5013  QualType InitTy = ToType;
5014  const ArrayType *AT = S.Context.getAsArrayType(ToType);
5015  if (AT && S.getLangOpts().CPlusPlus20)
5016  if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5017  // C++20 allows list initialization of an incomplete array type.
5018  InitTy = IAT->getElementType();
5019  if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5020  return Result;
5021 
5022  // Per DR1467:
5023  // If the parameter type is a class X and the initializer list has a single
5024  // element of type cv U, where U is X or a class derived from X, the
5025  // implicit conversion sequence is the one required to convert the element
5026  // to the parameter type.
5027  //
5028  // Otherwise, if the parameter type is a character array [... ]
5029  // and the initializer list has a single element that is an
5030  // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5031  // implicit conversion sequence is the identity conversion.
5032  if (From->getNumInits() == 1) {
5033  if (ToType->isRecordType()) {
5034  QualType InitType = From->getInit(0)->getType();
5035  if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5036  S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5037  return TryCopyInitialization(S, From->getInit(0), ToType,
5038  SuppressUserConversions,
5039  InOverloadResolution,
5040  AllowObjCWritebackConversion);
5041  }
5042 
5043  if (AT && S.IsStringInit(From->getInit(0), AT)) {
5044  InitializedEntity Entity =
5046  /*Consumed=*/false);
5047  if (S.CanPerformCopyInitialization(Entity, From)) {
5048  Result.setStandard();
5049  Result.Standard.setAsIdentityConversion();
5050  Result.Standard.setFromType(ToType);
5051  Result.Standard.setAllToTypes(ToType);
5052  return Result;
5053  }
5054  }
5055  }
5056 
5057  // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5058  // C++11 [over.ics.list]p2:
5059  // If the parameter type is std::initializer_list<X> or "array of X" and
5060  // all the elements can be implicitly converted to X, the implicit
5061  // conversion sequence is the worst conversion necessary to convert an
5062  // element of the list to X.
5063  //
5064  // C++14 [over.ics.list]p3:
5065  // Otherwise, if the parameter type is "array of N X", if the initializer
5066  // list has exactly N elements or if it has fewer than N elements and X is
5067  // default-constructible, and if all the elements of the initializer list
5068  // can be implicitly converted to X, the implicit conversion sequence is
5069  // the worst conversion necessary to convert an element of the list to X.
5070  if (AT || S.isStdInitializerList(ToType, &InitTy)) {
5071  unsigned e = From->getNumInits();
5074  QualType());
5075  QualType ContTy = ToType;
5076  bool IsUnbounded = false;
5077  if (AT) {
5078  InitTy = AT->getElementType();
5079  if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5080  if (CT->getSize().ult(e)) {
5081  // Too many inits, fatally bad
5083  ToType);
5084  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5085  return Result;
5086  }
5087  if (CT->getSize().ugt(e)) {
5088  // Need an init from empty {}, is there one?
5089  InitListExpr EmptyList(S.Context, From->getEndLoc(), None,
5090  From->getEndLoc());
5091  EmptyList.setType(S.Context.VoidTy);
5092  DfltElt = TryListConversion(
5093  S, &EmptyList, InitTy, SuppressUserConversions,
5094  InOverloadResolution, AllowObjCWritebackConversion);
5095  if (DfltElt.isBad()) {
5096  // No {} init, fatally bad
5097  Result.setBad(BadConversionSequence::too_few_initializers, From,
5098  ToType);
5099  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5100  return Result;
5101  }
5102  }
5103  } else {
5104  assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5105  IsUnbounded = true;
5106  if (!e) {
5107  // Cannot convert to zero-sized.
5108  Result.setBad(BadConversionSequence::too_few_initializers, From,
5109  ToType);
5110  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5111  return Result;
5112  }
5114  ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5115  ArrayType::Normal, 0);
5116  }
5117  }
5118 
5119  Result.setStandard();
5120  Result.Standard.setAsIdentityConversion();
5121  Result.Standard.setFromType(InitTy);
5122  Result.Standard.setAllToTypes(InitTy);
5123  for (unsigned i = 0; i < e; ++i) {
5124  Expr *Init = From->getInit(i);
5126  S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5127  AllowObjCWritebackConversion);
5128 
5129  // Keep the worse conversion seen so far.
5130  // FIXME: Sequences are not totally ordered, so 'worse' can be
5131  // ambiguous. CWG has been informed.
5132  if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5133  Result) ==
5135  Result = ICS;
5136  // Bail as soon as we find something unconvertible.
5137  if (Result.isBad()) {
5138  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5139  return Result;
5140  }
5141  }
5142  }
5143 
5144  // If we needed any implicit {} initialization, compare that now.
5145  // over.ics.list/6 indicates we should compare that conversion. Again CWG
5146  // has been informed that this might not be the best thing.
5147  if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5148  S, From->getEndLoc(), DfltElt, Result) ==
5150  Result = DfltElt;
5151  // Record the type being initialized so that we may compare sequences
5152  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5153  return Result;
5154  }
5155 
5156  // C++14 [over.ics.list]p4:
5157  // C++11 [over.ics.list]p3:
5158  // Otherwise, if the parameter is a non-aggregate class X and overload
5159  // resolution chooses a single best constructor [...] the implicit
5160  // conversion sequence is a user-defined conversion sequence. If multiple
5161  // constructors are viable but none is better than the others, the
5162  // implicit conversion sequence is a user-defined conversion sequence.
5163  if (ToType->isRecordType() && !ToType->isAggregateType()) {
5164  // This function can deal with initializer lists.
5165  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5166  AllowedExplicit::None,
5167  InOverloadResolution, /*CStyle=*/false,
5168  AllowObjCWritebackConversion,
5169  /*AllowObjCConversionOnExplicit=*/false);
5170  }
5171 
5172  // C++14 [over.ics.list]p5:
5173  // C++11 [over.ics.list]p4:
5174  // Otherwise, if the parameter has an aggregate type which can be
5175  // initialized from the initializer list [...] the implicit conversion
5176  // sequence is a user-defined conversion sequence.
5177  if (ToType->isAggregateType()) {
5178  // Type is an aggregate, argument is an init list. At this point it comes
5179  // down to checking whether the initialization works.
5180  // FIXME: Find out whether this parameter is consumed or not.
5181  InitializedEntity Entity =
5183  /*Consumed=*/false);
5185  From)) {
5186  Result.setUserDefined();
5187  Result.UserDefined.Before.setAsIdentityConversion();
5188  // Initializer lists don't have a type.
5189  Result.UserDefined.Before.setFromType(QualType());
5190  Result.UserDefined.Before.setAllToTypes(QualType());
5191 
5192  Result.UserDefined.After.setAsIdentityConversion();
5193  Result.UserDefined.After.setFromType(ToType);
5194  Result.UserDefined.After.setAllToTypes(ToType);
5195  Result.UserDefined.ConversionFunction = nullptr;
5196  }
5197  return Result;
5198  }
5199 
5200  // C++14 [over.ics.list]p6:
5201  // C++11 [over.ics.list]p5:
5202  // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5203  if (ToType->isReferenceType()) {
5204  // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5205  // mention initializer lists in any way. So we go by what list-
5206  // initialization would do and try to extrapolate from that.
5207 
5208  QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5209 
5210  // If the initializer list has a single element that is reference-related
5211  // to the parameter type, we initialize the reference from that.
5212  if (From->getNumInits() == 1) {
5213  Expr *Init = From->getInit(0);
5214 
5215  QualType T2 = Init->getType();
5216 
5217  // If the initializer is the address of an overloaded function, try
5218  // to resolve the overloaded function. If all goes well, T2 is the
5219  // type of the resulting function.
5220  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5221  DeclAccessPair Found;
5223  Init, ToType, false, Found))
5224  T2 = Fn->getType();
5225  }
5226 
5227  // Compute some basic properties of the types and the initializer.
5228  Sema::ReferenceCompareResult RefRelationship =
5229  S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5230 
5231  if (RefRelationship >= Sema::Ref_Related) {
5232  return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5233  SuppressUserConversions,
5234  /*AllowExplicit=*/false);
5235  }
5236  }
5237 
5238  // Otherwise, we bind the reference to a temporary created from the
5239  // initializer list.
5240  Result = TryListConversion(S, From, T1, SuppressUserConversions,
5241  InOverloadResolution,
5242  AllowObjCWritebackConversion);
5243  if (Result.isFailure())
5244  return Result;
5245  assert(!Result.isEllipsis() &&
5246  "Sub-initialization cannot result in ellipsis conversion.");
5247 
5248  // Can we even bind to a temporary?
5249  if (ToType->isRValueReferenceType() ||
5250  (T1.isConstQualified() && !T1.isVolatileQualified())) {
5251  StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5252  Result.UserDefined.After;
5253  SCS.ReferenceBinding = true;