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