clang API Documentation

SemaOverload.cpp
Go to the documentation of this file.
00001 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file provides Sema routines for C++ overloading.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Sema/Overload.h"
00015 #include "clang/AST/ASTContext.h"
00016 #include "clang/AST/CXXInheritance.h"
00017 #include "clang/AST/DeclObjC.h"
00018 #include "clang/AST/Expr.h"
00019 #include "clang/AST/ExprCXX.h"
00020 #include "clang/AST/ExprObjC.h"
00021 #include "clang/AST/TypeOrdering.h"
00022 #include "clang/Basic/Diagnostic.h"
00023 #include "clang/Basic/DiagnosticOptions.h"
00024 #include "clang/Basic/PartialDiagnostic.h"
00025 #include "clang/Basic/TargetInfo.h"
00026 #include "clang/Sema/Initialization.h"
00027 #include "clang/Sema/Lookup.h"
00028 #include "clang/Sema/SemaInternal.h"
00029 #include "clang/Sema/Template.h"
00030 #include "clang/Sema/TemplateDeduction.h"
00031 #include "llvm/ADT/DenseSet.h"
00032 #include "llvm/ADT/STLExtras.h"
00033 #include "llvm/ADT/SmallPtrSet.h"
00034 #include "llvm/ADT/SmallString.h"
00035 #include <algorithm>
00036 #include <cstdlib>
00037 
00038 using namespace clang;
00039 using namespace sema;
00040 
00041 /// A convenience routine for creating a decayed reference to a function.
00042 static ExprResult
00043 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
00044                       bool HadMultipleCandidates,
00045                       SourceLocation Loc = SourceLocation(), 
00046                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
00047   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
00048     return ExprError(); 
00049   // If FoundDecl is different from Fn (such as if one is a template
00050   // and the other a specialization), make sure DiagnoseUseOfDecl is 
00051   // called on both.
00052   // FIXME: This would be more comprehensively addressed by modifying
00053   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
00054   // being used.
00055   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
00056     return ExprError();
00057   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
00058                                                  VK_LValue, Loc, LocInfo);
00059   if (HadMultipleCandidates)
00060     DRE->setHadMultipleCandidates(true);
00061 
00062   S.MarkDeclRefReferenced(DRE);
00063 
00064   ExprResult E = DRE;
00065   E = S.DefaultFunctionArrayConversion(E.get());
00066   if (E.isInvalid())
00067     return ExprError();
00068   return E;
00069 }
00070 
00071 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
00072                                  bool InOverloadResolution,
00073                                  StandardConversionSequence &SCS,
00074                                  bool CStyle,
00075                                  bool AllowObjCWritebackConversion);
00076 
00077 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 
00078                                                  QualType &ToType,
00079                                                  bool InOverloadResolution,
00080                                                  StandardConversionSequence &SCS,
00081                                                  bool CStyle);
00082 static OverloadingResult
00083 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
00084                         UserDefinedConversionSequence& User,
00085                         OverloadCandidateSet& Conversions,
00086                         bool AllowExplicit,
00087                         bool AllowObjCConversionOnExplicit);
00088 
00089 
00090 static ImplicitConversionSequence::CompareKind
00091 CompareStandardConversionSequences(Sema &S,
00092                                    const StandardConversionSequence& SCS1,
00093                                    const StandardConversionSequence& SCS2);
00094 
00095 static ImplicitConversionSequence::CompareKind
00096 CompareQualificationConversions(Sema &S,
00097                                 const StandardConversionSequence& SCS1,
00098                                 const StandardConversionSequence& SCS2);
00099 
00100 static ImplicitConversionSequence::CompareKind
00101 CompareDerivedToBaseConversions(Sema &S,
00102                                 const StandardConversionSequence& SCS1,
00103                                 const StandardConversionSequence& SCS2);
00104 
00105 /// GetConversionRank - Retrieve the implicit conversion rank
00106 /// corresponding to the given implicit conversion kind.
00107 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
00108   static const ImplicitConversionRank
00109     Rank[(int)ICK_Num_Conversion_Kinds] = {
00110     ICR_Exact_Match,
00111     ICR_Exact_Match,
00112     ICR_Exact_Match,
00113     ICR_Exact_Match,
00114     ICR_Exact_Match,
00115     ICR_Exact_Match,
00116     ICR_Promotion,
00117     ICR_Promotion,
00118     ICR_Promotion,
00119     ICR_Conversion,
00120     ICR_Conversion,
00121     ICR_Conversion,
00122     ICR_Conversion,
00123     ICR_Conversion,
00124     ICR_Conversion,
00125     ICR_Conversion,
00126     ICR_Conversion,
00127     ICR_Conversion,
00128     ICR_Conversion,
00129     ICR_Conversion,
00130     ICR_Complex_Real_Conversion,
00131     ICR_Conversion,
00132     ICR_Conversion,
00133     ICR_Writeback_Conversion
00134   };
00135   return Rank[(int)Kind];
00136 }
00137 
00138 /// GetImplicitConversionName - Return the name of this kind of
00139 /// implicit conversion.
00140 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
00141   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
00142     "No conversion",
00143     "Lvalue-to-rvalue",
00144     "Array-to-pointer",
00145     "Function-to-pointer",
00146     "Noreturn adjustment",
00147     "Qualification",
00148     "Integral promotion",
00149     "Floating point promotion",
00150     "Complex promotion",
00151     "Integral conversion",
00152     "Floating conversion",
00153     "Complex conversion",
00154     "Floating-integral conversion",
00155     "Pointer conversion",
00156     "Pointer-to-member conversion",
00157     "Boolean conversion",
00158     "Compatible-types conversion",
00159     "Derived-to-base conversion",
00160     "Vector conversion",
00161     "Vector splat",
00162     "Complex-real conversion",
00163     "Block Pointer conversion",
00164     "Transparent Union Conversion",
00165     "Writeback conversion"
00166   };
00167   return Name[Kind];
00168 }
00169 
00170 /// StandardConversionSequence - Set the standard conversion
00171 /// sequence to the identity conversion.
00172 void StandardConversionSequence::setAsIdentityConversion() {
00173   First = ICK_Identity;
00174   Second = ICK_Identity;
00175   Third = ICK_Identity;
00176   DeprecatedStringLiteralToCharPtr = false;
00177   QualificationIncludesObjCLifetime = false;
00178   ReferenceBinding = false;
00179   DirectBinding = false;
00180   IsLvalueReference = true;
00181   BindsToFunctionLvalue = false;
00182   BindsToRvalue = false;
00183   BindsImplicitObjectArgumentWithoutRefQualifier = false;
00184   ObjCLifetimeConversionBinding = false;
00185   CopyConstructor = nullptr;
00186 }
00187 
00188 /// getRank - Retrieve the rank of this standard conversion sequence
00189 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
00190 /// implicit conversions.
00191 ImplicitConversionRank StandardConversionSequence::getRank() const {
00192   ImplicitConversionRank Rank = ICR_Exact_Match;
00193   if  (GetConversionRank(First) > Rank)
00194     Rank = GetConversionRank(First);
00195   if  (GetConversionRank(Second) > Rank)
00196     Rank = GetConversionRank(Second);
00197   if  (GetConversionRank(Third) > Rank)
00198     Rank = GetConversionRank(Third);
00199   return Rank;
00200 }
00201 
00202 /// isPointerConversionToBool - Determines whether this conversion is
00203 /// a conversion of a pointer or pointer-to-member to bool. This is
00204 /// used as part of the ranking of standard conversion sequences
00205 /// (C++ 13.3.3.2p4).
00206 bool StandardConversionSequence::isPointerConversionToBool() const {
00207   // Note that FromType has not necessarily been transformed by the
00208   // array-to-pointer or function-to-pointer implicit conversions, so
00209   // check for their presence as well as checking whether FromType is
00210   // a pointer.
00211   if (getToType(1)->isBooleanType() &&
00212       (getFromType()->isPointerType() ||
00213        getFromType()->isObjCObjectPointerType() ||
00214        getFromType()->isBlockPointerType() ||
00215        getFromType()->isNullPtrType() ||
00216        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
00217     return true;
00218 
00219   return false;
00220 }
00221 
00222 /// isPointerConversionToVoidPointer - Determines whether this
00223 /// conversion is a conversion of a pointer to a void pointer. This is
00224 /// used as part of the ranking of standard conversion sequences (C++
00225 /// 13.3.3.2p4).
00226 bool
00227 StandardConversionSequence::
00228 isPointerConversionToVoidPointer(ASTContext& Context) const {
00229   QualType FromType = getFromType();
00230   QualType ToType = getToType(1);
00231 
00232   // Note that FromType has not necessarily been transformed by the
00233   // array-to-pointer implicit conversion, so check for its presence
00234   // and redo the conversion to get a pointer.
00235   if (First == ICK_Array_To_Pointer)
00236     FromType = Context.getArrayDecayedType(FromType);
00237 
00238   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
00239     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
00240       return ToPtrType->getPointeeType()->isVoidType();
00241 
00242   return false;
00243 }
00244 
00245 /// Skip any implicit casts which could be either part of a narrowing conversion
00246 /// or after one in an implicit conversion.
00247 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
00248   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
00249     switch (ICE->getCastKind()) {
00250     case CK_NoOp:
00251     case CK_IntegralCast:
00252     case CK_IntegralToBoolean:
00253     case CK_IntegralToFloating:
00254     case CK_FloatingToIntegral:
00255     case CK_FloatingToBoolean:
00256     case CK_FloatingCast:
00257       Converted = ICE->getSubExpr();
00258       continue;
00259 
00260     default:
00261       return Converted;
00262     }
00263   }
00264 
00265   return Converted;
00266 }
00267 
00268 /// Check if this standard conversion sequence represents a narrowing
00269 /// conversion, according to C++11 [dcl.init.list]p7.
00270 ///
00271 /// \param Ctx  The AST context.
00272 /// \param Converted  The result of applying this standard conversion sequence.
00273 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
00274 ///        value of the expression prior to the narrowing conversion.
00275 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
00276 ///        type of the expression prior to the narrowing conversion.
00277 NarrowingKind
00278 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
00279                                              const Expr *Converted,
00280                                              APValue &ConstantValue,
00281                                              QualType &ConstantType) const {
00282   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
00283 
00284   // C++11 [dcl.init.list]p7:
00285   //   A narrowing conversion is an implicit conversion ...
00286   QualType FromType = getToType(0);
00287   QualType ToType = getToType(1);
00288   switch (Second) {
00289   // -- from a floating-point type to an integer type, or
00290   //
00291   // -- from an integer type or unscoped enumeration type to a floating-point
00292   //    type, except where the source is a constant expression and the actual
00293   //    value after conversion will fit into the target type and will produce
00294   //    the original value when converted back to the original type, or
00295   case ICK_Floating_Integral:
00296     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
00297       return NK_Type_Narrowing;
00298     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
00299       llvm::APSInt IntConstantValue;
00300       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
00301       if (Initializer &&
00302           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
00303         // Convert the integer to the floating type.
00304         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
00305         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
00306                                 llvm::APFloat::rmNearestTiesToEven);
00307         // And back.
00308         llvm::APSInt ConvertedValue = IntConstantValue;
00309         bool ignored;
00310         Result.convertToInteger(ConvertedValue,
00311                                 llvm::APFloat::rmTowardZero, &ignored);
00312         // If the resulting value is different, this was a narrowing conversion.
00313         if (IntConstantValue != ConvertedValue) {
00314           ConstantValue = APValue(IntConstantValue);
00315           ConstantType = Initializer->getType();
00316           return NK_Constant_Narrowing;
00317         }
00318       } else {
00319         // Variables are always narrowings.
00320         return NK_Variable_Narrowing;
00321       }
00322     }
00323     return NK_Not_Narrowing;
00324 
00325   // -- from long double to double or float, or from double to float, except
00326   //    where the source is a constant expression and the actual value after
00327   //    conversion is within the range of values that can be represented (even
00328   //    if it cannot be represented exactly), or
00329   case ICK_Floating_Conversion:
00330     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
00331         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
00332       // FromType is larger than ToType.
00333       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
00334       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
00335         // Constant!
00336         assert(ConstantValue.isFloat());
00337         llvm::APFloat FloatVal = ConstantValue.getFloat();
00338         // Convert the source value into the target type.
00339         bool ignored;
00340         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
00341           Ctx.getFloatTypeSemantics(ToType),
00342           llvm::APFloat::rmNearestTiesToEven, &ignored);
00343         // If there was no overflow, the source value is within the range of
00344         // values that can be represented.
00345         if (ConvertStatus & llvm::APFloat::opOverflow) {
00346           ConstantType = Initializer->getType();
00347           return NK_Constant_Narrowing;
00348         }
00349       } else {
00350         return NK_Variable_Narrowing;
00351       }
00352     }
00353     return NK_Not_Narrowing;
00354 
00355   // -- from an integer type or unscoped enumeration type to an integer type
00356   //    that cannot represent all the values of the original type, except where
00357   //    the source is a constant expression and the actual value after
00358   //    conversion will fit into the target type and will produce the original
00359   //    value when converted back to the original type.
00360   case ICK_Boolean_Conversion:  // Bools are integers too.
00361     if (!FromType->isIntegralOrUnscopedEnumerationType()) {
00362       // Boolean conversions can be from pointers and pointers to members
00363       // [conv.bool], and those aren't considered narrowing conversions.
00364       return NK_Not_Narrowing;
00365     }  // Otherwise, fall through to the integral case.
00366   case ICK_Integral_Conversion: {
00367     assert(FromType->isIntegralOrUnscopedEnumerationType());
00368     assert(ToType->isIntegralOrUnscopedEnumerationType());
00369     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
00370     const unsigned FromWidth = Ctx.getIntWidth(FromType);
00371     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
00372     const unsigned ToWidth = Ctx.getIntWidth(ToType);
00373 
00374     if (FromWidth > ToWidth ||
00375         (FromWidth == ToWidth && FromSigned != ToSigned) ||
00376         (FromSigned && !ToSigned)) {
00377       // Not all values of FromType can be represented in ToType.
00378       llvm::APSInt InitializerValue;
00379       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
00380       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
00381         // Such conversions on variables are always narrowing.
00382         return NK_Variable_Narrowing;
00383       }
00384       bool Narrowing = false;
00385       if (FromWidth < ToWidth) {
00386         // Negative -> unsigned is narrowing. Otherwise, more bits is never
00387         // narrowing.
00388         if (InitializerValue.isSigned() && InitializerValue.isNegative())
00389           Narrowing = true;
00390       } else {
00391         // Add a bit to the InitializerValue so we don't have to worry about
00392         // signed vs. unsigned comparisons.
00393         InitializerValue = InitializerValue.extend(
00394           InitializerValue.getBitWidth() + 1);
00395         // Convert the initializer to and from the target width and signed-ness.
00396         llvm::APSInt ConvertedValue = InitializerValue;
00397         ConvertedValue = ConvertedValue.trunc(ToWidth);
00398         ConvertedValue.setIsSigned(ToSigned);
00399         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
00400         ConvertedValue.setIsSigned(InitializerValue.isSigned());
00401         // If the result is different, this was a narrowing conversion.
00402         if (ConvertedValue != InitializerValue)
00403           Narrowing = true;
00404       }
00405       if (Narrowing) {
00406         ConstantType = Initializer->getType();
00407         ConstantValue = APValue(InitializerValue);
00408         return NK_Constant_Narrowing;
00409       }
00410     }
00411     return NK_Not_Narrowing;
00412   }
00413 
00414   default:
00415     // Other kinds of conversions are not narrowings.
00416     return NK_Not_Narrowing;
00417   }
00418 }
00419 
00420 /// dump - Print this standard conversion sequence to standard
00421 /// error. Useful for debugging overloading issues.
00422 void StandardConversionSequence::dump() const {
00423   raw_ostream &OS = llvm::errs();
00424   bool PrintedSomething = false;
00425   if (First != ICK_Identity) {
00426     OS << GetImplicitConversionName(First);
00427     PrintedSomething = true;
00428   }
00429 
00430   if (Second != ICK_Identity) {
00431     if (PrintedSomething) {
00432       OS << " -> ";
00433     }
00434     OS << GetImplicitConversionName(Second);
00435 
00436     if (CopyConstructor) {
00437       OS << " (by copy constructor)";
00438     } else if (DirectBinding) {
00439       OS << " (direct reference binding)";
00440     } else if (ReferenceBinding) {
00441       OS << " (reference binding)";
00442     }
00443     PrintedSomething = true;
00444   }
00445 
00446   if (Third != ICK_Identity) {
00447     if (PrintedSomething) {
00448       OS << " -> ";
00449     }
00450     OS << GetImplicitConversionName(Third);
00451     PrintedSomething = true;
00452   }
00453 
00454   if (!PrintedSomething) {
00455     OS << "No conversions required";
00456   }
00457 }
00458 
00459 /// dump - Print this user-defined conversion sequence to standard
00460 /// error. Useful for debugging overloading issues.
00461 void UserDefinedConversionSequence::dump() const {
00462   raw_ostream &OS = llvm::errs();
00463   if (Before.First || Before.Second || Before.Third) {
00464     Before.dump();
00465     OS << " -> ";
00466   }
00467   if (ConversionFunction)
00468     OS << '\'' << *ConversionFunction << '\'';
00469   else
00470     OS << "aggregate initialization";
00471   if (After.First || After.Second || After.Third) {
00472     OS << " -> ";
00473     After.dump();
00474   }
00475 }
00476 
00477 /// dump - Print this implicit conversion sequence to standard
00478 /// error. Useful for debugging overloading issues.
00479 void ImplicitConversionSequence::dump() const {
00480   raw_ostream &OS = llvm::errs();
00481   if (isStdInitializerListElement())
00482     OS << "Worst std::initializer_list element conversion: ";
00483   switch (ConversionKind) {
00484   case StandardConversion:
00485     OS << "Standard conversion: ";
00486     Standard.dump();
00487     break;
00488   case UserDefinedConversion:
00489     OS << "User-defined conversion: ";
00490     UserDefined.dump();
00491     break;
00492   case EllipsisConversion:
00493     OS << "Ellipsis conversion";
00494     break;
00495   case AmbiguousConversion:
00496     OS << "Ambiguous conversion";
00497     break;
00498   case BadConversion:
00499     OS << "Bad conversion";
00500     break;
00501   }
00502 
00503   OS << "\n";
00504 }
00505 
00506 void AmbiguousConversionSequence::construct() {
00507   new (&conversions()) ConversionSet();
00508 }
00509 
00510 void AmbiguousConversionSequence::destruct() {
00511   conversions().~ConversionSet();
00512 }
00513 
00514 void
00515 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
00516   FromTypePtr = O.FromTypePtr;
00517   ToTypePtr = O.ToTypePtr;
00518   new (&conversions()) ConversionSet(O.conversions());
00519 }
00520 
00521 namespace {
00522   // Structure used by DeductionFailureInfo to store
00523   // template argument information.
00524   struct DFIArguments {
00525     TemplateArgument FirstArg;
00526     TemplateArgument SecondArg;
00527   };
00528   // Structure used by DeductionFailureInfo to store
00529   // template parameter and template argument information.
00530   struct DFIParamWithArguments : DFIArguments {
00531     TemplateParameter Param;
00532   };
00533 }
00534 
00535 /// \brief Convert from Sema's representation of template deduction information
00536 /// to the form used in overload-candidate information.
00537 DeductionFailureInfo
00538 clang::MakeDeductionFailureInfo(ASTContext &Context,
00539                                 Sema::TemplateDeductionResult TDK,
00540                                 TemplateDeductionInfo &Info) {
00541   DeductionFailureInfo Result;
00542   Result.Result = static_cast<unsigned>(TDK);
00543   Result.HasDiagnostic = false;
00544   Result.Data = nullptr;
00545   switch (TDK) {
00546   case Sema::TDK_Success:
00547   case Sema::TDK_Invalid:
00548   case Sema::TDK_InstantiationDepth:
00549   case Sema::TDK_TooManyArguments:
00550   case Sema::TDK_TooFewArguments:
00551     break;
00552 
00553   case Sema::TDK_Incomplete:
00554   case Sema::TDK_InvalidExplicitArguments:
00555     Result.Data = Info.Param.getOpaqueValue();
00556     break;
00557 
00558   case Sema::TDK_NonDeducedMismatch: {
00559     // FIXME: Should allocate from normal heap so that we can free this later.
00560     DFIArguments *Saved = new (Context) DFIArguments;
00561     Saved->FirstArg = Info.FirstArg;
00562     Saved->SecondArg = Info.SecondArg;
00563     Result.Data = Saved;
00564     break;
00565   }
00566 
00567   case Sema::TDK_Inconsistent:
00568   case Sema::TDK_Underqualified: {
00569     // FIXME: Should allocate from normal heap so that we can free this later.
00570     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
00571     Saved->Param = Info.Param;
00572     Saved->FirstArg = Info.FirstArg;
00573     Saved->SecondArg = Info.SecondArg;
00574     Result.Data = Saved;
00575     break;
00576   }
00577 
00578   case Sema::TDK_SubstitutionFailure:
00579     Result.Data = Info.take();
00580     if (Info.hasSFINAEDiagnostic()) {
00581       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
00582           SourceLocation(), PartialDiagnostic::NullDiagnostic());
00583       Info.takeSFINAEDiagnostic(*Diag);
00584       Result.HasDiagnostic = true;
00585     }
00586     break;
00587 
00588   case Sema::TDK_FailedOverloadResolution:
00589     Result.Data = Info.Expression;
00590     break;
00591 
00592   case Sema::TDK_MiscellaneousDeductionFailure:
00593     break;
00594   }
00595 
00596   return Result;
00597 }
00598 
00599 void DeductionFailureInfo::Destroy() {
00600   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
00601   case Sema::TDK_Success:
00602   case Sema::TDK_Invalid:
00603   case Sema::TDK_InstantiationDepth:
00604   case Sema::TDK_Incomplete:
00605   case Sema::TDK_TooManyArguments:
00606   case Sema::TDK_TooFewArguments:
00607   case Sema::TDK_InvalidExplicitArguments:
00608   case Sema::TDK_FailedOverloadResolution:
00609     break;
00610 
00611   case Sema::TDK_Inconsistent:
00612   case Sema::TDK_Underqualified:
00613   case Sema::TDK_NonDeducedMismatch:
00614     // FIXME: Destroy the data?
00615     Data = nullptr;
00616     break;
00617 
00618   case Sema::TDK_SubstitutionFailure:
00619     // FIXME: Destroy the template argument list?
00620     Data = nullptr;
00621     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
00622       Diag->~PartialDiagnosticAt();
00623       HasDiagnostic = false;
00624     }
00625     break;
00626 
00627   // Unhandled
00628   case Sema::TDK_MiscellaneousDeductionFailure:
00629     break;
00630   }
00631 }
00632 
00633 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
00634   if (HasDiagnostic)
00635     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
00636   return nullptr;
00637 }
00638 
00639 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
00640   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
00641   case Sema::TDK_Success:
00642   case Sema::TDK_Invalid:
00643   case Sema::TDK_InstantiationDepth:
00644   case Sema::TDK_TooManyArguments:
00645   case Sema::TDK_TooFewArguments:
00646   case Sema::TDK_SubstitutionFailure:
00647   case Sema::TDK_NonDeducedMismatch:
00648   case Sema::TDK_FailedOverloadResolution:
00649     return TemplateParameter();
00650 
00651   case Sema::TDK_Incomplete:
00652   case Sema::TDK_InvalidExplicitArguments:
00653     return TemplateParameter::getFromOpaqueValue(Data);
00654 
00655   case Sema::TDK_Inconsistent:
00656   case Sema::TDK_Underqualified:
00657     return static_cast<DFIParamWithArguments*>(Data)->Param;
00658 
00659   // Unhandled
00660   case Sema::TDK_MiscellaneousDeductionFailure:
00661     break;
00662   }
00663 
00664   return TemplateParameter();
00665 }
00666 
00667 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
00668   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
00669   case Sema::TDK_Success:
00670   case Sema::TDK_Invalid:
00671   case Sema::TDK_InstantiationDepth:
00672   case Sema::TDK_TooManyArguments:
00673   case Sema::TDK_TooFewArguments:
00674   case Sema::TDK_Incomplete:
00675   case Sema::TDK_InvalidExplicitArguments:
00676   case Sema::TDK_Inconsistent:
00677   case Sema::TDK_Underqualified:
00678   case Sema::TDK_NonDeducedMismatch:
00679   case Sema::TDK_FailedOverloadResolution:
00680     return nullptr;
00681 
00682   case Sema::TDK_SubstitutionFailure:
00683     return static_cast<TemplateArgumentList*>(Data);
00684 
00685   // Unhandled
00686   case Sema::TDK_MiscellaneousDeductionFailure:
00687     break;
00688   }
00689 
00690   return nullptr;
00691 }
00692 
00693 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
00694   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
00695   case Sema::TDK_Success:
00696   case Sema::TDK_Invalid:
00697   case Sema::TDK_InstantiationDepth:
00698   case Sema::TDK_Incomplete:
00699   case Sema::TDK_TooManyArguments:
00700   case Sema::TDK_TooFewArguments:
00701   case Sema::TDK_InvalidExplicitArguments:
00702   case Sema::TDK_SubstitutionFailure:
00703   case Sema::TDK_FailedOverloadResolution:
00704     return nullptr;
00705 
00706   case Sema::TDK_Inconsistent:
00707   case Sema::TDK_Underqualified:
00708   case Sema::TDK_NonDeducedMismatch:
00709     return &static_cast<DFIArguments*>(Data)->FirstArg;
00710 
00711   // Unhandled
00712   case Sema::TDK_MiscellaneousDeductionFailure:
00713     break;
00714   }
00715 
00716   return nullptr;
00717 }
00718 
00719 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
00720   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
00721   case Sema::TDK_Success:
00722   case Sema::TDK_Invalid:
00723   case Sema::TDK_InstantiationDepth:
00724   case Sema::TDK_Incomplete:
00725   case Sema::TDK_TooManyArguments:
00726   case Sema::TDK_TooFewArguments:
00727   case Sema::TDK_InvalidExplicitArguments:
00728   case Sema::TDK_SubstitutionFailure:
00729   case Sema::TDK_FailedOverloadResolution:
00730     return nullptr;
00731 
00732   case Sema::TDK_Inconsistent:
00733   case Sema::TDK_Underqualified:
00734   case Sema::TDK_NonDeducedMismatch:
00735     return &static_cast<DFIArguments*>(Data)->SecondArg;
00736 
00737   // Unhandled
00738   case Sema::TDK_MiscellaneousDeductionFailure:
00739     break;
00740   }
00741 
00742   return nullptr;
00743 }
00744 
00745 Expr *DeductionFailureInfo::getExpr() {
00746   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
00747         Sema::TDK_FailedOverloadResolution)
00748     return static_cast<Expr*>(Data);
00749 
00750   return nullptr;
00751 }
00752 
00753 void OverloadCandidateSet::destroyCandidates() {
00754   for (iterator i = begin(), e = end(); i != e; ++i) {
00755     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
00756       i->Conversions[ii].~ImplicitConversionSequence();
00757     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
00758       i->DeductionFailure.Destroy();
00759   }
00760 }
00761 
00762 void OverloadCandidateSet::clear() {
00763   destroyCandidates();
00764   NumInlineSequences = 0;
00765   Candidates.clear();
00766   Functions.clear();
00767 }
00768 
00769 namespace {
00770   class UnbridgedCastsSet {
00771     struct Entry {
00772       Expr **Addr;
00773       Expr *Saved;
00774     };
00775     SmallVector<Entry, 2> Entries;
00776     
00777   public:
00778     void save(Sema &S, Expr *&E) {
00779       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
00780       Entry entry = { &E, E };
00781       Entries.push_back(entry);
00782       E = S.stripARCUnbridgedCast(E);
00783     }
00784 
00785     void restore() {
00786       for (SmallVectorImpl<Entry>::iterator
00787              i = Entries.begin(), e = Entries.end(); i != e; ++i) 
00788         *i->Addr = i->Saved;
00789     }
00790   };
00791 }
00792 
00793 /// checkPlaceholderForOverload - Do any interesting placeholder-like
00794 /// preprocessing on the given expression.
00795 ///
00796 /// \param unbridgedCasts a collection to which to add unbridged casts;
00797 ///   without this, they will be immediately diagnosed as errors
00798 ///
00799 /// Return true on unrecoverable error.
00800 static bool
00801 checkPlaceholderForOverload(Sema &S, Expr *&E,
00802                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
00803   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
00804     // We can't handle overloaded expressions here because overload
00805     // resolution might reasonably tweak them.
00806     if (placeholder->getKind() == BuiltinType::Overload) return false;
00807 
00808     // If the context potentially accepts unbridged ARC casts, strip
00809     // the unbridged cast and add it to the collection for later restoration.
00810     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
00811         unbridgedCasts) {
00812       unbridgedCasts->save(S, E);
00813       return false;
00814     }
00815 
00816     // Go ahead and check everything else.
00817     ExprResult result = S.CheckPlaceholderExpr(E);
00818     if (result.isInvalid())
00819       return true;
00820 
00821     E = result.get();
00822     return false;
00823   }
00824 
00825   // Nothing to do.
00826   return false;
00827 }
00828 
00829 /// checkArgPlaceholdersForOverload - Check a set of call operands for
00830 /// placeholders.
00831 static bool checkArgPlaceholdersForOverload(Sema &S,
00832                                             MultiExprArg Args,
00833                                             UnbridgedCastsSet &unbridged) {
00834   for (unsigned i = 0, e = Args.size(); i != e; ++i)
00835     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
00836       return true;
00837 
00838   return false;
00839 }
00840 
00841 // IsOverload - Determine whether the given New declaration is an
00842 // overload of the declarations in Old. This routine returns false if
00843 // New and Old cannot be overloaded, e.g., if New has the same
00844 // signature as some function in Old (C++ 1.3.10) or if the Old
00845 // declarations aren't functions (or function templates) at all. When
00846 // it does return false, MatchedDecl will point to the decl that New
00847 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
00848 // top of the underlying declaration.
00849 //
00850 // Example: Given the following input:
00851 //
00852 //   void f(int, float); // #1
00853 //   void f(int, int); // #2
00854 //   int f(int, int); // #3
00855 //
00856 // When we process #1, there is no previous declaration of "f",
00857 // so IsOverload will not be used.
00858 //
00859 // When we process #2, Old contains only the FunctionDecl for #1.  By
00860 // comparing the parameter types, we see that #1 and #2 are overloaded
00861 // (since they have different signatures), so this routine returns
00862 // false; MatchedDecl is unchanged.
00863 //
00864 // When we process #3, Old is an overload set containing #1 and #2. We
00865 // compare the signatures of #3 to #1 (they're overloaded, so we do
00866 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
00867 // identical (return types of functions are not part of the
00868 // signature), IsOverload returns false and MatchedDecl will be set to
00869 // point to the FunctionDecl for #2.
00870 //
00871 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
00872 // into a class by a using declaration.  The rules for whether to hide
00873 // shadow declarations ignore some properties which otherwise figure
00874 // into a function template's signature.
00875 Sema::OverloadKind
00876 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
00877                     NamedDecl *&Match, bool NewIsUsingDecl) {
00878   for (LookupResult::iterator I = Old.begin(), E = Old.end();
00879          I != E; ++I) {
00880     NamedDecl *OldD = *I;
00881 
00882     bool OldIsUsingDecl = false;
00883     if (isa<UsingShadowDecl>(OldD)) {
00884       OldIsUsingDecl = true;
00885 
00886       // We can always introduce two using declarations into the same
00887       // context, even if they have identical signatures.
00888       if (NewIsUsingDecl) continue;
00889 
00890       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
00891     }
00892 
00893     // If either declaration was introduced by a using declaration,
00894     // we'll need to use slightly different rules for matching.
00895     // Essentially, these rules are the normal rules, except that
00896     // function templates hide function templates with different
00897     // return types or template parameter lists.
00898     bool UseMemberUsingDeclRules =
00899       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
00900       !New->getFriendObjectKind();
00901 
00902     if (FunctionDecl *OldF = OldD->getAsFunction()) {
00903       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
00904         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
00905           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
00906           continue;
00907         }
00908 
00909         if (!isa<FunctionTemplateDecl>(OldD) &&
00910             !shouldLinkPossiblyHiddenDecl(*I, New))
00911           continue;
00912 
00913         Match = *I;
00914         return Ovl_Match;
00915       }
00916     } else if (isa<UsingDecl>(OldD)) {
00917       // We can overload with these, which can show up when doing
00918       // redeclaration checks for UsingDecls.
00919       assert(Old.getLookupKind() == LookupUsingDeclName);
00920     } else if (isa<TagDecl>(OldD)) {
00921       // We can always overload with tags by hiding them.
00922     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
00923       // Optimistically assume that an unresolved using decl will
00924       // overload; if it doesn't, we'll have to diagnose during
00925       // template instantiation.
00926     } else {
00927       // (C++ 13p1):
00928       //   Only function declarations can be overloaded; object and type
00929       //   declarations cannot be overloaded.
00930       Match = *I;
00931       return Ovl_NonFunction;
00932     }
00933   }
00934 
00935   return Ovl_Overload;
00936 }
00937 
00938 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
00939                       bool UseUsingDeclRules) {
00940   // C++ [basic.start.main]p2: This function shall not be overloaded.
00941   if (New->isMain())
00942     return false;
00943 
00944   // MSVCRT user defined entry points cannot be overloaded.
00945   if (New->isMSVCRTEntryPoint())
00946     return false;
00947 
00948   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
00949   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
00950 
00951   // C++ [temp.fct]p2:
00952   //   A function template can be overloaded with other function templates
00953   //   and with normal (non-template) functions.
00954   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
00955     return true;
00956 
00957   // Is the function New an overload of the function Old?
00958   QualType OldQType = Context.getCanonicalType(Old->getType());
00959   QualType NewQType = Context.getCanonicalType(New->getType());
00960 
00961   // Compare the signatures (C++ 1.3.10) of the two functions to
00962   // determine whether they are overloads. If we find any mismatch
00963   // in the signature, they are overloads.
00964 
00965   // If either of these functions is a K&R-style function (no
00966   // prototype), then we consider them to have matching signatures.
00967   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
00968       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
00969     return false;
00970 
00971   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
00972   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
00973 
00974   // The signature of a function includes the types of its
00975   // parameters (C++ 1.3.10), which includes the presence or absence
00976   // of the ellipsis; see C++ DR 357).
00977   if (OldQType != NewQType &&
00978       (OldType->getNumParams() != NewType->getNumParams() ||
00979        OldType->isVariadic() != NewType->isVariadic() ||
00980        !FunctionParamTypesAreEqual(OldType, NewType)))
00981     return true;
00982 
00983   // C++ [temp.over.link]p4:
00984   //   The signature of a function template consists of its function
00985   //   signature, its return type and its template parameter list. The names
00986   //   of the template parameters are significant only for establishing the
00987   //   relationship between the template parameters and the rest of the
00988   //   signature.
00989   //
00990   // We check the return type and template parameter lists for function
00991   // templates first; the remaining checks follow.
00992   //
00993   // However, we don't consider either of these when deciding whether
00994   // a member introduced by a shadow declaration is hidden.
00995   if (!UseUsingDeclRules && NewTemplate &&
00996       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
00997                                        OldTemplate->getTemplateParameters(),
00998                                        false, TPL_TemplateMatch) ||
00999        OldType->getReturnType() != NewType->getReturnType()))
01000     return true;
01001 
01002   // If the function is a class member, its signature includes the
01003   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
01004   //
01005   // As part of this, also check whether one of the member functions
01006   // is static, in which case they are not overloads (C++
01007   // 13.1p2). While not part of the definition of the signature,
01008   // this check is important to determine whether these functions
01009   // can be overloaded.
01010   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
01011   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
01012   if (OldMethod && NewMethod &&
01013       !OldMethod->isStatic() && !NewMethod->isStatic()) {
01014     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
01015       if (!UseUsingDeclRules &&
01016           (OldMethod->getRefQualifier() == RQ_None ||
01017            NewMethod->getRefQualifier() == RQ_None)) {
01018         // C++0x [over.load]p2:
01019         //   - Member function declarations with the same name and the same
01020         //     parameter-type-list as well as member function template
01021         //     declarations with the same name, the same parameter-type-list, and
01022         //     the same template parameter lists cannot be overloaded if any of
01023         //     them, but not all, have a ref-qualifier (8.3.5).
01024         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
01025           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
01026         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
01027       }
01028       return true;
01029     }
01030 
01031     // We may not have applied the implicit const for a constexpr member
01032     // function yet (because we haven't yet resolved whether this is a static
01033     // or non-static member function). Add it now, on the assumption that this
01034     // is a redeclaration of OldMethod.
01035     unsigned OldQuals = OldMethod->getTypeQualifiers();
01036     unsigned NewQuals = NewMethod->getTypeQualifiers();
01037     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
01038         !isa<CXXConstructorDecl>(NewMethod))
01039       NewQuals |= Qualifiers::Const;
01040 
01041     // We do not allow overloading based off of '__restrict'.
01042     OldQuals &= ~Qualifiers::Restrict;
01043     NewQuals &= ~Qualifiers::Restrict;
01044     if (OldQuals != NewQuals)
01045       return true;
01046   }
01047 
01048   // enable_if attributes are an order-sensitive part of the signature.
01049   for (specific_attr_iterator<EnableIfAttr>
01050          NewI = New->specific_attr_begin<EnableIfAttr>(),
01051          NewE = New->specific_attr_end<EnableIfAttr>(),
01052          OldI = Old->specific_attr_begin<EnableIfAttr>(),
01053          OldE = Old->specific_attr_end<EnableIfAttr>();
01054        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
01055     if (NewI == NewE || OldI == OldE)
01056       return true;
01057     llvm::FoldingSetNodeID NewID, OldID;
01058     NewI->getCond()->Profile(NewID, Context, true);
01059     OldI->getCond()->Profile(OldID, Context, true);
01060     if (NewID != OldID)
01061       return true;
01062   }
01063 
01064   // The signatures match; this is not an overload.
01065   return false;
01066 }
01067 
01068 /// \brief Checks availability of the function depending on the current
01069 /// function context. Inside an unavailable function, unavailability is ignored.
01070 ///
01071 /// \returns true if \arg FD is unavailable and current context is inside
01072 /// an available function, false otherwise.
01073 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
01074   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
01075 }
01076 
01077 /// \brief Tries a user-defined conversion from From to ToType.
01078 ///
01079 /// Produces an implicit conversion sequence for when a standard conversion
01080 /// is not an option. See TryImplicitConversion for more information.
01081 static ImplicitConversionSequence
01082 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
01083                          bool SuppressUserConversions,
01084                          bool AllowExplicit,
01085                          bool InOverloadResolution,
01086                          bool CStyle,
01087                          bool AllowObjCWritebackConversion,
01088                          bool AllowObjCConversionOnExplicit) {
01089   ImplicitConversionSequence ICS;
01090 
01091   if (SuppressUserConversions) {
01092     // We're not in the case above, so there is no conversion that
01093     // we can perform.
01094     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
01095     return ICS;
01096   }
01097 
01098   // Attempt user-defined conversion.
01099   OverloadCandidateSet Conversions(From->getExprLoc(),
01100                                    OverloadCandidateSet::CSK_Normal);
01101   OverloadingResult UserDefResult
01102     = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
01103                               AllowExplicit, AllowObjCConversionOnExplicit);
01104 
01105   if (UserDefResult == OR_Success) {
01106     ICS.setUserDefined();
01107     ICS.UserDefined.Before.setAsIdentityConversion();
01108     // C++ [over.ics.user]p4:
01109     //   A conversion of an expression of class type to the same class
01110     //   type is given Exact Match rank, and a conversion of an
01111     //   expression of class type to a base class of that type is
01112     //   given Conversion rank, in spite of the fact that a copy
01113     //   constructor (i.e., a user-defined conversion function) is
01114     //   called for those cases.
01115     if (CXXConstructorDecl *Constructor
01116           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
01117       QualType FromCanon
01118         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
01119       QualType ToCanon
01120         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
01121       if (Constructor->isCopyConstructor() &&
01122           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
01123         // Turn this into a "standard" conversion sequence, so that it
01124         // gets ranked with standard conversion sequences.
01125         ICS.setStandard();
01126         ICS.Standard.setAsIdentityConversion();
01127         ICS.Standard.setFromType(From->getType());
01128         ICS.Standard.setAllToTypes(ToType);
01129         ICS.Standard.CopyConstructor = Constructor;
01130         if (ToCanon != FromCanon)
01131           ICS.Standard.Second = ICK_Derived_To_Base;
01132       }
01133     }
01134   } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
01135     ICS.setAmbiguous();
01136     ICS.Ambiguous.setFromType(From->getType());
01137     ICS.Ambiguous.setToType(ToType);
01138     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
01139          Cand != Conversions.end(); ++Cand)
01140       if (Cand->Viable)
01141         ICS.Ambiguous.addConversion(Cand->Function);
01142   } else {
01143     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
01144   }
01145 
01146   return ICS;
01147 }
01148 
01149 /// TryImplicitConversion - Attempt to perform an implicit conversion
01150 /// from the given expression (Expr) to the given type (ToType). This
01151 /// function returns an implicit conversion sequence that can be used
01152 /// to perform the initialization. Given
01153 ///
01154 ///   void f(float f);
01155 ///   void g(int i) { f(i); }
01156 ///
01157 /// this routine would produce an implicit conversion sequence to
01158 /// describe the initialization of f from i, which will be a standard
01159 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
01160 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
01161 //
01162 /// Note that this routine only determines how the conversion can be
01163 /// performed; it does not actually perform the conversion. As such,
01164 /// it will not produce any diagnostics if no conversion is available,
01165 /// but will instead return an implicit conversion sequence of kind
01166 /// "BadConversion".
01167 ///
01168 /// If @p SuppressUserConversions, then user-defined conversions are
01169 /// not permitted.
01170 /// If @p AllowExplicit, then explicit user-defined conversions are
01171 /// permitted.
01172 ///
01173 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
01174 /// writeback conversion, which allows __autoreleasing id* parameters to
01175 /// be initialized with __strong id* or __weak id* arguments.
01176 static ImplicitConversionSequence
01177 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
01178                       bool SuppressUserConversions,
01179                       bool AllowExplicit,
01180                       bool InOverloadResolution,
01181                       bool CStyle,
01182                       bool AllowObjCWritebackConversion,
01183                       bool AllowObjCConversionOnExplicit) {
01184   ImplicitConversionSequence ICS;
01185   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
01186                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
01187     ICS.setStandard();
01188     return ICS;
01189   }
01190 
01191   if (!S.getLangOpts().CPlusPlus) {
01192     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
01193     return ICS;
01194   }
01195 
01196   // C++ [over.ics.user]p4:
01197   //   A conversion of an expression of class type to the same class
01198   //   type is given Exact Match rank, and a conversion of an
01199   //   expression of class type to a base class of that type is
01200   //   given Conversion rank, in spite of the fact that a copy/move
01201   //   constructor (i.e., a user-defined conversion function) is
01202   //   called for those cases.
01203   QualType FromType = From->getType();
01204   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
01205       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
01206        S.IsDerivedFrom(FromType, ToType))) {
01207     ICS.setStandard();
01208     ICS.Standard.setAsIdentityConversion();
01209     ICS.Standard.setFromType(FromType);
01210     ICS.Standard.setAllToTypes(ToType);
01211 
01212     // We don't actually check at this point whether there is a valid
01213     // copy/move constructor, since overloading just assumes that it
01214     // exists. When we actually perform initialization, we'll find the
01215     // appropriate constructor to copy the returned object, if needed.
01216     ICS.Standard.CopyConstructor = nullptr;
01217 
01218     // Determine whether this is considered a derived-to-base conversion.
01219     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
01220       ICS.Standard.Second = ICK_Derived_To_Base;
01221 
01222     return ICS;
01223   }
01224 
01225   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
01226                                   AllowExplicit, InOverloadResolution, CStyle,
01227                                   AllowObjCWritebackConversion,
01228                                   AllowObjCConversionOnExplicit);
01229 }
01230 
01231 ImplicitConversionSequence
01232 Sema::TryImplicitConversion(Expr *From, QualType ToType,
01233                             bool SuppressUserConversions,
01234                             bool AllowExplicit,
01235                             bool InOverloadResolution,
01236                             bool CStyle,
01237                             bool AllowObjCWritebackConversion) {
01238   return ::TryImplicitConversion(*this, From, ToType, 
01239                                  SuppressUserConversions, AllowExplicit,
01240                                  InOverloadResolution, CStyle, 
01241                                  AllowObjCWritebackConversion,
01242                                  /*AllowObjCConversionOnExplicit=*/false);
01243 }
01244 
01245 /// PerformImplicitConversion - Perform an implicit conversion of the
01246 /// expression From to the type ToType. Returns the
01247 /// converted expression. Flavor is the kind of conversion we're
01248 /// performing, used in the error message. If @p AllowExplicit,
01249 /// explicit user-defined conversions are permitted.
01250 ExprResult
01251 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
01252                                 AssignmentAction Action, bool AllowExplicit) {
01253   ImplicitConversionSequence ICS;
01254   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
01255 }
01256 
01257 ExprResult
01258 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
01259                                 AssignmentAction Action, bool AllowExplicit,
01260                                 ImplicitConversionSequence& ICS) {
01261   if (checkPlaceholderForOverload(*this, From))
01262     return ExprError();
01263 
01264   // Objective-C ARC: Determine whether we will allow the writeback conversion.
01265   bool AllowObjCWritebackConversion
01266     = getLangOpts().ObjCAutoRefCount && 
01267       (Action == AA_Passing || Action == AA_Sending);
01268   if (getLangOpts().ObjC1)
01269     CheckObjCBridgeRelatedConversions(From->getLocStart(),
01270                                       ToType, From->getType(), From);
01271   ICS = ::TryImplicitConversion(*this, From, ToType,
01272                                 /*SuppressUserConversions=*/false,
01273                                 AllowExplicit,
01274                                 /*InOverloadResolution=*/false,
01275                                 /*CStyle=*/false,
01276                                 AllowObjCWritebackConversion,
01277                                 /*AllowObjCConversionOnExplicit=*/false);
01278   return PerformImplicitConversion(From, ToType, ICS, Action);
01279 }
01280 
01281 /// \brief Determine whether the conversion from FromType to ToType is a valid
01282 /// conversion that strips "noreturn" off the nested function type.
01283 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
01284                                 QualType &ResultTy) {
01285   if (Context.hasSameUnqualifiedType(FromType, ToType))
01286     return false;
01287 
01288   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
01289   // where F adds one of the following at most once:
01290   //   - a pointer
01291   //   - a member pointer
01292   //   - a block pointer
01293   CanQualType CanTo = Context.getCanonicalType(ToType);
01294   CanQualType CanFrom = Context.getCanonicalType(FromType);
01295   Type::TypeClass TyClass = CanTo->getTypeClass();
01296   if (TyClass != CanFrom->getTypeClass()) return false;
01297   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
01298     if (TyClass == Type::Pointer) {
01299       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
01300       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
01301     } else if (TyClass == Type::BlockPointer) {
01302       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
01303       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
01304     } else if (TyClass == Type::MemberPointer) {
01305       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
01306       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
01307     } else {
01308       return false;
01309     }
01310 
01311     TyClass = CanTo->getTypeClass();
01312     if (TyClass != CanFrom->getTypeClass()) return false;
01313     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
01314       return false;
01315   }
01316 
01317   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
01318   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
01319   if (!EInfo.getNoReturn()) return false;
01320 
01321   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
01322   assert(QualType(FromFn, 0).isCanonical());
01323   if (QualType(FromFn, 0) != CanTo) return false;
01324 
01325   ResultTy = ToType;
01326   return true;
01327 }
01328 
01329 /// \brief Determine whether the conversion from FromType to ToType is a valid
01330 /// vector conversion.
01331 ///
01332 /// \param ICK Will be set to the vector conversion kind, if this is a vector
01333 /// conversion.
01334 static bool IsVectorConversion(Sema &S, QualType FromType,
01335                                QualType ToType, ImplicitConversionKind &ICK) {
01336   // We need at least one of these types to be a vector type to have a vector
01337   // conversion.
01338   if (!ToType->isVectorType() && !FromType->isVectorType())
01339     return false;
01340 
01341   // Identical types require no conversions.
01342   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
01343     return false;
01344 
01345   // There are no conversions between extended vector types, only identity.
01346   if (ToType->isExtVectorType()) {
01347     // There are no conversions between extended vector types other than the
01348     // identity conversion.
01349     if (FromType->isExtVectorType())
01350       return false;
01351 
01352     // Vector splat from any arithmetic type to a vector.
01353     if (FromType->isArithmeticType()) {
01354       ICK = ICK_Vector_Splat;
01355       return true;
01356     }
01357   }
01358 
01359   // We can perform the conversion between vector types in the following cases:
01360   // 1)vector types are equivalent AltiVec and GCC vector types
01361   // 2)lax vector conversions are permitted and the vector types are of the
01362   //   same size
01363   if (ToType->isVectorType() && FromType->isVectorType()) {
01364     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
01365         S.isLaxVectorConversion(FromType, ToType)) {
01366       ICK = ICK_Vector_Conversion;
01367       return true;
01368     }
01369   }
01370 
01371   return false;
01372 }
01373 
01374 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
01375                                 bool InOverloadResolution,
01376                                 StandardConversionSequence &SCS,
01377                                 bool CStyle);
01378   
01379 /// IsStandardConversion - Determines whether there is a standard
01380 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
01381 /// expression From to the type ToType. Standard conversion sequences
01382 /// only consider non-class types; for conversions that involve class
01383 /// types, use TryImplicitConversion. If a conversion exists, SCS will
01384 /// contain the standard conversion sequence required to perform this
01385 /// conversion and this routine will return true. Otherwise, this
01386 /// routine will return false and the value of SCS is unspecified.
01387 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
01388                                  bool InOverloadResolution,
01389                                  StandardConversionSequence &SCS,
01390                                  bool CStyle,
01391                                  bool AllowObjCWritebackConversion) {
01392   QualType FromType = From->getType();
01393 
01394   // Standard conversions (C++ [conv])
01395   SCS.setAsIdentityConversion();
01396   SCS.IncompatibleObjC = false;
01397   SCS.setFromType(FromType);
01398   SCS.CopyConstructor = nullptr;
01399 
01400   // There are no standard conversions for class types in C++, so
01401   // abort early. When overloading in C, however, we do permit
01402   if (FromType->isRecordType() || ToType->isRecordType()) {
01403     if (S.getLangOpts().CPlusPlus)
01404       return false;
01405 
01406     // When we're overloading in C, we allow, as standard conversions,
01407   }
01408 
01409   // The first conversion can be an lvalue-to-rvalue conversion,
01410   // array-to-pointer conversion, or function-to-pointer conversion
01411   // (C++ 4p1).
01412 
01413   if (FromType == S.Context.OverloadTy) {
01414     DeclAccessPair AccessPair;
01415     if (FunctionDecl *Fn
01416           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
01417                                                  AccessPair)) {
01418       // We were able to resolve the address of the overloaded function,
01419       // so we can convert to the type of that function.
01420       FromType = Fn->getType();
01421       SCS.setFromType(FromType);
01422 
01423       // we can sometimes resolve &foo<int> regardless of ToType, so check
01424       // if the type matches (identity) or we are converting to bool
01425       if (!S.Context.hasSameUnqualifiedType(
01426                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
01427         QualType resultTy;
01428         // if the function type matches except for [[noreturn]], it's ok
01429         if (!S.IsNoReturnConversion(FromType,
01430               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
01431           // otherwise, only a boolean conversion is standard   
01432           if (!ToType->isBooleanType()) 
01433             return false; 
01434       }
01435 
01436       // Check if the "from" expression is taking the address of an overloaded
01437       // function and recompute the FromType accordingly. Take advantage of the
01438       // fact that non-static member functions *must* have such an address-of
01439       // expression. 
01440       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
01441       if (Method && !Method->isStatic()) {
01442         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
01443                "Non-unary operator on non-static member address");
01444         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
01445                == UO_AddrOf &&
01446                "Non-address-of operator on non-static member address");
01447         const Type *ClassType
01448           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
01449         FromType = S.Context.getMemberPointerType(FromType, ClassType);
01450       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
01451         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
01452                UO_AddrOf &&
01453                "Non-address-of operator for overloaded function expression");
01454         FromType = S.Context.getPointerType(FromType);
01455       }
01456 
01457       // Check that we've computed the proper type after overload resolution.
01458       assert(S.Context.hasSameType(
01459         FromType,
01460         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
01461     } else {
01462       return false;
01463     }
01464   }
01465   // Lvalue-to-rvalue conversion (C++11 4.1):
01466   //   A glvalue (3.10) of a non-function, non-array type T can
01467   //   be converted to a prvalue.
01468   bool argIsLValue = From->isGLValue();
01469   if (argIsLValue &&
01470       !FromType->isFunctionType() && !FromType->isArrayType() &&
01471       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
01472     SCS.First = ICK_Lvalue_To_Rvalue;
01473 
01474     // C11 6.3.2.1p2:
01475     //   ... if the lvalue has atomic type, the value has the non-atomic version 
01476     //   of the type of the lvalue ...
01477     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
01478       FromType = Atomic->getValueType();
01479 
01480     // If T is a non-class type, the type of the rvalue is the
01481     // cv-unqualified version of T. Otherwise, the type of the rvalue
01482     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
01483     // just strip the qualifiers because they don't matter.
01484     FromType = FromType.getUnqualifiedType();
01485   } else if (FromType->isArrayType()) {
01486     // Array-to-pointer conversion (C++ 4.2)
01487     SCS.First = ICK_Array_To_Pointer;
01488 
01489     // An lvalue or rvalue of type "array of N T" or "array of unknown
01490     // bound of T" can be converted to an rvalue of type "pointer to
01491     // T" (C++ 4.2p1).
01492     FromType = S.Context.getArrayDecayedType(FromType);
01493 
01494     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
01495       // This conversion is deprecated in C++03 (D.4)
01496       SCS.DeprecatedStringLiteralToCharPtr = true;
01497 
01498       // For the purpose of ranking in overload resolution
01499       // (13.3.3.1.1), this conversion is considered an
01500       // array-to-pointer conversion followed by a qualification
01501       // conversion (4.4). (C++ 4.2p2)
01502       SCS.Second = ICK_Identity;
01503       SCS.Third = ICK_Qualification;
01504       SCS.QualificationIncludesObjCLifetime = false;
01505       SCS.setAllToTypes(FromType);
01506       return true;
01507     }
01508   } else if (FromType->isFunctionType() && argIsLValue) {
01509     // Function-to-pointer conversion (C++ 4.3).
01510     SCS.First = ICK_Function_To_Pointer;
01511 
01512     // An lvalue of function type T can be converted to an rvalue of
01513     // type "pointer to T." The result is a pointer to the
01514     // function. (C++ 4.3p1).
01515     FromType = S.Context.getPointerType(FromType);
01516   } else {
01517     // We don't require any conversions for the first step.
01518     SCS.First = ICK_Identity;
01519   }
01520   SCS.setToType(0, FromType);
01521 
01522   // The second conversion can be an integral promotion, floating
01523   // point promotion, integral conversion, floating point conversion,
01524   // floating-integral conversion, pointer conversion,
01525   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
01526   // For overloading in C, this can also be a "compatible-type"
01527   // conversion.
01528   bool IncompatibleObjC = false;
01529   ImplicitConversionKind SecondICK = ICK_Identity;
01530   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
01531     // The unqualified versions of the types are the same: there's no
01532     // conversion to do.
01533     SCS.Second = ICK_Identity;
01534   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
01535     // Integral promotion (C++ 4.5).
01536     SCS.Second = ICK_Integral_Promotion;
01537     FromType = ToType.getUnqualifiedType();
01538   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
01539     // Floating point promotion (C++ 4.6).
01540     SCS.Second = ICK_Floating_Promotion;
01541     FromType = ToType.getUnqualifiedType();
01542   } else if (S.IsComplexPromotion(FromType, ToType)) {
01543     // Complex promotion (Clang extension)
01544     SCS.Second = ICK_Complex_Promotion;
01545     FromType = ToType.getUnqualifiedType();
01546   } else if (ToType->isBooleanType() &&
01547              (FromType->isArithmeticType() ||
01548               FromType->isAnyPointerType() ||
01549               FromType->isBlockPointerType() ||
01550               FromType->isMemberPointerType() ||
01551               FromType->isNullPtrType())) {
01552     // Boolean conversions (C++ 4.12).
01553     SCS.Second = ICK_Boolean_Conversion;
01554     FromType = S.Context.BoolTy;
01555   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
01556              ToType->isIntegralType(S.Context)) {
01557     // Integral conversions (C++ 4.7).
01558     SCS.Second = ICK_Integral_Conversion;
01559     FromType = ToType.getUnqualifiedType();
01560   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
01561     // Complex conversions (C99 6.3.1.6)
01562     SCS.Second = ICK_Complex_Conversion;
01563     FromType = ToType.getUnqualifiedType();
01564   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
01565              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
01566     // Complex-real conversions (C99 6.3.1.7)
01567     SCS.Second = ICK_Complex_Real;
01568     FromType = ToType.getUnqualifiedType();
01569   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
01570     // Floating point conversions (C++ 4.8).
01571     SCS.Second = ICK_Floating_Conversion;
01572     FromType = ToType.getUnqualifiedType();
01573   } else if ((FromType->isRealFloatingType() &&
01574               ToType->isIntegralType(S.Context)) ||
01575              (FromType->isIntegralOrUnscopedEnumerationType() &&
01576               ToType->isRealFloatingType())) {
01577     // Floating-integral conversions (C++ 4.9).
01578     SCS.Second = ICK_Floating_Integral;
01579     FromType = ToType.getUnqualifiedType();
01580   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
01581     SCS.Second = ICK_Block_Pointer_Conversion;
01582   } else if (AllowObjCWritebackConversion &&
01583              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
01584     SCS.Second = ICK_Writeback_Conversion;
01585   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
01586                                    FromType, IncompatibleObjC)) {
01587     // Pointer conversions (C++ 4.10).
01588     SCS.Second = ICK_Pointer_Conversion;
01589     SCS.IncompatibleObjC = IncompatibleObjC;
01590     FromType = FromType.getUnqualifiedType();
01591   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
01592                                          InOverloadResolution, FromType)) {
01593     // Pointer to member conversions (4.11).
01594     SCS.Second = ICK_Pointer_Member;
01595   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
01596     SCS.Second = SecondICK;
01597     FromType = ToType.getUnqualifiedType();
01598   } else if (!S.getLangOpts().CPlusPlus &&
01599              S.Context.typesAreCompatible(ToType, FromType)) {
01600     // Compatible conversions (Clang extension for C function overloading)
01601     SCS.Second = ICK_Compatible_Conversion;
01602     FromType = ToType.getUnqualifiedType();
01603   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
01604     // Treat a conversion that strips "noreturn" as an identity conversion.
01605     SCS.Second = ICK_NoReturn_Adjustment;
01606   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
01607                                              InOverloadResolution,
01608                                              SCS, CStyle)) {
01609     SCS.Second = ICK_TransparentUnionConversion;
01610     FromType = ToType;
01611   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
01612                                  CStyle)) {
01613     // tryAtomicConversion has updated the standard conversion sequence
01614     // appropriately.
01615     return true;
01616   } else if (ToType->isEventT() && 
01617              From->isIntegerConstantExpr(S.getASTContext()) &&
01618              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
01619     SCS.Second = ICK_Zero_Event_Conversion;
01620     FromType = ToType;
01621   } else {
01622     // No second conversion required.
01623     SCS.Second = ICK_Identity;
01624   }
01625   SCS.setToType(1, FromType);
01626 
01627   QualType CanonFrom;
01628   QualType CanonTo;
01629   // The third conversion can be a qualification conversion (C++ 4p1).
01630   bool ObjCLifetimeConversion;
01631   if (S.IsQualificationConversion(FromType, ToType, CStyle, 
01632                                   ObjCLifetimeConversion)) {
01633     SCS.Third = ICK_Qualification;
01634     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
01635     FromType = ToType;
01636     CanonFrom = S.Context.getCanonicalType(FromType);
01637     CanonTo = S.Context.getCanonicalType(ToType);
01638   } else {
01639     // No conversion required
01640     SCS.Third = ICK_Identity;
01641 
01642     // C++ [over.best.ics]p6:
01643     //   [...] Any difference in top-level cv-qualification is
01644     //   subsumed by the initialization itself and does not constitute
01645     //   a conversion. [...]
01646     CanonFrom = S.Context.getCanonicalType(FromType);
01647     CanonTo = S.Context.getCanonicalType(ToType);
01648     if (CanonFrom.getLocalUnqualifiedType()
01649                                        == CanonTo.getLocalUnqualifiedType() &&
01650         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
01651       FromType = ToType;
01652       CanonFrom = CanonTo;
01653     }
01654   }
01655   SCS.setToType(2, FromType);
01656 
01657   // If we have not converted the argument type to the parameter type,
01658   // this is a bad conversion sequence.
01659   if (CanonFrom != CanonTo)
01660     return false;
01661 
01662   return true;
01663 }
01664   
01665 static bool
01666 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 
01667                                      QualType &ToType,
01668                                      bool InOverloadResolution,
01669                                      StandardConversionSequence &SCS,
01670                                      bool CStyle) {
01671     
01672   const RecordType *UT = ToType->getAsUnionType();
01673   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
01674     return false;
01675   // The field to initialize within the transparent union.
01676   RecordDecl *UD = UT->getDecl();
01677   // It's compatible if the expression matches any of the fields.
01678   for (const auto *it : UD->fields()) {
01679     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
01680                              CStyle, /*ObjCWritebackConversion=*/false)) {
01681       ToType = it->getType();
01682       return true;
01683     }
01684   }
01685   return false;
01686 }
01687 
01688 /// IsIntegralPromotion - Determines whether the conversion from the
01689 /// expression From (whose potentially-adjusted type is FromType) to
01690 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
01691 /// sets PromotedType to the promoted type.
01692 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
01693   const BuiltinType *To = ToType->getAs<BuiltinType>();
01694   // All integers are built-in.
01695   if (!To) {
01696     return false;
01697   }
01698 
01699   // An rvalue of type char, signed char, unsigned char, short int, or
01700   // unsigned short int can be converted to an rvalue of type int if
01701   // int can represent all the values of the source type; otherwise,
01702   // the source rvalue can be converted to an rvalue of type unsigned
01703   // int (C++ 4.5p1).
01704   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
01705       !FromType->isEnumeralType()) {
01706     if (// We can promote any signed, promotable integer type to an int
01707         (FromType->isSignedIntegerType() ||
01708          // We can promote any unsigned integer type whose size is
01709          // less than int to an int.
01710          (!FromType->isSignedIntegerType() &&
01711           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
01712       return To->getKind() == BuiltinType::Int;
01713     }
01714 
01715     return To->getKind() == BuiltinType::UInt;
01716   }
01717 
01718   // C++11 [conv.prom]p3:
01719   //   A prvalue of an unscoped enumeration type whose underlying type is not
01720   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
01721   //   following types that can represent all the values of the enumeration
01722   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
01723   //   unsigned int, long int, unsigned long int, long long int, or unsigned
01724   //   long long int. If none of the types in that list can represent all the
01725   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
01726   //   type can be converted to an rvalue a prvalue of the extended integer type
01727   //   with lowest integer conversion rank (4.13) greater than the rank of long
01728   //   long in which all the values of the enumeration can be represented. If
01729   //   there are two such extended types, the signed one is chosen.
01730   // C++11 [conv.prom]p4:
01731   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
01732   //   can be converted to a prvalue of its underlying type. Moreover, if
01733   //   integral promotion can be applied to its underlying type, a prvalue of an
01734   //   unscoped enumeration type whose underlying type is fixed can also be
01735   //   converted to a prvalue of the promoted underlying type.
01736   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
01737     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
01738     // provided for a scoped enumeration.
01739     if (FromEnumType->getDecl()->isScoped())
01740       return false;
01741 
01742     // We can perform an integral promotion to the underlying type of the enum,
01743     // even if that's not the promoted type.
01744     if (FromEnumType->getDecl()->isFixed()) {
01745       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
01746       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
01747              IsIntegralPromotion(From, Underlying, ToType);
01748     }
01749 
01750     // We have already pre-calculated the promotion type, so this is trivial.
01751     if (ToType->isIntegerType() &&
01752         !RequireCompleteType(From->getLocStart(), FromType, 0))
01753       return Context.hasSameUnqualifiedType(ToType,
01754                                 FromEnumType->getDecl()->getPromotionType());
01755   }
01756 
01757   // C++0x [conv.prom]p2:
01758   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
01759   //   to an rvalue a prvalue of the first of the following types that can
01760   //   represent all the values of its underlying type: int, unsigned int,
01761   //   long int, unsigned long int, long long int, or unsigned long long int.
01762   //   If none of the types in that list can represent all the values of its
01763   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
01764   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
01765   //   type.
01766   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
01767       ToType->isIntegerType()) {
01768     // Determine whether the type we're converting from is signed or
01769     // unsigned.
01770     bool FromIsSigned = FromType->isSignedIntegerType();
01771     uint64_t FromSize = Context.getTypeSize(FromType);
01772 
01773     // The types we'll try to promote to, in the appropriate
01774     // order. Try each of these types.
01775     QualType PromoteTypes[6] = {
01776       Context.IntTy, Context.UnsignedIntTy,
01777       Context.LongTy, Context.UnsignedLongTy ,
01778       Context.LongLongTy, Context.UnsignedLongLongTy
01779     };
01780     for (int Idx = 0; Idx < 6; ++Idx) {
01781       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
01782       if (FromSize < ToSize ||
01783           (FromSize == ToSize &&
01784            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
01785         // We found the type that we can promote to. If this is the
01786         // type we wanted, we have a promotion. Otherwise, no
01787         // promotion.
01788         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
01789       }
01790     }
01791   }
01792 
01793   // An rvalue for an integral bit-field (9.6) can be converted to an
01794   // rvalue of type int if int can represent all the values of the
01795   // bit-field; otherwise, it can be converted to unsigned int if
01796   // unsigned int can represent all the values of the bit-field. If
01797   // the bit-field is larger yet, no integral promotion applies to
01798   // it. If the bit-field has an enumerated type, it is treated as any
01799   // other value of that type for promotion purposes (C++ 4.5p3).
01800   // FIXME: We should delay checking of bit-fields until we actually perform the
01801   // conversion.
01802   using llvm::APSInt;
01803   if (From)
01804     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
01805       APSInt BitWidth;
01806       if (FromType->isIntegralType(Context) &&
01807           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
01808         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
01809         ToSize = Context.getTypeSize(ToType);
01810 
01811         // Are we promoting to an int from a bitfield that fits in an int?
01812         if (BitWidth < ToSize ||
01813             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
01814           return To->getKind() == BuiltinType::Int;
01815         }
01816 
01817         // Are we promoting to an unsigned int from an unsigned bitfield
01818         // that fits into an unsigned int?
01819         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
01820           return To->getKind() == BuiltinType::UInt;
01821         }
01822 
01823         return false;
01824       }
01825     }
01826 
01827   // An rvalue of type bool can be converted to an rvalue of type int,
01828   // with false becoming zero and true becoming one (C++ 4.5p4).
01829   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
01830     return true;
01831   }
01832 
01833   return false;
01834 }
01835 
01836 /// IsFloatingPointPromotion - Determines whether the conversion from
01837 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
01838 /// returns true and sets PromotedType to the promoted type.
01839 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
01840   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
01841     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
01842       /// An rvalue of type float can be converted to an rvalue of type
01843       /// double. (C++ 4.6p1).
01844       if (FromBuiltin->getKind() == BuiltinType::Float &&
01845           ToBuiltin->getKind() == BuiltinType::Double)
01846         return true;
01847 
01848       // C99 6.3.1.5p1:
01849       //   When a float is promoted to double or long double, or a
01850       //   double is promoted to long double [...].
01851       if (!getLangOpts().CPlusPlus &&
01852           (FromBuiltin->getKind() == BuiltinType::Float ||
01853            FromBuiltin->getKind() == BuiltinType::Double) &&
01854           (ToBuiltin->getKind() == BuiltinType::LongDouble))
01855         return true;
01856 
01857       // Half can be promoted to float.
01858       if (!getLangOpts().NativeHalfType &&
01859            FromBuiltin->getKind() == BuiltinType::Half &&
01860           ToBuiltin->getKind() == BuiltinType::Float)
01861         return true;
01862     }
01863 
01864   return false;
01865 }
01866 
01867 /// \brief Determine if a conversion is a complex promotion.
01868 ///
01869 /// A complex promotion is defined as a complex -> complex conversion
01870 /// where the conversion between the underlying real types is a
01871 /// floating-point or integral promotion.
01872 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
01873   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
01874   if (!FromComplex)
01875     return false;
01876 
01877   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
01878   if (!ToComplex)
01879     return false;
01880 
01881   return IsFloatingPointPromotion(FromComplex->getElementType(),
01882                                   ToComplex->getElementType()) ||
01883     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
01884                         ToComplex->getElementType());
01885 }
01886 
01887 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
01888 /// the pointer type FromPtr to a pointer to type ToPointee, with the
01889 /// same type qualifiers as FromPtr has on its pointee type. ToType,
01890 /// if non-empty, will be a pointer to ToType that may or may not have
01891 /// the right set of qualifiers on its pointee.
01892 ///
01893 static QualType
01894 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
01895                                    QualType ToPointee, QualType ToType,
01896                                    ASTContext &Context,
01897                                    bool StripObjCLifetime = false) {
01898   assert((FromPtr->getTypeClass() == Type::Pointer ||
01899           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
01900          "Invalid similarly-qualified pointer type");
01901 
01902   /// Conversions to 'id' subsume cv-qualifier conversions.
01903   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 
01904     return ToType.getUnqualifiedType();
01905 
01906   QualType CanonFromPointee
01907     = Context.getCanonicalType(FromPtr->getPointeeType());
01908   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
01909   Qualifiers Quals = CanonFromPointee.getQualifiers();
01910 
01911   if (StripObjCLifetime)
01912     Quals.removeObjCLifetime();
01913   
01914   // Exact qualifier match -> return the pointer type we're converting to.
01915   if (CanonToPointee.getLocalQualifiers() == Quals) {
01916     // ToType is exactly what we need. Return it.
01917     if (!ToType.isNull())
01918       return ToType.getUnqualifiedType();
01919 
01920     // Build a pointer to ToPointee. It has the right qualifiers
01921     // already.
01922     if (isa<ObjCObjectPointerType>(ToType))
01923       return Context.getObjCObjectPointerType(ToPointee);
01924     return Context.getPointerType(ToPointee);
01925   }
01926 
01927   // Just build a canonical type that has the right qualifiers.
01928   QualType QualifiedCanonToPointee
01929     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
01930 
01931   if (isa<ObjCObjectPointerType>(ToType))
01932     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
01933   return Context.getPointerType(QualifiedCanonToPointee);
01934 }
01935 
01936 static bool isNullPointerConstantForConversion(Expr *Expr,
01937                                                bool InOverloadResolution,
01938                                                ASTContext &Context) {
01939   // Handle value-dependent integral null pointer constants correctly.
01940   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
01941   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
01942       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
01943     return !InOverloadResolution;
01944 
01945   return Expr->isNullPointerConstant(Context,
01946                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
01947                                         : Expr::NPC_ValueDependentIsNull);
01948 }
01949 
01950 /// IsPointerConversion - Determines whether the conversion of the
01951 /// expression From, which has the (possibly adjusted) type FromType,
01952 /// can be converted to the type ToType via a pointer conversion (C++
01953 /// 4.10). If so, returns true and places the converted type (that
01954 /// might differ from ToType in its cv-qualifiers at some level) into
01955 /// ConvertedType.
01956 ///
01957 /// This routine also supports conversions to and from block pointers
01958 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
01959 /// pointers to interfaces. FIXME: Once we've determined the
01960 /// appropriate overloading rules for Objective-C, we may want to
01961 /// split the Objective-C checks into a different routine; however,
01962 /// GCC seems to consider all of these conversions to be pointer
01963 /// conversions, so for now they live here. IncompatibleObjC will be
01964 /// set if the conversion is an allowed Objective-C conversion that
01965 /// should result in a warning.
01966 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
01967                                bool InOverloadResolution,
01968                                QualType& ConvertedType,
01969                                bool &IncompatibleObjC) {
01970   IncompatibleObjC = false;
01971   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
01972                               IncompatibleObjC))
01973     return true;
01974 
01975   // Conversion from a null pointer constant to any Objective-C pointer type.
01976   if (ToType->isObjCObjectPointerType() &&
01977       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
01978     ConvertedType = ToType;
01979     return true;
01980   }
01981 
01982   // Blocks: Block pointers can be converted to void*.
01983   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
01984       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
01985     ConvertedType = ToType;
01986     return true;
01987   }
01988   // Blocks: A null pointer constant can be converted to a block
01989   // pointer type.
01990   if (ToType->isBlockPointerType() &&
01991       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
01992     ConvertedType = ToType;
01993     return true;
01994   }
01995 
01996   // If the left-hand-side is nullptr_t, the right side can be a null
01997   // pointer constant.
01998   if (ToType->isNullPtrType() &&
01999       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
02000     ConvertedType = ToType;
02001     return true;
02002   }
02003 
02004   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
02005   if (!ToTypePtr)
02006     return false;
02007 
02008   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
02009   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
02010     ConvertedType = ToType;
02011     return true;
02012   }
02013 
02014   // Beyond this point, both types need to be pointers
02015   // , including objective-c pointers.
02016   QualType ToPointeeType = ToTypePtr->getPointeeType();
02017   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
02018       !getLangOpts().ObjCAutoRefCount) {
02019     ConvertedType = BuildSimilarlyQualifiedPointerType(
02020                                       FromType->getAs<ObjCObjectPointerType>(),
02021                                                        ToPointeeType,
02022                                                        ToType, Context);
02023     return true;
02024   }
02025   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
02026   if (!FromTypePtr)
02027     return false;
02028 
02029   QualType FromPointeeType = FromTypePtr->getPointeeType();
02030 
02031   // If the unqualified pointee types are the same, this can't be a
02032   // pointer conversion, so don't do all of the work below.
02033   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
02034     return false;
02035 
02036   // An rvalue of type "pointer to cv T," where T is an object type,
02037   // can be converted to an rvalue of type "pointer to cv void" (C++
02038   // 4.10p2).
02039   if (FromPointeeType->isIncompleteOrObjectType() &&
02040       ToPointeeType->isVoidType()) {
02041     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
02042                                                        ToPointeeType,
02043                                                        ToType, Context,
02044                                                    /*StripObjCLifetime=*/true);
02045     return true;
02046   }
02047 
02048   // MSVC allows implicit function to void* type conversion.
02049   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
02050       ToPointeeType->isVoidType()) {
02051     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
02052                                                        ToPointeeType,
02053                                                        ToType, Context);
02054     return true;
02055   }
02056 
02057   // When we're overloading in C, we allow a special kind of pointer
02058   // conversion for compatible-but-not-identical pointee types.
02059   if (!getLangOpts().CPlusPlus &&
02060       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
02061     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
02062                                                        ToPointeeType,
02063                                                        ToType, Context);
02064     return true;
02065   }
02066 
02067   // C++ [conv.ptr]p3:
02068   //
02069   //   An rvalue of type "pointer to cv D," where D is a class type,
02070   //   can be converted to an rvalue of type "pointer to cv B," where
02071   //   B is a base class (clause 10) of D. If B is an inaccessible
02072   //   (clause 11) or ambiguous (10.2) base class of D, a program that
02073   //   necessitates this conversion is ill-formed. The result of the
02074   //   conversion is a pointer to the base class sub-object of the
02075   //   derived class object. The null pointer value is converted to
02076   //   the null pointer value of the destination type.
02077   //
02078   // Note that we do not check for ambiguity or inaccessibility
02079   // here. That is handled by CheckPointerConversion.
02080   if (getLangOpts().CPlusPlus &&
02081       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
02082       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
02083       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
02084       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
02085     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
02086                                                        ToPointeeType,
02087                                                        ToType, Context);
02088     return true;
02089   }
02090 
02091   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
02092       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
02093     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
02094                                                        ToPointeeType,
02095                                                        ToType, Context);
02096     return true;
02097   }
02098   
02099   return false;
02100 }
02101  
02102 /// \brief Adopt the given qualifiers for the given type.
02103 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
02104   Qualifiers TQs = T.getQualifiers();
02105   
02106   // Check whether qualifiers already match.
02107   if (TQs == Qs)
02108     return T;
02109   
02110   if (Qs.compatiblyIncludes(TQs))
02111     return Context.getQualifiedType(T, Qs);
02112   
02113   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
02114 }
02115 
02116 /// isObjCPointerConversion - Determines whether this is an
02117 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
02118 /// with the same arguments and return values.
02119 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
02120                                    QualType& ConvertedType,
02121                                    bool &IncompatibleObjC) {
02122   if (!getLangOpts().ObjC1)
02123     return false;
02124 
02125   // The set of qualifiers on the type we're converting from.
02126   Qualifiers FromQualifiers = FromType.getQualifiers();
02127   
02128   // First, we handle all conversions on ObjC object pointer types.
02129   const ObjCObjectPointerType* ToObjCPtr =
02130     ToType->getAs<ObjCObjectPointerType>();
02131   const ObjCObjectPointerType *FromObjCPtr =
02132     FromType->getAs<ObjCObjectPointerType>();
02133 
02134   if (ToObjCPtr && FromObjCPtr) {
02135     // If the pointee types are the same (ignoring qualifications),
02136     // then this is not a pointer conversion.
02137     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
02138                                        FromObjCPtr->getPointeeType()))
02139       return false;
02140 
02141     // Check for compatible 
02142     // Objective C++: We're able to convert between "id" or "Class" and a
02143     // pointer to any interface (in both directions).
02144     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
02145       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
02146       return true;
02147     }
02148     // Conversions with Objective-C's id<...>.
02149     if ((FromObjCPtr->isObjCQualifiedIdType() ||
02150          ToObjCPtr->isObjCQualifiedIdType()) &&
02151         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
02152                                                   /*compare=*/false)) {
02153       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
02154       return true;
02155     }
02156     // Objective C++: We're able to convert from a pointer to an
02157     // interface to a pointer to a different interface.
02158     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
02159       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
02160       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
02161       if (getLangOpts().CPlusPlus && LHS && RHS &&
02162           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
02163                                                 FromObjCPtr->getPointeeType()))
02164         return false;
02165       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
02166                                                    ToObjCPtr->getPointeeType(),
02167                                                          ToType, Context);
02168       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
02169       return true;
02170     }
02171 
02172     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
02173       // Okay: this is some kind of implicit downcast of Objective-C
02174       // interfaces, which is permitted. However, we're going to
02175       // complain about it.
02176       IncompatibleObjC = true;
02177       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
02178                                                    ToObjCPtr->getPointeeType(),
02179                                                          ToType, Context);
02180       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
02181       return true;
02182     }
02183   }
02184   // Beyond this point, both types need to be C pointers or block pointers.
02185   QualType ToPointeeType;
02186   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
02187     ToPointeeType = ToCPtr->getPointeeType();
02188   else if (const BlockPointerType *ToBlockPtr =
02189             ToType->getAs<BlockPointerType>()) {
02190     // Objective C++: We're able to convert from a pointer to any object
02191     // to a block pointer type.
02192     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
02193       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
02194       return true;
02195     }
02196     ToPointeeType = ToBlockPtr->getPointeeType();
02197   }
02198   else if (FromType->getAs<BlockPointerType>() &&
02199            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
02200     // Objective C++: We're able to convert from a block pointer type to a
02201     // pointer to any object.
02202     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
02203     return true;
02204   }
02205   else
02206     return false;
02207 
02208   QualType FromPointeeType;
02209   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
02210     FromPointeeType = FromCPtr->getPointeeType();
02211   else if (const BlockPointerType *FromBlockPtr =
02212            FromType->getAs<BlockPointerType>())
02213     FromPointeeType = FromBlockPtr->getPointeeType();
02214   else
02215     return false;
02216 
02217   // If we have pointers to pointers, recursively check whether this
02218   // is an Objective-C conversion.
02219   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
02220       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
02221                               IncompatibleObjC)) {
02222     // We always complain about this conversion.
02223     IncompatibleObjC = true;
02224     ConvertedType = Context.getPointerType(ConvertedType);
02225     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
02226     return true;
02227   }
02228   // Allow conversion of pointee being objective-c pointer to another one;
02229   // as in I* to id.
02230   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
02231       ToPointeeType->getAs<ObjCObjectPointerType>() &&
02232       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
02233                               IncompatibleObjC)) {
02234         
02235     ConvertedType = Context.getPointerType(ConvertedType);
02236     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
02237     return true;
02238   }
02239 
02240   // If we have pointers to functions or blocks, check whether the only
02241   // differences in the argument and result types are in Objective-C
02242   // pointer conversions. If so, we permit the conversion (but
02243   // complain about it).
02244   const FunctionProtoType *FromFunctionType
02245     = FromPointeeType->getAs<FunctionProtoType>();
02246   const FunctionProtoType *ToFunctionType
02247     = ToPointeeType->getAs<FunctionProtoType>();
02248   if (FromFunctionType && ToFunctionType) {
02249     // If the function types are exactly the same, this isn't an
02250     // Objective-C pointer conversion.
02251     if (Context.getCanonicalType(FromPointeeType)
02252           == Context.getCanonicalType(ToPointeeType))
02253       return false;
02254 
02255     // Perform the quick checks that will tell us whether these
02256     // function types are obviously different.
02257     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
02258         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
02259         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
02260       return false;
02261 
02262     bool HasObjCConversion = false;
02263     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
02264         Context.getCanonicalType(ToFunctionType->getReturnType())) {
02265       // Okay, the types match exactly. Nothing to do.
02266     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
02267                                        ToFunctionType->getReturnType(),
02268                                        ConvertedType, IncompatibleObjC)) {
02269       // Okay, we have an Objective-C pointer conversion.
02270       HasObjCConversion = true;
02271     } else {
02272       // Function types are too different. Abort.
02273       return false;
02274     }
02275 
02276     // Check argument types.
02277     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
02278          ArgIdx != NumArgs; ++ArgIdx) {
02279       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
02280       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
02281       if (Context.getCanonicalType(FromArgType)
02282             == Context.getCanonicalType(ToArgType)) {
02283         // Okay, the types match exactly. Nothing to do.
02284       } else if (isObjCPointerConversion(FromArgType, ToArgType,
02285                                          ConvertedType, IncompatibleObjC)) {
02286         // Okay, we have an Objective-C pointer conversion.
02287         HasObjCConversion = true;
02288       } else {
02289         // Argument types are too different. Abort.
02290         return false;
02291       }
02292     }
02293 
02294     if (HasObjCConversion) {
02295       // We had an Objective-C conversion. Allow this pointer
02296       // conversion, but complain about it.
02297       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
02298       IncompatibleObjC = true;
02299       return true;
02300     }
02301   }
02302 
02303   return false;
02304 }
02305 
02306 /// \brief Determine whether this is an Objective-C writeback conversion,
02307 /// used for parameter passing when performing automatic reference counting.
02308 ///
02309 /// \param FromType The type we're converting form.
02310 ///
02311 /// \param ToType The type we're converting to.
02312 ///
02313 /// \param ConvertedType The type that will be produced after applying
02314 /// this conversion.
02315 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
02316                                      QualType &ConvertedType) {
02317   if (!getLangOpts().ObjCAutoRefCount || 
02318       Context.hasSameUnqualifiedType(FromType, ToType))
02319     return false;
02320   
02321   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
02322   QualType ToPointee;
02323   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
02324     ToPointee = ToPointer->getPointeeType();
02325   else
02326     return false;
02327   
02328   Qualifiers ToQuals = ToPointee.getQualifiers();
02329   if (!ToPointee->isObjCLifetimeType() || 
02330       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
02331       !ToQuals.withoutObjCLifetime().empty())
02332     return false;
02333   
02334   // Argument must be a pointer to __strong to __weak.
02335   QualType FromPointee;
02336   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
02337     FromPointee = FromPointer->getPointeeType();
02338   else
02339     return false;
02340   
02341   Qualifiers FromQuals = FromPointee.getQualifiers();
02342   if (!FromPointee->isObjCLifetimeType() ||
02343       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
02344        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
02345     return false;
02346   
02347   // Make sure that we have compatible qualifiers.
02348   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
02349   if (!ToQuals.compatiblyIncludes(FromQuals))
02350     return false;
02351   
02352   // Remove qualifiers from the pointee type we're converting from; they
02353   // aren't used in the compatibility check belong, and we'll be adding back
02354   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
02355   FromPointee = FromPointee.getUnqualifiedType();
02356   
02357   // The unqualified form of the pointee types must be compatible.
02358   ToPointee = ToPointee.getUnqualifiedType();
02359   bool IncompatibleObjC;
02360   if (Context.typesAreCompatible(FromPointee, ToPointee))
02361     FromPointee = ToPointee;
02362   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
02363                                     IncompatibleObjC))
02364     return false;
02365   
02366   /// \brief Construct the type we're converting to, which is a pointer to
02367   /// __autoreleasing pointee.
02368   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
02369   ConvertedType = Context.getPointerType(FromPointee);
02370   return true;
02371 }
02372 
02373 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
02374                                     QualType& ConvertedType) {
02375   QualType ToPointeeType;
02376   if (const BlockPointerType *ToBlockPtr =
02377         ToType->getAs<BlockPointerType>())
02378     ToPointeeType = ToBlockPtr->getPointeeType();
02379   else
02380     return false;
02381   
02382   QualType FromPointeeType;
02383   if (const BlockPointerType *FromBlockPtr =
02384       FromType->getAs<BlockPointerType>())
02385     FromPointeeType = FromBlockPtr->getPointeeType();
02386   else
02387     return false;
02388   // We have pointer to blocks, check whether the only
02389   // differences in the argument and result types are in Objective-C
02390   // pointer conversions. If so, we permit the conversion.
02391   
02392   const FunctionProtoType *FromFunctionType
02393     = FromPointeeType->getAs<FunctionProtoType>();
02394   const FunctionProtoType *ToFunctionType
02395     = ToPointeeType->getAs<FunctionProtoType>();
02396   
02397   if (!FromFunctionType || !ToFunctionType)
02398     return false;
02399 
02400   if (Context.hasSameType(FromPointeeType, ToPointeeType))
02401     return true;
02402     
02403   // Perform the quick checks that will tell us whether these
02404   // function types are obviously different.
02405   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
02406       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
02407     return false;
02408     
02409   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
02410   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
02411   if (FromEInfo != ToEInfo)
02412     return false;
02413 
02414   bool IncompatibleObjC = false;
02415   if (Context.hasSameType(FromFunctionType->getReturnType(),
02416                           ToFunctionType->getReturnType())) {
02417     // Okay, the types match exactly. Nothing to do.
02418   } else {
02419     QualType RHS = FromFunctionType->getReturnType();
02420     QualType LHS = ToFunctionType->getReturnType();
02421     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
02422         !RHS.hasQualifiers() && LHS.hasQualifiers())
02423        LHS = LHS.getUnqualifiedType();
02424 
02425      if (Context.hasSameType(RHS,LHS)) {
02426        // OK exact match.
02427      } else if (isObjCPointerConversion(RHS, LHS,
02428                                         ConvertedType, IncompatibleObjC)) {
02429      if (IncompatibleObjC)
02430        return false;
02431      // Okay, we have an Objective-C pointer conversion.
02432      }
02433      else
02434        return false;
02435    }
02436     
02437    // Check argument types.
02438    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
02439         ArgIdx != NumArgs; ++ArgIdx) {
02440      IncompatibleObjC = false;
02441      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
02442      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
02443      if (Context.hasSameType(FromArgType, ToArgType)) {
02444        // Okay, the types match exactly. Nothing to do.
02445      } else if (isObjCPointerConversion(ToArgType, FromArgType,
02446                                         ConvertedType, IncompatibleObjC)) {
02447        if (IncompatibleObjC)
02448          return false;
02449        // Okay, we have an Objective-C pointer conversion.
02450      } else
02451        // Argument types are too different. Abort.
02452        return false;
02453    }
02454    if (LangOpts.ObjCAutoRefCount && 
02455        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 
02456                                                     ToFunctionType))
02457      return false;
02458    
02459    ConvertedType = ToType;
02460    return true;
02461 }
02462 
02463 enum {
02464   ft_default,
02465   ft_different_class,
02466   ft_parameter_arity,
02467   ft_parameter_mismatch,
02468   ft_return_type,
02469   ft_qualifer_mismatch
02470 };
02471 
02472 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
02473 /// function types.  Catches different number of parameter, mismatch in
02474 /// parameter types, and different return types.
02475 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
02476                                       QualType FromType, QualType ToType) {
02477   // If either type is not valid, include no extra info.
02478   if (FromType.isNull() || ToType.isNull()) {
02479     PDiag << ft_default;
02480     return;
02481   }
02482 
02483   // Get the function type from the pointers.
02484   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
02485     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
02486                             *ToMember = ToType->getAs<MemberPointerType>();
02487     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
02488       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
02489             << QualType(FromMember->getClass(), 0);
02490       return;
02491     }
02492     FromType = FromMember->getPointeeType();
02493     ToType = ToMember->getPointeeType();
02494   }
02495 
02496   if (FromType->isPointerType())
02497     FromType = FromType->getPointeeType();
02498   if (ToType->isPointerType())
02499     ToType = ToType->getPointeeType();
02500 
02501   // Remove references.
02502   FromType = FromType.getNonReferenceType();
02503   ToType = ToType.getNonReferenceType();
02504 
02505   // Don't print extra info for non-specialized template functions.
02506   if (FromType->isInstantiationDependentType() &&
02507       !FromType->getAs<TemplateSpecializationType>()) {
02508     PDiag << ft_default;
02509     return;
02510   }
02511 
02512   // No extra info for same types.
02513   if (Context.hasSameType(FromType, ToType)) {
02514     PDiag << ft_default;
02515     return;
02516   }
02517 
02518   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
02519                           *ToFunction = ToType->getAs<FunctionProtoType>();
02520 
02521   // Both types need to be function types.
02522   if (!FromFunction || !ToFunction) {
02523     PDiag << ft_default;
02524     return;
02525   }
02526 
02527   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
02528     PDiag << ft_parameter_arity << ToFunction->getNumParams()
02529           << FromFunction->getNumParams();
02530     return;
02531   }
02532 
02533   // Handle different parameter types.
02534   unsigned ArgPos;
02535   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
02536     PDiag << ft_parameter_mismatch << ArgPos + 1
02537           << ToFunction->getParamType(ArgPos)
02538           << FromFunction->getParamType(ArgPos);
02539     return;
02540   }
02541 
02542   // Handle different return type.
02543   if (!Context.hasSameType(FromFunction->getReturnType(),
02544                            ToFunction->getReturnType())) {
02545     PDiag << ft_return_type << ToFunction->getReturnType()
02546           << FromFunction->getReturnType();
02547     return;
02548   }
02549 
02550   unsigned FromQuals = FromFunction->getTypeQuals(),
02551            ToQuals = ToFunction->getTypeQuals();
02552   if (FromQuals != ToQuals) {
02553     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
02554     return;
02555   }
02556 
02557   // Unable to find a difference, so add no extra info.
02558   PDiag << ft_default;
02559 }
02560 
02561 /// FunctionParamTypesAreEqual - This routine checks two function proto types
02562 /// for equality of their argument types. Caller has already checked that
02563 /// they have same number of arguments.  If the parameters are different,
02564 /// ArgPos will have the parameter index of the first different parameter.
02565 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
02566                                       const FunctionProtoType *NewType,
02567                                       unsigned *ArgPos) {
02568   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
02569                                               N = NewType->param_type_begin(),
02570                                               E = OldType->param_type_end();
02571        O && (O != E); ++O, ++N) {
02572     if (!Context.hasSameType(O->getUnqualifiedType(),
02573                              N->getUnqualifiedType())) {
02574       if (ArgPos)
02575         *ArgPos = O - OldType->param_type_begin();
02576       return false;
02577     }
02578   }
02579   return true;
02580 }
02581 
02582 /// CheckPointerConversion - Check the pointer conversion from the
02583 /// expression From to the type ToType. This routine checks for
02584 /// ambiguous or inaccessible derived-to-base pointer
02585 /// conversions for which IsPointerConversion has already returned
02586 /// true. It returns true and produces a diagnostic if there was an
02587 /// error, or returns false otherwise.
02588 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
02589                                   CastKind &Kind,
02590                                   CXXCastPath& BasePath,
02591                                   bool IgnoreBaseAccess) {
02592   QualType FromType = From->getType();
02593   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
02594 
02595   Kind = CK_BitCast;
02596 
02597   if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
02598       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
02599       Expr::NPCK_ZeroExpression) {
02600     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
02601       DiagRuntimeBehavior(From->getExprLoc(), From,
02602                           PDiag(diag::warn_impcast_bool_to_null_pointer)
02603                             << ToType << From->getSourceRange());
02604     else if (!isUnevaluatedContext())
02605       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
02606         << ToType << From->getSourceRange();
02607   }
02608   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
02609     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
02610       QualType FromPointeeType = FromPtrType->getPointeeType(),
02611                ToPointeeType   = ToPtrType->getPointeeType();
02612 
02613       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
02614           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
02615         // We must have a derived-to-base conversion. Check an
02616         // ambiguous or inaccessible conversion.
02617         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
02618                                          From->getExprLoc(),
02619                                          From->getSourceRange(), &BasePath,
02620                                          IgnoreBaseAccess))
02621           return true;
02622 
02623         // The conversion was successful.
02624         Kind = CK_DerivedToBase;
02625       }
02626     }
02627   } else if (const ObjCObjectPointerType *ToPtrType =
02628                ToType->getAs<ObjCObjectPointerType>()) {
02629     if (const ObjCObjectPointerType *FromPtrType =
02630           FromType->getAs<ObjCObjectPointerType>()) {
02631       // Objective-C++ conversions are always okay.
02632       // FIXME: We should have a different class of conversions for the
02633       // Objective-C++ implicit conversions.
02634       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
02635         return false;
02636     } else if (FromType->isBlockPointerType()) {
02637       Kind = CK_BlockPointerToObjCPointerCast;
02638     } else {
02639       Kind = CK_CPointerToObjCPointerCast;
02640     }
02641   } else if (ToType->isBlockPointerType()) {
02642     if (!FromType->isBlockPointerType())
02643       Kind = CK_AnyPointerToBlockPointerCast;
02644   }
02645 
02646   // We shouldn't fall into this case unless it's valid for other
02647   // reasons.
02648   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
02649     Kind = CK_NullToPointer;
02650 
02651   return false;
02652 }
02653 
02654 /// IsMemberPointerConversion - Determines whether the conversion of the
02655 /// expression From, which has the (possibly adjusted) type FromType, can be
02656 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
02657 /// If so, returns true and places the converted type (that might differ from
02658 /// ToType in its cv-qualifiers at some level) into ConvertedType.
02659 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
02660                                      QualType ToType,
02661                                      bool InOverloadResolution,
02662                                      QualType &ConvertedType) {
02663   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
02664   if (!ToTypePtr)
02665     return false;
02666 
02667   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
02668   if (From->isNullPointerConstant(Context,
02669                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
02670                                         : Expr::NPC_ValueDependentIsNull)) {
02671     ConvertedType = ToType;
02672     return true;
02673   }
02674 
02675   // Otherwise, both types have to be member pointers.
02676   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
02677   if (!FromTypePtr)
02678     return false;
02679 
02680   // A pointer to member of B can be converted to a pointer to member of D,
02681   // where D is derived from B (C++ 4.11p2).
02682   QualType FromClass(FromTypePtr->getClass(), 0);
02683   QualType ToClass(ToTypePtr->getClass(), 0);
02684 
02685   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
02686       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
02687       IsDerivedFrom(ToClass, FromClass)) {
02688     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
02689                                                  ToClass.getTypePtr());
02690     return true;
02691   }
02692 
02693   return false;
02694 }
02695 
02696 /// CheckMemberPointerConversion - Check the member pointer conversion from the
02697 /// expression From to the type ToType. This routine checks for ambiguous or
02698 /// virtual or inaccessible base-to-derived member pointer conversions
02699 /// for which IsMemberPointerConversion has already returned true. It returns
02700 /// true and produces a diagnostic if there was an error, or returns false
02701 /// otherwise.
02702 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
02703                                         CastKind &Kind,
02704                                         CXXCastPath &BasePath,
02705                                         bool IgnoreBaseAccess) {
02706   QualType FromType = From->getType();
02707   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
02708   if (!FromPtrType) {
02709     // This must be a null pointer to member pointer conversion
02710     assert(From->isNullPointerConstant(Context,
02711                                        Expr::NPC_ValueDependentIsNull) &&
02712            "Expr must be null pointer constant!");
02713     Kind = CK_NullToMemberPointer;
02714     return false;
02715   }
02716 
02717   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
02718   assert(ToPtrType && "No member pointer cast has a target type "
02719                       "that is not a member pointer.");
02720 
02721   QualType FromClass = QualType(FromPtrType->getClass(), 0);
02722   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
02723 
02724   // FIXME: What about dependent types?
02725   assert(FromClass->isRecordType() && "Pointer into non-class.");
02726   assert(ToClass->isRecordType() && "Pointer into non-class.");
02727 
02728   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
02729                      /*DetectVirtual=*/true);
02730   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
02731   assert(DerivationOkay &&
02732          "Should not have been called if derivation isn't OK.");
02733   (void)DerivationOkay;
02734 
02735   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
02736                                   getUnqualifiedType())) {
02737     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
02738     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
02739       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
02740     return true;
02741   }
02742 
02743   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
02744     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
02745       << FromClass << ToClass << QualType(VBase, 0)
02746       << From->getSourceRange();
02747     return true;
02748   }
02749 
02750   if (!IgnoreBaseAccess)
02751     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
02752                          Paths.front(),
02753                          diag::err_downcast_from_inaccessible_base);
02754 
02755   // Must be a base to derived member conversion.
02756   BuildBasePathArray(Paths, BasePath);
02757   Kind = CK_BaseToDerivedMemberPointer;
02758   return false;
02759 }
02760 
02761 /// Determine whether the lifetime conversion between the two given
02762 /// qualifiers sets is nontrivial.
02763 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
02764                                                Qualifiers ToQuals) {
02765   // Converting anything to const __unsafe_unretained is trivial.
02766   if (ToQuals.hasConst() && 
02767       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
02768     return false;
02769 
02770   return true;
02771 }
02772 
02773 /// IsQualificationConversion - Determines whether the conversion from
02774 /// an rvalue of type FromType to ToType is a qualification conversion
02775 /// (C++ 4.4).
02776 ///
02777 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
02778 /// when the qualification conversion involves a change in the Objective-C
02779 /// object lifetime.
02780 bool
02781 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
02782                                 bool CStyle, bool &ObjCLifetimeConversion) {
02783   FromType = Context.getCanonicalType(FromType);
02784   ToType = Context.getCanonicalType(ToType);
02785   ObjCLifetimeConversion = false;
02786   
02787   // If FromType and ToType are the same type, this is not a
02788   // qualification conversion.
02789   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
02790     return false;
02791 
02792   // (C++ 4.4p4):
02793   //   A conversion can add cv-qualifiers at levels other than the first
02794   //   in multi-level pointers, subject to the following rules: [...]
02795   bool PreviousToQualsIncludeConst = true;
02796   bool UnwrappedAnyPointer = false;
02797   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
02798     // Within each iteration of the loop, we check the qualifiers to
02799     // determine if this still looks like a qualification
02800     // conversion. Then, if all is well, we unwrap one more level of
02801     // pointers or pointers-to-members and do it all again
02802     // until there are no more pointers or pointers-to-members left to
02803     // unwrap.
02804     UnwrappedAnyPointer = true;
02805 
02806     Qualifiers FromQuals = FromType.getQualifiers();
02807     Qualifiers ToQuals = ToType.getQualifiers();
02808     
02809     // Objective-C ARC:
02810     //   Check Objective-C lifetime conversions.
02811     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
02812         UnwrappedAnyPointer) {
02813       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
02814         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
02815           ObjCLifetimeConversion = true;
02816         FromQuals.removeObjCLifetime();
02817         ToQuals.removeObjCLifetime();
02818       } else {
02819         // Qualification conversions cannot cast between different
02820         // Objective-C lifetime qualifiers.
02821         return false;
02822       }
02823     }
02824     
02825     // Allow addition/removal of GC attributes but not changing GC attributes.
02826     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
02827         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
02828       FromQuals.removeObjCGCAttr();
02829       ToQuals.removeObjCGCAttr();
02830     }
02831     
02832     //   -- for every j > 0, if const is in cv 1,j then const is in cv
02833     //      2,j, and similarly for volatile.
02834     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
02835       return false;
02836 
02837     //   -- if the cv 1,j and cv 2,j are different, then const is in
02838     //      every cv for 0 < k < j.
02839     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
02840         && !PreviousToQualsIncludeConst)
02841       return false;
02842 
02843     // Keep track of whether all prior cv-qualifiers in the "to" type
02844     // include const.
02845     PreviousToQualsIncludeConst
02846       = PreviousToQualsIncludeConst && ToQuals.hasConst();
02847   }
02848 
02849   // We are left with FromType and ToType being the pointee types
02850   // after unwrapping the original FromType and ToType the same number
02851   // of types. If we unwrapped any pointers, and if FromType and
02852   // ToType have the same unqualified type (since we checked
02853   // qualifiers above), then this is a qualification conversion.
02854   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
02855 }
02856 
02857 /// \brief - Determine whether this is a conversion from a scalar type to an
02858 /// atomic type.
02859 ///
02860 /// If successful, updates \c SCS's second and third steps in the conversion
02861 /// sequence to finish the conversion.
02862 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
02863                                 bool InOverloadResolution,
02864                                 StandardConversionSequence &SCS,
02865                                 bool CStyle) {
02866   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
02867   if (!ToAtomic)
02868     return false;
02869   
02870   StandardConversionSequence InnerSCS;
02871   if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 
02872                             InOverloadResolution, InnerSCS,
02873                             CStyle, /*AllowObjCWritebackConversion=*/false))
02874     return false;
02875   
02876   SCS.Second = InnerSCS.Second;
02877   SCS.setToType(1, InnerSCS.getToType(1));
02878   SCS.Third = InnerSCS.Third;
02879   SCS.QualificationIncludesObjCLifetime
02880     = InnerSCS.QualificationIncludesObjCLifetime;
02881   SCS.setToType(2, InnerSCS.getToType(2));
02882   return true;
02883 }
02884 
02885 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
02886                                               CXXConstructorDecl *Constructor,
02887                                               QualType Type) {
02888   const FunctionProtoType *CtorType =
02889       Constructor->getType()->getAs<FunctionProtoType>();
02890   if (CtorType->getNumParams() > 0) {
02891     QualType FirstArg = CtorType->getParamType(0);
02892     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
02893       return true;
02894   }
02895   return false;
02896 }
02897 
02898 static OverloadingResult
02899 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
02900                                        CXXRecordDecl *To,
02901                                        UserDefinedConversionSequence &User,
02902                                        OverloadCandidateSet &CandidateSet,
02903                                        bool AllowExplicit) {
02904   DeclContext::lookup_result R = S.LookupConstructors(To);
02905   for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
02906        Con != ConEnd; ++Con) {
02907     NamedDecl *D = *Con;
02908     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
02909 
02910     // Find the constructor (which may be a template).
02911     CXXConstructorDecl *Constructor = nullptr;
02912     FunctionTemplateDecl *ConstructorTmpl
02913       = dyn_cast<FunctionTemplateDecl>(D);
02914     if (ConstructorTmpl)
02915       Constructor
02916         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
02917     else
02918       Constructor = cast<CXXConstructorDecl>(D);
02919 
02920     bool Usable = !Constructor->isInvalidDecl() &&
02921                   S.isInitListConstructor(Constructor) &&
02922                   (AllowExplicit || !Constructor->isExplicit());
02923     if (Usable) {
02924       // If the first argument is (a reference to) the target type,
02925       // suppress conversions.
02926       bool SuppressUserConversions =
02927           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
02928       if (ConstructorTmpl)
02929         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
02930                                        /*ExplicitArgs*/ nullptr,
02931                                        From, CandidateSet,
02932                                        SuppressUserConversions);
02933       else
02934         S.AddOverloadCandidate(Constructor, FoundDecl,
02935                                From, CandidateSet,
02936                                SuppressUserConversions);
02937     }
02938   }
02939 
02940   bool HadMultipleCandidates = (CandidateSet.size() > 1);
02941 
02942   OverloadCandidateSet::iterator Best;
02943   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
02944   case OR_Success: {
02945     // Record the standard conversion we used and the conversion function.
02946     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
02947     QualType ThisType = Constructor->getThisType(S.Context);
02948     // Initializer lists don't have conversions as such.
02949     User.Before.setAsIdentityConversion();
02950     User.HadMultipleCandidates = HadMultipleCandidates;
02951     User.ConversionFunction = Constructor;
02952     User.FoundConversionFunction = Best->FoundDecl;
02953     User.After.setAsIdentityConversion();
02954     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
02955     User.After.setAllToTypes(ToType);
02956     return OR_Success;
02957   }
02958 
02959   case OR_No_Viable_Function:
02960     return OR_No_Viable_Function;
02961   case OR_Deleted:
02962     return OR_Deleted;
02963   case OR_Ambiguous:
02964     return OR_Ambiguous;
02965   }
02966 
02967   llvm_unreachable("Invalid OverloadResult!");
02968 }
02969 
02970 /// Determines whether there is a user-defined conversion sequence
02971 /// (C++ [over.ics.user]) that converts expression From to the type
02972 /// ToType. If such a conversion exists, User will contain the
02973 /// user-defined conversion sequence that performs such a conversion
02974 /// and this routine will return true. Otherwise, this routine returns
02975 /// false and User is unspecified.
02976 ///
02977 /// \param AllowExplicit  true if the conversion should consider C++0x
02978 /// "explicit" conversion functions as well as non-explicit conversion
02979 /// functions (C++0x [class.conv.fct]p2).
02980 ///
02981 /// \param AllowObjCConversionOnExplicit true if the conversion should
02982 /// allow an extra Objective-C pointer conversion on uses of explicit
02983 /// constructors. Requires \c AllowExplicit to also be set.
02984 static OverloadingResult
02985 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
02986                         UserDefinedConversionSequence &User,
02987                         OverloadCandidateSet &CandidateSet,
02988                         bool AllowExplicit,
02989                         bool AllowObjCConversionOnExplicit) {
02990   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
02991 
02992   // Whether we will only visit constructors.
02993   bool ConstructorsOnly = false;
02994 
02995   // If the type we are conversion to is a class type, enumerate its
02996   // constructors.
02997   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
02998     // C++ [over.match.ctor]p1:
02999     //   When objects of class type are direct-initialized (8.5), or
03000     //   copy-initialized from an expression of the same or a
03001     //   derived class type (8.5), overload resolution selects the
03002     //   constructor. [...] For copy-initialization, the candidate
03003     //   functions are all the converting constructors (12.3.1) of
03004     //   that class. The argument list is the expression-list within
03005     //   the parentheses of the initializer.
03006     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
03007         (From->getType()->getAs<RecordType>() &&
03008          S.IsDerivedFrom(From->getType(), ToType)))
03009       ConstructorsOnly = true;
03010 
03011     S.RequireCompleteType(From->getExprLoc(), ToType, 0);
03012     // RequireCompleteType may have returned true due to some invalid decl
03013     // during template instantiation, but ToType may be complete enough now
03014     // to try to recover.
03015     if (ToType->isIncompleteType()) {
03016       // We're not going to find any constructors.
03017     } else if (CXXRecordDecl *ToRecordDecl
03018                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
03019 
03020       Expr **Args = &From;
03021       unsigned NumArgs = 1;
03022       bool ListInitializing = false;
03023       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
03024         // But first, see if there is an init-list-constructor that will work.
03025         OverloadingResult Result = IsInitializerListConstructorConversion(
03026             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
03027         if (Result != OR_No_Viable_Function)
03028           return Result;
03029         // Never mind.
03030         CandidateSet.clear();
03031 
03032         // If we're list-initializing, we pass the individual elements as
03033         // arguments, not the entire list.
03034         Args = InitList->getInits();
03035         NumArgs = InitList->getNumInits();
03036         ListInitializing = true;
03037       }
03038 
03039       DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
03040       for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
03041            Con != ConEnd; ++Con) {
03042         NamedDecl *D = *Con;
03043         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
03044 
03045         // Find the constructor (which may be a template).
03046         CXXConstructorDecl *Constructor = nullptr;
03047         FunctionTemplateDecl *ConstructorTmpl
03048           = dyn_cast<FunctionTemplateDecl>(D);
03049         if (ConstructorTmpl)
03050           Constructor
03051             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
03052         else
03053           Constructor = cast<CXXConstructorDecl>(D);
03054 
03055         bool Usable = !Constructor->isInvalidDecl();
03056         if (ListInitializing)
03057           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
03058         else
03059           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
03060         if (Usable) {
03061           bool SuppressUserConversions = !ConstructorsOnly;
03062           if (SuppressUserConversions && ListInitializing) {
03063             SuppressUserConversions = false;
03064             if (NumArgs == 1) {
03065               // If the first argument is (a reference to) the target type,
03066               // suppress conversions.
03067               SuppressUserConversions = isFirstArgumentCompatibleWithType(
03068                                                 S.Context, Constructor, ToType);
03069             }
03070           }
03071           if (ConstructorTmpl)
03072             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
03073                                            /*ExplicitArgs*/ nullptr,
03074                                            llvm::makeArrayRef(Args, NumArgs),
03075                                            CandidateSet, SuppressUserConversions);
03076           else
03077             // Allow one user-defined conversion when user specifies a
03078             // From->ToType conversion via an static cast (c-style, etc).
03079             S.AddOverloadCandidate(Constructor, FoundDecl,
03080                                    llvm::makeArrayRef(Args, NumArgs),
03081                                    CandidateSet, SuppressUserConversions);
03082         }
03083       }
03084     }
03085   }
03086 
03087   // Enumerate conversion functions, if we're allowed to.
03088   if (ConstructorsOnly || isa<InitListExpr>(From)) {
03089   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
03090     // No conversion functions from incomplete types.
03091   } else if (const RecordType *FromRecordType
03092                                    = From->getType()->getAs<RecordType>()) {
03093     if (CXXRecordDecl *FromRecordDecl
03094          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
03095       // Add all of the conversion functions as candidates.
03096       std::pair<CXXRecordDecl::conversion_iterator,
03097                 CXXRecordDecl::conversion_iterator>
03098         Conversions = FromRecordDecl->getVisibleConversionFunctions();
03099       for (CXXRecordDecl::conversion_iterator
03100              I = Conversions.first, E = Conversions.second; I != E; ++I) {
03101         DeclAccessPair FoundDecl = I.getPair();
03102         NamedDecl *D = FoundDecl.getDecl();
03103         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
03104         if (isa<UsingShadowDecl>(D))
03105           D = cast<UsingShadowDecl>(D)->getTargetDecl();
03106 
03107         CXXConversionDecl *Conv;
03108         FunctionTemplateDecl *ConvTemplate;
03109         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
03110           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
03111         else
03112           Conv = cast<CXXConversionDecl>(D);
03113 
03114         if (AllowExplicit || !Conv->isExplicit()) {
03115           if (ConvTemplate)
03116             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
03117                                              ActingContext, From, ToType,
03118                                              CandidateSet,
03119                                              AllowObjCConversionOnExplicit);
03120           else
03121             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
03122                                      From, ToType, CandidateSet,
03123                                      AllowObjCConversionOnExplicit);
03124         }
03125       }
03126     }
03127   }
03128 
03129   bool HadMultipleCandidates = (CandidateSet.size() > 1);
03130 
03131   OverloadCandidateSet::iterator Best;
03132   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
03133   case OR_Success:
03134     // Record the standard conversion we used and the conversion function.
03135     if (CXXConstructorDecl *Constructor
03136           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
03137       // C++ [over.ics.user]p1:
03138       //   If the user-defined conversion is specified by a
03139       //   constructor (12.3.1), the initial standard conversion
03140       //   sequence converts the source type to the type required by
03141       //   the argument of the constructor.
03142       //
03143       QualType ThisType = Constructor->getThisType(S.Context);
03144       if (isa<InitListExpr>(From)) {
03145         // Initializer lists don't have conversions as such.
03146         User.Before.setAsIdentityConversion();
03147       } else {
03148         if (Best->Conversions[0].isEllipsis())
03149           User.EllipsisConversion = true;
03150         else {
03151           User.Before = Best->Conversions[0].Standard;
03152           User.EllipsisConversion = false;
03153         }
03154       }
03155       User.HadMultipleCandidates = HadMultipleCandidates;
03156       User.ConversionFunction = Constructor;
03157       User.FoundConversionFunction = Best->FoundDecl;
03158       User.After.setAsIdentityConversion();
03159       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
03160       User.After.setAllToTypes(ToType);
03161       return OR_Success;
03162     }
03163     if (CXXConversionDecl *Conversion
03164                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
03165       // C++ [over.ics.user]p1:
03166       //
03167       //   [...] If the user-defined conversion is specified by a
03168       //   conversion function (12.3.2), the initial standard
03169       //   conversion sequence converts the source type to the
03170       //   implicit object parameter of the conversion function.
03171       User.Before = Best->Conversions[0].Standard;
03172       User.HadMultipleCandidates = HadMultipleCandidates;
03173       User.ConversionFunction = Conversion;
03174       User.FoundConversionFunction = Best->FoundDecl;
03175       User.EllipsisConversion = false;
03176 
03177       // C++ [over.ics.user]p2:
03178       //   The second standard conversion sequence converts the
03179       //   result of the user-defined conversion to the target type
03180       //   for the sequence. Since an implicit conversion sequence
03181       //   is an initialization, the special rules for
03182       //   initialization by user-defined conversion apply when
03183       //   selecting the best user-defined conversion for a
03184       //   user-defined conversion sequence (see 13.3.3 and
03185       //   13.3.3.1).
03186       User.After = Best->FinalConversion;
03187       return OR_Success;
03188     }
03189     llvm_unreachable("Not a constructor or conversion function?");
03190 
03191   case OR_No_Viable_Function:
03192     return OR_No_Viable_Function;
03193   case OR_Deleted:
03194     // No conversion here! We're done.
03195     return OR_Deleted;
03196 
03197   case OR_Ambiguous:
03198     return OR_Ambiguous;
03199   }
03200 
03201   llvm_unreachable("Invalid OverloadResult!");
03202 }
03203 
03204 bool
03205 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
03206   ImplicitConversionSequence ICS;
03207   OverloadCandidateSet CandidateSet(From->getExprLoc(),
03208                                     OverloadCandidateSet::CSK_Normal);
03209   OverloadingResult OvResult =
03210     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
03211                             CandidateSet, false, false);
03212   if (OvResult == OR_Ambiguous)
03213     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
03214         << From->getType() << ToType << From->getSourceRange();
03215   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
03216     if (!RequireCompleteType(From->getLocStart(), ToType,
03217                              diag::err_typecheck_nonviable_condition_incomplete,
03218                              From->getType(), From->getSourceRange()))
03219       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
03220           << From->getType() << From->getSourceRange() << ToType;
03221   } else
03222     return false;
03223   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
03224   return true;
03225 }
03226 
03227 /// \brief Compare the user-defined conversion functions or constructors
03228 /// of two user-defined conversion sequences to determine whether any ordering
03229 /// is possible.
03230 static ImplicitConversionSequence::CompareKind
03231 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
03232                            FunctionDecl *Function2) {
03233   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
03234     return ImplicitConversionSequence::Indistinguishable;
03235 
03236   // Objective-C++:
03237   //   If both conversion functions are implicitly-declared conversions from
03238   //   a lambda closure type to a function pointer and a block pointer,
03239   //   respectively, always prefer the conversion to a function pointer,
03240   //   because the function pointer is more lightweight and is more likely
03241   //   to keep code working.
03242   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
03243   if (!Conv1)
03244     return ImplicitConversionSequence::Indistinguishable;
03245 
03246   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
03247   if (!Conv2)
03248     return ImplicitConversionSequence::Indistinguishable;
03249 
03250   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
03251     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
03252     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
03253     if (Block1 != Block2)
03254       return Block1 ? ImplicitConversionSequence::Worse
03255                     : ImplicitConversionSequence::Better;
03256   }
03257 
03258   return ImplicitConversionSequence::Indistinguishable;
03259 }
03260 
03261 static bool hasDeprecatedStringLiteralToCharPtrConversion(
03262     const ImplicitConversionSequence &ICS) {
03263   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
03264          (ICS.isUserDefined() &&
03265           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
03266 }
03267 
03268 /// CompareImplicitConversionSequences - Compare two implicit
03269 /// conversion sequences to determine whether one is better than the
03270 /// other or if they are indistinguishable (C++ 13.3.3.2).
03271 static ImplicitConversionSequence::CompareKind
03272 CompareImplicitConversionSequences(Sema &S,
03273                                    const ImplicitConversionSequence& ICS1,
03274                                    const ImplicitConversionSequence& ICS2)
03275 {
03276   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
03277   // conversion sequences (as defined in 13.3.3.1)
03278   //   -- a standard conversion sequence (13.3.3.1.1) is a better
03279   //      conversion sequence than a user-defined conversion sequence or
03280   //      an ellipsis conversion sequence, and
03281   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
03282   //      conversion sequence than an ellipsis conversion sequence
03283   //      (13.3.3.1.3).
03284   //
03285   // C++0x [over.best.ics]p10:
03286   //   For the purpose of ranking implicit conversion sequences as
03287   //   described in 13.3.3.2, the ambiguous conversion sequence is
03288   //   treated as a user-defined sequence that is indistinguishable
03289   //   from any other user-defined conversion sequence.
03290 
03291   // String literal to 'char *' conversion has been deprecated in C++03. It has
03292   // been removed from C++11. We still accept this conversion, if it happens at
03293   // the best viable function. Otherwise, this conversion is considered worse
03294   // than ellipsis conversion. Consider this as an extension; this is not in the
03295   // standard. For example:
03296   //
03297   // int &f(...);    // #1
03298   // void f(char*);  // #2
03299   // void g() { int &r = f("foo"); }
03300   //
03301   // In C++03, we pick #2 as the best viable function.
03302   // In C++11, we pick #1 as the best viable function, because ellipsis
03303   // conversion is better than string-literal to char* conversion (since there
03304   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
03305   // convert arguments, #2 would be the best viable function in C++11.
03306   // If the best viable function has this conversion, a warning will be issued
03307   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
03308 
03309   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
03310       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
03311       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
03312     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
03313                ? ImplicitConversionSequence::Worse
03314                : ImplicitConversionSequence::Better;
03315 
03316   if (ICS1.getKindRank() < ICS2.getKindRank())
03317     return ImplicitConversionSequence::Better;
03318   if (ICS2.getKindRank() < ICS1.getKindRank())
03319     return ImplicitConversionSequence::Worse;
03320 
03321   // The following checks require both conversion sequences to be of
03322   // the same kind.
03323   if (ICS1.getKind() != ICS2.getKind())
03324     return ImplicitConversionSequence::Indistinguishable;
03325 
03326   ImplicitConversionSequence::CompareKind Result =
03327       ImplicitConversionSequence::Indistinguishable;
03328 
03329   // Two implicit conversion sequences of the same form are
03330   // indistinguishable conversion sequences unless one of the
03331   // following rules apply: (C++ 13.3.3.2p3):
03332   if (ICS1.isStandard())
03333     Result = CompareStandardConversionSequences(S,
03334                                                 ICS1.Standard, ICS2.Standard);
03335   else if (ICS1.isUserDefined()) {
03336     // User-defined conversion sequence U1 is a better conversion
03337     // sequence than another user-defined conversion sequence U2 if
03338     // they contain the same user-defined conversion function or
03339     // constructor and if the second standard conversion sequence of
03340     // U1 is better than the second standard conversion sequence of
03341     // U2 (C++ 13.3.3.2p3).
03342     if (ICS1.UserDefined.ConversionFunction ==
03343           ICS2.UserDefined.ConversionFunction)
03344       Result = CompareStandardConversionSequences(S,
03345                                                   ICS1.UserDefined.After,
03346                                                   ICS2.UserDefined.After);
03347     else
03348       Result = compareConversionFunctions(S, 
03349                                           ICS1.UserDefined.ConversionFunction,
03350                                           ICS2.UserDefined.ConversionFunction);
03351   }
03352 
03353   // List-initialization sequence L1 is a better conversion sequence than
03354   // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
03355   // for some X and L2 does not.
03356   if (Result == ImplicitConversionSequence::Indistinguishable &&
03357       !ICS1.isBad()) {
03358     if (ICS1.isStdInitializerListElement() &&
03359         !ICS2.isStdInitializerListElement())
03360       return ImplicitConversionSequence::Better;
03361     if (!ICS1.isStdInitializerListElement() &&
03362         ICS2.isStdInitializerListElement())
03363       return ImplicitConversionSequence::Worse;
03364   }
03365 
03366   return Result;
03367 }
03368 
03369 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
03370   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
03371     Qualifiers Quals;
03372     T1 = Context.getUnqualifiedArrayType(T1, Quals);
03373     T2 = Context.getUnqualifiedArrayType(T2, Quals);
03374   }
03375 
03376   return Context.hasSameUnqualifiedType(T1, T2);
03377 }
03378 
03379 // Per 13.3.3.2p3, compare the given standard conversion sequences to
03380 // determine if one is a proper subset of the other.
03381 static ImplicitConversionSequence::CompareKind
03382 compareStandardConversionSubsets(ASTContext &Context,
03383                                  const StandardConversionSequence& SCS1,
03384                                  const StandardConversionSequence& SCS2) {
03385   ImplicitConversionSequence::CompareKind Result
03386     = ImplicitConversionSequence::Indistinguishable;
03387 
03388   // the identity conversion sequence is considered to be a subsequence of
03389   // any non-identity conversion sequence
03390   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
03391     return ImplicitConversionSequence::Better;
03392   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
03393     return ImplicitConversionSequence::Worse;
03394 
03395   if (SCS1.Second != SCS2.Second) {
03396     if (SCS1.Second == ICK_Identity)
03397       Result = ImplicitConversionSequence::Better;
03398     else if (SCS2.Second == ICK_Identity)
03399       Result = ImplicitConversionSequence::Worse;
03400     else
03401       return ImplicitConversionSequence::Indistinguishable;
03402   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
03403     return ImplicitConversionSequence::Indistinguishable;
03404 
03405   if (SCS1.Third == SCS2.Third) {
03406     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
03407                              : ImplicitConversionSequence::Indistinguishable;
03408   }
03409 
03410   if (SCS1.Third == ICK_Identity)
03411     return Result == ImplicitConversionSequence::Worse
03412              ? ImplicitConversionSequence::Indistinguishable
03413              : ImplicitConversionSequence::Better;
03414 
03415   if (SCS2.Third == ICK_Identity)
03416     return Result == ImplicitConversionSequence::Better
03417              ? ImplicitConversionSequence::Indistinguishable
03418              : ImplicitConversionSequence::Worse;
03419 
03420   return ImplicitConversionSequence::Indistinguishable;
03421 }
03422 
03423 /// \brief Determine whether one of the given reference bindings is better
03424 /// than the other based on what kind of bindings they are.
03425 static bool
03426 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
03427                              const StandardConversionSequence &SCS2) {
03428   // C++0x [over.ics.rank]p3b4:
03429   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
03430   //      implicit object parameter of a non-static member function declared
03431   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
03432   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
03433   //      lvalue reference to a function lvalue and S2 binds an rvalue
03434   //      reference*.
03435   //
03436   // FIXME: Rvalue references. We're going rogue with the above edits,
03437   // because the semantics in the current C++0x working paper (N3225 at the
03438   // time of this writing) break the standard definition of std::forward
03439   // and std::reference_wrapper when dealing with references to functions.
03440   // Proposed wording changes submitted to CWG for consideration.
03441   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
03442       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
03443     return false;
03444 
03445   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
03446           SCS2.IsLvalueReference) ||
03447          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
03448           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
03449 }
03450 
03451 /// CompareStandardConversionSequences - Compare two standard
03452 /// conversion sequences to determine whether one is better than the
03453 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
03454 static ImplicitConversionSequence::CompareKind
03455 CompareStandardConversionSequences(Sema &S,
03456                                    const StandardConversionSequence& SCS1,
03457                                    const StandardConversionSequence& SCS2)
03458 {
03459   // Standard conversion sequence S1 is a better conversion sequence
03460   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
03461 
03462   //  -- S1 is a proper subsequence of S2 (comparing the conversion
03463   //     sequences in the canonical form defined by 13.3.3.1.1,
03464   //     excluding any Lvalue Transformation; the identity conversion
03465   //     sequence is considered to be a subsequence of any
03466   //     non-identity conversion sequence) or, if not that,
03467   if (ImplicitConversionSequence::CompareKind CK
03468         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
03469     return CK;
03470 
03471   //  -- the rank of S1 is better than the rank of S2 (by the rules
03472   //     defined below), or, if not that,
03473   ImplicitConversionRank Rank1 = SCS1.getRank();
03474   ImplicitConversionRank Rank2 = SCS2.getRank();
03475   if (Rank1 < Rank2)
03476     return ImplicitConversionSequence::Better;
03477   else if (Rank2 < Rank1)
03478     return ImplicitConversionSequence::Worse;
03479 
03480   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
03481   // are indistinguishable unless one of the following rules
03482   // applies:
03483 
03484   //   A conversion that is not a conversion of a pointer, or
03485   //   pointer to member, to bool is better than another conversion
03486   //   that is such a conversion.
03487   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
03488     return SCS2.isPointerConversionToBool()
03489              ? ImplicitConversionSequence::Better
03490              : ImplicitConversionSequence::Worse;
03491 
03492   // C++ [over.ics.rank]p4b2:
03493   //
03494   //   If class B is derived directly or indirectly from class A,
03495   //   conversion of B* to A* is better than conversion of B* to
03496   //   void*, and conversion of A* to void* is better than conversion
03497   //   of B* to void*.
03498   bool SCS1ConvertsToVoid
03499     = SCS1.isPointerConversionToVoidPointer(S.Context);
03500   bool SCS2ConvertsToVoid
03501     = SCS2.isPointerConversionToVoidPointer(S.Context);
03502   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
03503     // Exactly one of the conversion sequences is a conversion to
03504     // a void pointer; it's the worse conversion.
03505     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
03506                               : ImplicitConversionSequence::Worse;
03507   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
03508     // Neither conversion sequence converts to a void pointer; compare
03509     // their derived-to-base conversions.
03510     if (ImplicitConversionSequence::CompareKind DerivedCK
03511           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
03512       return DerivedCK;
03513   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
03514              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
03515     // Both conversion sequences are conversions to void
03516     // pointers. Compare the source types to determine if there's an
03517     // inheritance relationship in their sources.
03518     QualType FromType1 = SCS1.getFromType();
03519     QualType FromType2 = SCS2.getFromType();
03520 
03521     // Adjust the types we're converting from via the array-to-pointer
03522     // conversion, if we need to.
03523     if (SCS1.First == ICK_Array_To_Pointer)
03524       FromType1 = S.Context.getArrayDecayedType(FromType1);
03525     if (SCS2.First == ICK_Array_To_Pointer)
03526       FromType2 = S.Context.getArrayDecayedType(FromType2);
03527 
03528     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
03529     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
03530 
03531     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
03532       return ImplicitConversionSequence::Better;
03533     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
03534       return ImplicitConversionSequence::Worse;
03535 
03536     // Objective-C++: If one interface is more specific than the
03537     // other, it is the better one.
03538     const ObjCObjectPointerType* FromObjCPtr1
03539       = FromType1->getAs<ObjCObjectPointerType>();
03540     const ObjCObjectPointerType* FromObjCPtr2
03541       = FromType2->getAs<ObjCObjectPointerType>();
03542     if (FromObjCPtr1 && FromObjCPtr2) {
03543       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 
03544                                                           FromObjCPtr2);
03545       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 
03546                                                            FromObjCPtr1);
03547       if (AssignLeft != AssignRight) {
03548         return AssignLeft? ImplicitConversionSequence::Better
03549                          : ImplicitConversionSequence::Worse;
03550       }
03551     }
03552   }
03553 
03554   // Compare based on qualification conversions (C++ 13.3.3.2p3,
03555   // bullet 3).
03556   if (ImplicitConversionSequence::CompareKind QualCK
03557         = CompareQualificationConversions(S, SCS1, SCS2))
03558     return QualCK;
03559 
03560   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
03561     // Check for a better reference binding based on the kind of bindings.
03562     if (isBetterReferenceBindingKind(SCS1, SCS2))
03563       return ImplicitConversionSequence::Better;
03564     else if (isBetterReferenceBindingKind(SCS2, SCS1))
03565       return ImplicitConversionSequence::Worse;
03566 
03567     // C++ [over.ics.rank]p3b4:
03568     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
03569     //      which the references refer are the same type except for
03570     //      top-level cv-qualifiers, and the type to which the reference
03571     //      initialized by S2 refers is more cv-qualified than the type
03572     //      to which the reference initialized by S1 refers.
03573     QualType T1 = SCS1.getToType(2);
03574     QualType T2 = SCS2.getToType(2);
03575     T1 = S.Context.getCanonicalType(T1);
03576     T2 = S.Context.getCanonicalType(T2);
03577     Qualifiers T1Quals, T2Quals;
03578     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
03579     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
03580     if (UnqualT1 == UnqualT2) {
03581       // Objective-C++ ARC: If the references refer to objects with different
03582       // lifetimes, prefer bindings that don't change lifetime.
03583       if (SCS1.ObjCLifetimeConversionBinding != 
03584                                           SCS2.ObjCLifetimeConversionBinding) {
03585         return SCS1.ObjCLifetimeConversionBinding
03586                                            ? ImplicitConversionSequence::Worse
03587                                            : ImplicitConversionSequence::Better;
03588       }
03589       
03590       // If the type is an array type, promote the element qualifiers to the
03591       // type for comparison.
03592       if (isa<ArrayType>(T1) && T1Quals)
03593         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
03594       if (isa<ArrayType>(T2) && T2Quals)
03595         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
03596       if (T2.isMoreQualifiedThan(T1))
03597         return ImplicitConversionSequence::Better;
03598       else if (T1.isMoreQualifiedThan(T2))
03599         return ImplicitConversionSequence::Worse;      
03600     }
03601   }
03602 
03603   // In Microsoft mode, prefer an integral conversion to a
03604   // floating-to-integral conversion if the integral conversion
03605   // is between types of the same size.
03606   // For example:
03607   // void f(float);
03608   // void f(int);
03609   // int main {
03610   //    long a;
03611   //    f(a);
03612   // }
03613   // Here, MSVC will call f(int) instead of generating a compile error
03614   // as clang will do in standard mode.
03615   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
03616       SCS2.Second == ICK_Floating_Integral &&
03617       S.Context.getTypeSize(SCS1.getFromType()) ==
03618           S.Context.getTypeSize(SCS1.getToType(2)))
03619     return ImplicitConversionSequence::Better;
03620 
03621   return ImplicitConversionSequence::Indistinguishable;
03622 }
03623 
03624 /// CompareQualificationConversions - Compares two standard conversion
03625 /// sequences to determine whether they can be ranked based on their
03626 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
03627 static ImplicitConversionSequence::CompareKind
03628 CompareQualificationConversions(Sema &S,
03629                                 const StandardConversionSequence& SCS1,
03630                                 const StandardConversionSequence& SCS2) {
03631   // C++ 13.3.3.2p3:
03632   //  -- S1 and S2 differ only in their qualification conversion and
03633   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
03634   //     cv-qualification signature of type T1 is a proper subset of
03635   //     the cv-qualification signature of type T2, and S1 is not the
03636   //     deprecated string literal array-to-pointer conversion (4.2).
03637   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
03638       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
03639     return ImplicitConversionSequence::Indistinguishable;
03640 
03641   // FIXME: the example in the standard doesn't use a qualification
03642   // conversion (!)
03643   QualType T1 = SCS1.getToType(2);
03644   QualType T2 = SCS2.getToType(2);
03645   T1 = S.Context.getCanonicalType(T1);
03646   T2 = S.Context.getCanonicalType(T2);
03647   Qualifiers T1Quals, T2Quals;
03648   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
03649   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
03650 
03651   // If the types are the same, we won't learn anything by unwrapped
03652   // them.
03653   if (UnqualT1 == UnqualT2)
03654     return ImplicitConversionSequence::Indistinguishable;
03655 
03656   // If the type is an array type, promote the element qualifiers to the type
03657   // for comparison.
03658   if (isa<ArrayType>(T1) && T1Quals)
03659     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
03660   if (isa<ArrayType>(T2) && T2Quals)
03661     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
03662 
03663   ImplicitConversionSequence::CompareKind Result
03664     = ImplicitConversionSequence::Indistinguishable;
03665   
03666   // Objective-C++ ARC:
03667   //   Prefer qualification conversions not involving a change in lifetime
03668   //   to qualification conversions that do not change lifetime.
03669   if (SCS1.QualificationIncludesObjCLifetime != 
03670                                       SCS2.QualificationIncludesObjCLifetime) {
03671     Result = SCS1.QualificationIncludesObjCLifetime
03672                ? ImplicitConversionSequence::Worse
03673                : ImplicitConversionSequence::Better;
03674   }
03675   
03676   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
03677     // Within each iteration of the loop, we check the qualifiers to
03678     // determine if this still looks like a qualification
03679     // conversion. Then, if all is well, we unwrap one more level of
03680     // pointers or pointers-to-members and do it all again
03681     // until there are no more pointers or pointers-to-members left
03682     // to unwrap. This essentially mimics what
03683     // IsQualificationConversion does, but here we're checking for a
03684     // strict subset of qualifiers.
03685     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
03686       // The qualifiers are the same, so this doesn't tell us anything
03687       // about how the sequences rank.
03688       ;
03689     else if (T2.isMoreQualifiedThan(T1)) {
03690       // T1 has fewer qualifiers, so it could be the better sequence.
03691       if (Result == ImplicitConversionSequence::Worse)
03692         // Neither has qualifiers that are a subset of the other's
03693         // qualifiers.
03694         return ImplicitConversionSequence::Indistinguishable;
03695 
03696       Result = ImplicitConversionSequence::Better;
03697     } else if (T1.isMoreQualifiedThan(T2)) {
03698       // T2 has fewer qualifiers, so it could be the better sequence.
03699       if (Result == ImplicitConversionSequence::Better)
03700         // Neither has qualifiers that are a subset of the other's
03701         // qualifiers.
03702         return ImplicitConversionSequence::Indistinguishable;
03703 
03704       Result = ImplicitConversionSequence::Worse;
03705     } else {
03706       // Qualifiers are disjoint.
03707       return ImplicitConversionSequence::Indistinguishable;
03708     }
03709 
03710     // If the types after this point are equivalent, we're done.
03711     if (S.Context.hasSameUnqualifiedType(T1, T2))
03712       break;
03713   }
03714 
03715   // Check that the winning standard conversion sequence isn't using
03716   // the deprecated string literal array to pointer conversion.
03717   switch (Result) {
03718   case ImplicitConversionSequence::Better:
03719     if (SCS1.DeprecatedStringLiteralToCharPtr)
03720       Result = ImplicitConversionSequence::Indistinguishable;
03721     break;
03722 
03723   case ImplicitConversionSequence::Indistinguishable:
03724     break;
03725 
03726   case ImplicitConversionSequence::Worse:
03727     if (SCS2.DeprecatedStringLiteralToCharPtr)
03728       Result = ImplicitConversionSequence::Indistinguishable;
03729     break;
03730   }
03731 
03732   return Result;
03733 }
03734 
03735 /// CompareDerivedToBaseConversions - Compares two standard conversion
03736 /// sequences to determine whether they can be ranked based on their
03737 /// various kinds of derived-to-base conversions (C++
03738 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
03739 /// conversions between Objective-C interface types.
03740 static ImplicitConversionSequence::CompareKind
03741 CompareDerivedToBaseConversions(Sema &S,
03742                                 const StandardConversionSequence& SCS1,
03743                                 const StandardConversionSequence& SCS2) {
03744   QualType FromType1 = SCS1.getFromType();
03745   QualType ToType1 = SCS1.getToType(1);
03746   QualType FromType2 = SCS2.getFromType();
03747   QualType ToType2 = SCS2.getToType(1);
03748 
03749   // Adjust the types we're converting from via the array-to-pointer
03750   // conversion, if we need to.
03751   if (SCS1.First == ICK_Array_To_Pointer)
03752     FromType1 = S.Context.getArrayDecayedType(FromType1);
03753   if (SCS2.First == ICK_Array_To_Pointer)
03754     FromType2 = S.Context.getArrayDecayedType(FromType2);
03755 
03756   // Canonicalize all of the types.
03757   FromType1 = S.Context.getCanonicalType(FromType1);
03758   ToType1 = S.Context.getCanonicalType(ToType1);
03759   FromType2 = S.Context.getCanonicalType(FromType2);
03760   ToType2 = S.Context.getCanonicalType(ToType2);
03761 
03762   // C++ [over.ics.rank]p4b3:
03763   //
03764   //   If class B is derived directly or indirectly from class A and
03765   //   class C is derived directly or indirectly from B,
03766   //
03767   // Compare based on pointer conversions.
03768   if (SCS1.Second == ICK_Pointer_Conversion &&
03769       SCS2.Second == ICK_Pointer_Conversion &&
03770       /*FIXME: Remove if Objective-C id conversions get their own rank*/
03771       FromType1->isPointerType() && FromType2->isPointerType() &&
03772       ToType1->isPointerType() && ToType2->isPointerType()) {
03773     QualType FromPointee1
03774       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
03775     QualType ToPointee1
03776       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
03777     QualType FromPointee2
03778       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
03779     QualType ToPointee2
03780       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
03781 
03782     //   -- conversion of C* to B* is better than conversion of C* to A*,
03783     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
03784       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
03785         return ImplicitConversionSequence::Better;
03786       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
03787         return ImplicitConversionSequence::Worse;
03788     }
03789 
03790     //   -- conversion of B* to A* is better than conversion of C* to A*,
03791     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
03792       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
03793         return ImplicitConversionSequence::Better;
03794       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
03795         return ImplicitConversionSequence::Worse;
03796     }
03797   } else if (SCS1.Second == ICK_Pointer_Conversion &&
03798              SCS2.Second == ICK_Pointer_Conversion) {
03799     const ObjCObjectPointerType *FromPtr1
03800       = FromType1->getAs<ObjCObjectPointerType>();
03801     const ObjCObjectPointerType *FromPtr2
03802       = FromType2->getAs<ObjCObjectPointerType>();
03803     const ObjCObjectPointerType *ToPtr1
03804       = ToType1->getAs<ObjCObjectPointerType>();
03805     const ObjCObjectPointerType *ToPtr2
03806       = ToType2->getAs<ObjCObjectPointerType>();
03807     
03808     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
03809       // Apply the same conversion ranking rules for Objective-C pointer types
03810       // that we do for C++ pointers to class types. However, we employ the
03811       // Objective-C pseudo-subtyping relationship used for assignment of
03812       // Objective-C pointer types.
03813       bool FromAssignLeft
03814         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
03815       bool FromAssignRight
03816         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
03817       bool ToAssignLeft
03818         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
03819       bool ToAssignRight
03820         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
03821       
03822       // A conversion to an a non-id object pointer type or qualified 'id' 
03823       // type is better than a conversion to 'id'.
03824       if (ToPtr1->isObjCIdType() &&
03825           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
03826         return ImplicitConversionSequence::Worse;
03827       if (ToPtr2->isObjCIdType() &&
03828           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
03829         return ImplicitConversionSequence::Better;
03830       
03831       // A conversion to a non-id object pointer type is better than a 
03832       // conversion to a qualified 'id' type 
03833       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
03834         return ImplicitConversionSequence::Worse;
03835       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
03836         return ImplicitConversionSequence::Better;
03837   
03838       // A conversion to an a non-Class object pointer type or qualified 'Class' 
03839       // type is better than a conversion to 'Class'.
03840       if (ToPtr1->isObjCClassType() &&
03841           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
03842         return ImplicitConversionSequence::Worse;
03843       if (ToPtr2->isObjCClassType() &&
03844           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
03845         return ImplicitConversionSequence::Better;
03846       
03847       // A conversion to a non-Class object pointer type is better than a 
03848       // conversion to a qualified 'Class' type.
03849       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
03850         return ImplicitConversionSequence::Worse;
03851       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
03852         return ImplicitConversionSequence::Better;
03853 
03854       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
03855       if (S.Context.hasSameType(FromType1, FromType2) && 
03856           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
03857           (ToAssignLeft != ToAssignRight))
03858         return ToAssignLeft? ImplicitConversionSequence::Worse
03859                            : ImplicitConversionSequence::Better;
03860 
03861       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
03862       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
03863           (FromAssignLeft != FromAssignRight))
03864         return FromAssignLeft? ImplicitConversionSequence::Better
03865         : ImplicitConversionSequence::Worse;
03866     }
03867   }
03868   
03869   // Ranking of member-pointer types.
03870   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
03871       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
03872       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
03873     const MemberPointerType * FromMemPointer1 =
03874                                         FromType1->getAs<MemberPointerType>();
03875     const MemberPointerType * ToMemPointer1 =
03876                                           ToType1->getAs<MemberPointerType>();
03877     const MemberPointerType * FromMemPointer2 =
03878                                           FromType2->getAs<MemberPointerType>();
03879     const MemberPointerType * ToMemPointer2 =
03880                                           ToType2->getAs<MemberPointerType>();
03881     const Type *FromPointeeType1 = FromMemPointer1->getClass();
03882     const Type *ToPointeeType1 = ToMemPointer1->getClass();
03883     const Type *FromPointeeType2 = FromMemPointer2->getClass();
03884     const Type *ToPointeeType2 = ToMemPointer2->getClass();
03885     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
03886     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
03887     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
03888     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
03889     // conversion of A::* to B::* is better than conversion of A::* to C::*,
03890     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
03891       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
03892         return ImplicitConversionSequence::Worse;
03893       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
03894         return ImplicitConversionSequence::Better;
03895     }
03896     // conversion of B::* to C::* is better than conversion of A::* to C::*
03897     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
03898       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
03899         return ImplicitConversionSequence::Better;
03900       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
03901         return ImplicitConversionSequence::Worse;
03902     }
03903   }
03904 
03905   if (SCS1.Second == ICK_Derived_To_Base) {
03906     //   -- conversion of C to B is better than conversion of C to A,
03907     //   -- binding of an expression of type C to a reference of type
03908     //      B& is better than binding an expression of type C to a
03909     //      reference of type A&,
03910     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
03911         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
03912       if (S.IsDerivedFrom(ToType1, ToType2))
03913         return ImplicitConversionSequence::Better;
03914       else if (S.IsDerivedFrom(ToType2, ToType1))
03915         return ImplicitConversionSequence::Worse;
03916     }
03917 
03918     //   -- conversion of B to A is better than conversion of C to A.
03919     //   -- binding of an expression of type B to a reference of type
03920     //      A& is better than binding an expression of type C to a
03921     //      reference of type A&,
03922     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
03923         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
03924       if (S.IsDerivedFrom(FromType2, FromType1))
03925         return ImplicitConversionSequence::Better;
03926       else if (S.IsDerivedFrom(FromType1, FromType2))
03927         return ImplicitConversionSequence::Worse;
03928     }
03929   }
03930 
03931   return ImplicitConversionSequence::Indistinguishable;
03932 }
03933 
03934 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
03935 /// C++ class.
03936 static bool isTypeValid(QualType T) {
03937   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
03938     return !Record->isInvalidDecl();
03939 
03940   return true;
03941 }
03942 
03943 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
03944 /// determine whether they are reference-related,
03945 /// reference-compatible, reference-compatible with added
03946 /// qualification, or incompatible, for use in C++ initialization by
03947 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
03948 /// type, and the first type (T1) is the pointee type of the reference
03949 /// type being initialized.
03950 Sema::ReferenceCompareResult
03951 Sema::CompareReferenceRelationship(SourceLocation Loc,
03952                                    QualType OrigT1, QualType OrigT2,
03953                                    bool &DerivedToBase,
03954                                    bool &ObjCConversion,
03955                                    bool &ObjCLifetimeConversion) {
03956   assert(!OrigT1->isReferenceType() &&
03957     "T1 must be the pointee type of the reference type");
03958   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
03959 
03960   QualType T1 = Context.getCanonicalType(OrigT1);
03961   QualType T2 = Context.getCanonicalType(OrigT2);
03962   Qualifiers T1Quals, T2Quals;
03963   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
03964   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
03965 
03966   // C++ [dcl.init.ref]p4:
03967   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
03968   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
03969   //   T1 is a base class of T2.
03970   DerivedToBase = false;
03971   ObjCConversion = false;
03972   ObjCLifetimeConversion = false;
03973   if (UnqualT1 == UnqualT2) {
03974     // Nothing to do.
03975   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
03976              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
03977              IsDerivedFrom(UnqualT2, UnqualT1))
03978     DerivedToBase = true;
03979   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
03980            UnqualT2->isObjCObjectOrInterfaceType() &&
03981            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
03982     ObjCConversion = true;
03983   else
03984     return Ref_Incompatible;
03985 
03986   // At this point, we know that T1 and T2 are reference-related (at
03987   // least).
03988 
03989   // If the type is an array type, promote the element qualifiers to the type
03990   // for comparison.
03991   if (isa<ArrayType>(T1) && T1Quals)
03992     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
03993   if (isa<ArrayType>(T2) && T2Quals)
03994     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
03995 
03996   // C++ [dcl.init.ref]p4:
03997   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
03998   //   reference-related to T2 and cv1 is the same cv-qualification
03999   //   as, or greater cv-qualification than, cv2. For purposes of
04000   //   overload resolution, cases for which cv1 is greater
04001   //   cv-qualification than cv2 are identified as
04002   //   reference-compatible with added qualification (see 13.3.3.2).
04003   //
04004   // Note that we also require equivalence of Objective-C GC and address-space
04005   // qualifiers when performing these computations, so that e.g., an int in
04006   // address space 1 is not reference-compatible with an int in address
04007   // space 2.
04008   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
04009       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
04010     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
04011       ObjCLifetimeConversion = true;
04012 
04013     T1Quals.removeObjCLifetime();
04014     T2Quals.removeObjCLifetime();    
04015   }
04016     
04017   if (T1Quals == T2Quals)
04018     return Ref_Compatible;
04019   else if (T1Quals.compatiblyIncludes(T2Quals))
04020     return Ref_Compatible_With_Added_Qualification;
04021   else
04022     return Ref_Related;
04023 }
04024 
04025 /// \brief Look for a user-defined conversion to an value reference-compatible
04026 ///        with DeclType. Return true if something definite is found.
04027 static bool
04028 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
04029                          QualType DeclType, SourceLocation DeclLoc,
04030                          Expr *Init, QualType T2, bool AllowRvalues,
04031                          bool AllowExplicit) {
04032   assert(T2->isRecordType() && "Can only find conversions of record types.");
04033   CXXRecordDecl *T2RecordDecl
04034     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
04035 
04036   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
04037   std::pair<CXXRecordDecl::conversion_iterator,
04038             CXXRecordDecl::conversion_iterator>
04039     Conversions = T2RecordDecl->getVisibleConversionFunctions();
04040   for (CXXRecordDecl::conversion_iterator
04041          I = Conversions.first, E = Conversions.second; I != E; ++I) {
04042     NamedDecl *D = *I;
04043     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
04044     if (isa<UsingShadowDecl>(D))
04045       D = cast<UsingShadowDecl>(D)->getTargetDecl();
04046 
04047     FunctionTemplateDecl *ConvTemplate
04048       = dyn_cast<FunctionTemplateDecl>(D);
04049     CXXConversionDecl *Conv;
04050     if (ConvTemplate)
04051       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
04052     else
04053       Conv = cast<CXXConversionDecl>(D);
04054 
04055     // If this is an explicit conversion, and we're not allowed to consider
04056     // explicit conversions, skip it.
04057     if (!AllowExplicit && Conv->isExplicit())
04058       continue;
04059 
04060     if (AllowRvalues) {
04061       bool DerivedToBase = false;
04062       bool ObjCConversion = false;
04063       bool ObjCLifetimeConversion = false;
04064       
04065       // If we are initializing an rvalue reference, don't permit conversion
04066       // functions that return lvalues.
04067       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
04068         const ReferenceType *RefType
04069           = Conv->getConversionType()->getAs<LValueReferenceType>();
04070         if (RefType && !RefType->getPointeeType()->isFunctionType())
04071           continue;
04072       }
04073       
04074       if (!ConvTemplate &&
04075           S.CompareReferenceRelationship(
04076             DeclLoc,
04077             Conv->getConversionType().getNonReferenceType()
04078               .getUnqualifiedType(),
04079             DeclType.getNonReferenceType().getUnqualifiedType(),
04080             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
04081           Sema::Ref_Incompatible)
04082         continue;
04083     } else {
04084       // If the conversion function doesn't return a reference type,
04085       // it can't be considered for this conversion. An rvalue reference
04086       // is only acceptable if its referencee is a function type.
04087 
04088       const ReferenceType *RefType =
04089         Conv->getConversionType()->getAs<ReferenceType>();
04090       if (!RefType ||
04091           (!RefType->isLValueReferenceType() &&
04092            !RefType->getPointeeType()->isFunctionType()))
04093         continue;
04094     }
04095 
04096     if (ConvTemplate)
04097       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
04098                                        Init, DeclType, CandidateSet,
04099                                        /*AllowObjCConversionOnExplicit=*/false);
04100     else
04101       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
04102                                DeclType, CandidateSet,
04103                                /*AllowObjCConversionOnExplicit=*/false);
04104   }
04105 
04106   bool HadMultipleCandidates = (CandidateSet.size() > 1);
04107 
04108   OverloadCandidateSet::iterator Best;
04109   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
04110   case OR_Success:
04111     // C++ [over.ics.ref]p1:
04112     //
04113     //   [...] If the parameter binds directly to the result of
04114     //   applying a conversion function to the argument
04115     //   expression, the implicit conversion sequence is a
04116     //   user-defined conversion sequence (13.3.3.1.2), with the
04117     //   second standard conversion sequence either an identity
04118     //   conversion or, if the conversion function returns an
04119     //   entity of a type that is a derived class of the parameter
04120     //   type, a derived-to-base Conversion.
04121     if (!Best->FinalConversion.DirectBinding)
04122       return false;
04123 
04124     ICS.setUserDefined();
04125     ICS.UserDefined.Before = Best->Conversions[0].Standard;
04126     ICS.UserDefined.After = Best->FinalConversion;
04127     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
04128     ICS.UserDefined.ConversionFunction = Best->Function;
04129     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
04130     ICS.UserDefined.EllipsisConversion = false;
04131     assert(ICS.UserDefined.After.ReferenceBinding &&
04132            ICS.UserDefined.After.DirectBinding &&
04133            "Expected a direct reference binding!");
04134     return true;
04135 
04136   case OR_Ambiguous:
04137     ICS.setAmbiguous();
04138     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
04139          Cand != CandidateSet.end(); ++Cand)
04140       if (Cand->Viable)
04141         ICS.Ambiguous.addConversion(Cand->Function);
04142     return true;
04143 
04144   case OR_No_Viable_Function:
04145   case OR_Deleted:
04146     // There was no suitable conversion, or we found a deleted
04147     // conversion; continue with other checks.
04148     return false;
04149   }
04150 
04151   llvm_unreachable("Invalid OverloadResult!");
04152 }
04153 
04154 /// \brief Compute an implicit conversion sequence for reference
04155 /// initialization.
04156 static ImplicitConversionSequence
04157 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
04158                  SourceLocation DeclLoc,
04159                  bool SuppressUserConversions,
04160                  bool AllowExplicit) {
04161   assert(DeclType->isReferenceType() && "Reference init needs a reference");
04162 
04163   // Most paths end in a failed conversion.
04164   ImplicitConversionSequence ICS;
04165   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
04166 
04167   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
04168   QualType T2 = Init->getType();
04169 
04170   // If the initializer is the address of an overloaded function, try
04171   // to resolve the overloaded function. If all goes well, T2 is the
04172   // type of the resulting function.
04173   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
04174     DeclAccessPair Found;
04175     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
04176                                                                 false, Found))
04177       T2 = Fn->getType();
04178   }
04179 
04180   // Compute some basic properties of the types and the initializer.
04181   bool isRValRef = DeclType->isRValueReferenceType();
04182   bool DerivedToBase = false;
04183   bool ObjCConversion = false;
04184   bool ObjCLifetimeConversion = false;
04185   Expr::Classification InitCategory = Init->Classify(S.Context);
04186   Sema::ReferenceCompareResult RefRelationship
04187     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
04188                                      ObjCConversion, ObjCLifetimeConversion);
04189 
04190 
04191   // C++0x [dcl.init.ref]p5:
04192   //   A reference to type "cv1 T1" is initialized by an expression
04193   //   of type "cv2 T2" as follows:
04194 
04195   //     -- If reference is an lvalue reference and the initializer expression
04196   if (!isRValRef) {
04197     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
04198     //        reference-compatible with "cv2 T2," or
04199     //
04200     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
04201     if (InitCategory.isLValue() &&
04202         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
04203       // C++ [over.ics.ref]p1:
04204       //   When a parameter of reference type binds directly (8.5.3)
04205       //   to an argument expression, the implicit conversion sequence
04206       //   is the identity conversion, unless the argument expression
04207       //   has a type that is a derived class of the parameter type,
04208       //   in which case the implicit conversion sequence is a
04209       //   derived-to-base Conversion (13.3.3.1).
04210       ICS.setStandard();
04211       ICS.Standard.First = ICK_Identity;
04212       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
04213                          : ObjCConversion? ICK_Compatible_Conversion
04214                          : ICK_Identity;
04215       ICS.Standard.Third = ICK_Identity;
04216       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
04217       ICS.Standard.setToType(0, T2);
04218       ICS.Standard.setToType(1, T1);
04219       ICS.Standard.setToType(2, T1);
04220       ICS.Standard.ReferenceBinding = true;
04221       ICS.Standard.DirectBinding = true;
04222       ICS.Standard.IsLvalueReference = !isRValRef;
04223       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
04224       ICS.Standard.BindsToRvalue = false;
04225       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
04226       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
04227       ICS.Standard.CopyConstructor = nullptr;
04228       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
04229 
04230       // Nothing more to do: the inaccessibility/ambiguity check for
04231       // derived-to-base conversions is suppressed when we're
04232       // computing the implicit conversion sequence (C++
04233       // [over.best.ics]p2).
04234       return ICS;
04235     }
04236 
04237     //       -- has a class type (i.e., T2 is a class type), where T1 is
04238     //          not reference-related to T2, and can be implicitly
04239     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
04240     //          is reference-compatible with "cv3 T3" 92) (this
04241     //          conversion is selected by enumerating the applicable
04242     //          conversion functions (13.3.1.6) and choosing the best
04243     //          one through overload resolution (13.3)),
04244     if (!SuppressUserConversions && T2->isRecordType() &&
04245         !S.RequireCompleteType(DeclLoc, T2, 0) &&
04246         RefRelationship == Sema::Ref_Incompatible) {
04247       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
04248                                    Init, T2, /*AllowRvalues=*/false,
04249                                    AllowExplicit))
04250         return ICS;
04251     }
04252   }
04253 
04254   //     -- Otherwise, the reference shall be an lvalue reference to a
04255   //        non-volatile const type (i.e., cv1 shall be const), or the reference
04256   //        shall be an rvalue reference.
04257   //
04258   // We actually handle one oddity of C++ [over.ics.ref] at this
04259   // point, which is that, due to p2 (which short-circuits reference
04260   // binding by only attempting a simple conversion for non-direct
04261   // bindings) and p3's strange wording, we allow a const volatile
04262   // reference to bind to an rvalue. Hence the check for the presence
04263   // of "const" rather than checking for "const" being the only
04264   // qualifier.
04265   // This is also the point where rvalue references and lvalue inits no longer
04266   // go together.
04267   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
04268     return ICS;
04269 
04270   //       -- If the initializer expression
04271   //
04272   //            -- is an xvalue, class prvalue, array prvalue or function
04273   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
04274   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
04275       (InitCategory.isXValue() ||
04276       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
04277       (InitCategory.isLValue() && T2->isFunctionType()))) {
04278     ICS.setStandard();
04279     ICS.Standard.First = ICK_Identity;
04280     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
04281                       : ObjCConversion? ICK_Compatible_Conversion
04282                       : ICK_Identity;
04283     ICS.Standard.Third = ICK_Identity;
04284     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
04285     ICS.Standard.setToType(0, T2);
04286     ICS.Standard.setToType(1, T1);
04287     ICS.Standard.setToType(2, T1);
04288     ICS.Standard.ReferenceBinding = true;
04289     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
04290     // binding unless we're binding to a class prvalue.
04291     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
04292     // allow the use of rvalue references in C++98/03 for the benefit of
04293     // standard library implementors; therefore, we need the xvalue check here.
04294     ICS.Standard.DirectBinding =
04295       S.getLangOpts().CPlusPlus11 ||
04296       !(InitCategory.isPRValue() || T2->isRecordType());
04297     ICS.Standard.IsLvalueReference = !isRValRef;
04298     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
04299     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
04300     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
04301     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
04302     ICS.Standard.CopyConstructor = nullptr;
04303     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
04304     return ICS;
04305   }
04306 
04307   //            -- has a class type (i.e., T2 is a class type), where T1 is not
04308   //               reference-related to T2, and can be implicitly converted to
04309   //               an xvalue, class prvalue, or function lvalue of type
04310   //               "cv3 T3", where "cv1 T1" is reference-compatible with
04311   //               "cv3 T3",
04312   //
04313   //          then the reference is bound to the value of the initializer
04314   //          expression in the first case and to the result of the conversion
04315   //          in the second case (or, in either case, to an appropriate base
04316   //          class subobject).
04317   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
04318       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
04319       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
04320                                Init, T2, /*AllowRvalues=*/true,
04321                                AllowExplicit)) {
04322     // In the second case, if the reference is an rvalue reference
04323     // and the second standard conversion sequence of the
04324     // user-defined conversion sequence includes an lvalue-to-rvalue
04325     // conversion, the program is ill-formed.
04326     if (ICS.isUserDefined() && isRValRef &&
04327         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
04328       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
04329 
04330     return ICS;
04331   }
04332 
04333   // A temporary of function type cannot be created; don't even try.
04334   if (T1->isFunctionType())
04335     return ICS;
04336 
04337   //       -- Otherwise, a temporary of type "cv1 T1" is created and
04338   //          initialized from the initializer expression using the
04339   //          rules for a non-reference copy initialization (8.5). The
04340   //          reference is then bound to the temporary. If T1 is
04341   //          reference-related to T2, cv1 must be the same
04342   //          cv-qualification as, or greater cv-qualification than,
04343   //          cv2; otherwise, the program is ill-formed.
04344   if (RefRelationship == Sema::Ref_Related) {
04345     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
04346     // we would be reference-compatible or reference-compatible with
04347     // added qualification. But that wasn't the case, so the reference
04348     // initialization fails.
04349     //
04350     // Note that we only want to check address spaces and cvr-qualifiers here.
04351     // ObjC GC and lifetime qualifiers aren't important.
04352     Qualifiers T1Quals = T1.getQualifiers();
04353     Qualifiers T2Quals = T2.getQualifiers();
04354     T1Quals.removeObjCGCAttr();
04355     T1Quals.removeObjCLifetime();
04356     T2Quals.removeObjCGCAttr();
04357     T2Quals.removeObjCLifetime();
04358     if (!T1Quals.compatiblyIncludes(T2Quals))
04359       return ICS;
04360   }
04361 
04362   // If at least one of the types is a class type, the types are not
04363   // related, and we aren't allowed any user conversions, the
04364   // reference binding fails. This case is important for breaking
04365   // recursion, since TryImplicitConversion below will attempt to
04366   // create a temporary through the use of a copy constructor.
04367   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
04368       (T1->isRecordType() || T2->isRecordType()))
04369     return ICS;
04370 
04371   // If T1 is reference-related to T2 and the reference is an rvalue
04372   // reference, the initializer expression shall not be an lvalue.
04373   if (RefRelationship >= Sema::Ref_Related &&
04374       isRValRef && Init->Classify(S.Context).isLValue())
04375     return ICS;
04376 
04377   // C++ [over.ics.ref]p2:
04378   //   When a parameter of reference type is not bound directly to
04379   //   an argument expression, the conversion sequence is the one
04380   //   required to convert the argument expression to the
04381   //   underlying type of the reference according to
04382   //   13.3.3.1. Conceptually, this conversion sequence corresponds
04383   //   to copy-initializing a temporary of the underlying type with
04384   //   the argument expression. Any difference in top-level
04385   //   cv-qualification is subsumed by the initialization itself
04386   //   and does not constitute a conversion.
04387   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
04388                               /*AllowExplicit=*/false,
04389                               /*InOverloadResolution=*/false,
04390                               /*CStyle=*/false,
04391                               /*AllowObjCWritebackConversion=*/false,
04392                               /*AllowObjCConversionOnExplicit=*/false);
04393 
04394   // Of course, that's still a reference binding.
04395   if (ICS.isStandard()) {
04396     ICS.Standard.ReferenceBinding = true;
04397     ICS.Standard.IsLvalueReference = !isRValRef;
04398     ICS.Standard.BindsToFunctionLvalue = false;
04399     ICS.Standard.BindsToRvalue = true;
04400     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
04401     ICS.Standard.ObjCLifetimeConversionBinding = false;
04402   } else if (ICS.isUserDefined()) {
04403     const ReferenceType *LValRefType =
04404         ICS.UserDefined.ConversionFunction->getReturnType()
04405             ->getAs<LValueReferenceType>();
04406 
04407     // C++ [over.ics.ref]p3:
04408     //   Except for an implicit object parameter, for which see 13.3.1, a
04409     //   standard conversion sequence cannot be formed if it requires [...]
04410     //   binding an rvalue reference to an lvalue other than a function
04411     //   lvalue.
04412     // Note that the function case is not possible here.
04413     if (DeclType->isRValueReferenceType() && LValRefType) {
04414       // FIXME: This is the wrong BadConversionSequence. The problem is binding
04415       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
04416       // reference to an rvalue!
04417       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
04418       return ICS;
04419     }
04420 
04421     ICS.UserDefined.Before.setAsIdentityConversion();
04422     ICS.UserDefined.After.ReferenceBinding = true;
04423     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
04424     ICS.UserDefined.After.BindsToFunctionLvalue = false;
04425     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
04426     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
04427     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
04428   }
04429 
04430   return ICS;
04431 }
04432 
04433 static ImplicitConversionSequence
04434 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
04435                       bool SuppressUserConversions,
04436                       bool InOverloadResolution,
04437                       bool AllowObjCWritebackConversion,
04438                       bool AllowExplicit = false);
04439 
04440 /// TryListConversion - Try to copy-initialize a value of type ToType from the
04441 /// initializer list From.
04442 static ImplicitConversionSequence
04443 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
04444                   bool SuppressUserConversions,
04445                   bool InOverloadResolution,
04446                   bool AllowObjCWritebackConversion) {
04447   // C++11 [over.ics.list]p1:
04448   //   When an argument is an initializer list, it is not an expression and
04449   //   special rules apply for converting it to a parameter type.
04450 
04451   ImplicitConversionSequence Result;
04452   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
04453 
04454   // We need a complete type for what follows. Incomplete types can never be
04455   // initialized from init lists.
04456   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
04457     return Result;
04458 
04459   // C++11 [over.ics.list]p2:
04460   //   If the parameter type is std::initializer_list<X> or "array of X" and
04461   //   all the elements can be implicitly converted to X, the implicit
04462   //   conversion sequence is the worst conversion necessary to convert an
04463   //   element of the list to X.
04464   bool toStdInitializerList = false;
04465   QualType X;
04466   if (ToType->isArrayType())
04467     X = S.Context.getAsArrayType(ToType)->getElementType();
04468   else
04469     toStdInitializerList = S.isStdInitializerList(ToType, &X);
04470   if (!X.isNull()) {
04471     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
04472       Expr *Init = From->getInit(i);
04473       ImplicitConversionSequence ICS =
04474           TryCopyInitialization(S, Init, X, SuppressUserConversions,
04475                                 InOverloadResolution,
04476                                 AllowObjCWritebackConversion);
04477       // If a single element isn't convertible, fail.
04478       if (ICS.isBad()) {
04479         Result = ICS;
04480         break;
04481       }
04482       // Otherwise, look for the worst conversion.
04483       if (Result.isBad() ||
04484           CompareImplicitConversionSequences(S, ICS, Result) ==
04485               ImplicitConversionSequence::Worse)
04486         Result = ICS;
04487     }
04488 
04489     // For an empty list, we won't have computed any conversion sequence.
04490     // Introduce the identity conversion sequence.
04491     if (From->getNumInits() == 0) {
04492       Result.setStandard();
04493       Result.Standard.setAsIdentityConversion();
04494       Result.Standard.setFromType(ToType);
04495       Result.Standard.setAllToTypes(ToType);
04496     }
04497 
04498     Result.setStdInitializerListElement(toStdInitializerList);
04499     return Result;
04500   }
04501 
04502   // C++11 [over.ics.list]p3:
04503   //   Otherwise, if the parameter is a non-aggregate class X and overload
04504   //   resolution chooses a single best constructor [...] the implicit
04505   //   conversion sequence is a user-defined conversion sequence. If multiple
04506   //   constructors are viable but none is better than the others, the
04507   //   implicit conversion sequence is a user-defined conversion sequence.
04508   if (ToType->isRecordType() && !ToType->isAggregateType()) {
04509     // This function can deal with initializer lists.
04510     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
04511                                     /*AllowExplicit=*/false,
04512                                     InOverloadResolution, /*CStyle=*/false,
04513                                     AllowObjCWritebackConversion,
04514                                     /*AllowObjCConversionOnExplicit=*/false);
04515   }
04516 
04517   // C++11 [over.ics.list]p4:
04518   //   Otherwise, if the parameter has an aggregate type which can be
04519   //   initialized from the initializer list [...] the implicit conversion
04520   //   sequence is a user-defined conversion sequence.
04521   if (ToType->isAggregateType()) {
04522     // Type is an aggregate, argument is an init list. At this point it comes
04523     // down to checking whether the initialization works.
04524     // FIXME: Find out whether this parameter is consumed or not.
04525     InitializedEntity Entity =
04526         InitializedEntity::InitializeParameter(S.Context, ToType,
04527                                                /*Consumed=*/false);
04528     if (S.CanPerformCopyInitialization(Entity, From)) {
04529       Result.setUserDefined();
04530       Result.UserDefined.Before.setAsIdentityConversion();
04531       // Initializer lists don't have a type.
04532       Result.UserDefined.Before.setFromType(QualType());
04533       Result.UserDefined.Before.setAllToTypes(QualType());
04534 
04535       Result.UserDefined.After.setAsIdentityConversion();
04536       Result.UserDefined.After.setFromType(ToType);
04537       Result.UserDefined.After.setAllToTypes(ToType);
04538       Result.UserDefined.ConversionFunction = nullptr;
04539     }
04540     return Result;
04541   }
04542 
04543   // C++11 [over.ics.list]p5:
04544   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
04545   if (ToType->isReferenceType()) {
04546     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
04547     // mention initializer lists in any way. So we go by what list-
04548     // initialization would do and try to extrapolate from that.
04549 
04550     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
04551 
04552     // If the initializer list has a single element that is reference-related
04553     // to the parameter type, we initialize the reference from that.
04554     if (From->getNumInits() == 1) {
04555       Expr *Init = From->getInit(0);
04556 
04557       QualType T2 = Init->getType();
04558 
04559       // If the initializer is the address of an overloaded function, try
04560       // to resolve the overloaded function. If all goes well, T2 is the
04561       // type of the resulting function.
04562       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
04563         DeclAccessPair Found;
04564         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
04565                                    Init, ToType, false, Found))
04566           T2 = Fn->getType();
04567       }
04568 
04569       // Compute some basic properties of the types and the initializer.
04570       bool dummy1 = false;
04571       bool dummy2 = false;
04572       bool dummy3 = false;
04573       Sema::ReferenceCompareResult RefRelationship
04574         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
04575                                          dummy2, dummy3);
04576 
04577       if (RefRelationship >= Sema::Ref_Related) {
04578         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
04579                                 SuppressUserConversions,
04580                                 /*AllowExplicit=*/false);
04581       }
04582     }
04583 
04584     // Otherwise, we bind the reference to a temporary created from the
04585     // initializer list.
04586     Result = TryListConversion(S, From, T1, SuppressUserConversions,
04587                                InOverloadResolution,
04588                                AllowObjCWritebackConversion);
04589     if (Result.isFailure())
04590       return Result;
04591     assert(!Result.isEllipsis() &&
04592            "Sub-initialization cannot result in ellipsis conversion.");
04593 
04594     // Can we even bind to a temporary?
04595     if (ToType->isRValueReferenceType() ||
04596         (T1.isConstQualified() && !T1.isVolatileQualified())) {
04597       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
04598                                             Result.UserDefined.After;
04599       SCS.ReferenceBinding = true;
04600       SCS.IsLvalueReference = ToType->isLValueReferenceType();
04601       SCS.BindsToRvalue = true;
04602       SCS.BindsToFunctionLvalue = false;
04603       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
04604       SCS.ObjCLifetimeConversionBinding = false;
04605     } else
04606       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
04607                     From, ToType);
04608     return Result;
04609   }
04610 
04611   // C++11 [over.ics.list]p6:
04612   //   Otherwise, if the parameter type is not a class:
04613   if (!ToType->isRecordType()) {
04614     //    - if the initializer list has one element, the implicit conversion
04615     //      sequence is the one required to convert the element to the
04616     //      parameter type.
04617     unsigned NumInits = From->getNumInits();
04618     if (NumInits == 1)
04619       Result = TryCopyInitialization(S, From->getInit(0), ToType,
04620                                      SuppressUserConversions,
04621                                      InOverloadResolution,
04622                                      AllowObjCWritebackConversion);
04623     //    - if the initializer list has no elements, the implicit conversion
04624     //      sequence is the identity conversion.
04625     else if (NumInits == 0) {
04626       Result.setStandard();
04627       Result.Standard.setAsIdentityConversion();
04628       Result.Standard.setFromType(ToType);
04629       Result.Standard.setAllToTypes(ToType);
04630     }
04631     return Result;
04632   }
04633 
04634   // C++11 [over.ics.list]p7:
04635   //   In all cases other than those enumerated above, no conversion is possible
04636   return Result;
04637 }
04638 
04639 /// TryCopyInitialization - Try to copy-initialize a value of type
04640 /// ToType from the expression From. Return the implicit conversion
04641 /// sequence required to pass this argument, which may be a bad
04642 /// conversion sequence (meaning that the argument cannot be passed to
04643 /// a parameter of this type). If @p SuppressUserConversions, then we
04644 /// do not permit any user-defined conversion sequences.
04645 static ImplicitConversionSequence
04646 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
04647                       bool SuppressUserConversions,
04648                       bool InOverloadResolution,
04649                       bool AllowObjCWritebackConversion,
04650                       bool AllowExplicit) {
04651   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
04652     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
04653                              InOverloadResolution,AllowObjCWritebackConversion);
04654 
04655   if (ToType->isReferenceType())
04656     return TryReferenceInit(S, From, ToType,
04657                             /*FIXME:*/From->getLocStart(),
04658                             SuppressUserConversions,
04659                             AllowExplicit);
04660 
04661   return TryImplicitConversion(S, From, ToType,
04662                                SuppressUserConversions,
04663                                /*AllowExplicit=*/false,
04664                                InOverloadResolution,
04665                                /*CStyle=*/false,
04666                                AllowObjCWritebackConversion,
04667                                /*AllowObjCConversionOnExplicit=*/false);
04668 }
04669 
04670 static bool TryCopyInitialization(const CanQualType FromQTy,
04671                                   const CanQualType ToQTy,
04672                                   Sema &S,
04673                                   SourceLocation Loc,
04674                                   ExprValueKind FromVK) {
04675   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
04676   ImplicitConversionSequence ICS =
04677     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
04678 
04679   return !ICS.isBad();
04680 }
04681 
04682 /// TryObjectArgumentInitialization - Try to initialize the object
04683 /// parameter of the given member function (@c Method) from the
04684 /// expression @p From.
04685 static ImplicitConversionSequence
04686 TryObjectArgumentInitialization(Sema &S, QualType FromType,
04687                                 Expr::Classification FromClassification,
04688                                 CXXMethodDecl *Method,
04689                                 CXXRecordDecl *ActingContext) {
04690   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
04691   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
04692   //                 const volatile object.
04693   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
04694     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
04695   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
04696 
04697   // Set up the conversion sequence as a "bad" conversion, to allow us
04698   // to exit early.
04699   ImplicitConversionSequence ICS;
04700 
04701   // We need to have an object of class type.
04702   if (const PointerType *PT = FromType->getAs<PointerType>()) {
04703     FromType = PT->getPointeeType();
04704 
04705     // When we had a pointer, it's implicitly dereferenced, so we
04706     // better have an lvalue.
04707     assert(FromClassification.isLValue());
04708   }
04709 
04710   assert(FromType->isRecordType());
04711 
04712   // C++0x [over.match.funcs]p4:
04713   //   For non-static member functions, the type of the implicit object
04714   //   parameter is
04715   //
04716   //     - "lvalue reference to cv X" for functions declared without a
04717   //        ref-qualifier or with the & ref-qualifier
04718   //     - "rvalue reference to cv X" for functions declared with the &&
04719   //        ref-qualifier
04720   //
04721   // where X is the class of which the function is a member and cv is the
04722   // cv-qualification on the member function declaration.
04723   //
04724   // However, when finding an implicit conversion sequence for the argument, we
04725   // are not allowed to create temporaries or perform user-defined conversions
04726   // (C++ [over.match.funcs]p5). We perform a simplified version of
04727   // reference binding here, that allows class rvalues to bind to
04728   // non-constant references.
04729 
04730   // First check the qualifiers.
04731   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
04732   if (ImplicitParamType.getCVRQualifiers()
04733                                     != FromTypeCanon.getLocalCVRQualifiers() &&
04734       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
04735     ICS.setBad(BadConversionSequence::bad_qualifiers,
04736                FromType, ImplicitParamType);
04737     return ICS;
04738   }
04739 
04740   // Check that we have either the same type or a derived type. It
04741   // affects the conversion rank.
04742   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
04743   ImplicitConversionKind SecondKind;
04744   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
04745     SecondKind = ICK_Identity;
04746   } else if (S.IsDerivedFrom(FromType, ClassType))
04747     SecondKind = ICK_Derived_To_Base;
04748   else {
04749     ICS.setBad(BadConversionSequence::unrelated_class,
04750                FromType, ImplicitParamType);
04751     return ICS;
04752   }
04753 
04754   // Check the ref-qualifier.
04755   switch (Method->getRefQualifier()) {
04756   case RQ_None:
04757     // Do nothing; we don't care about lvalueness or rvalueness.
04758     break;
04759 
04760   case RQ_LValue:
04761     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
04762       // non-const lvalue reference cannot bind to an rvalue
04763       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
04764                  ImplicitParamType);
04765       return ICS;
04766     }
04767     break;
04768 
04769   case RQ_RValue:
04770     if (!FromClassification.isRValue()) {
04771       // rvalue reference cannot bind to an lvalue
04772       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
04773                  ImplicitParamType);
04774       return ICS;
04775     }
04776     break;
04777   }
04778 
04779   // Success. Mark this as a reference binding.
04780   ICS.setStandard();
04781   ICS.Standard.setAsIdentityConversion();
04782   ICS.Standard.Second = SecondKind;
04783   ICS.Standard.setFromType(FromType);
04784   ICS.Standard.setAllToTypes(ImplicitParamType);
04785   ICS.Standard.ReferenceBinding = true;
04786   ICS.Standard.DirectBinding = true;
04787   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
04788   ICS.Standard.BindsToFunctionLvalue = false;
04789   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
04790   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
04791     = (Method->getRefQualifier() == RQ_None);
04792   return ICS;
04793 }
04794 
04795 /// PerformObjectArgumentInitialization - Perform initialization of
04796 /// the implicit object parameter for the given Method with the given
04797 /// expression.
04798 ExprResult
04799 Sema::PerformObjectArgumentInitialization(Expr *From,
04800                                           NestedNameSpecifier *Qualifier,
04801                                           NamedDecl *FoundDecl,
04802                                           CXXMethodDecl *Method) {
04803   QualType FromRecordType, DestType;
04804   QualType ImplicitParamRecordType  =
04805     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
04806 
04807   Expr::Classification FromClassification;
04808   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
04809     FromRecordType = PT->getPointeeType();
04810     DestType = Method->getThisType(Context);
04811     FromClassification = Expr::Classification::makeSimpleLValue();
04812   } else {
04813     FromRecordType = From->getType();
04814     DestType = ImplicitParamRecordType;
04815     FromClassification = From->Classify(Context);
04816   }
04817 
04818   // Note that we always use the true parent context when performing
04819   // the actual argument initialization.
04820   ImplicitConversionSequence ICS
04821     = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
04822                                       Method, Method->getParent());
04823   if (ICS.isBad()) {
04824     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
04825       Qualifiers FromQs = FromRecordType.getQualifiers();
04826       Qualifiers ToQs = DestType.getQualifiers();
04827       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
04828       if (CVR) {
04829         Diag(From->getLocStart(),
04830              diag::err_member_function_call_bad_cvr)
04831           << Method->getDeclName() << FromRecordType << (CVR - 1)
04832           << From->getSourceRange();
04833         Diag(Method->getLocation(), diag::note_previous_decl)
04834           << Method->getDeclName();
04835         return ExprError();
04836       }
04837     }
04838 
04839     return Diag(From->getLocStart(),
04840                 diag::err_implicit_object_parameter_init)
04841        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
04842   }
04843 
04844   if (ICS.Standard.Second == ICK_Derived_To_Base) {
04845     ExprResult FromRes =
04846       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
04847     if (FromRes.isInvalid())
04848       return ExprError();
04849     From = FromRes.get();
04850   }
04851 
04852   if (!Context.hasSameType(From->getType(), DestType))
04853     From = ImpCastExprToType(From, DestType, CK_NoOp,
04854                              From->getValueKind()).get();
04855   return From;
04856 }
04857 
04858 /// TryContextuallyConvertToBool - Attempt to contextually convert the
04859 /// expression From to bool (C++0x [conv]p3).
04860 static ImplicitConversionSequence
04861 TryContextuallyConvertToBool(Sema &S, Expr *From) {
04862   return TryImplicitConversion(S, From, S.Context.BoolTy,
04863                                /*SuppressUserConversions=*/false,
04864                                /*AllowExplicit=*/true,
04865                                /*InOverloadResolution=*/false,
04866                                /*CStyle=*/false,
04867                                /*AllowObjCWritebackConversion=*/false,
04868                                /*AllowObjCConversionOnExplicit=*/false);
04869 }
04870 
04871 /// PerformContextuallyConvertToBool - Perform a contextual conversion
04872 /// of the expression From to bool (C++0x [conv]p3).
04873 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
04874   if (checkPlaceholderForOverload(*this, From))
04875     return ExprError();
04876 
04877   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
04878   if (!ICS.isBad())
04879     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
04880 
04881   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
04882     return Diag(From->getLocStart(),
04883                 diag::err_typecheck_bool_condition)
04884                   << From->getType() << From->getSourceRange();
04885   return ExprError();
04886 }
04887 
04888 /// Check that the specified conversion is permitted in a converted constant
04889 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
04890 /// is acceptable.
04891 static bool CheckConvertedConstantConversions(Sema &S,
04892                                               StandardConversionSequence &SCS) {
04893   // Since we know that the target type is an integral or unscoped enumeration
04894   // type, most conversion kinds are impossible. All possible First and Third
04895   // conversions are fine.
04896   switch (SCS.Second) {
04897   case ICK_Identity:
04898   case ICK_Integral_Promotion:
04899   case ICK_Integral_Conversion:
04900   case ICK_Zero_Event_Conversion:
04901     return true;
04902 
04903   case ICK_Boolean_Conversion:
04904     // Conversion from an integral or unscoped enumeration type to bool is
04905     // classified as ICK_Boolean_Conversion, but it's also an integral
04906     // conversion, so it's permitted in a converted constant expression.
04907     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
04908            SCS.getToType(2)->isBooleanType();
04909 
04910   case ICK_Floating_Integral:
04911   case ICK_Complex_Real:
04912     return false;
04913 
04914   case ICK_Lvalue_To_Rvalue:
04915   case ICK_Array_To_Pointer:
04916   case ICK_Function_To_Pointer:
04917   case ICK_NoReturn_Adjustment:
04918   case ICK_Qualification:
04919   case ICK_Compatible_Conversion:
04920   case ICK_Vector_Conversion:
04921   case ICK_Vector_Splat:
04922   case ICK_Derived_To_Base:
04923   case ICK_Pointer_Conversion:
04924   case ICK_Pointer_Member:
04925   case ICK_Block_Pointer_Conversion:
04926   case ICK_Writeback_Conversion:
04927   case ICK_Floating_Promotion:
04928   case ICK_Complex_Promotion:
04929   case ICK_Complex_Conversion:
04930   case ICK_Floating_Conversion:
04931   case ICK_TransparentUnionConversion:
04932     llvm_unreachable("unexpected second conversion kind");
04933 
04934   case ICK_Num_Conversion_Kinds:
04935     break;
04936   }
04937 
04938   llvm_unreachable("unknown conversion kind");
04939 }
04940 
04941 /// CheckConvertedConstantExpression - Check that the expression From is a
04942 /// converted constant expression of type T, perform the conversion and produce
04943 /// the converted expression, per C++11 [expr.const]p3.
04944 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
04945                                                   llvm::APSInt &Value,
04946                                                   CCEKind CCE) {
04947   assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
04948   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
04949 
04950   if (checkPlaceholderForOverload(*this, From))
04951     return ExprError();
04952 
04953   // C++11 [expr.const]p3 with proposed wording fixes:
04954   //  A converted constant expression of type T is a core constant expression,
04955   //  implicitly converted to a prvalue of type T, where the converted
04956   //  expression is a literal constant expression and the implicit conversion
04957   //  sequence contains only user-defined conversions, lvalue-to-rvalue
04958   //  conversions, integral promotions, and integral conversions other than
04959   //  narrowing conversions.
04960   ImplicitConversionSequence ICS =
04961     TryImplicitConversion(From, T,
04962                           /*SuppressUserConversions=*/false,
04963                           /*AllowExplicit=*/false,
04964                           /*InOverloadResolution=*/false,
04965                           /*CStyle=*/false,
04966                           /*AllowObjcWritebackConversion=*/false);
04967   StandardConversionSequence *SCS = nullptr;
04968   switch (ICS.getKind()) {
04969   case ImplicitConversionSequence::StandardConversion:
04970     if (!CheckConvertedConstantConversions(*this, ICS.Standard))
04971       return Diag(From->getLocStart(),
04972                   diag::err_typecheck_converted_constant_expression_disallowed)
04973                << From->getType() << From->getSourceRange() << T;
04974     SCS = &ICS.Standard;
04975     break;
04976   case ImplicitConversionSequence::UserDefinedConversion:
04977     // We are converting from class type to an integral or enumeration type, so
04978     // the Before sequence must be trivial.
04979     if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
04980       return Diag(From->getLocStart(),
04981                   diag::err_typecheck_converted_constant_expression_disallowed)
04982                << From->getType() << From->getSourceRange() << T;
04983     SCS = &ICS.UserDefined.After;
04984     break;
04985   case ImplicitConversionSequence::AmbiguousConversion:
04986   case ImplicitConversionSequence::BadConversion:
04987     if (!DiagnoseMultipleUserDefinedConversion(From, T))
04988       return Diag(From->getLocStart(),
04989                   diag::err_typecheck_converted_constant_expression)
04990                     << From->getType() << From->getSourceRange() << T;
04991     return ExprError();
04992 
04993   case ImplicitConversionSequence::EllipsisConversion:
04994     llvm_unreachable("ellipsis conversion in converted constant expression");
04995   }
04996 
04997   ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
04998   if (Result.isInvalid())
04999     return Result;
05000 
05001   // Check for a narrowing implicit conversion.
05002   APValue PreNarrowingValue;
05003   QualType PreNarrowingType;
05004   switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
05005                                 PreNarrowingType)) {
05006   case NK_Variable_Narrowing:
05007     // Implicit conversion to a narrower type, and the value is not a constant
05008     // expression. We'll diagnose this in a moment.
05009   case NK_Not_Narrowing:
05010     break;
05011 
05012   case NK_Constant_Narrowing:
05013     Diag(From->getLocStart(), diag::ext_cce_narrowing)
05014       << CCE << /*Constant*/1
05015       << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
05016     break;
05017 
05018   case NK_Type_Narrowing:
05019     Diag(From->getLocStart(), diag::ext_cce_narrowing)
05020       << CCE << /*Constant*/0 << From->getType() << T;
05021     break;
05022   }
05023 
05024   // Check the expression is a constant expression.
05025   SmallVector<PartialDiagnosticAt, 8> Notes;
05026   Expr::EvalResult Eval;
05027   Eval.Diag = &Notes;
05028 
05029   if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
05030     // The expression can't be folded, so we can't keep it at this position in
05031     // the AST.
05032     Result = ExprError();
05033   } else {
05034     Value = Eval.Val.getInt();
05035 
05036     if (Notes.empty()) {
05037       // It's a constant expression.
05038       return Result;
05039     }
05040   }
05041 
05042   // It's not a constant expression. Produce an appropriate diagnostic.
05043   if (Notes.size() == 1 &&
05044       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
05045     Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
05046   else {
05047     Diag(From->getLocStart(), diag::err_expr_not_cce)
05048       << CCE << From->getSourceRange();
05049     for (unsigned I = 0; I < Notes.size(); ++I)
05050       Diag(Notes[I].first, Notes[I].second);
05051   }
05052   return Result;
05053 }
05054 
05055 /// dropPointerConversions - If the given standard conversion sequence
05056 /// involves any pointer conversions, remove them.  This may change
05057 /// the result type of the conversion sequence.
05058 static void dropPointerConversion(StandardConversionSequence &SCS) {
05059   if (SCS.Second == ICK_Pointer_Conversion) {
05060     SCS.Second = ICK_Identity;
05061     SCS.Third = ICK_Identity;
05062     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
05063   }
05064 }
05065 
05066 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
05067 /// convert the expression From to an Objective-C pointer type.
05068 static ImplicitConversionSequence
05069 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
05070   // Do an implicit conversion to 'id'.
05071   QualType Ty = S.Context.getObjCIdType();
05072   ImplicitConversionSequence ICS
05073     = TryImplicitConversion(S, From, Ty,
05074                             // FIXME: Are these flags correct?
05075                             /*SuppressUserConversions=*/false,
05076                             /*AllowExplicit=*/true,
05077                             /*InOverloadResolution=*/false,
05078                             /*CStyle=*/false,
05079                             /*AllowObjCWritebackConversion=*/false,
05080                             /*AllowObjCConversionOnExplicit=*/true);
05081 
05082   // Strip off any final conversions to 'id'.
05083   switch (ICS.getKind()) {
05084   case ImplicitConversionSequence::BadConversion:
05085   case ImplicitConversionSequence::AmbiguousConversion:
05086   case ImplicitConversionSequence::EllipsisConversion:
05087     break;
05088 
05089   case ImplicitConversionSequence::UserDefinedConversion:
05090     dropPointerConversion(ICS.UserDefined.After);
05091     break;
05092 
05093   case ImplicitConversionSequence::StandardConversion:
05094     dropPointerConversion(ICS.Standard);
05095     break;
05096   }
05097 
05098   return ICS;
05099 }
05100 
05101 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
05102 /// conversion of the expression From to an Objective-C pointer type.
05103 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
05104   if (checkPlaceholderForOverload(*this, From))
05105     return ExprError();
05106 
05107   QualType Ty = Context.getObjCIdType();
05108   ImplicitConversionSequence ICS =
05109     TryContextuallyConvertToObjCPointer(*this, From);
05110   if (!ICS.isBad())
05111     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
05112   return ExprError();
05113 }
05114 
05115 /// Determine whether the provided type is an integral type, or an enumeration
05116 /// type of a permitted flavor.
05117 bool Sema::ICEConvertDiagnoser::match(QualType T) {
05118   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
05119                                  : T->isIntegralOrUnscopedEnumerationType();
05120 }
05121 
05122 static ExprResult
05123 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
05124                             Sema::ContextualImplicitConverter &Converter,
05125                             QualType T, UnresolvedSetImpl &ViableConversions) {
05126 
05127   if (Converter.Suppress)
05128     return ExprError();
05129 
05130   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
05131   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
05132     CXXConversionDecl *Conv =
05133         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
05134     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
05135     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
05136   }
05137   return From;
05138 }
05139 
05140 static bool
05141 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
05142                            Sema::ContextualImplicitConverter &Converter,
05143                            QualType T, bool HadMultipleCandidates,
05144                            UnresolvedSetImpl &ExplicitConversions) {
05145   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
05146     DeclAccessPair Found = ExplicitConversions[0];
05147     CXXConversionDecl *Conversion =
05148         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
05149 
05150     // The user probably meant to invoke the given explicit
05151     // conversion; use it.
05152     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
05153     std::string TypeStr;
05154     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
05155 
05156     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
05157         << FixItHint::CreateInsertion(From->getLocStart(),
05158                                       "static_cast<" + TypeStr + ">(")
05159         << FixItHint::CreateInsertion(
05160                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
05161     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
05162 
05163     // If we aren't in a SFINAE context, build a call to the
05164     // explicit conversion function.
05165     if (SemaRef.isSFINAEContext())
05166       return true;
05167 
05168     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
05169     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
05170                                                        HadMultipleCandidates);
05171     if (Result.isInvalid())
05172       return true;
05173     // Record usage of conversion in an implicit cast.
05174     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
05175                                     CK_UserDefinedConversion, Result.get(),
05176                                     nullptr, Result.get()->getValueKind());
05177   }
05178   return false;
05179 }
05180 
05181 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
05182                              Sema::ContextualImplicitConverter &Converter,
05183                              QualType T, bool HadMultipleCandidates,
05184                              DeclAccessPair &Found) {
05185   CXXConversionDecl *Conversion =
05186       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
05187   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
05188 
05189   QualType ToType = Conversion->getConversionType().getNonReferenceType();
05190   if (!Converter.SuppressConversion) {
05191     if (SemaRef.isSFINAEContext())
05192       return true;
05193 
05194     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
05195         << From->getSourceRange();
05196   }
05197 
05198   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
05199                                                      HadMultipleCandidates);
05200   if (Result.isInvalid())
05201     return true;
05202   // Record usage of conversion in an implicit cast.
05203   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
05204                                   CK_UserDefinedConversion, Result.get(),
05205                                   nullptr, Result.get()->getValueKind());
05206   return false;
05207 }
05208 
05209 static ExprResult finishContextualImplicitConversion(
05210     Sema &SemaRef, SourceLocation Loc, Expr *From,
05211     Sema::ContextualImplicitConverter &Converter) {
05212   if (!Converter.match(From->getType()) && !Converter.Suppress)
05213     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
05214         << From->getSourceRange();
05215 
05216   return SemaRef.DefaultLvalueConversion(From);
05217 }
05218 
05219 static void
05220 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
05221                                   UnresolvedSetImpl &ViableConversions,
05222                                   OverloadCandidateSet &CandidateSet) {
05223   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
05224     DeclAccessPair FoundDecl = ViableConversions[I];
05225     NamedDecl *D = FoundDecl.getDecl();
05226     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
05227     if (isa<UsingShadowDecl>(D))
05228       D = cast<UsingShadowDecl>(D)->getTargetDecl();
05229 
05230     CXXConversionDecl *Conv;
05231     FunctionTemplateDecl *ConvTemplate;
05232     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
05233       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
05234     else
05235       Conv = cast<CXXConversionDecl>(D);
05236 
05237     if (ConvTemplate)
05238       SemaRef.AddTemplateConversionCandidate(
05239         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
05240         /*AllowObjCConversionOnExplicit=*/false);
05241     else
05242       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
05243                                      ToType, CandidateSet,
05244                                      /*AllowObjCConversionOnExplicit=*/false);
05245   }
05246 }
05247 
05248 /// \brief Attempt to convert the given expression to a type which is accepted
05249 /// by the given converter.
05250 ///
05251 /// This routine will attempt to convert an expression of class type to a
05252 /// type accepted by the specified converter. In C++11 and before, the class
05253 /// must have a single non-explicit conversion function converting to a matching
05254 /// type. In C++1y, there can be multiple such conversion functions, but only
05255 /// one target type.
05256 ///
05257 /// \param Loc The source location of the construct that requires the
05258 /// conversion.
05259 ///
05260 /// \param From The expression we're converting from.
05261 ///
05262 /// \param Converter Used to control and diagnose the conversion process.
05263 ///
05264 /// \returns The expression, converted to an integral or enumeration type if
05265 /// successful.
05266 ExprResult Sema::PerformContextualImplicitConversion(
05267     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
05268   // We can't perform any more checking for type-dependent expressions.
05269   if (From->isTypeDependent())
05270     return From;
05271 
05272   // Process placeholders immediately.
05273   if (From->hasPlaceholderType()) {
05274     ExprResult result = CheckPlaceholderExpr(From);
05275     if (result.isInvalid())
05276       return result;
05277     From = result.get();
05278   }
05279 
05280   // If the expression already has a matching type, we're golden.
05281   QualType T = From->getType();
05282   if (Converter.match(T))
05283     return DefaultLvalueConversion(From);
05284 
05285   // FIXME: Check for missing '()' if T is a function type?
05286 
05287   // We can only perform contextual implicit conversions on objects of class
05288   // type.
05289   const RecordType *RecordTy = T->getAs<RecordType>();
05290   if (!RecordTy || !getLangOpts().CPlusPlus) {
05291     if (!Converter.Suppress)
05292       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
05293     return From;
05294   }
05295 
05296   // We must have a complete class type.
05297   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
05298     ContextualImplicitConverter &Converter;
05299     Expr *From;
05300 
05301     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
05302         : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
05303 
05304     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
05305       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
05306     }
05307   } IncompleteDiagnoser(Converter, From);
05308 
05309   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
05310     return From;
05311 
05312   // Look for a conversion to an integral or enumeration type.
05313   UnresolvedSet<4>
05314       ViableConversions; // These are *potentially* viable in C++1y.
05315   UnresolvedSet<4> ExplicitConversions;
05316   std::pair<CXXRecordDecl::conversion_iterator,
05317             CXXRecordDecl::conversion_iterator> Conversions =
05318       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
05319 
05320   bool HadMultipleCandidates =
05321       (std::distance(Conversions.first, Conversions.second) > 1);
05322 
05323   // To check that there is only one target type, in C++1y:
05324   QualType ToType;
05325   bool HasUniqueTargetType = true;
05326 
05327   // Collect explicit or viable (potentially in C++1y) conversions.
05328   for (CXXRecordDecl::conversion_iterator I = Conversions.first,
05329                                           E = Conversions.second;
05330        I != E; ++I) {
05331     NamedDecl *D = (*I)->getUnderlyingDecl();
05332     CXXConversionDecl *Conversion;
05333     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
05334     if (ConvTemplate) {
05335       if (getLangOpts().CPlusPlus14)
05336         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
05337       else
05338         continue; // C++11 does not consider conversion operator templates(?).
05339     } else
05340       Conversion = cast<CXXConversionDecl>(D);
05341 
05342     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
05343            "Conversion operator templates are considered potentially "
05344            "viable in C++1y");
05345 
05346     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
05347     if (Converter.match(CurToType) || ConvTemplate) {
05348 
05349       if (Conversion->isExplicit()) {
05350         // FIXME: For C++1y, do we need this restriction?
05351         // cf. diagnoseNoViableConversion()
05352         if (!ConvTemplate)
05353           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
05354       } else {
05355         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
05356           if (ToType.isNull())
05357             ToType = CurToType.getUnqualifiedType();
05358           else if (HasUniqueTargetType &&
05359                    (CurToType.getUnqualifiedType() != ToType))
05360             HasUniqueTargetType = false;
05361         }
05362         ViableConversions.addDecl(I.getDecl(), I.getAccess());
05363       }
05364     }
05365   }
05366 
05367   if (getLangOpts().CPlusPlus14) {
05368     // C++1y [conv]p6:
05369     // ... An expression e of class type E appearing in such a context
05370     // is said to be contextually implicitly converted to a specified
05371     // type T and is well-formed if and only if e can be implicitly
05372     // converted to a type T that is determined as follows: E is searched
05373     // for conversion functions whose return type is cv T or reference to
05374     // cv T such that T is allowed by the context. There shall be
05375     // exactly one such T.
05376 
05377     // If no unique T is found:
05378     if (ToType.isNull()) {
05379       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
05380                                      HadMultipleCandidates,
05381                                      ExplicitConversions))
05382         return ExprError();
05383       return finishContextualImplicitConversion(*this, Loc, From, Converter);
05384     }
05385 
05386     // If more than one unique Ts are found:
05387     if (!HasUniqueTargetType)
05388       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
05389                                          ViableConversions);
05390 
05391     // If one unique T is found:
05392     // First, build a candidate set from the previously recorded
05393     // potentially viable conversions.
05394     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
05395     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
05396                                       CandidateSet);
05397 
05398     // Then, perform overload resolution over the candidate set.
05399     OverloadCandidateSet::iterator Best;
05400     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
05401     case OR_Success: {
05402       // Apply this conversion.
05403       DeclAccessPair Found =
05404           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
05405       if (recordConversion(*this, Loc, From, Converter, T,
05406                            HadMultipleCandidates, Found))
05407         return ExprError();
05408       break;
05409     }
05410     case OR_Ambiguous:
05411       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
05412                                          ViableConversions);
05413     case OR_No_Viable_Function:
05414       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
05415                                      HadMultipleCandidates,
05416                                      ExplicitConversions))
05417         return ExprError();
05418     // fall through 'OR_Deleted' case.
05419     case OR_Deleted:
05420       // We'll complain below about a non-integral condition type.
05421       break;
05422     }
05423   } else {
05424     switch (ViableConversions.size()) {
05425     case 0: {
05426       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
05427                                      HadMultipleCandidates,
05428                                      ExplicitConversions))
05429         return ExprError();
05430 
05431       // We'll complain below about a non-integral condition type.
05432       break;
05433     }
05434     case 1: {
05435       // Apply this conversion.
05436       DeclAccessPair Found = ViableConversions[0];
05437       if (recordConversion(*this, Loc, From, Converter, T,
05438                            HadMultipleCandidates, Found))
05439         return ExprError();
05440       break;
05441     }
05442     default:
05443       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
05444                                          ViableConversions);
05445     }
05446   }
05447 
05448   return finishContextualImplicitConversion(*this, Loc, From, Converter);
05449 }
05450 
05451 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
05452 /// an acceptable non-member overloaded operator for a call whose
05453 /// arguments have types T1 (and, if non-empty, T2). This routine
05454 /// implements the check in C++ [over.match.oper]p3b2 concerning
05455 /// enumeration types.
05456 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
05457                                                    FunctionDecl *Fn,
05458                                                    ArrayRef<Expr *> Args) {
05459   QualType T1 = Args[0]->getType();
05460   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
05461 
05462   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
05463     return true;
05464 
05465   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
05466     return true;
05467 
05468   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
05469   if (Proto->getNumParams() < 1)
05470     return false;
05471 
05472   if (T1->isEnumeralType()) {
05473     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
05474     if (Context.hasSameUnqualifiedType(T1, ArgType))
05475       return true;
05476   }
05477 
05478   if (Proto->getNumParams() < 2)
05479     return false;
05480 
05481   if (!T2.isNull() && T2->isEnumeralType()) {
05482     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
05483     if (Context.hasSameUnqualifiedType(T2, ArgType))
05484       return true;
05485   }
05486 
05487   return false;
05488 }
05489 
05490 /// AddOverloadCandidate - Adds the given function to the set of
05491 /// candidate functions, using the given function call arguments.  If
05492 /// @p SuppressUserConversions, then don't allow user-defined
05493 /// conversions via constructors or conversion operators.
05494 ///
05495 /// \param PartialOverloading true if we are performing "partial" overloading
05496 /// based on an incomplete set of function arguments. This feature is used by
05497 /// code completion.
05498 void
05499 Sema::AddOverloadCandidate(FunctionDecl *Function,
05500                            DeclAccessPair FoundDecl,
05501                            ArrayRef<Expr *> Args,
05502                            OverloadCandidateSet &CandidateSet,
05503                            bool SuppressUserConversions,
05504                            bool PartialOverloading,
05505                            bool AllowExplicit) {
05506   const FunctionProtoType *Proto
05507     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
05508   assert(Proto && "Functions without a prototype cannot be overloaded");
05509   assert(!Function->getDescribedFunctionTemplate() &&
05510          "Use AddTemplateOverloadCandidate for function templates");
05511 
05512   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
05513     if (!isa<CXXConstructorDecl>(Method)) {
05514       // If we get here, it's because we're calling a member function
05515       // that is named without a member access expression (e.g.,
05516       // "this->f") that was either written explicitly or created
05517       // implicitly. This can happen with a qualified call to a member
05518       // function, e.g., X::f(). We use an empty type for the implied
05519       // object argument (C++ [over.call.func]p3), and the acting context
05520       // is irrelevant.
05521       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
05522                          QualType(), Expr::Classification::makeSimpleLValue(),
05523                          Args, CandidateSet, SuppressUserConversions);
05524       return;
05525     }
05526     // We treat a constructor like a non-member function, since its object
05527     // argument doesn't participate in overload resolution.
05528   }
05529 
05530   if (!CandidateSet.isNewCandidate(Function))
05531     return;
05532 
05533   // C++ [over.match.oper]p3:
05534   //   if no operand has a class type, only those non-member functions in the
05535   //   lookup set that have a first parameter of type T1 or "reference to
05536   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
05537   //   is a right operand) a second parameter of type T2 or "reference to
05538   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
05539   //   candidate functions.
05540   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
05541       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
05542     return;
05543 
05544   // C++11 [class.copy]p11: [DR1402]
05545   //   A defaulted move constructor that is defined as deleted is ignored by
05546   //   overload resolution.
05547   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
05548   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
05549       Constructor->isMoveConstructor())
05550     return;
05551 
05552   // Overload resolution is always an unevaluated context.
05553   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
05554 
05555   if (Constructor) {
05556     // C++ [class.copy]p3:
05557     //   A member function template is never instantiated to perform the copy
05558     //   of a class object to an object of its class type.
05559     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
05560     if (Args.size() == 1 &&
05561         Constructor->isSpecializationCopyingObject() &&
05562         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
05563          IsDerivedFrom(Args[0]->getType(), ClassType)))
05564       return;
05565   }
05566 
05567   // Add this candidate
05568   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
05569   Candidate.FoundDecl = FoundDecl;
05570   Candidate.Function = Function;
05571   Candidate.Viable = true;
05572   Candidate.IsSurrogate = false;
05573   Candidate.IgnoreObjectArgument = false;
05574   Candidate.ExplicitCallArguments = Args.size();
05575 
05576   unsigned NumParams = Proto->getNumParams();
05577 
05578   // (C++ 13.3.2p2): A candidate function having fewer than m
05579   // parameters is viable only if it has an ellipsis in its parameter
05580   // list (8.3.5).
05581   if ((Args.size() + (PartialOverloading && Args.size())) > NumParams &&
05582       !Proto->isVariadic()) {
05583     Candidate.Viable = false;
05584     Candidate.FailureKind = ovl_fail_too_many_arguments;
05585     return;
05586   }
05587 
05588   // (C++ 13.3.2p2): A candidate function having more than m parameters
05589   // is viable only if the (m+1)st parameter has a default argument
05590   // (8.3.6). For the purposes of overload resolution, the
05591   // parameter list is truncated on the right, so that there are
05592   // exactly m parameters.
05593   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
05594   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
05595     // Not enough arguments.
05596     Candidate.Viable = false;
05597     Candidate.FailureKind = ovl_fail_too_few_arguments;
05598     return;
05599   }
05600 
05601   // (CUDA B.1): Check for invalid calls between targets.
05602   if (getLangOpts().CUDA)
05603     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
05604       // Skip the check for callers that are implicit members, because in this
05605       // case we may not yet know what the member's target is; the target is
05606       // inferred for the member automatically, based on the bases and fields of
05607       // the class.
05608       if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
05609         Candidate.Viable = false;
05610         Candidate.FailureKind = ovl_fail_bad_target;
05611         return;
05612       }
05613 
05614   // Determine the implicit conversion sequences for each of the
05615   // arguments.
05616   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
05617     if (ArgIdx < NumParams) {
05618       // (C++ 13.3.2p3): for F to be a viable function, there shall
05619       // exist for each argument an implicit conversion sequence
05620       // (13.3.3.1) that converts that argument to the corresponding
05621       // parameter of F.
05622       QualType ParamType = Proto->getParamType(ArgIdx);
05623       Candidate.Conversions[ArgIdx]
05624         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
05625                                 SuppressUserConversions,
05626                                 /*InOverloadResolution=*/true,
05627                                 /*AllowObjCWritebackConversion=*/
05628                                   getLangOpts().ObjCAutoRefCount,
05629                                 AllowExplicit);
05630       if (Candidate.Conversions[ArgIdx].isBad()) {
05631         Candidate.Viable = false;
05632         Candidate.FailureKind = ovl_fail_bad_conversion;
05633         return;
05634       }
05635     } else {
05636       // (C++ 13.3.2p2): For the purposes of overload resolution, any
05637       // argument for which there is no corresponding parameter is
05638       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
05639       Candidate.Conversions[ArgIdx].setEllipsis();
05640     }
05641   }
05642 
05643   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
05644     Candidate.Viable = false;
05645     Candidate.FailureKind = ovl_fail_enable_if;
05646     Candidate.DeductionFailure.Data = FailedAttr;
05647     return;
05648   }
05649 }
05650 
05651 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
05652                                        bool IsInstance) {
05653   SmallVector<ObjCMethodDecl*, 4> Methods;
05654   if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
05655     return nullptr;
05656     
05657   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
05658     bool Match = true;
05659     ObjCMethodDecl *Method = Methods[b];
05660     unsigned NumNamedArgs = Sel.getNumArgs();
05661     // Method might have more arguments than selector indicates. This is due
05662     // to addition of c-style arguments in method.
05663     if (Method->param_size() > NumNamedArgs)
05664       NumNamedArgs = Method->param_size();
05665     if (Args.size() < NumNamedArgs)
05666       continue;
05667             
05668     for (unsigned i = 0; i < NumNamedArgs; i++) {
05669       // We can't do any type-checking on a type-dependent argument.
05670       if (Args[i]->isTypeDependent()) {
05671         Match = false;
05672         break;
05673       }
05674         
05675       ParmVarDecl *param = Method->parameters()[i];
05676       Expr *argExpr = Args[i];
05677       assert(argExpr && "SelectBestMethod(): missing expression");
05678                 
05679       // Strip the unbridged-cast placeholder expression off unless it's
05680       // a consumed argument.
05681       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
05682           !param->hasAttr<CFConsumedAttr>())
05683         argExpr = stripARCUnbridgedCast(argExpr);
05684                 
05685       // If the parameter is __unknown_anytype, move on to the next method.
05686       if (param->getType() == Context.UnknownAnyTy) {
05687         Match = false;
05688         break;
05689       }
05690                 
05691       ImplicitConversionSequence ConversionState
05692         = TryCopyInitialization(*this, argExpr, param->getType(),
05693                                 /*SuppressUserConversions*/false,
05694                                 /*InOverloadResolution=*/true,
05695                                 /*AllowObjCWritebackConversion=*/
05696                                 getLangOpts().ObjCAutoRefCount,
05697                                 /*AllowExplicit*/false);
05698         if (ConversionState.isBad()) {
05699           Match = false;
05700           break;
05701         }
05702     }
05703     // Promote additional arguments to variadic methods.
05704     if (Match && Method->isVariadic()) {
05705       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
05706         if (Args[i]->isTypeDependent()) {
05707           Match = false;
05708           break;
05709         }
05710         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
05711                                                           nullptr);
05712         if (Arg.isInvalid()) {
05713           Match = false;
05714           break;
05715         }
05716       }
05717     } else {
05718       // Check for extra arguments to non-variadic methods.
05719       if (Args.size() != NumNamedArgs)
05720         Match = false;
05721       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
05722         // Special case when selectors have no argument. In this case, select
05723         // one with the most general result type of 'id'.
05724         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
05725           QualType ReturnT = Methods[b]->getReturnType();
05726           if (ReturnT->isObjCIdType())
05727             return Methods[b];
05728         }
05729       }
05730     }
05731 
05732     if (Match)
05733       return Method;
05734   }
05735   return nullptr;
05736 }
05737 
05738 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
05739 
05740 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
05741                                   bool MissingImplicitThis) {
05742   // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
05743   // we need to find the first failing one.
05744   if (!Function->hasAttrs())
05745     return nullptr;
05746   AttrVec Attrs = Function->getAttrs();
05747   AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
05748                                        IsNotEnableIfAttr);
05749   if (Attrs.begin() == E)
05750     return nullptr;
05751   std::reverse(Attrs.begin(), E);
05752 
05753   SFINAETrap Trap(*this);
05754 
05755   // Convert the arguments.
05756   SmallVector<Expr *, 16> ConvertedArgs;
05757   bool InitializationFailed = false;
05758   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
05759     if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
05760         !cast<CXXMethodDecl>(Function)->isStatic() &&
05761         !isa<CXXConstructorDecl>(Function)) {
05762       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
05763       ExprResult R =
05764         PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
05765                                             Method, Method);
05766       if (R.isInvalid()) {
05767         InitializationFailed = true;
05768         break;
05769       }
05770       ConvertedArgs.push_back(R.get());
05771     } else {
05772       ExprResult R =
05773         PerformCopyInitialization(InitializedEntity::InitializeParameter(
05774                                                 Context,
05775                                                 Function->getParamDecl(i)),
05776                                   SourceLocation(),
05777                                   Args[i]);
05778       if (R.isInvalid()) {
05779         InitializationFailed = true;
05780         break;
05781       }
05782       ConvertedArgs.push_back(R.get());
05783     }
05784   }
05785 
05786   if (InitializationFailed || Trap.hasErrorOccurred())
05787     return cast<EnableIfAttr>(Attrs[0]);
05788 
05789   for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
05790     APValue Result;
05791     EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
05792     if (!EIA->getCond()->EvaluateWithSubstitution(
05793             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)) ||
05794         !Result.isInt() || !Result.getInt().getBoolValue()) {
05795       return EIA;
05796     }
05797   }
05798   return nullptr;
05799 }
05800 
05801 /// \brief Add all of the function declarations in the given function set to
05802 /// the overload candidate set.
05803 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
05804                                  ArrayRef<Expr *> Args,
05805                                  OverloadCandidateSet& CandidateSet,
05806                                  bool SuppressUserConversions,
05807                                TemplateArgumentListInfo *ExplicitTemplateArgs) {
05808   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
05809     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
05810     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
05811       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
05812         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
05813                            cast<CXXMethodDecl>(FD)->getParent(),
05814                            Args[0]->getType(), Args[0]->Classify(Context),
05815                            Args.slice(1), CandidateSet,
05816                            SuppressUserConversions);
05817       else
05818         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
05819                              SuppressUserConversions);
05820     } else {
05821       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
05822       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
05823           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
05824         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
05825                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
05826                                    ExplicitTemplateArgs,
05827                                    Args[0]->getType(),
05828                                    Args[0]->Classify(Context), Args.slice(1),
05829                                    CandidateSet, SuppressUserConversions);
05830       else
05831         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
05832                                      ExplicitTemplateArgs, Args,
05833                                      CandidateSet, SuppressUserConversions);
05834     }
05835   }
05836 }
05837 
05838 /// AddMethodCandidate - Adds a named decl (which is some kind of
05839 /// method) as a method candidate to the given overload set.
05840 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
05841                               QualType ObjectType,
05842                               Expr::Classification ObjectClassification,
05843                               ArrayRef<Expr *> Args,
05844                               OverloadCandidateSet& CandidateSet,
05845                               bool SuppressUserConversions) {
05846   NamedDecl *Decl = FoundDecl.getDecl();
05847   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
05848 
05849   if (isa<UsingShadowDecl>(Decl))
05850     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
05851 
05852   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
05853     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
05854            "Expected a member function template");
05855     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
05856                                /*ExplicitArgs*/ nullptr,
05857                                ObjectType, ObjectClassification,
05858                                Args, CandidateSet,
05859                                SuppressUserConversions);
05860   } else {
05861     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
05862                        ObjectType, ObjectClassification,
05863                        Args,
05864                        CandidateSet, SuppressUserConversions);
05865   }
05866 }
05867 
05868 /// AddMethodCandidate - Adds the given C++ member function to the set
05869 /// of candidate functions, using the given function call arguments
05870 /// and the object argument (@c Object). For example, in a call
05871 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
05872 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
05873 /// allow user-defined conversions via constructors or conversion
05874 /// operators.
05875 void
05876 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
05877                          CXXRecordDecl *ActingContext, QualType ObjectType,
05878                          Expr::Classification ObjectClassification,
05879                          ArrayRef<Expr *> Args,
05880                          OverloadCandidateSet &CandidateSet,
05881                          bool SuppressUserConversions) {
05882   const FunctionProtoType *Proto
05883     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
05884   assert(Proto && "Methods without a prototype cannot be overloaded");
05885   assert(!isa<CXXConstructorDecl>(Method) &&
05886          "Use AddOverloadCandidate for constructors");
05887 
05888   if (!CandidateSet.isNewCandidate(Method))
05889     return;
05890 
05891   // C++11 [class.copy]p23: [DR1402]
05892   //   A defaulted move assignment operator that is defined as deleted is
05893   //   ignored by overload resolution.
05894   if (Method->isDefaulted() && Method->isDeleted() &&
05895       Method->isMoveAssignmentOperator())
05896     return;
05897 
05898   // Overload resolution is always an unevaluated context.
05899   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
05900 
05901   // Add this candidate
05902   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
05903   Candidate.FoundDecl = FoundDecl;
05904   Candidate.Function = Method;
05905   Candidate.IsSurrogate = false;
05906   Candidate.IgnoreObjectArgument = false;
05907   Candidate.ExplicitCallArguments = Args.size();
05908 
05909   unsigned NumParams = Proto->getNumParams();
05910 
05911   // (C++ 13.3.2p2): A candidate function having fewer than m
05912   // parameters is viable only if it has an ellipsis in its parameter
05913   // list (8.3.5).
05914   if (Args.size() > NumParams && !Proto->isVariadic()) {
05915     Candidate.Viable = false;
05916     Candidate.FailureKind = ovl_fail_too_many_arguments;
05917     return;
05918   }
05919 
05920   // (C++ 13.3.2p2): A candidate function having more than m parameters
05921   // is viable only if the (m+1)st parameter has a default argument
05922   // (8.3.6). For the purposes of overload resolution, the
05923   // parameter list is truncated on the right, so that there are
05924   // exactly m parameters.
05925   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
05926   if (Args.size() < MinRequiredArgs) {
05927     // Not enough arguments.
05928     Candidate.Viable = false;
05929     Candidate.FailureKind = ovl_fail_too_few_arguments;
05930     return;
05931   }
05932 
05933   Candidate.Viable = true;
05934 
05935   if (Method->isStatic() || ObjectType.isNull())
05936     // The implicit object argument is ignored.
05937     Candidate.IgnoreObjectArgument = true;
05938   else {
05939     // Determine the implicit conversion sequence for the object
05940     // parameter.
05941     Candidate.Conversions[0]
05942       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
05943                                         Method, ActingContext);
05944     if (Candidate.Conversions[0].isBad()) {
05945       Candidate.Viable = false;
05946       Candidate.FailureKind = ovl_fail_bad_conversion;
05947       return;
05948     }
05949   }
05950 
05951   // (CUDA B.1): Check for invalid calls between targets.
05952   if (getLangOpts().CUDA)
05953     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
05954       if (CheckCUDATarget(Caller, Method)) {
05955         Candidate.Viable = false;
05956         Candidate.FailureKind = ovl_fail_bad_target;
05957         return;
05958       }
05959 
05960   // Determine the implicit conversion sequences for each of the
05961   // arguments.
05962   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
05963     if (ArgIdx < NumParams) {
05964       // (C++ 13.3.2p3): for F to be a viable function, there shall
05965       // exist for each argument an implicit conversion sequence
05966       // (13.3.3.1) that converts that argument to the corresponding
05967       // parameter of F.
05968       QualType ParamType = Proto->getParamType(ArgIdx);
05969       Candidate.Conversions[ArgIdx + 1]
05970         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
05971                                 SuppressUserConversions,
05972                                 /*InOverloadResolution=*/true,
05973                                 /*AllowObjCWritebackConversion=*/
05974                                   getLangOpts().ObjCAutoRefCount);
05975       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
05976         Candidate.Viable = false;
05977         Candidate.FailureKind = ovl_fail_bad_conversion;
05978         return;
05979       }
05980     } else {
05981       // (C++ 13.3.2p2): For the purposes of overload resolution, any
05982       // argument for which there is no corresponding parameter is
05983       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
05984       Candidate.Conversions[ArgIdx + 1].setEllipsis();
05985     }
05986   }
05987 
05988   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
05989     Candidate.Viable = false;
05990     Candidate.FailureKind = ovl_fail_enable_if;
05991     Candidate.DeductionFailure.Data = FailedAttr;
05992     return;
05993   }
05994 }
05995 
05996 /// \brief Add a C++ member function template as a candidate to the candidate
05997 /// set, using template argument deduction to produce an appropriate member
05998 /// function template specialization.
05999 void
06000 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
06001                                  DeclAccessPair FoundDecl,
06002                                  CXXRecordDecl *ActingContext,
06003                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
06004                                  QualType ObjectType,
06005                                  Expr::Classification ObjectClassification,
06006                                  ArrayRef<Expr *> Args,
06007                                  OverloadCandidateSet& CandidateSet,
06008                                  bool SuppressUserConversions) {
06009   if (!CandidateSet.isNewCandidate(MethodTmpl))
06010     return;
06011 
06012   // C++ [over.match.funcs]p7:
06013   //   In each case where a candidate is a function template, candidate
06014   //   function template specializations are generated using template argument
06015   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
06016   //   candidate functions in the usual way.113) A given name can refer to one
06017   //   or more function templates and also to a set of overloaded non-template
06018   //   functions. In such a case, the candidate functions generated from each
06019   //   function template are combined with the set of non-template candidate
06020   //   functions.
06021   TemplateDeductionInfo Info(CandidateSet.getLocation());
06022   FunctionDecl *Specialization = nullptr;
06023   if (TemplateDeductionResult Result
06024       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
06025                                 Specialization, Info)) {
06026     OverloadCandidate &Candidate = CandidateSet.addCandidate();
06027     Candidate.FoundDecl = FoundDecl;
06028     Candidate.Function = MethodTmpl->getTemplatedDecl();
06029     Candidate.Viable = false;
06030     Candidate.FailureKind = ovl_fail_bad_deduction;
06031     Candidate.IsSurrogate = false;
06032     Candidate.IgnoreObjectArgument = false;
06033     Candidate.ExplicitCallArguments = Args.size();
06034     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
06035                                                           Info);
06036     return;
06037   }
06038 
06039   // Add the function template specialization produced by template argument
06040   // deduction as a candidate.
06041   assert(Specialization && "Missing member function template specialization?");
06042   assert(isa<CXXMethodDecl>(Specialization) &&
06043          "Specialization is not a member function?");
06044   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
06045                      ActingContext, ObjectType, ObjectClassification, Args,
06046                      CandidateSet, SuppressUserConversions);
06047 }
06048 
06049 /// \brief Add a C++ function template specialization as a candidate
06050 /// in the candidate set, using template argument deduction to produce
06051 /// an appropriate function template specialization.
06052 void
06053 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
06054                                    DeclAccessPair FoundDecl,
06055                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
06056                                    ArrayRef<Expr *> Args,
06057                                    OverloadCandidateSet& CandidateSet,
06058                                    bool SuppressUserConversions) {
06059   if (!CandidateSet.isNewCandidate(FunctionTemplate))
06060     return;
06061 
06062   // C++ [over.match.funcs]p7:
06063   //   In each case where a candidate is a function template, candidate
06064   //   function template specializations are generated using template argument
06065   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
06066   //   candidate functions in the usual way.113) A given name can refer to one
06067   //   or more function templates and also to a set of overloaded non-template
06068   //   functions. In such a case, the candidate functions generated from each
06069   //   function template are combined with the set of non-template candidate
06070   //   functions.
06071   TemplateDeductionInfo Info(CandidateSet.getLocation());
06072   FunctionDecl *Specialization = nullptr;
06073   if (TemplateDeductionResult Result
06074         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
06075                                   Specialization, Info)) {
06076     OverloadCandidate &Candidate = CandidateSet.addCandidate();
06077     Candidate.FoundDecl = FoundDecl;
06078     Candidate.Function = FunctionTemplate->getTemplatedDecl();
06079     Candidate.Viable = false;
06080     Candidate.FailureKind = ovl_fail_bad_deduction;
06081     Candidate.IsSurrogate = false;
06082     Candidate.IgnoreObjectArgument = false;
06083     Candidate.ExplicitCallArguments = Args.size();
06084     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
06085                                                           Info);
06086     return;
06087   }
06088 
06089   // Add the function template specialization produced by template argument
06090   // deduction as a candidate.
06091   assert(Specialization && "Missing function template specialization?");
06092   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
06093                        SuppressUserConversions);
06094 }
06095 
06096 /// Determine whether this is an allowable conversion from the result
06097 /// of an explicit conversion operator to the expected type, per C++
06098 /// [over.match.conv]p1 and [over.match.ref]p1.
06099 ///
06100 /// \param ConvType The return type of the conversion function.
06101 ///
06102 /// \param ToType The type we are converting to.
06103 ///
06104 /// \param AllowObjCPointerConversion Allow a conversion from one
06105 /// Objective-C pointer to another.
06106 ///
06107 /// \returns true if the conversion is allowable, false otherwise.
06108 static bool isAllowableExplicitConversion(Sema &S,
06109                                           QualType ConvType, QualType ToType,
06110                                           bool AllowObjCPointerConversion) {
06111   QualType ToNonRefType = ToType.getNonReferenceType();
06112 
06113   // Easy case: the types are the same.
06114   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
06115     return true;
06116 
06117   // Allow qualification conversions.
06118   bool ObjCLifetimeConversion;
06119   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
06120                                   ObjCLifetimeConversion))
06121     return true;
06122 
06123   // If we're not allowed to consider Objective-C pointer conversions,
06124   // we're done.
06125   if (!AllowObjCPointerConversion)
06126     return false;
06127 
06128   // Is this an Objective-C pointer conversion?
06129   bool IncompatibleObjC = false;
06130   QualType ConvertedType;
06131   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
06132                                    IncompatibleObjC);
06133 }
06134                                           
06135 /// AddConversionCandidate - Add a C++ conversion function as a
06136 /// candidate in the candidate set (C++ [over.match.conv],
06137 /// C++ [over.match.copy]). From is the expression we're converting from,
06138 /// and ToType is the type that we're eventually trying to convert to
06139 /// (which may or may not be the same type as the type that the
06140 /// conversion function produces).
06141 void
06142 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
06143                              DeclAccessPair FoundDecl,
06144                              CXXRecordDecl *ActingContext,
06145                              Expr *From, QualType ToType,
06146                              OverloadCandidateSet& CandidateSet,
06147                              bool AllowObjCConversionOnExplicit) {
06148   assert(!Conversion->getDescribedFunctionTemplate() &&
06149          "Conversion function templates use AddTemplateConversionCandidate");
06150   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
06151   if (!CandidateSet.isNewCandidate(Conversion))
06152     return;
06153 
06154   // If the conversion function has an undeduced return type, trigger its
06155   // deduction now.
06156   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
06157     if (DeduceReturnType(Conversion, From->getExprLoc()))
06158       return;
06159     ConvType = Conversion->getConversionType().getNonReferenceType();
06160   }
06161 
06162   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
06163   // operator is only a candidate if its return type is the target type or
06164   // can be converted to the target type with a qualification conversion.
06165   if (Conversion->isExplicit() && 
06166       !isAllowableExplicitConversion(*this, ConvType, ToType, 
06167                                      AllowObjCConversionOnExplicit))
06168     return;
06169 
06170   // Overload resolution is always an unevaluated context.
06171   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
06172 
06173   // Add this candidate
06174   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
06175   Candidate.FoundDecl = FoundDecl;
06176   Candidate.Function = Conversion;
06177   Candidate.IsSurrogate = false;
06178   Candidate.IgnoreObjectArgument = false;
06179   Candidate.FinalConversion.setAsIdentityConversion();
06180   Candidate.FinalConversion.setFromType(ConvType);
06181   Candidate.FinalConversion.setAllToTypes(ToType);
06182   Candidate.Viable = true;
06183   Candidate.ExplicitCallArguments = 1;
06184 
06185   // C++ [over.match.funcs]p4:
06186   //   For conversion functions, the function is considered to be a member of
06187   //   the class of the implicit implied object argument for the purpose of
06188   //   defining the type of the implicit object parameter.
06189   //
06190   // Determine the implicit conversion sequence for the implicit
06191   // object parameter.
06192   QualType ImplicitParamType = From->getType();
06193   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
06194     ImplicitParamType = FromPtrType->getPointeeType();
06195   CXXRecordDecl *ConversionContext
06196     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
06197 
06198   Candidate.Conversions[0]
06199     = TryObjectArgumentInitialization(*this, From->getType(),
06200                                       From->Classify(Context),
06201                                       Conversion, ConversionContext);
06202 
06203   if (Candidate.Conversions[0].isBad()) {
06204     Candidate.Viable = false;
06205     Candidate.FailureKind = ovl_fail_bad_conversion;
06206     return;
06207   }
06208 
06209   // We won't go through a user-defined type conversion function to convert a
06210   // derived to base as such conversions are given Conversion Rank. They only
06211   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
06212   QualType FromCanon
06213     = Context.getCanonicalType(From->getType().getUnqualifiedType());
06214   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
06215   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
06216     Candidate.Viable = false;
06217     Candidate.FailureKind = ovl_fail_trivial_conversion;
06218     return;
06219   }
06220 
06221   // To determine what the conversion from the result of calling the
06222   // conversion function to the type we're eventually trying to
06223   // convert to (ToType), we need to synthesize a call to the
06224   // conversion function and attempt copy initialization from it. This
06225   // makes sure that we get the right semantics with respect to
06226   // lvalues/rvalues and the type. Fortunately, we can allocate this
06227   // call on the stack and we don't need its arguments to be
06228   // well-formed.
06229   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
06230                             VK_LValue, From->getLocStart());
06231   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
06232                                 Context.getPointerType(Conversion->getType()),
06233                                 CK_FunctionToPointerDecay,
06234                                 &ConversionRef, VK_RValue);
06235 
06236   QualType ConversionType = Conversion->getConversionType();
06237   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
06238     Candidate.Viable = false;
06239     Candidate.FailureKind = ovl_fail_bad_final_conversion;
06240     return;
06241   }
06242 
06243   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
06244 
06245   // Note that it is safe to allocate CallExpr on the stack here because
06246   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
06247   // allocator).
06248   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
06249   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
06250                 From->getLocStart());
06251   ImplicitConversionSequence ICS =
06252     TryCopyInitialization(*this, &Call, ToType,
06253                           /*SuppressUserConversions=*/true,
06254                           /*InOverloadResolution=*/false,
06255                           /*AllowObjCWritebackConversion=*/false);
06256 
06257   switch (ICS.getKind()) {
06258   case ImplicitConversionSequence::StandardConversion:
06259     Candidate.FinalConversion = ICS.Standard;
06260 
06261     // C++ [over.ics.user]p3:
06262     //   If the user-defined conversion is specified by a specialization of a
06263     //   conversion function template, the second standard conversion sequence
06264     //   shall have exact match rank.
06265     if (Conversion->getPrimaryTemplate() &&
06266         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
06267       Candidate.Viable = false;
06268       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
06269       return;
06270     }
06271 
06272     // C++0x [dcl.init.ref]p5:
06273     //    In the second case, if the reference is an rvalue reference and
06274     //    the second standard conversion sequence of the user-defined
06275     //    conversion sequence includes an lvalue-to-rvalue conversion, the
06276     //    program is ill-formed.
06277     if (ToType->isRValueReferenceType() &&
06278         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
06279       Candidate.Viable = false;
06280       Candidate.FailureKind = ovl_fail_bad_final_conversion;
06281       return;
06282     }
06283     break;
06284 
06285   case ImplicitConversionSequence::BadConversion:
06286     Candidate.Viable = false;
06287     Candidate.FailureKind = ovl_fail_bad_final_conversion;
06288     return;
06289 
06290   default:
06291     llvm_unreachable(
06292            "Can only end up with a standard conversion sequence or failure");
06293   }
06294 
06295   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
06296     Candidate.Viable = false;
06297     Candidate.FailureKind = ovl_fail_enable_if;
06298     Candidate.DeductionFailure.Data = FailedAttr;
06299     return;
06300   }
06301 }
06302 
06303 /// \brief Adds a conversion function template specialization
06304 /// candidate to the overload set, using template argument deduction
06305 /// to deduce the template arguments of the conversion function
06306 /// template from the type that we are converting to (C++
06307 /// [temp.deduct.conv]).
06308 void
06309 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
06310                                      DeclAccessPair FoundDecl,
06311                                      CXXRecordDecl *ActingDC,
06312                                      Expr *From, QualType ToType,
06313                                      OverloadCandidateSet &CandidateSet,
06314                                      bool AllowObjCConversionOnExplicit) {
06315   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
06316          "Only conversion function templates permitted here");
06317 
06318   if (!CandidateSet.isNewCandidate(FunctionTemplate))
06319     return;
06320 
06321   TemplateDeductionInfo Info(CandidateSet.getLocation());
06322   CXXConversionDecl *Specialization = nullptr;
06323   if (TemplateDeductionResult Result
06324         = DeduceTemplateArguments(FunctionTemplate, ToType,
06325                                   Specialization, Info)) {
06326     OverloadCandidate &Candidate = CandidateSet.addCandidate();
06327     Candidate.FoundDecl = FoundDecl;
06328     Candidate.Function = FunctionTemplate->getTemplatedDecl();
06329     Candidate.Viable = false;
06330     Candidate.FailureKind = ovl_fail_bad_deduction;
06331     Candidate.IsSurrogate = false;
06332     Candidate.IgnoreObjectArgument = false;
06333     Candidate.ExplicitCallArguments = 1;
06334     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
06335                                                           Info);
06336     return;
06337   }
06338 
06339   // Add the conversion function template specialization produced by
06340   // template argument deduction as a candidate.
06341   assert(Specialization && "Missing function template specialization?");
06342   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
06343                          CandidateSet, AllowObjCConversionOnExplicit);
06344 }
06345 
06346 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
06347 /// converts the given @c Object to a function pointer via the
06348 /// conversion function @c Conversion, and then attempts to call it
06349 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
06350 /// the type of function that we'll eventually be calling.
06351 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
06352                                  DeclAccessPair FoundDecl,
06353                                  CXXRecordDecl *ActingContext,
06354                                  const FunctionProtoType *Proto,
06355                                  Expr *Object,
06356                                  ArrayRef<Expr *> Args,
06357                                  OverloadCandidateSet& CandidateSet) {
06358   if (!CandidateSet.isNewCandidate(Conversion))
06359     return;
06360 
06361   // Overload resolution is always an unevaluated context.
06362   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
06363 
06364   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
06365   Candidate.FoundDecl = FoundDecl;
06366   Candidate.Function = nullptr;
06367   Candidate.Surrogate = Conversion;
06368   Candidate.Viable = true;
06369   Candidate.IsSurrogate = true;
06370   Candidate.IgnoreObjectArgument = false;
06371   Candidate.ExplicitCallArguments = Args.size();
06372 
06373   // Determine the implicit conversion sequence for the implicit
06374   // object parameter.
06375   ImplicitConversionSequence ObjectInit
06376     = TryObjectArgumentInitialization(*this, Object->getType(),
06377                                       Object->Classify(Context),
06378                                       Conversion, ActingContext);
06379   if (ObjectInit.isBad()) {
06380     Candidate.Viable = false;
06381     Candidate.FailureKind = ovl_fail_bad_conversion;
06382     Candidate.Conversions[0] = ObjectInit;
06383     return;
06384   }
06385 
06386   // The first conversion is actually a user-defined conversion whose
06387   // first conversion is ObjectInit's standard conversion (which is
06388   // effectively a reference binding). Record it as such.
06389   Candidate.Conversions[0].setUserDefined();
06390   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
06391   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
06392   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
06393   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
06394   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
06395   Candidate.Conversions[0].UserDefined.After
06396     = Candidate.Conversions[0].UserDefined.Before;
06397   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
06398 
06399   // Find the
06400   unsigned NumParams = Proto->getNumParams();
06401 
06402   // (C++ 13.3.2p2): A candidate function having fewer than m
06403   // parameters is viable only if it has an ellipsis in its parameter
06404   // list (8.3.5).
06405   if (Args.size() > NumParams && !Proto->isVariadic()) {
06406     Candidate.Viable = false;
06407     Candidate.FailureKind = ovl_fail_too_many_arguments;
06408     return;
06409   }
06410 
06411   // Function types don't have any default arguments, so just check if
06412   // we have enough arguments.
06413   if (Args.size() < NumParams) {
06414     // Not enough arguments.
06415     Candidate.Viable = false;
06416     Candidate.FailureKind = ovl_fail_too_few_arguments;
06417     return;
06418   }
06419 
06420   // Determine the implicit conversion sequences for each of the
06421   // arguments.
06422   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
06423     if (ArgIdx < NumParams) {
06424       // (C++ 13.3.2p3): for F to be a viable function, there shall
06425       // exist for each argument an implicit conversion sequence
06426       // (13.3.3.1) that converts that argument to the corresponding
06427       // parameter of F.
06428       QualType ParamType = Proto->getParamType(ArgIdx);
06429       Candidate.Conversions[ArgIdx + 1]
06430         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
06431                                 /*SuppressUserConversions=*/false,
06432                                 /*InOverloadResolution=*/false,
06433                                 /*AllowObjCWritebackConversion=*/
06434                                   getLangOpts().ObjCAutoRefCount);
06435       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
06436         Candidate.Viable = false;
06437         Candidate.FailureKind = ovl_fail_bad_conversion;
06438         return;
06439       }
06440     } else {
06441       // (C++ 13.3.2p2): For the purposes of overload resolution, any
06442       // argument for which there is no corresponding parameter is
06443       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
06444       Candidate.Conversions[ArgIdx + 1].setEllipsis();
06445     }
06446   }
06447 
06448   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
06449     Candidate.Viable = false;
06450     Candidate.FailureKind = ovl_fail_enable_if;
06451     Candidate.DeductionFailure.Data = FailedAttr;
06452     return;
06453   }
06454 }
06455 
06456 /// \brief Add overload candidates for overloaded operators that are
06457 /// member functions.
06458 ///
06459 /// Add the overloaded operator candidates that are member functions
06460 /// for the operator Op that was used in an operator expression such
06461 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
06462 /// CandidateSet will store the added overload candidates. (C++
06463 /// [over.match.oper]).
06464 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
06465                                        SourceLocation OpLoc,
06466                                        ArrayRef<Expr *> Args,
06467                                        OverloadCandidateSet& CandidateSet,
06468                                        SourceRange OpRange) {
06469   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
06470 
06471   // C++ [over.match.oper]p3:
06472   //   For a unary operator @ with an operand of a type whose
06473   //   cv-unqualified version is T1, and for a binary operator @ with
06474   //   a left operand of a type whose cv-unqualified version is T1 and
06475   //   a right operand of a type whose cv-unqualified version is T2,
06476   //   three sets of candidate functions, designated member
06477   //   candidates, non-member candidates and built-in candidates, are
06478   //   constructed as follows:
06479   QualType T1 = Args[0]->getType();
06480 
06481   //     -- If T1 is a complete class type or a class currently being
06482   //        defined, the set of member candidates is the result of the
06483   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
06484   //        the set of member candidates is empty.
06485   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
06486     // Complete the type if it can be completed.
06487     RequireCompleteType(OpLoc, T1, 0);
06488     // If the type is neither complete nor being defined, bail out now.
06489     if (!T1Rec->getDecl()->getDefinition())
06490       return;
06491 
06492     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
06493     LookupQualifiedName(Operators, T1Rec->getDecl());
06494     Operators.suppressDiagnostics();
06495 
06496     for (LookupResult::iterator Oper = Operators.begin(),
06497                              OperEnd = Operators.end();
06498          Oper != OperEnd;
06499          ++Oper)
06500       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
06501                          Args[0]->Classify(Context), 
06502                          Args.slice(1),
06503                          CandidateSet,
06504                          /* SuppressUserConversions = */ false);
06505   }
06506 }
06507 
06508 /// AddBuiltinCandidate - Add a candidate for a built-in
06509 /// operator. ResultTy and ParamTys are the result and parameter types
06510 /// of the built-in candidate, respectively. Args and NumArgs are the
06511 /// arguments being passed to the candidate. IsAssignmentOperator
06512 /// should be true when this built-in candidate is an assignment
06513 /// operator. NumContextualBoolArguments is the number of arguments
06514 /// (at the beginning of the argument list) that will be contextually
06515 /// converted to bool.
06516 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
06517                                ArrayRef<Expr *> Args,
06518                                OverloadCandidateSet& CandidateSet,
06519                                bool IsAssignmentOperator,
06520                                unsigned NumContextualBoolArguments) {
06521   // Overload resolution is always an unevaluated context.
06522   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
06523 
06524   // Add this candidate
06525   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
06526   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
06527   Candidate.Function = nullptr;
06528   Candidate.IsSurrogate = false;
06529   Candidate.IgnoreObjectArgument = false;
06530   Candidate.BuiltinTypes.ResultTy = ResultTy;
06531   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
06532     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
06533 
06534   // Determine the implicit conversion sequences for each of the
06535   // arguments.
06536   Candidate.Viable = true;
06537   Candidate.ExplicitCallArguments = Args.size();
06538   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
06539     // C++ [over.match.oper]p4:
06540     //   For the built-in assignment operators, conversions of the
06541     //   left operand are restricted as follows:
06542     //     -- no temporaries are introduced to hold the left operand, and
06543     //     -- no user-defined conversions are applied to the left
06544     //        operand to achieve a type match with the left-most
06545     //        parameter of a built-in candidate.
06546     //
06547     // We block these conversions by turning off user-defined
06548     // conversions, since that is the only way that initialization of
06549     // a reference to a non-class type can occur from something that
06550     // is not of the same type.
06551     if (ArgIdx < NumContextualBoolArguments) {
06552       assert(ParamTys[ArgIdx] == Context.BoolTy &&
06553              "Contextual conversion to bool requires bool type");
06554       Candidate.Conversions[ArgIdx]
06555         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
06556     } else {
06557       Candidate.Conversions[ArgIdx]
06558         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
06559                                 ArgIdx == 0 && IsAssignmentOperator,
06560                                 /*InOverloadResolution=*/false,
06561                                 /*AllowObjCWritebackConversion=*/
06562                                   getLangOpts().ObjCAutoRefCount);
06563     }
06564     if (Candidate.Conversions[ArgIdx].isBad()) {
06565       Candidate.Viable = false;
06566       Candidate.FailureKind = ovl_fail_bad_conversion;
06567       break;
06568     }
06569   }
06570 }
06571 
06572 namespace {
06573 
06574 /// BuiltinCandidateTypeSet - A set of types that will be used for the
06575 /// candidate operator functions for built-in operators (C++
06576 /// [over.built]). The types are separated into pointer types and
06577 /// enumeration types.
06578 class BuiltinCandidateTypeSet  {
06579   /// TypeSet - A set of types.
06580   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
06581 
06582   /// PointerTypes - The set of pointer types that will be used in the
06583   /// built-in candidates.
06584   TypeSet PointerTypes;
06585 
06586   /// MemberPointerTypes - The set of member pointer types that will be
06587   /// used in the built-in candidates.
06588   TypeSet MemberPointerTypes;
06589 
06590   /// EnumerationTypes - The set of enumeration types that will be
06591   /// used in the built-in candidates.
06592   TypeSet EnumerationTypes;
06593 
06594   /// \brief The set of vector types that will be used in the built-in
06595   /// candidates.
06596   TypeSet VectorTypes;
06597 
06598   /// \brief A flag indicating non-record types are viable candidates
06599   bool HasNonRecordTypes;
06600 
06601   /// \brief A flag indicating whether either arithmetic or enumeration types
06602   /// were present in the candidate set.
06603   bool HasArithmeticOrEnumeralTypes;
06604 
06605   /// \brief A flag indicating whether the nullptr type was present in the
06606   /// candidate set.
06607   bool HasNullPtrType;
06608   
06609   /// Sema - The semantic analysis instance where we are building the
06610   /// candidate type set.
06611   Sema &SemaRef;
06612 
06613   /// Context - The AST context in which we will build the type sets.
06614   ASTContext &Context;
06615 
06616   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
06617                                                const Qualifiers &VisibleQuals);
06618   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
06619 
06620 public:
06621   /// iterator - Iterates through the types that are part of the set.
06622   typedef TypeSet::iterator iterator;
06623 
06624   BuiltinCandidateTypeSet(Sema &SemaRef)
06625     : HasNonRecordTypes(false),
06626       HasArithmeticOrEnumeralTypes(false),
06627       HasNullPtrType(false),
06628       SemaRef(SemaRef),
06629       Context(SemaRef.Context) { }
06630 
06631   void AddTypesConvertedFrom(QualType Ty,
06632                              SourceLocation Loc,
06633                              bool AllowUserConversions,
06634                              bool AllowExplicitConversions,
06635                              const Qualifiers &VisibleTypeConversionsQuals);
06636 
06637   /// pointer_begin - First pointer type found;
06638   iterator pointer_begin() { return PointerTypes.begin(); }
06639 
06640   /// pointer_end - Past the last pointer type found;
06641   iterator pointer_end() { return PointerTypes.end(); }
06642 
06643   /// member_pointer_begin - First member pointer type found;
06644   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
06645 
06646   /// member_pointer_end - Past the last member pointer type found;
06647   iterator member_pointer_end() { return MemberPointerTypes.end(); }
06648 
06649   /// enumeration_begin - First enumeration type found;
06650   iterator enumeration_begin() { return EnumerationTypes.begin(); }
06651 
06652   /// enumeration_end - Past the last enumeration type found;
06653   iterator enumeration_end() { return EnumerationTypes.end(); }
06654 
06655   iterator vector_begin() { return VectorTypes.begin(); }
06656   iterator vector_end() { return VectorTypes.end(); }
06657 
06658   bool hasNonRecordTypes() { return HasNonRecordTypes; }
06659   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
06660   bool hasNullPtrType() const { return HasNullPtrType; }
06661 };
06662 
06663 } // end anonymous namespace
06664 
06665 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
06666 /// the set of pointer types along with any more-qualified variants of
06667 /// that type. For example, if @p Ty is "int const *", this routine
06668 /// will add "int const *", "int const volatile *", "int const
06669 /// restrict *", and "int const volatile restrict *" to the set of
06670 /// pointer types. Returns true if the add of @p Ty itself succeeded,
06671 /// false otherwise.
06672 ///
06673 /// FIXME: what to do about extended qualifiers?
06674 bool
06675 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
06676                                              const Qualifiers &VisibleQuals) {
06677 
06678   // Insert this type.
06679   if (!PointerTypes.insert(Ty))
06680     return false;
06681 
06682   QualType PointeeTy;
06683   const PointerType *PointerTy = Ty->getAs<PointerType>();
06684   bool buildObjCPtr = false;
06685   if (!PointerTy) {
06686     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
06687     PointeeTy = PTy->getPointeeType();
06688     buildObjCPtr = true;
06689   } else {
06690     PointeeTy = PointerTy->getPointeeType();
06691   }
06692   
06693   // Don't add qualified variants of arrays. For one, they're not allowed
06694   // (the qualifier would sink to the element type), and for another, the
06695   // only overload situation where it matters is subscript or pointer +- int,
06696   // and those shouldn't have qualifier variants anyway.
06697   if (PointeeTy->isArrayType())
06698     return true;
06699   
06700   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
06701   bool hasVolatile = VisibleQuals.hasVolatile();
06702   bool hasRestrict = VisibleQuals.hasRestrict();
06703 
06704   // Iterate through all strict supersets of BaseCVR.
06705   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
06706     if ((CVR | BaseCVR) != CVR) continue;
06707     // Skip over volatile if no volatile found anywhere in the types.
06708     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
06709     
06710     // Skip over restrict if no restrict found anywhere in the types, or if
06711     // the type cannot be restrict-qualified.
06712     if ((CVR & Qualifiers::Restrict) &&
06713         (!hasRestrict ||
06714          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
06715       continue;
06716   
06717     // Build qualified pointee type.
06718     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
06719     
06720     // Build qualified pointer type.
06721     QualType QPointerTy;
06722     if (!buildObjCPtr)
06723       QPointerTy = Context.getPointerType(QPointeeTy);
06724     else
06725       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
06726     
06727     // Insert qualified pointer type.
06728     PointerTypes.insert(QPointerTy);
06729   }
06730 
06731   return true;
06732 }
06733 
06734 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
06735 /// to the set of pointer types along with any more-qualified variants of
06736 /// that type. For example, if @p Ty is "int const *", this routine
06737 /// will add "int const *", "int const volatile *", "int const
06738 /// restrict *", and "int const volatile restrict *" to the set of
06739 /// pointer types. Returns true if the add of @p Ty itself succeeded,
06740 /// false otherwise.
06741 ///
06742 /// FIXME: what to do about extended qualifiers?
06743 bool
06744 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
06745     QualType Ty) {
06746   // Insert this type.
06747   if (!MemberPointerTypes.insert(Ty))
06748     return false;
06749 
06750   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
06751   assert(PointerTy && "type was not a member pointer type!");
06752 
06753   QualType PointeeTy = PointerTy->getPointeeType();
06754   // Don't add qualified variants of arrays. For one, they're not allowed
06755   // (the qualifier would sink to the element type), and for another, the
06756   // only overload situation where it matters is subscript or pointer +- int,
06757   // and those shouldn't have qualifier variants anyway.
06758   if (PointeeTy->isArrayType())
06759     return true;
06760   const Type *ClassTy = PointerTy->getClass();
06761 
06762   // Iterate through all strict supersets of the pointee type's CVR
06763   // qualifiers.
06764   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
06765   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
06766     if ((CVR | BaseCVR) != CVR) continue;
06767 
06768     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
06769     MemberPointerTypes.insert(
06770       Context.getMemberPointerType(QPointeeTy, ClassTy));
06771   }
06772 
06773   return true;
06774 }
06775 
06776 /// AddTypesConvertedFrom - Add each of the types to which the type @p
06777 /// Ty can be implicit converted to the given set of @p Types. We're
06778 /// primarily interested in pointer types and enumeration types. We also
06779 /// take member pointer types, for the conditional operator.
06780 /// AllowUserConversions is true if we should look at the conversion
06781 /// functions of a class type, and AllowExplicitConversions if we
06782 /// should also include the explicit conversion functions of a class
06783 /// type.
06784 void
06785 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
06786                                                SourceLocation Loc,
06787                                                bool AllowUserConversions,
06788                                                bool AllowExplicitConversions,
06789                                                const Qualifiers &VisibleQuals) {
06790   // Only deal with canonical types.
06791   Ty = Context.getCanonicalType(Ty);
06792 
06793   // Look through reference types; they aren't part of the type of an
06794   // expression for the purposes of conversions.
06795   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
06796     Ty = RefTy->getPointeeType();
06797 
06798   // If we're dealing with an array type, decay to the pointer.
06799   if (Ty->isArrayType())
06800     Ty = SemaRef.Context.getArrayDecayedType(Ty);
06801 
06802   // Otherwise, we don't care about qualifiers on the type.
06803   Ty = Ty.getLocalUnqualifiedType();
06804 
06805   // Flag if we ever add a non-record type.
06806   const RecordType *TyRec = Ty->getAs<RecordType>();
06807   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
06808 
06809   // Flag if we encounter an arithmetic type.
06810   HasArithmeticOrEnumeralTypes =
06811     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
06812 
06813   if (Ty->isObjCIdType() || Ty->isObjCClassType())
06814     PointerTypes.insert(Ty);
06815   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
06816     // Insert our type, and its more-qualified variants, into the set
06817     // of types.
06818     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
06819       return;
06820   } else if (Ty->isMemberPointerType()) {
06821     // Member pointers are far easier, since the pointee can't be converted.
06822     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
06823       return;
06824   } else if (Ty->isEnumeralType()) {
06825     HasArithmeticOrEnumeralTypes = true;
06826     EnumerationTypes.insert(Ty);
06827   } else if (Ty->isVectorType()) {
06828     // We treat vector types as arithmetic types in many contexts as an
06829     // extension.
06830     HasArithmeticOrEnumeralTypes = true;
06831     VectorTypes.insert(Ty);
06832   } else if (Ty->isNullPtrType()) {
06833     HasNullPtrType = true;
06834   } else if (AllowUserConversions && TyRec) {
06835     // No conversion functions in incomplete types.
06836     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
06837       return;
06838 
06839     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
06840     std::pair<CXXRecordDecl::conversion_iterator,
06841               CXXRecordDecl::conversion_iterator>
06842       Conversions = ClassDecl->getVisibleConversionFunctions();
06843     for (CXXRecordDecl::conversion_iterator
06844            I = Conversions.first, E = Conversions.second; I != E; ++I) {
06845       NamedDecl *D = I.getDecl();
06846       if (isa<UsingShadowDecl>(D))
06847         D = cast<UsingShadowDecl>(D)->getTargetDecl();
06848 
06849       // Skip conversion function templates; they don't tell us anything
06850       // about which builtin types we can convert to.
06851       if (isa<FunctionTemplateDecl>(D))
06852         continue;
06853 
06854       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
06855       if (AllowExplicitConversions || !Conv->isExplicit()) {
06856         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
06857                               VisibleQuals);
06858       }
06859     }
06860   }
06861 }
06862 
06863 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
06864 /// the volatile- and non-volatile-qualified assignment operators for the
06865 /// given type to the candidate set.
06866 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
06867                                                    QualType T,
06868                                                    ArrayRef<Expr *> Args,
06869                                     OverloadCandidateSet &CandidateSet) {
06870   QualType ParamTypes[2];
06871 
06872   // T& operator=(T&, T)
06873   ParamTypes[0] = S.Context.getLValueReferenceType(T);
06874   ParamTypes[1] = T;
06875   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
06876                         /*IsAssignmentOperator=*/true);
06877 
06878   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
06879     // volatile T& operator=(volatile T&, T)
06880     ParamTypes[0]
06881       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
06882     ParamTypes[1] = T;
06883     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
06884                           /*IsAssignmentOperator=*/true);
06885   }
06886 }
06887 
06888 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
06889 /// if any, found in visible type conversion functions found in ArgExpr's type.
06890 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
06891     Qualifiers VRQuals;
06892     const RecordType *TyRec;
06893     if (const MemberPointerType *RHSMPType =
06894         ArgExpr->getType()->getAs<MemberPointerType>())
06895       TyRec = RHSMPType->getClass()->getAs<RecordType>();
06896     else
06897       TyRec = ArgExpr->getType()->getAs<RecordType>();
06898     if (!TyRec) {
06899       // Just to be safe, assume the worst case.
06900       VRQuals.addVolatile();
06901       VRQuals.addRestrict();
06902       return VRQuals;
06903     }
06904 
06905     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
06906     if (!ClassDecl->hasDefinition())
06907       return VRQuals;
06908 
06909     std::pair<CXXRecordDecl::conversion_iterator,
06910               CXXRecordDecl::conversion_iterator>
06911       Conversions = ClassDecl->getVisibleConversionFunctions();
06912 
06913     for (CXXRecordDecl::conversion_iterator
06914            I = Conversions.first, E = Conversions.second; I != E; ++I) {
06915       NamedDecl *D = I.getDecl();
06916       if (isa<UsingShadowDecl>(D))
06917         D = cast<UsingShadowDecl>(D)->getTargetDecl();
06918       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
06919         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
06920         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
06921           CanTy = ResTypeRef->getPointeeType();
06922         // Need to go down the pointer/mempointer chain and add qualifiers
06923         // as see them.
06924         bool done = false;
06925         while (!done) {
06926           if (CanTy.isRestrictQualified())
06927             VRQuals.addRestrict();
06928           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
06929             CanTy = ResTypePtr->getPointeeType();
06930           else if (const MemberPointerType *ResTypeMPtr =
06931                 CanTy->getAs<MemberPointerType>())
06932             CanTy = ResTypeMPtr->getPointeeType();
06933           else
06934             done = true;
06935           if (CanTy.isVolatileQualified())
06936             VRQuals.addVolatile();
06937           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
06938             return VRQuals;
06939         }
06940       }
06941     }
06942     return VRQuals;
06943 }
06944 
06945 namespace {
06946 
06947 /// \brief Helper class to manage the addition of builtin operator overload
06948 /// candidates. It provides shared state and utility methods used throughout
06949 /// the process, as well as a helper method to add each group of builtin
06950 /// operator overloads from the standard to a candidate set.
06951 class BuiltinOperatorOverloadBuilder {
06952   // Common instance state available to all overload candidate addition methods.
06953   Sema &S;
06954   ArrayRef<Expr *> Args;
06955   Qualifiers VisibleTypeConversionsQuals;
06956   bool HasArithmeticOrEnumeralCandidateType;
06957   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
06958   OverloadCandidateSet &CandidateSet;
06959 
06960   // Define some constants used to index and iterate over the arithemetic types
06961   // provided via the getArithmeticType() method below.
06962   // The "promoted arithmetic types" are the arithmetic
06963   // types are that preserved by promotion (C++ [over.built]p2).
06964   static const unsigned FirstIntegralType = 3;
06965   static const unsigned LastIntegralType = 20;
06966   static const unsigned FirstPromotedIntegralType = 3,
06967                         LastPromotedIntegralType = 11;
06968   static const unsigned FirstPromotedArithmeticType = 0,
06969                         LastPromotedArithmeticType = 11;
06970   static const unsigned NumArithmeticTypes = 20;
06971 
06972   /// \brief Get the canonical type for a given arithmetic type index.
06973   CanQualType getArithmeticType(unsigned index) {
06974     assert(index < NumArithmeticTypes);
06975     static CanQualType ASTContext::* const
06976       ArithmeticTypes[NumArithmeticTypes] = {
06977       // Start of promoted types.
06978       &ASTContext::FloatTy,
06979       &ASTContext::DoubleTy,
06980       &ASTContext::LongDoubleTy,
06981 
06982       // Start of integral types.
06983       &ASTContext::IntTy,
06984       &ASTContext::LongTy,
06985       &ASTContext::LongLongTy,
06986       &ASTContext::Int128Ty,
06987       &ASTContext::UnsignedIntTy,
06988       &ASTContext::UnsignedLongTy,
06989       &ASTContext::UnsignedLongLongTy,
06990       &ASTContext::UnsignedInt128Ty,
06991       // End of promoted types.
06992 
06993       &ASTContext::BoolTy,
06994       &ASTContext::CharTy,
06995       &ASTContext::WCharTy,
06996       &ASTContext::Char16Ty,
06997       &ASTContext::Char32Ty,
06998       &ASTContext::SignedCharTy,
06999       &ASTContext::ShortTy,
07000       &ASTContext::UnsignedCharTy,
07001       &ASTContext::UnsignedShortTy,
07002       // End of integral types.
07003       // FIXME: What about complex? What about half?
07004     };
07005     return S.Context.*ArithmeticTypes[index];
07006   }
07007 
07008   /// \brief Gets the canonical type resulting from the usual arithemetic
07009   /// converions for the given arithmetic types.
07010   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
07011     // Accelerator table for performing the usual arithmetic conversions.
07012     // The rules are basically:
07013     //   - if either is floating-point, use the wider floating-point
07014     //   - if same signedness, use the higher rank
07015     //   - if same size, use unsigned of the higher rank
07016     //   - use the larger type
07017     // These rules, together with the axiom that higher ranks are
07018     // never smaller, are sufficient to precompute all of these results
07019     // *except* when dealing with signed types of higher rank.
07020     // (we could precompute SLL x UI for all known platforms, but it's
07021     // better not to make any assumptions).
07022     // We assume that int128 has a higher rank than long long on all platforms.
07023     enum PromotedType {
07024             Dep=-1,
07025             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
07026     };
07027     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
07028                                         [LastPromotedArithmeticType] = {
07029 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
07030 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
07031 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
07032 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
07033 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
07034 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
07035 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
07036 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
07037 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
07038 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
07039 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
07040     };
07041 
07042     assert(L < LastPromotedArithmeticType);
07043     assert(R < LastPromotedArithmeticType);
07044     int Idx = ConversionsTable[L][R];
07045 
07046     // Fast path: the table gives us a concrete answer.
07047     if (Idx != Dep) return getArithmeticType(Idx);
07048 
07049     // Slow path: we need to compare widths.
07050     // An invariant is that the signed type has higher rank.
07051     CanQualType LT = getArithmeticType(L),
07052                 RT = getArithmeticType(R);
07053     unsigned LW = S.Context.getIntWidth(LT),
07054              RW = S.Context.getIntWidth(RT);
07055 
07056     // If they're different widths, use the signed type.
07057     if (LW > RW) return LT;
07058     else if (LW < RW) return RT;
07059 
07060     // Otherwise, use the unsigned type of the signed type's rank.
07061     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
07062     assert(L == SLL || R == SLL);
07063     return S.Context.UnsignedLongLongTy;
07064   }
07065 
07066   /// \brief Helper method to factor out the common pattern of adding overloads
07067   /// for '++' and '--' builtin operators.
07068   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
07069                                            bool HasVolatile,
07070                                            bool HasRestrict) {
07071     QualType ParamTypes[2] = {
07072       S.Context.getLValueReferenceType(CandidateTy),
07073       S.Context.IntTy
07074     };
07075 
07076     // Non-volatile version.
07077     if (Args.size() == 1)
07078       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
07079     else
07080       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
07081 
07082     // Use a heuristic to reduce number of builtin candidates in the set:
07083     // add volatile version only if there are conversions to a volatile type.
07084     if (HasVolatile) {
07085       ParamTypes[0] =
07086         S.Context.getLValueReferenceType(
07087           S.Context.getVolatileType(CandidateTy));
07088       if (Args.size() == 1)
07089         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
07090       else
07091         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
07092     }
07093     
07094     // Add restrict version only if there are conversions to a restrict type
07095     // and our candidate type is a non-restrict-qualified pointer.
07096     if (HasRestrict && CandidateTy->isAnyPointerType() &&
07097         !CandidateTy.isRestrictQualified()) {
07098       ParamTypes[0]
07099         = S.Context.getLValueReferenceType(
07100             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
07101       if (Args.size() == 1)
07102         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
07103       else
07104         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
07105       
07106       if (HasVolatile) {
07107         ParamTypes[0]
07108           = S.Context.getLValueReferenceType(
07109               S.Context.getCVRQualifiedType(CandidateTy,
07110                                             (Qualifiers::Volatile |
07111                                              Qualifiers::Restrict)));
07112         if (Args.size() == 1)
07113           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
07114         else
07115           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
07116       }
07117     }
07118 
07119   }
07120 
07121 public:
07122   BuiltinOperatorOverloadBuilder(
07123     Sema &S, ArrayRef<Expr *> Args,
07124     Qualifiers VisibleTypeConversionsQuals,
07125     bool HasArithmeticOrEnumeralCandidateType,
07126     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
07127     OverloadCandidateSet &CandidateSet)
07128     : S(S), Args(Args),
07129       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
07130       HasArithmeticOrEnumeralCandidateType(
07131         HasArithmeticOrEnumeralCandidateType),
07132       CandidateTypes(CandidateTypes),
07133       CandidateSet(CandidateSet) {
07134     // Validate some of our static helper constants in debug builds.
07135     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
07136            "Invalid first promoted integral type");
07137     assert(getArithmeticType(LastPromotedIntegralType - 1)
07138              == S.Context.UnsignedInt128Ty &&
07139            "Invalid last promoted integral type");
07140     assert(getArithmeticType(FirstPromotedArithmeticType)
07141              == S.Context.FloatTy &&
07142            "Invalid first promoted arithmetic type");
07143     assert(getArithmeticType(LastPromotedArithmeticType - 1)
07144              == S.Context.UnsignedInt128Ty &&
07145            "Invalid last promoted arithmetic type");
07146   }
07147 
07148   // C++ [over.built]p3:
07149   //
07150   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
07151   //   is either volatile or empty, there exist candidate operator
07152   //   functions of the form
07153   //
07154   //       VQ T&      operator++(VQ T&);
07155   //       T          operator++(VQ T&, int);
07156   //
07157   // C++ [over.built]p4:
07158   //
07159   //   For every pair (T, VQ), where T is an arithmetic type other
07160   //   than bool, and VQ is either volatile or empty, there exist
07161   //   candidate operator functions of the form
07162   //
07163   //       VQ T&      operator--(VQ T&);
07164   //       T          operator--(VQ T&, int);
07165   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
07166     if (!HasArithmeticOrEnumeralCandidateType)
07167       return;
07168 
07169     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
07170          Arith < NumArithmeticTypes; ++Arith) {
07171       addPlusPlusMinusMinusStyleOverloads(
07172         getArithmeticType(Arith),
07173         VisibleTypeConversionsQuals.hasVolatile(),
07174         VisibleTypeConversionsQuals.hasRestrict());
07175     }
07176   }
07177 
07178   // C++ [over.built]p5:
07179   //
07180   //   For every pair (T, VQ), where T is a cv-qualified or
07181   //   cv-unqualified object type, and VQ is either volatile or
07182   //   empty, there exist candidate operator functions of the form
07183   //
07184   //       T*VQ&      operator++(T*VQ&);
07185   //       T*VQ&      operator--(T*VQ&);
07186   //       T*         operator++(T*VQ&, int);
07187   //       T*         operator--(T*VQ&, int);
07188   void addPlusPlusMinusMinusPointerOverloads() {
07189     for (BuiltinCandidateTypeSet::iterator
07190               Ptr = CandidateTypes[0].pointer_begin(),
07191            PtrEnd = CandidateTypes[0].pointer_end();
07192          Ptr != PtrEnd; ++Ptr) {
07193       // Skip pointer types that aren't pointers to object types.
07194       if (!(*Ptr)->getPointeeType()->isObjectType())
07195         continue;
07196 
07197       addPlusPlusMinusMinusStyleOverloads(*Ptr,
07198         (!(*Ptr).isVolatileQualified() &&
07199          VisibleTypeConversionsQuals.hasVolatile()),
07200         (!(*Ptr).isRestrictQualified() &&
07201          VisibleTypeConversionsQuals.hasRestrict()));
07202     }
07203   }
07204 
07205   // C++ [over.built]p6:
07206   //   For every cv-qualified or cv-unqualified object type T, there
07207   //   exist candidate operator functions of the form
07208   //
07209   //       T&         operator*(T*);
07210   //
07211   // C++ [over.built]p7:
07212   //   For every function type T that does not have cv-qualifiers or a
07213   //   ref-qualifier, there exist candidate operator functions of the form
07214   //       T&         operator*(T*);
07215   void addUnaryStarPointerOverloads() {
07216     for (BuiltinCandidateTypeSet::iterator
07217               Ptr = CandidateTypes[0].pointer_begin(),
07218            PtrEnd = CandidateTypes[0].pointer_end();
07219          Ptr != PtrEnd; ++Ptr) {
07220       QualType ParamTy = *Ptr;
07221       QualType PointeeTy = ParamTy->getPointeeType();
07222       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
07223         continue;
07224 
07225       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
07226         if (Proto->getTypeQuals() || Proto->getRefQualifier())
07227           continue;
07228 
07229       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
07230                             &ParamTy, Args, CandidateSet);
07231     }
07232   }
07233 
07234   // C++ [over.built]p9:
07235   //  For every promoted arithmetic type T, there exist candidate
07236   //  operator functions of the form
07237   //
07238   //       T         operator+(T);
07239   //       T         operator-(T);
07240   void addUnaryPlusOrMinusArithmeticOverloads() {
07241     if (!HasArithmeticOrEnumeralCandidateType)
07242       return;
07243 
07244     for (unsigned Arith = FirstPromotedArithmeticType;
07245          Arith < LastPromotedArithmeticType; ++Arith) {
07246       QualType ArithTy = getArithmeticType(Arith);
07247       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
07248     }
07249 
07250     // Extension: We also add these operators for vector types.
07251     for (BuiltinCandidateTypeSet::iterator
07252               Vec = CandidateTypes[0].vector_begin(),
07253            VecEnd = CandidateTypes[0].vector_end();
07254          Vec != VecEnd; ++Vec) {
07255       QualType VecTy = *Vec;
07256       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
07257     }
07258   }
07259 
07260   // C++ [over.built]p8:
07261   //   For every type T, there exist candidate operator functions of
07262   //   the form
07263   //
07264   //       T*         operator+(T*);
07265   void addUnaryPlusPointerOverloads() {
07266     for (BuiltinCandidateTypeSet::iterator
07267               Ptr = CandidateTypes[0].pointer_begin(),
07268            PtrEnd = CandidateTypes[0].pointer_end();
07269          Ptr != PtrEnd; ++Ptr) {
07270       QualType ParamTy = *Ptr;
07271       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
07272     }
07273   }
07274 
07275   // C++ [over.built]p10:
07276   //   For every promoted integral type T, there exist candidate
07277   //   operator functions of the form
07278   //
07279   //        T         operator~(T);
07280   void addUnaryTildePromotedIntegralOverloads() {
07281     if (!HasArithmeticOrEnumeralCandidateType)
07282       return;
07283 
07284     for (unsigned Int = FirstPromotedIntegralType;
07285          Int < LastPromotedIntegralType; ++Int) {
07286       QualType IntTy = getArithmeticType(Int);
07287       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
07288     }
07289 
07290     // Extension: We also add this operator for vector types.
07291     for (BuiltinCandidateTypeSet::iterator
07292               Vec = CandidateTypes[0].vector_begin(),
07293            VecEnd = CandidateTypes[0].vector_end();
07294          Vec != VecEnd; ++Vec) {
07295       QualType VecTy = *Vec;
07296       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
07297     }
07298   }
07299 
07300   // C++ [over.match.oper]p16:
07301   //   For every pointer to member type T, there exist candidate operator
07302   //   functions of the form
07303   //
07304   //        bool operator==(T,T);
07305   //        bool operator!=(T,T);
07306   void addEqualEqualOrNotEqualMemberPointerOverloads() {
07307     /// Set of (canonical) types that we've already handled.
07308     llvm::SmallPtrSet<QualType, 8> AddedTypes;
07309 
07310     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
07311       for (BuiltinCandidateTypeSet::iterator
07312                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
07313              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
07314            MemPtr != MemPtrEnd;
07315            ++MemPtr) {
07316         // Don't add the same builtin candidate twice.
07317         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
07318           continue;
07319 
07320         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
07321         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
07322       }
07323     }
07324   }
07325 
07326   // C++ [over.built]p15:
07327   //
07328   //   For every T, where T is an enumeration type, a pointer type, or 
07329   //   std::nullptr_t, there exist candidate operator functions of the form
07330   //
07331   //        bool       operator<(T, T);
07332   //        bool       operator>(T, T);
07333   //        bool       operator<=(T, T);
07334   //        bool       operator>=(T, T);
07335   //        bool       operator==(T, T);
07336   //        bool       operator!=(T, T);
07337   void addRelationalPointerOrEnumeralOverloads() {
07338     // C++ [over.match.oper]p3:
07339     //   [...]the built-in candidates include all of the candidate operator
07340     //   functions defined in 13.6 that, compared to the given operator, [...]
07341     //   do not have the same parameter-type-list as any non-template non-member
07342     //   candidate.
07343     //
07344     // Note that in practice, this only affects enumeration types because there
07345     // aren't any built-in candidates of record type, and a user-defined operator
07346     // must have an operand of record or enumeration type. Also, the only other
07347     // overloaded operator with enumeration arguments, operator=,
07348     // cannot be overloaded for enumeration types, so this is the only place
07349     // where we must suppress candidates like this.
07350     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
07351       UserDefinedBinaryOperators;
07352 
07353     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
07354       if (CandidateTypes[ArgIdx].enumeration_begin() !=
07355           CandidateTypes[ArgIdx].enumeration_end()) {
07356         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
07357                                          CEnd = CandidateSet.end();
07358              C != CEnd; ++C) {
07359           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
07360             continue;
07361 
07362           if (C->Function->isFunctionTemplateSpecialization())
07363             continue;
07364 
07365           QualType FirstParamType =
07366             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
07367           QualType SecondParamType =
07368             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
07369 
07370           // Skip if either parameter isn't of enumeral type.
07371           if (!FirstParamType->isEnumeralType() ||
07372               !SecondParamType->isEnumeralType())
07373             continue;
07374 
07375           // Add this operator to the set of known user-defined operators.
07376           UserDefinedBinaryOperators.insert(
07377             std::make_pair(S.Context.getCanonicalType(FirstParamType),
07378                            S.Context.getCanonicalType(SecondParamType)));
07379         }
07380       }
07381     }
07382 
07383     /// Set of (canonical) types that we've already handled.
07384     llvm::SmallPtrSet<QualType, 8> AddedTypes;
07385 
07386     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
07387       for (BuiltinCandidateTypeSet::iterator
07388                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
07389              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
07390            Ptr != PtrEnd; ++Ptr) {
07391         // Don't add the same builtin candidate twice.
07392         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
07393           continue;
07394 
07395         QualType ParamTypes[2] = { *Ptr, *Ptr };
07396         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
07397       }
07398       for (BuiltinCandidateTypeSet::iterator
07399                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
07400              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
07401            Enum != EnumEnd; ++Enum) {
07402         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
07403 
07404         // Don't add the same builtin candidate twice, or if a user defined
07405         // candidate exists.
07406         if (!AddedTypes.insert(CanonType) ||
07407             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
07408                                                             CanonType)))
07409           continue;
07410 
07411         QualType ParamTypes[2] = { *Enum, *Enum };
07412         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
07413       }
07414       
07415       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
07416         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
07417         if (AddedTypes.insert(NullPtrTy) &&
07418             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
07419                                                              NullPtrTy))) {
07420           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
07421           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
07422                                 CandidateSet);
07423         }
07424       }
07425     }
07426   }
07427 
07428   // C++ [over.built]p13:
07429   //
07430   //   For every cv-qualified or cv-unqualified object type T
07431   //   there exist candidate operator functions of the form
07432   //
07433   //      T*         operator+(T*, ptrdiff_t);
07434   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
07435   //      T*         operator-(T*, ptrdiff_t);
07436   //      T*         operator+(ptrdiff_t, T*);
07437   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
07438   //
07439   // C++ [over.built]p14:
07440   //
07441   //   For every T, where T is a pointer to object type, there
07442   //   exist candidate operator functions of the form
07443   //
07444   //      ptrdiff_t  operator-(T, T);
07445   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
07446     /// Set of (canonical) types that we've already handled.
07447     llvm::SmallPtrSet<QualType, 8> AddedTypes;
07448 
07449     for (int Arg = 0; Arg < 2; ++Arg) {
07450       QualType AsymetricParamTypes[2] = {
07451         S.Context.getPointerDiffType(),
07452         S.Context.getPointerDiffType(),
07453       };
07454       for (BuiltinCandidateTypeSet::iterator
07455                 Ptr = CandidateTypes[Arg].pointer_begin(),
07456              PtrEnd = CandidateTypes[Arg].pointer_end();
07457            Ptr != PtrEnd; ++Ptr) {
07458         QualType PointeeTy = (*Ptr)->getPointeeType();
07459         if (!PointeeTy->isObjectType())
07460           continue;
07461 
07462         AsymetricParamTypes[Arg] = *Ptr;
07463         if (Arg == 0 || Op == OO_Plus) {
07464           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
07465           // T* operator+(ptrdiff_t, T*);
07466           S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
07467         }
07468         if (Op == OO_Minus) {
07469           // ptrdiff_t operator-(T, T);
07470           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
07471             continue;
07472 
07473           QualType ParamTypes[2] = { *Ptr, *Ptr };
07474           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
07475                                 Args, CandidateSet);
07476         }
07477       }
07478     }
07479   }
07480 
07481   // C++ [over.built]p12:
07482   //
07483   //   For every pair of promoted arithmetic types L and R, there
07484   //   exist candidate operator functions of the form
07485   //
07486   //        LR         operator*(L, R);
07487   //        LR         operator/(L, R);
07488   //        LR         operator+(L, R);
07489   //        LR         operator-(L, R);
07490   //        bool       operator<(L, R);
07491   //        bool       operator>(L, R);
07492   //        bool       operator<=(L, R);
07493   //        bool       operator>=(L, R);
07494   //        bool       operator==(L, R);
07495   //        bool       operator!=(L, R);
07496   //
07497   //   where LR is the result of the usual arithmetic conversions
07498   //   between types L and R.
07499   //
07500   // C++ [over.built]p24:
07501   //
07502   //   For every pair of promoted arithmetic types L and R, there exist
07503   //   candidate operator functions of the form
07504   //
07505   //        LR       operator?(bool, L, R);
07506   //
07507   //   where LR is the result of the usual arithmetic conversions
07508   //   between types L and R.
07509   // Our candidates ignore the first parameter.
07510   void addGenericBinaryArithmeticOverloads(bool isComparison) {
07511     if (!HasArithmeticOrEnumeralCandidateType)
07512       return;
07513 
07514     for (unsigned Left = FirstPromotedArithmeticType;
07515          Left < LastPromotedArithmeticType; ++Left) {
07516       for (unsigned Right = FirstPromotedArithmeticType;
07517            Right < LastPromotedArithmeticType; ++Right) {
07518         QualType LandR[2] = { getArithmeticType(Left),
07519                               getArithmeticType(Right) };
07520         QualType Result =
07521           isComparison ? S.Context.BoolTy
07522                        : getUsualArithmeticConversions(Left, Right);
07523         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
07524       }
07525     }
07526 
07527     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
07528     // conditional operator for vector types.
07529     for (BuiltinCandidateTypeSet::iterator
07530               Vec1 = CandidateTypes[0].vector_begin(),
07531            Vec1End = CandidateTypes[0].vector_end();
07532          Vec1 != Vec1End; ++Vec1) {
07533       for (BuiltinCandidateTypeSet::iterator
07534                 Vec2 = CandidateTypes[1].vector_begin(),
07535              Vec2End = CandidateTypes[1].vector_end();
07536            Vec2 != Vec2End; ++Vec2) {
07537         QualType LandR[2] = { *Vec1, *Vec2 };
07538         QualType Result = S.Context.BoolTy;
07539         if (!isComparison) {
07540           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
07541             Result = *Vec1;
07542           else
07543             Result = *Vec2;
07544         }
07545 
07546         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
07547       }
07548     }
07549   }
07550 
07551   // C++ [over.built]p17:
07552   //
07553   //   For every pair of promoted integral types L and R, there
07554   //   exist candidate operator functions of the form
07555   //
07556   //      LR         operator%(L, R);
07557   //      LR         operator&(L, R);
07558   //      LR         operator^(L, R);
07559   //      LR         operator|(L, R);
07560   //      L          operator<<(L, R);
07561   //      L          operator>>(L, R);
07562   //
07563   //   where LR is the result of the usual arithmetic conversions
07564   //   between types L and R.
07565   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
07566     if (!HasArithmeticOrEnumeralCandidateType)
07567       return;
07568 
07569     for (unsigned Left = FirstPromotedIntegralType;
07570          Left < LastPromotedIntegralType; ++Left) {
07571       for (unsigned Right = FirstPromotedIntegralType;
07572            Right < LastPromotedIntegralType; ++Right) {
07573         QualType LandR[2] = { getArithmeticType(Left),
07574                               getArithmeticType(Right) };
07575         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
07576             ? LandR[0]
07577             : getUsualArithmeticConversions(Left, Right);
07578         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
07579       }
07580     }
07581   }
07582 
07583   // C++ [over.built]p20:
07584   //
07585   //   For every pair (T, VQ), where T is an enumeration or
07586   //   pointer to member type and VQ is either volatile or
07587   //   empty, there exist candidate operator functions of the form
07588   //
07589   //        VQ T&      operator=(VQ T&, T);
07590   void addAssignmentMemberPointerOrEnumeralOverloads() {
07591     /// Set of (canonical) types that we've already handled.
07592     llvm::SmallPtrSet<QualType, 8> AddedTypes;
07593 
07594     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
07595       for (BuiltinCandidateTypeSet::iterator
07596                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
07597              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
07598            Enum != EnumEnd; ++Enum) {
07599         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
07600           continue;
07601 
07602         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
07603       }
07604 
07605       for (BuiltinCandidateTypeSet::iterator
07606                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
07607              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
07608            MemPtr != MemPtrEnd; ++MemPtr) {
07609         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
07610           continue;
07611 
07612         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
07613       }
07614     }
07615   }
07616 
07617   // C++ [over.built]p19:
07618   //
07619   //   For every pair (T, VQ), where T is any type and VQ is either
07620   //   volatile or empty, there exist candidate operator functions
07621   //   of the form
07622   //
07623   //        T*VQ&      operator=(T*VQ&, T*);
07624   //
07625   // C++ [over.built]p21:
07626   //
07627   //   For every pair (T, VQ), where T is a cv-qualified or
07628   //   cv-unqualified object type and VQ is either volatile or
07629   //   empty, there exist candidate operator functions of the form
07630   //
07631   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
07632   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
07633   void addAssignmentPointerOverloads(bool isEqualOp) {
07634     /// Set of (canonical) types that we've already handled.
07635     llvm::SmallPtrSet<QualType, 8> AddedTypes;
07636 
07637     for (BuiltinCandidateTypeSet::iterator
07638               Ptr = CandidateTypes[0].pointer_begin(),
07639            PtrEnd = CandidateTypes[0].pointer_end();
07640          Ptr != PtrEnd; ++Ptr) {
07641       // If this is operator=, keep track of the builtin candidates we added.
07642       if (isEqualOp)
07643         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
07644       else if (!(*Ptr)->getPointeeType()->isObjectType())
07645         continue;
07646 
07647       // non-volatile version
07648       QualType ParamTypes[2] = {
07649         S.Context.getLValueReferenceType(*Ptr),
07650         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
07651       };
07652       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
07653                             /*IsAssigmentOperator=*/ isEqualOp);
07654 
07655       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
07656                           VisibleTypeConversionsQuals.hasVolatile();
07657       if (NeedVolatile) {
07658         // volatile version
07659         ParamTypes[0] =
07660           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
07661         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
07662                               /*IsAssigmentOperator=*/isEqualOp);
07663       }
07664       
07665       if (!(*Ptr).isRestrictQualified() &&
07666           VisibleTypeConversionsQuals.hasRestrict()) {
07667         // restrict version
07668         ParamTypes[0]
07669           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
07670         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
07671                               /*IsAssigmentOperator=*/isEqualOp);
07672         
07673         if (NeedVolatile) {
07674           // volatile restrict version
07675           ParamTypes[0]
07676             = S.Context.getLValueReferenceType(
07677                 S.Context.getCVRQualifiedType(*Ptr,
07678                                               (Qualifiers::Volatile |
07679                                                Qualifiers::Restrict)));
07680           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
07681                                 /*IsAssigmentOperator=*/isEqualOp);
07682         }
07683       }
07684     }
07685 
07686     if (isEqualOp) {
07687       for (BuiltinCandidateTypeSet::iterator
07688                 Ptr = CandidateTypes[1].pointer_begin(),
07689              PtrEnd = CandidateTypes[1].pointer_end();
07690            Ptr != PtrEnd; ++Ptr) {
07691         // Make sure we don't add the same candidate twice.
07692         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
07693           continue;
07694 
07695         QualType ParamTypes[2] = {
07696           S.Context.getLValueReferenceType(*Ptr),
07697           *Ptr,
07698         };
07699 
07700         // non-volatile version
07701         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
07702                               /*IsAssigmentOperator=*/true);
07703 
07704         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
07705                            VisibleTypeConversionsQuals.hasVolatile();
07706         if (NeedVolatile) {
07707           // volatile version
07708           ParamTypes[0] =
07709             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
07710           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
07711                                 /*IsAssigmentOperator=*/true);
07712         }
07713       
07714         if (!(*Ptr).isRestrictQualified() &&
07715             VisibleTypeConversionsQuals.hasRestrict()) {
07716           // restrict version
07717           ParamTypes[0]
07718             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
07719           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
07720                                 /*IsAssigmentOperator=*/true);
07721           
07722           if (NeedVolatile) {
07723             // volatile restrict version
07724             ParamTypes[0]
07725               = S.Context.getLValueReferenceType(
07726                   S.Context.getCVRQualifiedType(*Ptr,
07727                                                 (Qualifiers::Volatile |
07728                                                  Qualifiers::Restrict)));
07729             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
07730                                   /*IsAssigmentOperator=*/true);
07731           }
07732         }
07733       }
07734     }
07735   }
07736 
07737   // C++ [over.built]p18:
07738   //
07739   //   For every triple (L, VQ, R), where L is an arithmetic type,
07740   //   VQ is either volatile or empty, and R is a promoted
07741   //   arithmetic type, there exist candidate operator functions of
07742   //   the form
07743   //
07744   //        VQ L&      operator=(VQ L&, R);
07745   //        VQ L&      operator*=(VQ L&, R);
07746   //        VQ L&      operator/=(VQ L&, R);
07747   //        VQ L&      operator+=(VQ L&, R);
07748   //        VQ L&      operator-=(VQ L&, R);
07749   void addAssignmentArithmeticOverloads(bool isEqualOp) {
07750     if (!HasArithmeticOrEnumeralCandidateType)
07751       return;
07752 
07753     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
07754       for (unsigned Right = FirstPromotedArithmeticType;
07755            Right < LastPromotedArithmeticType; ++Right) {
07756         QualType ParamTypes[2];
07757         ParamTypes[1] = getArithmeticType(Right);
07758 
07759         // Add this built-in operator as a candidate (VQ is empty).
07760         ParamTypes[0] =
07761           S.Context.getLValueReferenceType(getArithmeticType(Left));
07762         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
07763                               /*IsAssigmentOperator=*/isEqualOp);
07764 
07765         // Add this built-in operator as a candidate (VQ is 'volatile').
07766         if (VisibleTypeConversionsQuals.hasVolatile()) {
07767           ParamTypes[0] =
07768             S.Context.getVolatileType(getArithmeticType(Left));
07769           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
07770           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
07771                                 /*IsAssigmentOperator=*/isEqualOp);
07772         }
07773       }
07774     }
07775 
07776     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
07777     for (BuiltinCandidateTypeSet::iterator
07778               Vec1 = CandidateTypes[0].vector_begin(),
07779            Vec1End = CandidateTypes[0].vector_end();
07780          Vec1 != Vec1End; ++Vec1) {
07781       for (BuiltinCandidateTypeSet::iterator
07782                 Vec2 = CandidateTypes[1].vector_begin(),
07783              Vec2End = CandidateTypes[1].vector_end();
07784            Vec2 != Vec2End; ++Vec2) {
07785         QualType ParamTypes[2];
07786         ParamTypes[1] = *Vec2;
07787         // Add this built-in operator as a candidate (VQ is empty).
07788         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
07789         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
07790                               /*IsAssigmentOperator=*/isEqualOp);
07791 
07792         // Add this built-in operator as a candidate (VQ is 'volatile').
07793         if (VisibleTypeConversionsQuals.hasVolatile()) {
07794           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
07795           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
07796           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
07797                                 /*IsAssigmentOperator=*/isEqualOp);
07798         }
07799       }
07800     }
07801   }
07802 
07803   // C++ [over.built]p22:
07804   //
07805   //   For every triple (L, VQ, R), where L is an integral type, VQ
07806   //   is either volatile or empty, and R is a promoted integral
07807   //   type, there exist candidate operator functions of the form
07808   //
07809   //        VQ L&       operator%=(VQ L&, R);
07810   //        VQ L&       operator<<=(VQ L&, R);
07811   //        VQ L&       operator>>=(VQ L&, R);
07812   //        VQ L&       operator&=(VQ L&, R);
07813   //        VQ L&       operator^=(VQ L&, R);
07814   //        VQ L&       operator|=(VQ L&, R);
07815   void addAssignmentIntegralOverloads() {
07816     if (!HasArithmeticOrEnumeralCandidateType)
07817       return;
07818 
07819     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
07820       for (unsigned Right = FirstPromotedIntegralType;
07821            Right < LastPromotedIntegralType; ++Right) {
07822         QualType ParamTypes[2];
07823         ParamTypes[1] = getArithmeticType(Right);
07824 
07825         // Add this built-in operator as a candidate (VQ is empty).
07826         ParamTypes[0] =
07827           S.Context.getLValueReferenceType(getArithmeticType(Left));
07828         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
07829         if (VisibleTypeConversionsQuals.hasVolatile()) {
07830           // Add this built-in operator as a candidate (VQ is 'volatile').
07831           ParamTypes[0] = getArithmeticType(Left);
07832           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
07833           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
07834           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
07835         }
07836       }
07837     }
07838   }
07839 
07840   // C++ [over.operator]p23:
07841   //
07842   //   There also exist candidate operator functions of the form
07843   //
07844   //        bool        operator!(bool);
07845   //        bool        operator&&(bool, bool);
07846   //        bool        operator||(bool, bool);
07847   void addExclaimOverload() {
07848     QualType ParamTy = S.Context.BoolTy;
07849     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
07850                           /*IsAssignmentOperator=*/false,
07851                           /*NumContextualBoolArguments=*/1);
07852   }
07853   void addAmpAmpOrPipePipeOverload() {
07854     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
07855     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
07856                           /*IsAssignmentOperator=*/false,
07857                           /*NumContextualBoolArguments=*/2);
07858   }
07859 
07860   // C++ [over.built]p13:
07861   //
07862   //   For every cv-qualified or cv-unqualified object type T there
07863   //   exist candidate operator functions of the form
07864   //
07865   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
07866   //        T&         operator[](T*, ptrdiff_t);
07867   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
07868   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
07869   //        T&         operator[](ptrdiff_t, T*);
07870   void addSubscriptOverloads() {
07871     for (BuiltinCandidateTypeSet::iterator
07872               Ptr = CandidateTypes[0].pointer_begin(),
07873            PtrEnd = CandidateTypes[0].pointer_end();
07874          Ptr != PtrEnd; ++Ptr) {
07875       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
07876       QualType PointeeType = (*Ptr)->getPointeeType();
07877       if (!PointeeType->isObjectType())
07878         continue;
07879 
07880       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
07881 
07882       // T& operator[](T*, ptrdiff_t)
07883       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
07884     }
07885 
07886     for (BuiltinCandidateTypeSet::iterator
07887               Ptr = CandidateTypes[1].pointer_begin(),
07888            PtrEnd = CandidateTypes[1].pointer_end();
07889          Ptr != PtrEnd; ++Ptr) {
07890       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
07891       QualType PointeeType = (*Ptr)->getPointeeType();
07892       if (!PointeeType->isObjectType())
07893         continue;
07894 
07895       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
07896 
07897       // T& operator[](ptrdiff_t, T*)
07898       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
07899     }
07900   }
07901 
07902   // C++ [over.built]p11:
07903   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
07904   //    C1 is the same type as C2 or is a derived class of C2, T is an object
07905   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
07906   //    there exist candidate operator functions of the form
07907   //
07908   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
07909   //
07910   //    where CV12 is the union of CV1 and CV2.
07911   void addArrowStarOverloads() {
07912     for (BuiltinCandidateTypeSet::iterator
07913              Ptr = CandidateTypes[0].pointer_begin(),
07914            PtrEnd = CandidateTypes[0].pointer_end();
07915          Ptr != PtrEnd; ++Ptr) {
07916       QualType C1Ty = (*Ptr);
07917       QualType C1;
07918       QualifierCollector Q1;
07919       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
07920       if (!isa<RecordType>(C1))
07921         continue;
07922       // heuristic to reduce number of builtin candidates in the set.
07923       // Add volatile/restrict version only if there are conversions to a
07924       // volatile/restrict type.
07925       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
07926         continue;
07927       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
07928         continue;
07929       for (BuiltinCandidateTypeSet::iterator
07930                 MemPtr = CandidateTypes[1].member_pointer_begin(),
07931              MemPtrEnd = CandidateTypes[1].member_pointer_end();
07932            MemPtr != MemPtrEnd; ++MemPtr) {
07933         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
07934         QualType C2 = QualType(mptr->getClass(), 0);
07935         C2 = C2.getUnqualifiedType();
07936         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
07937           break;
07938         QualType ParamTypes[2] = { *Ptr, *MemPtr };
07939         // build CV12 T&
07940         QualType T = mptr->getPointeeType();
07941         if (!VisibleTypeConversionsQuals.hasVolatile() &&
07942             T.isVolatileQualified())
07943           continue;
07944         if (!VisibleTypeConversionsQuals.hasRestrict() &&
07945             T.isRestrictQualified())
07946           continue;
07947         T = Q1.apply(S.Context, T);
07948         QualType ResultTy = S.Context.getLValueReferenceType(T);
07949         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
07950       }
07951     }
07952   }
07953 
07954   // Note that we don't consider the first argument, since it has been
07955   // contextually converted to bool long ago. The candidates below are
07956   // therefore added as binary.
07957   //
07958   // C++ [over.built]p25:
07959   //   For every type T, where T is a pointer, pointer-to-member, or scoped
07960   //   enumeration type, there exist candidate operator functions of the form
07961   //
07962   //        T        operator?(bool, T, T);
07963   //
07964   void addConditionalOperatorOverloads() {
07965     /// Set of (canonical) types that we've already handled.
07966     llvm::SmallPtrSet<QualType, 8> AddedTypes;
07967 
07968     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
07969       for (BuiltinCandidateTypeSet::iterator
07970                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
07971              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
07972            Ptr != PtrEnd; ++Ptr) {
07973         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
07974           continue;
07975 
07976         QualType ParamTypes[2] = { *Ptr, *Ptr };
07977         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
07978       }
07979 
07980       for (BuiltinCandidateTypeSet::iterator
07981                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
07982              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
07983            MemPtr != MemPtrEnd; ++MemPtr) {
07984         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
07985           continue;
07986 
07987         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
07988         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
07989       }
07990 
07991       if (S.getLangOpts().CPlusPlus11) {
07992         for (BuiltinCandidateTypeSet::iterator
07993                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
07994                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
07995              Enum != EnumEnd; ++Enum) {
07996           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
07997             continue;
07998 
07999           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
08000             continue;
08001 
08002           QualType ParamTypes[2] = { *Enum, *Enum };
08003           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
08004         }
08005       }
08006     }
08007   }
08008 };
08009 
08010 } // end anonymous namespace
08011 
08012 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
08013 /// operator overloads to the candidate set (C++ [over.built]), based
08014 /// on the operator @p Op and the arguments given. For example, if the
08015 /// operator is a binary '+', this routine might add "int
08016 /// operator+(int, int)" to cover integer addition.
08017 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
08018                                         SourceLocation OpLoc,
08019                                         ArrayRef<Expr *> Args,
08020                                         OverloadCandidateSet &CandidateSet) {
08021   // Find all of the types that the arguments can convert to, but only
08022   // if the operator we're looking at has built-in operator candidates
08023   // that make use of these types. Also record whether we encounter non-record
08024   // candidate types or either arithmetic or enumeral candidate types.
08025   Qualifiers VisibleTypeConversionsQuals;
08026   VisibleTypeConversionsQuals.addConst();
08027   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
08028     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
08029 
08030   bool HasNonRecordCandidateType = false;
08031   bool HasArithmeticOrEnumeralCandidateType = false;
08032   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
08033   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
08034     CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
08035     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
08036                                                  OpLoc,
08037                                                  true,
08038                                                  (Op == OO_Exclaim ||
08039                                                   Op == OO_AmpAmp ||
08040                                                   Op == OO_PipePipe),
08041                                                  VisibleTypeConversionsQuals);
08042     HasNonRecordCandidateType = HasNonRecordCandidateType ||
08043         CandidateTypes[ArgIdx].hasNonRecordTypes();
08044     HasArithmeticOrEnumeralCandidateType =
08045         HasArithmeticOrEnumeralCandidateType ||
08046         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
08047   }
08048 
08049   // Exit early when no non-record types have been added to the candidate set
08050   // for any of the arguments to the operator.
08051   //
08052   // We can't exit early for !, ||, or &&, since there we have always have
08053   // 'bool' overloads.
08054   if (!HasNonRecordCandidateType &&
08055       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
08056     return;
08057 
08058   // Setup an object to manage the common state for building overloads.
08059   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
08060                                            VisibleTypeConversionsQuals,
08061                                            HasArithmeticOrEnumeralCandidateType,
08062                                            CandidateTypes, CandidateSet);
08063 
08064   // Dispatch over the operation to add in only those overloads which apply.
08065   switch (Op) {
08066   case OO_None:
08067   case NUM_OVERLOADED_OPERATORS:
08068     llvm_unreachable("Expected an overloaded operator");
08069 
08070   case OO_New:
08071   case OO_Delete:
08072   case OO_Array_New:
08073   case OO_Array_Delete:
08074   case OO_Call:
08075     llvm_unreachable(
08076                     "Special operators don't use AddBuiltinOperatorCandidates");
08077 
08078   case OO_Comma:
08079   case OO_Arrow:
08080     // C++ [over.match.oper]p3:
08081     //   -- For the operator ',', the unary operator '&', or the
08082     //      operator '->', the built-in candidates set is empty.
08083     break;
08084 
08085   case OO_Plus: // '+' is either unary or binary
08086     if (Args.size() == 1)
08087       OpBuilder.addUnaryPlusPointerOverloads();
08088     // Fall through.
08089 
08090   case OO_Minus: // '-' is either unary or binary
08091     if (Args.size() == 1) {
08092       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
08093     } else {
08094       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
08095       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
08096     }
08097     break;
08098 
08099   case OO_Star: // '*' is either unary or binary
08100     if (Args.size() == 1)
08101       OpBuilder.addUnaryStarPointerOverloads();
08102     else
08103       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
08104     break;
08105 
08106   case OO_Slash:
08107     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
08108     break;
08109 
08110   case OO_PlusPlus:
08111   case OO_MinusMinus:
08112     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
08113     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
08114     break;
08115 
08116   case OO_EqualEqual:
08117   case OO_ExclaimEqual:
08118     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
08119     // Fall through.
08120 
08121   case OO_Less:
08122   case OO_Greater:
08123   case OO_LessEqual:
08124   case OO_GreaterEqual:
08125     OpBuilder.addRelationalPointerOrEnumeralOverloads();
08126     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
08127     break;
08128 
08129   case OO_Percent:
08130   case OO_Caret:
08131   case OO_Pipe:
08132   case OO_LessLess:
08133   case OO_GreaterGreater:
08134     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
08135     break;
08136 
08137   case OO_Amp: // '&' is either unary or binary
08138     if (Args.size() == 1)
08139       // C++ [over.match.oper]p3:
08140       //   -- For the operator ',', the unary operator '&', or the
08141       //      operator '->', the built-in candidates set is empty.
08142       break;
08143 
08144     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
08145     break;
08146 
08147   case OO_Tilde:
08148     OpBuilder.addUnaryTildePromotedIntegralOverloads();
08149     break;
08150 
08151   case OO_Equal:
08152     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
08153     // Fall through.
08154 
08155   case OO_PlusEqual:
08156   case OO_MinusEqual:
08157     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
08158     // Fall through.
08159 
08160   case OO_StarEqual:
08161   case OO_SlashEqual:
08162     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
08163     break;
08164 
08165   case OO_PercentEqual:
08166   case OO_LessLessEqual:
08167   case OO_GreaterGreaterEqual:
08168   case OO_AmpEqual:
08169   case OO_CaretEqual:
08170   case OO_PipeEqual:
08171     OpBuilder.addAssignmentIntegralOverloads();
08172     break;
08173 
08174   case OO_Exclaim:
08175     OpBuilder.addExclaimOverload();
08176     break;
08177 
08178   case OO_AmpAmp:
08179   case OO_PipePipe:
08180     OpBuilder.addAmpAmpOrPipePipeOverload();
08181     break;
08182 
08183   case OO_Subscript:
08184     OpBuilder.addSubscriptOverloads();
08185     break;
08186 
08187   case OO_ArrowStar:
08188     OpBuilder.addArrowStarOverloads();
08189     break;
08190 
08191   case OO_Conditional:
08192     OpBuilder.addConditionalOperatorOverloads();
08193     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
08194     break;
08195   }
08196 }
08197 
08198 /// \brief Add function candidates found via argument-dependent lookup
08199 /// to the set of overloading candidates.
08200 ///
08201 /// This routine performs argument-dependent name lookup based on the
08202 /// given function name (which may also be an operator name) and adds
08203 /// all of the overload candidates found by ADL to the overload
08204 /// candidate set (C++ [basic.lookup.argdep]).
08205 void
08206 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
08207                                            SourceLocation Loc,
08208                                            ArrayRef<Expr *> Args,
08209                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
08210                                            OverloadCandidateSet& CandidateSet,
08211                                            bool PartialOverloading) {
08212   ADLResult Fns;
08213 
08214   // FIXME: This approach for uniquing ADL results (and removing
08215   // redundant candidates from the set) relies on pointer-equality,
08216   // which means we need to key off the canonical decl.  However,
08217   // always going back to the canonical decl might not get us the
08218   // right set of default arguments.  What default arguments are
08219   // we supposed to consider on ADL candidates, anyway?
08220 
08221   // FIXME: Pass in the explicit template arguments?
08222   ArgumentDependentLookup(Name, Loc, Args, Fns);
08223 
08224   // Erase all of the candidates we already knew about.
08225   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
08226                                    CandEnd = CandidateSet.end();
08227        Cand != CandEnd; ++Cand)
08228     if (Cand->Function) {
08229       Fns.erase(Cand->Function);
08230       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
08231         Fns.erase(FunTmpl);
08232     }
08233 
08234   // For each of the ADL candidates we found, add it to the overload
08235   // set.
08236   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
08237     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
08238     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
08239       if (ExplicitTemplateArgs)
08240         continue;
08241 
08242       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
08243                            PartialOverloading);
08244     } else
08245       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
08246                                    FoundDecl, ExplicitTemplateArgs,
08247                                    Args, CandidateSet);
08248   }
08249 }
08250 
08251 /// isBetterOverloadCandidate - Determines whether the first overload
08252 /// candidate is a better candidate than the second (C++ 13.3.3p1).
08253 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
08254                                       const OverloadCandidate &Cand2,
08255                                       SourceLocation Loc,
08256                                       bool UserDefinedConversion) {
08257   // Define viable functions to be better candidates than non-viable
08258   // functions.
08259   if (!Cand2.Viable)
08260     return Cand1.Viable;
08261   else if (!Cand1.Viable)
08262     return false;
08263 
08264   // C++ [over.match.best]p1:
08265   //
08266   //   -- if F is a static member function, ICS1(F) is defined such
08267   //      that ICS1(F) is neither better nor worse than ICS1(G) for
08268   //      any function G, and, symmetrically, ICS1(G) is neither
08269   //      better nor worse than ICS1(F).
08270   unsigned StartArg = 0;
08271   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
08272     StartArg = 1;
08273 
08274   // C++ [over.match.best]p1:
08275   //   A viable function F1 is defined to be a better function than another
08276   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
08277   //   conversion sequence than ICSi(F2), and then...
08278   unsigned NumArgs = Cand1.NumConversions;
08279   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
08280   bool HasBetterConversion = false;
08281   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
08282     switch (CompareImplicitConversionSequences(S,
08283                                                Cand1.Conversions[ArgIdx],
08284                                                Cand2.Conversions[ArgIdx])) {
08285     case ImplicitConversionSequence::Better:
08286       // Cand1 has a better conversion sequence.
08287       HasBetterConversion = true;
08288       break;
08289 
08290     case ImplicitConversionSequence::Worse:
08291       // Cand1 can't be better than Cand2.
08292       return false;
08293 
08294     case ImplicitConversionSequence::Indistinguishable:
08295       // Do nothing.
08296       break;
08297     }
08298   }
08299 
08300   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
08301   //       ICSj(F2), or, if not that,
08302   if (HasBetterConversion)
08303     return true;
08304 
08305   //   -- the context is an initialization by user-defined conversion
08306   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
08307   //      from the return type of F1 to the destination type (i.e.,
08308   //      the type of the entity being initialized) is a better
08309   //      conversion sequence than the standard conversion sequence
08310   //      from the return type of F2 to the destination type.
08311   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
08312       isa<CXXConversionDecl>(Cand1.Function) &&
08313       isa<CXXConversionDecl>(Cand2.Function)) {
08314     // First check whether we prefer one of the conversion functions over the
08315     // other. This only distinguishes the results in non-standard, extension
08316     // cases such as the conversion from a lambda closure type to a function
08317     // pointer or block.
08318     ImplicitConversionSequence::CompareKind Result =
08319         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
08320     if (Result == ImplicitConversionSequence::Indistinguishable)
08321       Result = CompareStandardConversionSequences(S,
08322                                                   Cand1.FinalConversion,
08323                                                   Cand2.FinalConversion);
08324 
08325     if (Result != ImplicitConversionSequence::Indistinguishable)
08326       return Result == ImplicitConversionSequence::Better;
08327 
08328     // FIXME: Compare kind of reference binding if conversion functions
08329     // convert to a reference type used in direct reference binding, per
08330     // C++14 [over.match.best]p1 section 2 bullet 3.
08331   }
08332 
08333   //    -- F1 is a non-template function and F2 is a function template
08334   //       specialization, or, if not that,
08335   bool Cand1IsSpecialization = Cand1.Function &&
08336                                Cand1.Function->getPrimaryTemplate();
08337   bool Cand2IsSpecialization = Cand2.Function &&
08338                                Cand2.Function->getPrimaryTemplate();
08339   if (Cand1IsSpecialization != Cand2IsSpecialization)
08340     return Cand2IsSpecialization;
08341 
08342   //   -- F1 and F2 are function template specializations, and the function
08343   //      template for F1 is more specialized than the template for F2
08344   //      according to the partial ordering rules described in 14.5.5.2, or,
08345   //      if not that,
08346   if (Cand1IsSpecialization && Cand2IsSpecialization) {
08347     if (FunctionTemplateDecl *BetterTemplate
08348           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
08349                                          Cand2.Function->getPrimaryTemplate(),
08350                                          Loc,
08351                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
08352                                                              : TPOC_Call,
08353                                          Cand1.ExplicitCallArguments,
08354                                          Cand2.ExplicitCallArguments))
08355       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
08356   }
08357 
08358   // Check for enable_if value-based overload resolution.
08359   if (Cand1.Function && Cand2.Function &&
08360       (Cand1.Function->hasAttr<EnableIfAttr>() ||
08361        Cand2.Function->hasAttr<EnableIfAttr>())) {
08362     // FIXME: The next several lines are just
08363     // specific_attr_iterator<EnableIfAttr> but going in declaration order,
08364     // instead of reverse order which is how they're stored in the AST.
08365     AttrVec Cand1Attrs;
08366     if (Cand1.Function->hasAttrs()) {
08367       Cand1Attrs = Cand1.Function->getAttrs();
08368       Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
08369                                       IsNotEnableIfAttr),
08370                        Cand1Attrs.end());
08371       std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
08372     }
08373 
08374     AttrVec Cand2Attrs;
08375     if (Cand2.Function->hasAttrs()) {
08376       Cand2Attrs = Cand2.Function->getAttrs();
08377       Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
08378                                       IsNotEnableIfAttr),
08379                        Cand2Attrs.end());
08380       std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
08381     }
08382 
08383     // Candidate 1 is better if it has strictly more attributes and
08384     // the common sequence is identical.
08385     if (Cand1Attrs.size() <= Cand2Attrs.size())
08386       return false;
08387 
08388     auto Cand1I = Cand1Attrs.begin();
08389     for (auto &Cand2A : Cand2Attrs) {
08390       auto &Cand1A = *Cand1I++;
08391       llvm::FoldingSetNodeID Cand1ID, Cand2ID;
08392       cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
08393                                                      S.getASTContext(), true);
08394       cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
08395                                                      S.getASTContext(), true);
08396       if (Cand1ID != Cand2ID)
08397         return false;
08398     }
08399 
08400     return true;
08401   }
08402 
08403   return false;
08404 }
08405 
08406 /// \brief Computes the best viable function (C++ 13.3.3)
08407 /// within an overload candidate set.
08408 ///
08409 /// \param Loc The location of the function name (or operator symbol) for
08410 /// which overload resolution occurs.
08411 ///
08412 /// \param Best If overload resolution was successful or found a deleted
08413 /// function, \p Best points to the candidate function found.
08414 ///
08415 /// \returns The result of overload resolution.
08416 OverloadingResult
08417 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
08418                                          iterator &Best,
08419                                          bool UserDefinedConversion) {
08420   // Find the best viable function.
08421   Best = end();
08422   for (iterator Cand = begin(); Cand != end(); ++Cand) {
08423     if (Cand->Viable)
08424       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
08425                                                      UserDefinedConversion))
08426         Best = Cand;
08427   }
08428 
08429   // If we didn't find any viable functions, abort.
08430   if (Best == end())
08431     return OR_No_Viable_Function;
08432 
08433   // Make sure that this function is better than every other viable
08434   // function. If not, we have an ambiguity.
08435   for (iterator Cand = begin(); Cand != end(); ++Cand) {
08436     if (Cand->Viable &&
08437         Cand != Best &&
08438         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
08439                                    UserDefinedConversion)) {
08440       Best = end();
08441       return OR_Ambiguous;
08442     }
08443   }
08444 
08445   // Best is the best viable function.
08446   if (Best->Function &&
08447       (Best->Function->isDeleted() ||
08448        S.isFunctionConsideredUnavailable(Best->Function)))
08449     return OR_Deleted;
08450 
08451   return OR_Success;
08452 }
08453 
08454 namespace {
08455 
08456 enum OverloadCandidateKind {
08457   oc_function,
08458   oc_method,
08459   oc_constructor,
08460   oc_function_template,
08461   oc_method_template,
08462   oc_constructor_template,
08463   oc_implicit_default_constructor,
08464   oc_implicit_copy_constructor,
08465   oc_implicit_move_constructor,
08466   oc_implicit_copy_assignment,
08467   oc_implicit_move_assignment,
08468   oc_implicit_inherited_constructor
08469 };
08470 
08471 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
08472                                                 FunctionDecl *Fn,
08473                                                 std::string &Description) {
08474   bool isTemplate = false;
08475 
08476   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
08477     isTemplate = true;
08478     Description = S.getTemplateArgumentBindingsText(
08479       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
08480   }
08481 
08482   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
08483     if (!Ctor->isImplicit())
08484       return isTemplate ? oc_constructor_template : oc_constructor;
08485 
08486     if (Ctor->getInheritedConstructor())
08487       return oc_implicit_inherited_constructor;
08488 
08489     if (Ctor->isDefaultConstructor())
08490       return oc_implicit_default_constructor;
08491 
08492     if (Ctor->isMoveConstructor())
08493       return oc_implicit_move_constructor;
08494 
08495     assert(Ctor->isCopyConstructor() &&
08496            "unexpected sort of implicit constructor");
08497     return oc_implicit_copy_constructor;
08498   }
08499 
08500   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
08501     // This actually gets spelled 'candidate function' for now, but
08502     // it doesn't hurt to split it out.
08503     if (!Meth->isImplicit())
08504       return isTemplate ? oc_method_template : oc_method;
08505 
08506     if (Meth->isMoveAssignmentOperator())
08507       return oc_implicit_move_assignment;
08508 
08509     if (Meth->isCopyAssignmentOperator())
08510       return oc_implicit_copy_assignment;
08511 
08512     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
08513     return oc_method;
08514   }
08515 
08516   return isTemplate ? oc_function_template : oc_function;
08517 }
08518 
08519 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
08520   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
08521   if (!Ctor) return;
08522 
08523   Ctor = Ctor->getInheritedConstructor();
08524   if (!Ctor) return;
08525 
08526   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
08527 }
08528 
08529 } // end anonymous namespace
08530 
08531 // Notes the location of an overload candidate.
08532 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
08533   std::string FnDesc;
08534   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
08535   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
08536                              << (unsigned) K << FnDesc;
08537   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
08538   Diag(Fn->getLocation(), PD);
08539   MaybeEmitInheritedConstructorNote(*this, Fn);
08540 }
08541 
08542 // Notes the location of all overload candidates designated through
08543 // OverloadedExpr
08544 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
08545   assert(OverloadedExpr->getType() == Context.OverloadTy);
08546 
08547   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
08548   OverloadExpr *OvlExpr = Ovl.Expression;
08549 
08550   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
08551                             IEnd = OvlExpr->decls_end(); 
08552        I != IEnd; ++I) {
08553     if (FunctionTemplateDecl *FunTmpl = 
08554                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
08555       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
08556     } else if (FunctionDecl *Fun 
08557                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
08558       NoteOverloadCandidate(Fun, DestType);
08559     }
08560   }
08561 }
08562 
08563 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
08564 /// "lead" diagnostic; it will be given two arguments, the source and
08565 /// target types of the conversion.
08566 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
08567                                  Sema &S,
08568                                  SourceLocation CaretLoc,
08569                                  const PartialDiagnostic &PDiag) const {
08570   S.Diag(CaretLoc, PDiag)
08571     << Ambiguous.getFromType() << Ambiguous.getToType();
08572   // FIXME: The note limiting machinery is borrowed from
08573   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
08574   // refactoring here.
08575   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
08576   unsigned CandsShown = 0;
08577   AmbiguousConversionSequence::const_iterator I, E;
08578   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
08579     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
08580       break;
08581     ++CandsShown;
08582     S.NoteOverloadCandidate(*I);
08583   }
08584   if (I != E)
08585     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
08586 }
08587 
08588 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
08589                                   unsigned I) {
08590   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
08591   assert(Conv.isBad());
08592   assert(Cand->Function && "for now, candidate must be a function");
08593   FunctionDecl *Fn = Cand->Function;
08594 
08595   // There's a conversion slot for the object argument if this is a
08596   // non-constructor method.  Note that 'I' corresponds the
08597   // conversion-slot index.
08598   bool isObjectArgument = false;
08599   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
08600     if (I == 0)
08601       isObjectArgument = true;
08602     else
08603       I--;
08604   }
08605 
08606   std::string FnDesc;
08607   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
08608 
08609   Expr *FromExpr = Conv.Bad.FromExpr;
08610   QualType FromTy = Conv.Bad.getFromType();
08611   QualType ToTy = Conv.Bad.getToType();
08612 
08613   if (FromTy == S.Context.OverloadTy) {
08614     assert(FromExpr && "overload set argument came from implicit argument?");
08615     Expr *E = FromExpr->IgnoreParens();
08616     if (isa<UnaryOperator>(E))
08617       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
08618     DeclarationName Name = cast<OverloadExpr>(E)->getName();
08619 
08620     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
08621       << (unsigned) FnKind << FnDesc
08622       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08623       << ToTy << Name << I+1;
08624     MaybeEmitInheritedConstructorNote(S, Fn);
08625     return;
08626   }
08627 
08628   // Do some hand-waving analysis to see if the non-viability is due
08629   // to a qualifier mismatch.
08630   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
08631   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
08632   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
08633     CToTy = RT->getPointeeType();
08634   else {
08635     // TODO: detect and diagnose the full richness of const mismatches.
08636     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
08637       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
08638         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
08639   }
08640 
08641   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
08642       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
08643     Qualifiers FromQs = CFromTy.getQualifiers();
08644     Qualifiers ToQs = CToTy.getQualifiers();
08645 
08646     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
08647       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
08648         << (unsigned) FnKind << FnDesc
08649         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08650         << FromTy
08651         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
08652         << (unsigned) isObjectArgument << I+1;
08653       MaybeEmitInheritedConstructorNote(S, Fn);
08654       return;
08655     }
08656 
08657     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
08658       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
08659         << (unsigned) FnKind << FnDesc
08660         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08661         << FromTy
08662         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
08663         << (unsigned) isObjectArgument << I+1;
08664       MaybeEmitInheritedConstructorNote(S, Fn);
08665       return;
08666     }
08667 
08668     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
08669       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
08670       << (unsigned) FnKind << FnDesc
08671       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08672       << FromTy
08673       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
08674       << (unsigned) isObjectArgument << I+1;
08675       MaybeEmitInheritedConstructorNote(S, Fn);
08676       return;
08677     }
08678 
08679     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
08680     assert(CVR && "unexpected qualifiers mismatch");
08681 
08682     if (isObjectArgument) {
08683       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
08684         << (unsigned) FnKind << FnDesc
08685         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08686         << FromTy << (CVR - 1);
08687     } else {
08688       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
08689         << (unsigned) FnKind << FnDesc
08690         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08691         << FromTy << (CVR - 1) << I+1;
08692     }
08693     MaybeEmitInheritedConstructorNote(S, Fn);
08694     return;
08695   }
08696 
08697   // Special diagnostic for failure to convert an initializer list, since
08698   // telling the user that it has type void is not useful.
08699   if (FromExpr && isa<InitListExpr>(FromExpr)) {
08700     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
08701       << (unsigned) FnKind << FnDesc
08702       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08703       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
08704     MaybeEmitInheritedConstructorNote(S, Fn);
08705     return;
08706   }
08707 
08708   // Diagnose references or pointers to incomplete types differently,
08709   // since it's far from impossible that the incompleteness triggered
08710   // the failure.
08711   QualType TempFromTy = FromTy.getNonReferenceType();
08712   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
08713     TempFromTy = PTy->getPointeeType();
08714   if (TempFromTy->isIncompleteType()) {
08715     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
08716       << (unsigned) FnKind << FnDesc
08717       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08718       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
08719     MaybeEmitInheritedConstructorNote(S, Fn);
08720     return;
08721   }
08722 
08723   // Diagnose base -> derived pointer conversions.
08724   unsigned BaseToDerivedConversion = 0;
08725   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
08726     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
08727       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
08728                                                FromPtrTy->getPointeeType()) &&
08729           !FromPtrTy->getPointeeType()->isIncompleteType() &&
08730           !ToPtrTy->getPointeeType()->isIncompleteType() &&
08731           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
08732                           FromPtrTy->getPointeeType()))
08733         BaseToDerivedConversion = 1;
08734     }
08735   } else if (const ObjCObjectPointerType *FromPtrTy
08736                                     = FromTy->getAs<ObjCObjectPointerType>()) {
08737     if (const ObjCObjectPointerType *ToPtrTy
08738                                         = ToTy->getAs<ObjCObjectPointerType>())
08739       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
08740         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
08741           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
08742                                                 FromPtrTy->getPointeeType()) &&
08743               FromIface->isSuperClassOf(ToIface))
08744             BaseToDerivedConversion = 2;
08745   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
08746     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
08747         !FromTy->isIncompleteType() &&
08748         !ToRefTy->getPointeeType()->isIncompleteType() &&
08749         S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
08750       BaseToDerivedConversion = 3;
08751     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
08752                ToTy.getNonReferenceType().getCanonicalType() ==
08753                FromTy.getNonReferenceType().getCanonicalType()) {
08754       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
08755         << (unsigned) FnKind << FnDesc
08756         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08757         << (unsigned) isObjectArgument << I + 1;
08758       MaybeEmitInheritedConstructorNote(S, Fn);
08759       return;
08760     }
08761   }
08762 
08763   if (BaseToDerivedConversion) {
08764     S.Diag(Fn->getLocation(),
08765            diag::note_ovl_candidate_bad_base_to_derived_conv)
08766       << (unsigned) FnKind << FnDesc
08767       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08768       << (BaseToDerivedConversion - 1)
08769       << FromTy << ToTy << I+1;
08770     MaybeEmitInheritedConstructorNote(S, Fn);
08771     return;
08772   }
08773 
08774   if (isa<ObjCObjectPointerType>(CFromTy) &&
08775       isa<PointerType>(CToTy)) {
08776       Qualifiers FromQs = CFromTy.getQualifiers();
08777       Qualifiers ToQs = CToTy.getQualifiers();
08778       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
08779         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
08780         << (unsigned) FnKind << FnDesc
08781         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08782         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
08783         MaybeEmitInheritedConstructorNote(S, Fn);
08784         return;
08785       }
08786   }
08787   
08788   // Emit the generic diagnostic and, optionally, add the hints to it.
08789   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
08790   FDiag << (unsigned) FnKind << FnDesc
08791     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08792     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
08793     << (unsigned) (Cand->Fix.Kind);
08794 
08795   // If we can fix the conversion, suggest the FixIts.
08796   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
08797        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
08798     FDiag << *HI;
08799   S.Diag(Fn->getLocation(), FDiag);
08800 
08801   MaybeEmitInheritedConstructorNote(S, Fn);
08802 }
08803 
08804 /// Additional arity mismatch diagnosis specific to a function overload
08805 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
08806 /// over a candidate in any candidate set.
08807 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
08808                                unsigned NumArgs) {
08809   FunctionDecl *Fn = Cand->Function;
08810   unsigned MinParams = Fn->getMinRequiredArguments();
08811 
08812   // With invalid overloaded operators, it's possible that we think we
08813   // have an arity mismatch when in fact it looks like we have the
08814   // right number of arguments, because only overloaded operators have
08815   // the weird behavior of overloading member and non-member functions.
08816   // Just don't report anything.
08817   if (Fn->isInvalidDecl() && 
08818       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
08819     return true;
08820 
08821   if (NumArgs < MinParams) {
08822     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
08823            (Cand->FailureKind == ovl_fail_bad_deduction &&
08824             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
08825   } else {
08826     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
08827            (Cand->FailureKind == ovl_fail_bad_deduction &&
08828             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
08829   }
08830 
08831   return false;
08832 }
08833 
08834 /// General arity mismatch diagnosis over a candidate in a candidate set.
08835 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
08836   assert(isa<FunctionDecl>(D) &&
08837       "The templated declaration should at least be a function"
08838       " when diagnosing bad template argument deduction due to too many"
08839       " or too few arguments");
08840   
08841   FunctionDecl *Fn = cast<FunctionDecl>(D);
08842   
08843   // TODO: treat calls to a missing default constructor as a special case
08844   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
08845   unsigned MinParams = Fn->getMinRequiredArguments();
08846 
08847   // at least / at most / exactly
08848   unsigned mode, modeCount;
08849   if (NumFormalArgs < MinParams) {
08850     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
08851         FnTy->isTemplateVariadic())
08852       mode = 0; // "at least"
08853     else
08854       mode = 2; // "exactly"
08855     modeCount = MinParams;
08856   } else {
08857     if (MinParams != FnTy->getNumParams())
08858       mode = 1; // "at most"
08859     else
08860       mode = 2; // "exactly"
08861     modeCount = FnTy->getNumParams();
08862   }
08863 
08864   std::string Description;
08865   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
08866 
08867   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
08868     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
08869       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
08870       << mode << Fn->getParamDecl(0) << NumFormalArgs;
08871   else
08872     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
08873       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
08874       << mode << modeCount << NumFormalArgs;
08875   MaybeEmitInheritedConstructorNote(S, Fn);
08876 }
08877 
08878 /// Arity mismatch diagnosis specific to a function overload candidate.
08879 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
08880                                   unsigned NumFormalArgs) {
08881   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
08882     DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
08883 }
08884 
08885 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
08886   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
08887     return FD->getDescribedFunctionTemplate();
08888   else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
08889     return RD->getDescribedClassTemplate();
08890 
08891   llvm_unreachable("Unsupported: Getting the described template declaration"
08892                    " for bad deduction diagnosis");
08893 }
08894 
08895 /// Diagnose a failed template-argument deduction.
08896 static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
08897                                  DeductionFailureInfo &DeductionFailure,
08898                                  unsigned NumArgs) {
08899   TemplateParameter Param = DeductionFailure.getTemplateParameter();
08900   NamedDecl *ParamD;
08901   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
08902   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
08903   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
08904   switch (DeductionFailure.Result) {
08905   case Sema::TDK_Success:
08906     llvm_unreachable("TDK_success while diagnosing bad deduction");
08907 
08908   case Sema::TDK_Incomplete: {
08909     assert(ParamD && "no parameter found for incomplete deduction result");
08910     S.Diag(Templated->getLocation(),
08911            diag::note_ovl_candidate_incomplete_deduction)
08912         << ParamD->getDeclName();
08913     MaybeEmitInheritedConstructorNote(S, Templated);
08914     return;
08915   }
08916 
08917   case Sema::TDK_Underqualified: {
08918     assert(ParamD && "no parameter found for bad qualifiers deduction result");
08919     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
08920 
08921     QualType Param = DeductionFailure.getFirstArg()->getAsType();
08922 
08923     // Param will have been canonicalized, but it should just be a
08924     // qualified version of ParamD, so move the qualifiers to that.
08925     QualifierCollector Qs;
08926     Qs.strip(Param);
08927     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
08928     assert(S.Context.hasSameType(Param, NonCanonParam));
08929 
08930     // Arg has also been canonicalized, but there's nothing we can do
08931     // about that.  It also doesn't matter as much, because it won't
08932     // have any template parameters in it (because deduction isn't
08933     // done on dependent types).
08934     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
08935 
08936     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
08937         << ParamD->getDeclName() << Arg << NonCanonParam;
08938     MaybeEmitInheritedConstructorNote(S, Templated);
08939     return;
08940   }
08941 
08942   case Sema::TDK_Inconsistent: {
08943     assert(ParamD && "no parameter found for inconsistent deduction result");
08944     int which = 0;
08945     if (isa<TemplateTypeParmDecl>(ParamD))
08946       which = 0;
08947     else if (isa<NonTypeTemplateParmDecl>(ParamD))
08948       which = 1;
08949     else {
08950       which = 2;
08951     }
08952 
08953     S.Diag(Templated->getLocation(),
08954            diag::note_ovl_candidate_inconsistent_deduction)
08955         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
08956         << *DeductionFailure.getSecondArg();
08957     MaybeEmitInheritedConstructorNote(S, Templated);
08958     return;
08959   }
08960 
08961   case Sema::TDK_InvalidExplicitArguments:
08962     assert(ParamD && "no parameter found for invalid explicit arguments");
08963     if (ParamD->getDeclName())
08964       S.Diag(Templated->getLocation(),
08965              diag::note_ovl_candidate_explicit_arg_mismatch_named)
08966           << ParamD->getDeclName();
08967     else {
08968       int index = 0;
08969       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
08970         index = TTP->getIndex();
08971       else if (NonTypeTemplateParmDecl *NTTP
08972                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
08973         index = NTTP->getIndex();
08974       else
08975         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
08976       S.Diag(Templated->getLocation(),
08977              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
08978           << (index + 1);
08979     }
08980     MaybeEmitInheritedConstructorNote(S, Templated);
08981     return;
08982 
08983   case Sema::TDK_TooManyArguments:
08984   case Sema::TDK_TooFewArguments:
08985     DiagnoseArityMismatch(S, Templated, NumArgs);
08986     return;
08987 
08988   case Sema::TDK_InstantiationDepth:
08989     S.Diag(Templated->getLocation(),
08990            diag::note_ovl_candidate_instantiation_depth);
08991     MaybeEmitInheritedConstructorNote(S, Templated);
08992     return;
08993 
08994   case Sema::TDK_SubstitutionFailure: {
08995     // Format the template argument list into the argument string.
08996     SmallString<128> TemplateArgString;
08997     if (TemplateArgumentList *Args =
08998             DeductionFailure.getTemplateArgumentList()) {
08999       TemplateArgString = " ";
09000       TemplateArgString += S.getTemplateArgumentBindingsText(
09001           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
09002     }
09003 
09004     // If this candidate was disabled by enable_if, say so.
09005     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
09006     if (PDiag && PDiag->second.getDiagID() ==
09007           diag::err_typename_nested_not_found_enable_if) {
09008       // FIXME: Use the source range of the condition, and the fully-qualified
09009       //        name of the enable_if template. These are both present in PDiag.
09010       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
09011         << "'enable_if'" << TemplateArgString;
09012       return;
09013     }
09014 
09015     // Format the SFINAE diagnostic into the argument string.
09016     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
09017     //        formatted message in another diagnostic.
09018     SmallString<128> SFINAEArgString;
09019     SourceRange R;
09020     if (PDiag) {
09021       SFINAEArgString = ": ";
09022       R = SourceRange(PDiag->first, PDiag->first);
09023       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
09024     }
09025 
09026     S.Diag(Templated->getLocation(),
09027            diag::note_ovl_candidate_substitution_failure)
09028         << TemplateArgString << SFINAEArgString << R;
09029     MaybeEmitInheritedConstructorNote(S, Templated);
09030     return;
09031   }
09032 
09033   case Sema::TDK_FailedOverloadResolution: {
09034     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
09035     S.Diag(Templated->getLocation(),
09036            diag::note_ovl_candidate_failed_overload_resolution)
09037         << R.Expression->getName();
09038     return;
09039   }
09040 
09041   case Sema::TDK_NonDeducedMismatch: {
09042     // FIXME: Provide a source location to indicate what we couldn't match.
09043     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
09044     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
09045     if (FirstTA.getKind() == TemplateArgument::Template &&
09046         SecondTA.getKind() == TemplateArgument::Template) {
09047       TemplateName FirstTN = FirstTA.getAsTemplate();
09048       TemplateName SecondTN = SecondTA.getAsTemplate();
09049       if (FirstTN.getKind() == TemplateName::Template &&
09050           SecondTN.getKind() == TemplateName::Template) {
09051         if (FirstTN.getAsTemplateDecl()->getName() ==
09052             SecondTN.getAsTemplateDecl()->getName()) {
09053           // FIXME: This fixes a bad diagnostic where both templates are named
09054           // the same.  This particular case is a bit difficult since:
09055           // 1) It is passed as a string to the diagnostic printer.
09056           // 2) The diagnostic printer only attempts to find a better
09057           //    name for types, not decls.
09058           // Ideally, this should folded into the diagnostic printer.
09059           S.Diag(Templated->getLocation(),
09060                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
09061               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
09062           return;
09063         }
09064       }
09065     }
09066     // FIXME: For generic lambda parameters, check if the function is a lambda
09067     // call operator, and if so, emit a prettier and more informative 
09068     // diagnostic that mentions 'auto' and lambda in addition to 
09069     // (or instead of?) the canonical template type parameters.
09070     S.Diag(Templated->getLocation(),
09071            diag::note_ovl_candidate_non_deduced_mismatch)
09072         << FirstTA << SecondTA;
09073     return;
09074   }
09075   // TODO: diagnose these individually, then kill off
09076   // note_ovl_candidate_bad_deduction, which is uselessly vague.
09077   case Sema::TDK_MiscellaneousDeductionFailure:
09078     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
09079     MaybeEmitInheritedConstructorNote(S, Templated);
09080     return;
09081   }
09082 }
09083 
09084 /// Diagnose a failed template-argument deduction, for function calls.
09085 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
09086                                  unsigned NumArgs) {
09087   unsigned TDK = Cand->DeductionFailure.Result;
09088   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
09089     if (CheckArityMismatch(S, Cand, NumArgs))
09090       return;
09091   }
09092   DiagnoseBadDeduction(S, Cand->Function, // pattern
09093                        Cand->DeductionFailure, NumArgs);
09094 }
09095 
09096 /// CUDA: diagnose an invalid call across targets.
09097 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
09098   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
09099   FunctionDecl *Callee = Cand->Function;
09100 
09101   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
09102                            CalleeTarget = S.IdentifyCUDATarget(Callee);
09103 
09104   std::string FnDesc;
09105   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
09106 
09107   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
09108       << (unsigned)FnKind << CalleeTarget << CallerTarget;
09109 
09110   // This could be an implicit constructor for which we could not infer the
09111   // target due to a collsion. Diagnose that case.
09112   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
09113   if (Meth != nullptr && Meth->isImplicit()) {
09114     CXXRecordDecl *ParentClass = Meth->getParent();
09115     Sema::CXXSpecialMember CSM;
09116 
09117     switch (FnKind) {
09118     default:
09119       return;
09120     case oc_implicit_default_constructor:
09121       CSM = Sema::CXXDefaultConstructor;
09122       break;
09123     case oc_implicit_copy_constructor:
09124       CSM = Sema::CXXCopyConstructor;
09125       break;
09126     case oc_implicit_move_constructor:
09127       CSM = Sema::CXXMoveConstructor;
09128       break;
09129     case oc_implicit_copy_assignment:
09130       CSM = Sema::CXXCopyAssignment;
09131       break;
09132     case oc_implicit_move_assignment:
09133       CSM = Sema::CXXMoveAssignment;
09134       break;
09135     };
09136 
09137     bool ConstRHS = false;
09138     if (Meth->getNumParams()) {
09139       if (const ReferenceType *RT =
09140               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
09141         ConstRHS = RT->getPointeeType().isConstQualified();
09142       }
09143     }
09144 
09145     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
09146                                               /* ConstRHS */ ConstRHS,
09147                                               /* Diagnose */ true);
09148   }
09149 }
09150 
09151 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
09152   FunctionDecl *Callee = Cand->Function;
09153   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
09154 
09155   S.Diag(Callee->getLocation(),
09156          diag::note_ovl_candidate_disabled_by_enable_if_attr)
09157       << Attr->getCond()->getSourceRange() << Attr->getMessage();
09158 }
09159 
09160 /// Generates a 'note' diagnostic for an overload candidate.  We've
09161 /// already generated a primary error at the call site.
09162 ///
09163 /// It really does need to be a single diagnostic with its caret
09164 /// pointed at the candidate declaration.  Yes, this creates some
09165 /// major challenges of technical writing.  Yes, this makes pointing
09166 /// out problems with specific arguments quite awkward.  It's still
09167 /// better than generating twenty screens of text for every failed
09168 /// overload.
09169 ///
09170 /// It would be great to be able to express per-candidate problems
09171 /// more richly for those diagnostic clients that cared, but we'd
09172 /// still have to be just as careful with the default diagnostics.
09173 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
09174                                   unsigned NumArgs) {
09175   FunctionDecl *Fn = Cand->Function;
09176 
09177   // Note deleted candidates, but only if they're viable.
09178   if (Cand->Viable && (Fn->isDeleted() ||
09179       S.isFunctionConsideredUnavailable(Fn))) {
09180     std::string FnDesc;
09181     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
09182 
09183     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
09184       << FnKind << FnDesc
09185       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
09186     MaybeEmitInheritedConstructorNote(S, Fn);
09187     return;
09188   }
09189 
09190   // We don't really have anything else to say about viable candidates.
09191   if (Cand->Viable) {
09192     S.NoteOverloadCandidate(Fn);
09193     return;
09194   }
09195 
09196   switch (Cand->FailureKind) {
09197   case ovl_fail_too_many_arguments:
09198   case ovl_fail_too_few_arguments:
09199     return DiagnoseArityMismatch(S, Cand, NumArgs);
09200 
09201   case ovl_fail_bad_deduction:
09202     return DiagnoseBadDeduction(S, Cand, NumArgs);
09203 
09204   case ovl_fail_trivial_conversion:
09205   case ovl_fail_bad_final_conversion:
09206   case ovl_fail_final_conversion_not_exact:
09207     return S.NoteOverloadCandidate(Fn);
09208 
09209   case ovl_fail_bad_conversion: {
09210     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
09211     for (unsigned N = Cand->NumConversions; I != N; ++I)
09212       if (Cand->Conversions[I].isBad())
09213         return DiagnoseBadConversion(S, Cand, I);
09214 
09215     // FIXME: this currently happens when we're called from SemaInit
09216     // when user-conversion overload fails.  Figure out how to handle
09217     // those conditions and diagnose them well.
09218     return S.NoteOverloadCandidate(Fn);
09219   }
09220 
09221   case ovl_fail_bad_target:
09222     return DiagnoseBadTarget(S, Cand);
09223 
09224   case ovl_fail_enable_if:
09225     return DiagnoseFailedEnableIfAttr(S, Cand);
09226   }
09227 }
09228 
09229 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
09230   // Desugar the type of the surrogate down to a function type,
09231   // retaining as many typedefs as possible while still showing
09232   // the function type (and, therefore, its parameter types).
09233   QualType FnType = Cand->Surrogate->getConversionType();
09234   bool isLValueReference = false;
09235   bool isRValueReference = false;
09236   bool isPointer = false;
09237   if (const LValueReferenceType *FnTypeRef =
09238         FnType->getAs<LValueReferenceType>()) {
09239     FnType = FnTypeRef->getPointeeType();
09240     isLValueReference = true;
09241   } else if (const RValueReferenceType *FnTypeRef =
09242                FnType->getAs<RValueReferenceType>()) {
09243     FnType = FnTypeRef->getPointeeType();
09244     isRValueReference = true;
09245   }
09246   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
09247     FnType = FnTypePtr->getPointeeType();
09248     isPointer = true;
09249   }
09250   // Desugar down to a function type.
09251   FnType = QualType(FnType->getAs<FunctionType>(), 0);
09252   // Reconstruct the pointer/reference as appropriate.
09253   if (isPointer) FnType = S.Context.getPointerType(FnType);
09254   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
09255   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
09256 
09257   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
09258     << FnType;
09259   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
09260 }
09261 
09262 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
09263                                          SourceLocation OpLoc,
09264                                          OverloadCandidate *Cand) {
09265   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
09266   std::string TypeStr("operator");
09267   TypeStr += Opc;
09268   TypeStr += "(";
09269   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
09270   if (Cand->NumConversions == 1) {
09271     TypeStr += ")";
09272     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
09273   } else {
09274     TypeStr += ", ";
09275     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
09276     TypeStr += ")";
09277     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
09278   }
09279 }
09280 
09281 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
09282                                          OverloadCandidate *Cand) {
09283   unsigned NoOperands = Cand->NumConversions;
09284   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
09285     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
09286     if (ICS.isBad()) break; // all meaningless after first invalid
09287     if (!ICS.isAmbiguous()) continue;
09288 
09289     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
09290                               S.PDiag(diag::note_ambiguous_type_conversion));
09291   }
09292 }
09293 
09294 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
09295   if (Cand->Function)
09296     return Cand->Function->getLocation();
09297   if (Cand->IsSurrogate)
09298     return Cand->Surrogate->getLocation();
09299   return SourceLocation();
09300 }
09301 
09302 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
09303   switch ((Sema::TemplateDeductionResult)DFI.Result) {
09304   case Sema::TDK_Success:
09305     llvm_unreachable("TDK_success while diagnosing bad deduction");
09306 
09307   case Sema::TDK_Invalid:
09308   case Sema::TDK_Incomplete:
09309     return 1;
09310 
09311   case Sema::TDK_Underqualified:
09312   case Sema::TDK_Inconsistent:
09313     return 2;
09314 
09315   case Sema::TDK_SubstitutionFailure:
09316   case Sema::TDK_NonDeducedMismatch:
09317   case Sema::TDK_MiscellaneousDeductionFailure:
09318     return 3;
09319 
09320   case Sema::TDK_InstantiationDepth:
09321   case Sema::TDK_FailedOverloadResolution:
09322     return 4;
09323 
09324   case Sema::TDK_InvalidExplicitArguments:
09325     return 5;
09326 
09327   case Sema::TDK_TooManyArguments:
09328   case Sema::TDK_TooFewArguments:
09329     return 6;
09330   }
09331   llvm_unreachable("Unhandled deduction result");
09332 }
09333 
09334 namespace {
09335 struct CompareOverloadCandidatesForDisplay {
09336   Sema &S;
09337   size_t NumArgs;
09338 
09339   CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
09340       : S(S), NumArgs(nArgs) {}
09341 
09342   bool operator()(const OverloadCandidate *L,
09343                   const OverloadCandidate *R) {
09344     // Fast-path this check.
09345     if (L == R) return false;
09346 
09347     // Order first by viability.
09348     if (L->Viable) {
09349       if (!R->Viable) return true;
09350 
09351       // TODO: introduce a tri-valued comparison for overload
09352       // candidates.  Would be more worthwhile if we had a sort
09353       // that could exploit it.
09354       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
09355       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
09356     } else if (R->Viable)
09357       return false;
09358 
09359     assert(L->Viable == R->Viable);
09360 
09361     // Criteria by which we can sort non-viable candidates:
09362     if (!L->Viable) {
09363       // 1. Arity mismatches come after other candidates.
09364       if (L->FailureKind == ovl_fail_too_many_arguments ||
09365           L->FailureKind == ovl_fail_too_few_arguments) {
09366         if (R->FailureKind == ovl_fail_too_many_arguments ||
09367             R->FailureKind == ovl_fail_too_few_arguments) {
09368           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
09369           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
09370           if (LDist == RDist) {
09371             if (L->FailureKind == R->FailureKind)
09372               // Sort non-surrogates before surrogates.
09373               return !L->IsSurrogate && R->IsSurrogate;
09374             // Sort candidates requiring fewer parameters than there were
09375             // arguments given after candidates requiring more parameters
09376             // than there were arguments given.
09377             return L->FailureKind == ovl_fail_too_many_arguments;
09378           }
09379           return LDist < RDist;
09380         }
09381         return false;
09382       }
09383       if (R->FailureKind == ovl_fail_too_many_arguments ||
09384           R->FailureKind == ovl_fail_too_few_arguments)
09385         return true;
09386 
09387       // 2. Bad conversions come first and are ordered by the number
09388       // of bad conversions and quality of good conversions.
09389       if (L->FailureKind == ovl_fail_bad_conversion) {
09390         if (R->FailureKind != ovl_fail_bad_conversion)
09391           return true;
09392 
09393         // The conversion that can be fixed with a smaller number of changes,
09394         // comes first.
09395         unsigned numLFixes = L->Fix.NumConversionsFixed;
09396         unsigned numRFixes = R->Fix.NumConversionsFixed;
09397         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
09398         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
09399         if (numLFixes != numRFixes) {
09400           if (numLFixes < numRFixes)
09401             return true;
09402           else
09403             return false;
09404         }
09405 
09406         // If there's any ordering between the defined conversions...
09407         // FIXME: this might not be transitive.
09408         assert(L->NumConversions == R->NumConversions);
09409 
09410         int leftBetter = 0;
09411         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
09412         for (unsigned E = L->NumConversions; I != E; ++I) {
09413           switch (CompareImplicitConversionSequences(S,
09414                                                      L->Conversions[I],
09415                                                      R->Conversions[I])) {
09416           case ImplicitConversionSequence::Better:
09417             leftBetter++;
09418             break;
09419 
09420           case ImplicitConversionSequence::Worse:
09421             leftBetter--;
09422             break;
09423 
09424           case ImplicitConversionSequence::Indistinguishable:
09425             break;
09426           }
09427         }
09428         if (leftBetter > 0) return true;
09429         if (leftBetter < 0) return false;
09430 
09431       } else if (R->FailureKind == ovl_fail_bad_conversion)
09432         return false;
09433 
09434       if (L->FailureKind == ovl_fail_bad_deduction) {
09435         if (R->FailureKind != ovl_fail_bad_deduction)
09436           return true;
09437 
09438         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
09439           return RankDeductionFailure(L->DeductionFailure)
09440                < RankDeductionFailure(R->DeductionFailure);
09441       } else if (R->FailureKind == ovl_fail_bad_deduction)
09442         return false;
09443 
09444       // TODO: others?
09445     }
09446 
09447     // Sort everything else by location.
09448     SourceLocation LLoc = GetLocationForCandidate(L);
09449     SourceLocation RLoc = GetLocationForCandidate(R);
09450 
09451     // Put candidates without locations (e.g. builtins) at the end.
09452     if (LLoc.isInvalid()) return false;
09453     if (RLoc.isInvalid()) return true;
09454 
09455     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
09456   }
09457 };
09458 }
09459 
09460 /// CompleteNonViableCandidate - Normally, overload resolution only
09461 /// computes up to the first. Produces the FixIt set if possible.
09462 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
09463                                        ArrayRef<Expr *> Args) {
09464   assert(!Cand->Viable);
09465 
09466   // Don't do anything on failures other than bad conversion.
09467   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
09468 
09469   // We only want the FixIts if all the arguments can be corrected.
09470   bool Unfixable = false;
09471   // Use a implicit copy initialization to check conversion fixes.
09472   Cand->Fix.setConversionChecker(TryCopyInitialization);
09473 
09474   // Skip forward to the first bad conversion.
09475   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
09476   unsigned ConvCount = Cand->NumConversions;
09477   while (true) {
09478     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
09479     ConvIdx++;
09480     if (Cand->Conversions[ConvIdx - 1].isBad()) {
09481       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
09482       break;
09483     }
09484   }
09485 
09486   if (ConvIdx == ConvCount)
09487     return;
09488 
09489   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
09490          "remaining conversion is initialized?");
09491 
09492   // FIXME: this should probably be preserved from the overload
09493   // operation somehow.
09494   bool SuppressUserConversions = false;
09495 
09496   const FunctionProtoType* Proto;
09497   unsigned ArgIdx = ConvIdx;
09498 
09499   if (Cand->IsSurrogate) {
09500     QualType ConvType
09501       = Cand->Surrogate->getConversionType().getNonReferenceType();
09502     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
09503       ConvType = ConvPtrType->getPointeeType();
09504     Proto = ConvType->getAs<FunctionProtoType>();
09505     ArgIdx--;
09506   } else if (Cand->Function) {
09507     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
09508     if (isa<CXXMethodDecl>(Cand->Function) &&
09509         !isa<CXXConstructorDecl>(Cand->Function))
09510       ArgIdx--;
09511   } else {
09512     // Builtin binary operator with a bad first conversion.
09513     assert(ConvCount <= 3);
09514     for (; ConvIdx != ConvCount; ++ConvIdx)
09515       Cand->Conversions[ConvIdx]
09516         = TryCopyInitialization(S, Args[ConvIdx],
09517                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
09518                                 SuppressUserConversions,
09519                                 /*InOverloadResolution*/ true,
09520                                 /*AllowObjCWritebackConversion=*/
09521                                   S.getLangOpts().ObjCAutoRefCount);
09522     return;
09523   }
09524 
09525   // Fill in the rest of the conversions.
09526   unsigned NumParams = Proto->getNumParams();
09527   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
09528     if (ArgIdx < NumParams) {
09529       Cand->Conversions[ConvIdx] = TryCopyInitialization(
09530           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
09531           /*InOverloadResolution=*/true,
09532           /*AllowObjCWritebackConversion=*/
09533           S.getLangOpts().ObjCAutoRefCount);
09534       // Store the FixIt in the candidate if it exists.
09535       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
09536         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
09537     }
09538     else
09539       Cand->Conversions[ConvIdx].setEllipsis();
09540   }
09541 }
09542 
09543 /// PrintOverloadCandidates - When overload resolution fails, prints
09544 /// diagnostic messages containing the candidates in the candidate
09545 /// set.
09546 void OverloadCandidateSet::NoteCandidates(Sema &S,
09547                                           OverloadCandidateDisplayKind OCD,
09548                                           ArrayRef<Expr *> Args,
09549                                           StringRef Opc,
09550                                           SourceLocation OpLoc) {
09551   // Sort the candidates by viability and position.  Sorting directly would
09552   // be prohibitive, so we make a set of pointers and sort those.
09553   SmallVector<OverloadCandidate*, 32> Cands;
09554   if (OCD == OCD_AllCandidates) Cands.reserve(size());
09555   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
09556     if (Cand->Viable)
09557       Cands.push_back(Cand);
09558     else if (OCD == OCD_AllCandidates) {
09559       CompleteNonViableCandidate(S, Cand, Args);
09560       if (Cand->Function || Cand->IsSurrogate)
09561         Cands.push_back(Cand);
09562       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
09563       // want to list every possible builtin candidate.
09564     }
09565   }
09566 
09567   std::sort(Cands.begin(), Cands.end(),
09568             CompareOverloadCandidatesForDisplay(S, Args.size()));
09569 
09570   bool ReportedAmbiguousConversions = false;
09571 
09572   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
09573   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
09574   unsigned CandsShown = 0;
09575   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
09576     OverloadCandidate *Cand = *I;
09577 
09578     // Set an arbitrary limit on the number of candidate functions we'll spam
09579     // the user with.  FIXME: This limit should depend on details of the
09580     // candidate list.
09581     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
09582       break;
09583     }
09584     ++CandsShown;
09585 
09586     if (Cand->Function)
09587       NoteFunctionCandidate(S, Cand, Args.size());
09588     else if (Cand->IsSurrogate)
09589       NoteSurrogateCandidate(S, Cand);
09590     else {
09591       assert(Cand->Viable &&
09592              "Non-viable built-in candidates are not added to Cands.");
09593       // Generally we only see ambiguities including viable builtin
09594       // operators if overload resolution got screwed up by an
09595       // ambiguous user-defined conversion.
09596       //
09597       // FIXME: It's quite possible for different conversions to see
09598       // different ambiguities, though.
09599       if (!ReportedAmbiguousConversions) {
09600         NoteAmbiguousUserConversions(S, OpLoc, Cand);
09601         ReportedAmbiguousConversions = true;
09602       }
09603 
09604       // If this is a viable builtin, print it.
09605       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
09606     }
09607   }
09608 
09609   if (I != E)
09610     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
09611 }
09612 
09613 static SourceLocation
09614 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
09615   return Cand->Specialization ? Cand->Specialization->getLocation()
09616                               : SourceLocation();
09617 }
09618 
09619 namespace {
09620 struct CompareTemplateSpecCandidatesForDisplay {
09621   Sema &S;
09622   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
09623 
09624   bool operator()(const TemplateSpecCandidate *L,
09625                   const TemplateSpecCandidate *R) {
09626     // Fast-path this check.
09627     if (L == R)
09628       return false;
09629 
09630     // Assuming that both candidates are not matches...
09631 
09632     // Sort by the ranking of deduction failures.
09633     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
09634       return RankDeductionFailure(L->DeductionFailure) <
09635              RankDeductionFailure(R->DeductionFailure);
09636 
09637     // Sort everything else by location.
09638     SourceLocation LLoc = GetLocationForCandidate(L);
09639     SourceLocation RLoc = GetLocationForCandidate(R);
09640 
09641     // Put candidates without locations (e.g. builtins) at the end.
09642     if (LLoc.isInvalid())
09643       return false;
09644     if (RLoc.isInvalid())
09645       return true;
09646 
09647     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
09648   }
09649 };
09650 }
09651 
09652 /// Diagnose a template argument deduction failure.
09653 /// We are treating these failures as overload failures due to bad
09654 /// deductions.
09655 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
09656   DiagnoseBadDeduction(S, Specialization, // pattern
09657                        DeductionFailure, /*NumArgs=*/0);
09658 }
09659 
09660 void TemplateSpecCandidateSet::destroyCandidates() {
09661   for (iterator i = begin(), e = end(); i != e; ++i) {
09662     i->DeductionFailure.Destroy();
09663   }
09664 }
09665 
09666 void TemplateSpecCandidateSet::clear() {
09667   destroyCandidates();
09668   Candidates.clear();
09669 }
09670 
09671 /// NoteCandidates - When no template specialization match is found, prints
09672 /// diagnostic messages containing the non-matching specializations that form
09673 /// the candidate set.
09674 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
09675 /// OCD == OCD_AllCandidates and Cand->Viable == false.
09676 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
09677   // Sort the candidates by position (assuming no candidate is a match).
09678   // Sorting directly would be prohibitive, so we make a set of pointers
09679   // and sort those.
09680   SmallVector<TemplateSpecCandidate *, 32> Cands;
09681   Cands.reserve(size());
09682   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
09683     if (Cand->Specialization)
09684       Cands.push_back(Cand);
09685     // Otherwise, this is a non-matching builtin candidate.  We do not,
09686     // in general, want to list every possible builtin candidate.
09687   }
09688 
09689   std::sort(Cands.begin(), Cands.end(),
09690             CompareTemplateSpecCandidatesForDisplay(S));
09691 
09692   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
09693   // for generalization purposes (?).
09694   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
09695 
09696   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
09697   unsigned CandsShown = 0;
09698   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
09699     TemplateSpecCandidate *Cand = *I;
09700 
09701     // Set an arbitrary limit on the number of candidates we'll spam
09702     // the user with.  FIXME: This limit should depend on details of the
09703     // candidate list.
09704     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
09705       break;
09706     ++CandsShown;
09707 
09708     assert(Cand->Specialization &&
09709            "Non-matching built-in candidates are not added to Cands.");
09710     Cand->NoteDeductionFailure(S);
09711   }
09712 
09713   if (I != E)
09714     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
09715 }
09716 
09717 // [PossiblyAFunctionType]  -->   [Return]
09718 // NonFunctionType --> NonFunctionType
09719 // R (A) --> R(A)
09720 // R (*)(A) --> R (A)
09721 // R (&)(A) --> R (A)
09722 // R (S::*)(A) --> R (A)
09723 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
09724   QualType Ret = PossiblyAFunctionType;
09725   if (const PointerType *ToTypePtr = 
09726     PossiblyAFunctionType->getAs<PointerType>())
09727     Ret = ToTypePtr->getPointeeType();
09728   else if (const ReferenceType *ToTypeRef = 
09729     PossiblyAFunctionType->getAs<ReferenceType>())
09730     Ret = ToTypeRef->getPointeeType();
09731   else if (const MemberPointerType *MemTypePtr =
09732     PossiblyAFunctionType->getAs<MemberPointerType>()) 
09733     Ret = MemTypePtr->getPointeeType();   
09734   Ret = 
09735     Context.getCanonicalType(Ret).getUnqualifiedType();
09736   return Ret;
09737 }
09738 
09739 namespace {
09740 // A helper class to help with address of function resolution
09741 // - allows us to avoid passing around all those ugly parameters
09742 class AddressOfFunctionResolver {
09743   Sema& S;
09744   Expr* SourceExpr;
09745   const QualType& TargetType; 
09746   QualType TargetFunctionType; // Extracted function type from target type 
09747    
09748   bool Complain;
09749   //DeclAccessPair& ResultFunctionAccessPair;
09750   ASTContext& Context;
09751 
09752   bool TargetTypeIsNonStaticMemberFunction;
09753   bool FoundNonTemplateFunction;
09754   bool StaticMemberFunctionFromBoundPointer;
09755 
09756   OverloadExpr::FindResult OvlExprInfo; 
09757   OverloadExpr *OvlExpr;
09758   TemplateArgumentListInfo OvlExplicitTemplateArgs;
09759   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
09760   TemplateSpecCandidateSet FailedCandidates;
09761 
09762 public:
09763   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
09764                             const QualType &TargetType, bool Complain)
09765       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
09766         Complain(Complain), Context(S.getASTContext()),
09767         TargetTypeIsNonStaticMemberFunction(
09768             !!TargetType->getAs<MemberPointerType>()),
09769         FoundNonTemplateFunction(false),
09770         StaticMemberFunctionFromBoundPointer(false),
09771         OvlExprInfo(OverloadExpr::find(SourceExpr)),
09772         OvlExpr(OvlExprInfo.Expression),
09773         FailedCandidates(OvlExpr->getNameLoc()) {
09774     ExtractUnqualifiedFunctionTypeFromTargetType();
09775 
09776     if (TargetFunctionType->isFunctionType()) {
09777       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
09778         if (!UME->isImplicitAccess() &&
09779             !S.ResolveSingleFunctionTemplateSpecialization(UME))
09780           StaticMemberFunctionFromBoundPointer = true;
09781     } else if (OvlExpr->hasExplicitTemplateArgs()) {
09782       DeclAccessPair dap;
09783       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
09784               OvlExpr, false, &dap)) {
09785         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
09786           if (!Method->isStatic()) {
09787             // If the target type is a non-function type and the function found
09788             // is a non-static member function, pretend as if that was the
09789             // target, it's the only possible type to end up with.
09790             TargetTypeIsNonStaticMemberFunction = true;
09791 
09792             // And skip adding the function if its not in the proper form.
09793             // We'll diagnose this due to an empty set of functions.
09794             if (!OvlExprInfo.HasFormOfMemberPointer)
09795               return;
09796           }
09797 
09798         Matches.push_back(std::make_pair(dap, Fn));
09799       }
09800       return;
09801     }
09802     
09803     if (OvlExpr->hasExplicitTemplateArgs())
09804       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
09805 
09806     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
09807       // C++ [over.over]p4:
09808       //   If more than one function is selected, [...]
09809       if (Matches.size() > 1) {
09810         if (FoundNonTemplateFunction)
09811           EliminateAllTemplateMatches();
09812         else
09813           EliminateAllExceptMostSpecializedTemplate();
09814       }
09815     }
09816   }
09817   
09818 private:
09819   bool isTargetTypeAFunction() const {
09820     return TargetFunctionType->isFunctionType();
09821   }
09822 
09823   // [ToType]     [Return]
09824 
09825   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
09826   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
09827   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
09828   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
09829     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
09830   }
09831 
09832   // return true if any matching specializations were found
09833   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 
09834                                    const DeclAccessPair& CurAccessFunPair) {
09835     if (CXXMethodDecl *Method
09836               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
09837       // Skip non-static function templates when converting to pointer, and
09838       // static when converting to member pointer.
09839       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
09840         return false;
09841     } 
09842     else if (TargetTypeIsNonStaticMemberFunction)
09843       return false;
09844 
09845     // C++ [over.over]p2:
09846     //   If the name is a function template, template argument deduction is
09847     //   done (14.8.2.2), and if the argument deduction succeeds, the
09848     //   resulting template argument list is used to generate a single
09849     //   function template specialization, which is added to the set of
09850     //   overloaded functions considered.
09851     FunctionDecl *Specialization = nullptr;
09852     TemplateDeductionInfo Info(FailedCandidates.getLocation());
09853     if (Sema::TemplateDeductionResult Result
09854           = S.DeduceTemplateArguments(FunctionTemplate, 
09855                                       &OvlExplicitTemplateArgs,
09856                                       TargetFunctionType, Specialization, 
09857                                       Info, /*InOverloadResolution=*/true)) {
09858       // Make a note of the failed deduction for diagnostics.
09859       FailedCandidates.addCandidate()
09860           .set(FunctionTemplate->getTemplatedDecl(),
09861                MakeDeductionFailureInfo(Context, Result, Info));
09862       return false;
09863     } 
09864     
09865     // Template argument deduction ensures that we have an exact match or
09866     // compatible pointer-to-function arguments that would be adjusted by ICS.
09867     // This function template specicalization works.
09868     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
09869     assert(S.isSameOrCompatibleFunctionType(
09870               Context.getCanonicalType(Specialization->getType()),
09871               Context.getCanonicalType(TargetFunctionType)));
09872     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
09873     return true;
09874   }
09875   
09876   bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 
09877                                       const DeclAccessPair& CurAccessFunPair) {
09878     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
09879       // Skip non-static functions when converting to pointer, and static
09880       // when converting to member pointer.
09881       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
09882         return false;
09883     } 
09884     else if (TargetTypeIsNonStaticMemberFunction)
09885       return false;
09886 
09887     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
09888       if (S.getLangOpts().CUDA)
09889         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
09890           if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
09891             return false;
09892 
09893       // If any candidate has a placeholder return type, trigger its deduction
09894       // now.
09895       if (S.getLangOpts().CPlusPlus14 &&
09896           FunDecl->getReturnType()->isUndeducedType() &&
09897           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
09898         return false;
09899 
09900       QualType ResultTy;
09901       if (Context.hasSameUnqualifiedType(TargetFunctionType, 
09902                                          FunDecl->getType()) ||
09903           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
09904                                  ResultTy)) {
09905         Matches.push_back(std::make_pair(CurAccessFunPair,
09906           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
09907         FoundNonTemplateFunction = true;
09908         return true;
09909       }
09910     }
09911     
09912     return false;
09913   }
09914   
09915   bool FindAllFunctionsThatMatchTargetTypeExactly() {
09916     bool Ret = false;
09917     
09918     // If the overload expression doesn't have the form of a pointer to
09919     // member, don't try to convert it to a pointer-to-member type.
09920     if (IsInvalidFormOfPointerToMemberFunction())
09921       return false;
09922 
09923     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
09924                                E = OvlExpr->decls_end(); 
09925          I != E; ++I) {
09926       // Look through any using declarations to find the underlying function.
09927       NamedDecl *Fn = (*I)->getUnderlyingDecl();
09928 
09929       // C++ [over.over]p3:
09930       //   Non-member functions and static member functions match
09931       //   targets of type "pointer-to-function" or "reference-to-function."
09932       //   Nonstatic member functions match targets of
09933       //   type "pointer-to-member-function."
09934       // Note that according to DR 247, the containing class does not matter.
09935       if (FunctionTemplateDecl *FunctionTemplate
09936                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
09937         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
09938           Ret = true;
09939       }
09940       // If we have explicit template arguments supplied, skip non-templates.
09941       else if (!OvlExpr->hasExplicitTemplateArgs() &&
09942                AddMatchingNonTemplateFunction(Fn, I.getPair()))
09943         Ret = true;
09944     }
09945     assert(Ret || Matches.empty());
09946     return Ret;
09947   }
09948 
09949   void EliminateAllExceptMostSpecializedTemplate() {
09950     //   [...] and any given function template specialization F1 is
09951     //   eliminated if the set contains a second function template
09952     //   specialization whose function template is more specialized
09953     //   than the function template of F1 according to the partial
09954     //   ordering rules of 14.5.5.2.
09955 
09956     // The algorithm specified above is quadratic. We instead use a
09957     // two-pass algorithm (similar to the one used to identify the
09958     // best viable function in an overload set) that identifies the
09959     // best function template (if it exists).
09960 
09961     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
09962     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
09963       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
09964 
09965     // TODO: It looks like FailedCandidates does not serve much purpose
09966     // here, since the no_viable diagnostic has index 0.
09967     UnresolvedSetIterator Result = S.getMostSpecialized(
09968         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
09969         SourceExpr->getLocStart(), S.PDiag(),
09970         S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
09971                                                      .second->getDeclName(),
09972         S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
09973         Complain, TargetFunctionType);
09974 
09975     if (Result != MatchesCopy.end()) {
09976       // Make it the first and only element
09977       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
09978       Matches[0].second = cast<FunctionDecl>(*Result);
09979       Matches.resize(1);
09980     }
09981   }
09982 
09983   void EliminateAllTemplateMatches() {
09984     //   [...] any function template specializations in the set are
09985     //   eliminated if the set also contains a non-template function, [...]
09986     for (unsigned I = 0, N = Matches.size(); I != N; ) {
09987       if (Matches[I].second->getPrimaryTemplate() == nullptr)
09988         ++I;
09989       else {
09990         Matches[I] = Matches[--N];
09991         Matches.set_size(N);
09992       }
09993     }
09994   }
09995 
09996 public:
09997   void ComplainNoMatchesFound() const {
09998     assert(Matches.empty());
09999     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10000         << OvlExpr->getName() << TargetFunctionType
10001         << OvlExpr->getSourceRange();
10002     if (FailedCandidates.empty())
10003       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10004     else {
10005       // We have some deduction failure messages. Use them to diagnose
10006       // the function templates, and diagnose the non-template candidates
10007       // normally.
10008       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10009                                  IEnd = OvlExpr->decls_end();
10010            I != IEnd; ++I)
10011         if (FunctionDecl *Fun =
10012                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10013           S.NoteOverloadCandidate(Fun, TargetFunctionType);
10014       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10015     }
10016   }
10017 
10018   bool IsInvalidFormOfPointerToMemberFunction() const {
10019     return TargetTypeIsNonStaticMemberFunction &&
10020       !OvlExprInfo.HasFormOfMemberPointer;
10021   }
10022 
10023   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10024       // TODO: Should we condition this on whether any functions might
10025       // have matched, or is it more appropriate to do that in callers?
10026       // TODO: a fixit wouldn't hurt.
10027       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10028         << TargetType << OvlExpr->getSourceRange();
10029   }
10030 
10031   bool IsStaticMemberFunctionFromBoundPointer() const {
10032     return StaticMemberFunctionFromBoundPointer;
10033   }
10034 
10035   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10036     S.Diag(OvlExpr->getLocStart(),
10037            diag::err_invalid_form_pointer_member_function)
10038       << OvlExpr->getSourceRange();
10039   }
10040 
10041   void ComplainOfInvalidConversion() const {
10042     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10043       << OvlExpr->getName() << TargetType;
10044   }
10045 
10046   void ComplainMultipleMatchesFound() const {
10047     assert(Matches.size() > 1);
10048     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10049       << OvlExpr->getName()
10050       << OvlExpr->getSourceRange();
10051     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10052   }
10053 
10054   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10055 
10056   int getNumMatches() const { return Matches.size(); }
10057   
10058   FunctionDecl* getMatchingFunctionDecl() const {
10059     if (Matches.size() != 1) return nullptr;
10060     return Matches[0].second;
10061   }
10062   
10063   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10064     if (Matches.size() != 1) return nullptr;
10065     return &Matches[0].first;
10066   }
10067 };
10068 }
10069 
10070 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10071 /// an overloaded function (C++ [over.over]), where @p From is an
10072 /// expression with overloaded function type and @p ToType is the type
10073 /// we're trying to resolve to. For example:
10074 ///
10075 /// @code
10076 /// int f(double);
10077 /// int f(int);
10078 ///
10079 /// int (*pfd)(double) = f; // selects f(double)
10080 /// @endcode
10081 ///
10082 /// This routine returns the resulting FunctionDecl if it could be
10083 /// resolved, and NULL otherwise. When @p Complain is true, this
10084 /// routine will emit diagnostics if there is an error.
10085 FunctionDecl *
10086 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10087                                          QualType TargetType,
10088                                          bool Complain,
10089                                          DeclAccessPair &FoundResult,
10090                                          bool *pHadMultipleCandidates) {
10091   assert(AddressOfExpr->getType() == Context.OverloadTy);
10092 
10093   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10094                                      Complain);
10095   int NumMatches = Resolver.getNumMatches();
10096   FunctionDecl *Fn = nullptr;
10097   if (NumMatches == 0 && Complain) {
10098     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10099       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10100     else
10101       Resolver.ComplainNoMatchesFound();
10102   }
10103   else if (NumMatches > 1 && Complain)
10104     Resolver.ComplainMultipleMatchesFound();
10105   else if (NumMatches == 1) {
10106     Fn = Resolver.getMatchingFunctionDecl();
10107     assert(Fn);
10108     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10109     if (Complain) {
10110       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10111         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10112       else
10113         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10114     }
10115   }
10116 
10117   if (pHadMultipleCandidates)
10118     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10119   return Fn;
10120 }
10121 
10122 /// \brief Given an expression that refers to an overloaded function, try to
10123 /// resolve that overloaded function expression down to a single function.
10124 ///
10125 /// This routine can only resolve template-ids that refer to a single function
10126 /// template, where that template-id refers to a single template whose template
10127 /// arguments are either provided by the template-id or have defaults,
10128 /// as described in C++0x [temp.arg.explicit]p3.
10129 ///
10130 /// If no template-ids are found, no diagnostics are emitted and NULL is
10131 /// returned.
10132 FunctionDecl *
10133 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 
10134                                                   bool Complain,
10135                                                   DeclAccessPair *FoundResult) {
10136   // C++ [over.over]p1:
10137   //   [...] [Note: any redundant set of parentheses surrounding the
10138   //   overloaded function name is ignored (5.1). ]
10139   // C++ [over.over]p1:
10140   //   [...] The overloaded function name can be preceded by the &
10141   //   operator.
10142 
10143   // If we didn't actually find any template-ids, we're done.
10144   if (!ovl->hasExplicitTemplateArgs())
10145     return nullptr;
10146 
10147   TemplateArgumentListInfo ExplicitTemplateArgs;
10148   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
10149   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10150 
10151   // Look through all of the overloaded functions, searching for one
10152   // whose type matches exactly.
10153   FunctionDecl *Matched = nullptr;
10154   for (UnresolvedSetIterator I = ovl->decls_begin(),
10155          E = ovl->decls_end(); I != E; ++I) {
10156     // C++0x [temp.arg.explicit]p3:
10157     //   [...] In contexts where deduction is done and fails, or in contexts
10158     //   where deduction is not done, if a template argument list is
10159     //   specified and it, along with any default template arguments,
10160     //   identifies a single function template specialization, then the
10161     //   template-id is an lvalue for the function template specialization.
10162     FunctionTemplateDecl *FunctionTemplate
10163       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10164 
10165     // C++ [over.over]p2:
10166     //   If the name is a function template, template argument deduction is
10167     //   done (14.8.2.2), and if the argument deduction succeeds, the
10168     //   resulting template argument list is used to generate a single
10169     //   function template specialization, which is added to the set of
10170     //   overloaded functions considered.
10171     FunctionDecl *Specialization = nullptr;
10172     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10173     if (TemplateDeductionResult Result
10174           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10175                                     Specialization, Info,
10176                                     /*InOverloadResolution=*/true)) {
10177       // Make a note of the failed deduction for diagnostics.
10178       // TODO: Actually use the failed-deduction info?
10179       FailedCandidates.addCandidate()
10180           .set(FunctionTemplate->getTemplatedDecl(),
10181                MakeDeductionFailureInfo(Context, Result, Info));
10182       continue;
10183     }
10184 
10185     assert(Specialization && "no specialization and no error?");
10186 
10187     // Multiple matches; we can't resolve to a single declaration.
10188     if (Matched) {
10189       if (Complain) {
10190         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10191           << ovl->getName();
10192         NoteAllOverloadCandidates(ovl);
10193       }
10194       return nullptr;
10195     }
10196     
10197     Matched = Specialization;
10198     if (FoundResult) *FoundResult = I.getPair();    
10199   }
10200 
10201   if (Matched && getLangOpts().CPlusPlus14 &&
10202       Matched->getReturnType()->isUndeducedType() &&
10203       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10204     return nullptr;
10205 
10206   return Matched;
10207 }
10208 
10209 
10210 
10211 
10212 // Resolve and fix an overloaded expression that can be resolved
10213 // because it identifies a single function template specialization.
10214 //
10215 // Last three arguments should only be supplied if Complain = true
10216 //
10217 // Return true if it was logically possible to so resolve the
10218 // expression, regardless of whether or not it succeeded.  Always
10219 // returns true if 'complain' is set.
10220 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10221                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10222                    bool complain, const SourceRange& OpRangeForComplaining, 
10223                                            QualType DestTypeForComplaining, 
10224                                             unsigned DiagIDForComplaining) {
10225   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10226 
10227   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10228 
10229   DeclAccessPair found;
10230   ExprResult SingleFunctionExpression;
10231   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10232                            ovl.Expression, /*complain*/ false, &found)) {
10233     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10234       SrcExpr = ExprError();
10235       return true;
10236     }
10237 
10238     // It is only correct to resolve to an instance method if we're
10239     // resolving a form that's permitted to be a pointer to member.
10240     // Otherwise we'll end up making a bound member expression, which
10241     // is illegal in all the contexts we resolve like this.
10242     if (!ovl.HasFormOfMemberPointer &&
10243         isa<CXXMethodDecl>(fn) &&
10244         cast<CXXMethodDecl>(fn)->isInstance()) {
10245       if (!complain) return false;
10246 
10247       Diag(ovl.Expression->getExprLoc(),
10248            diag::err_bound_member_function)
10249         << 0 << ovl.Expression->getSourceRange();
10250 
10251       // TODO: I believe we only end up here if there's a mix of
10252       // static and non-static candidates (otherwise the expression
10253       // would have 'bound member' type, not 'overload' type).
10254       // Ideally we would note which candidate was chosen and why
10255       // the static candidates were rejected.
10256       SrcExpr = ExprError();
10257       return true;
10258     }
10259 
10260     // Fix the expression to refer to 'fn'.
10261     SingleFunctionExpression =
10262         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10263 
10264     // If desired, do function-to-pointer decay.
10265     if (doFunctionPointerConverion) {
10266       SingleFunctionExpression =
10267         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10268       if (SingleFunctionExpression.isInvalid()) {
10269         SrcExpr = ExprError();
10270         return true;
10271       }
10272     }
10273   }
10274 
10275   if (!SingleFunctionExpression.isUsable()) {
10276     if (complain) {
10277       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10278         << ovl.Expression->getName()
10279         << DestTypeForComplaining
10280         << OpRangeForComplaining 
10281         << ovl.Expression->getQualifierLoc().getSourceRange();
10282       NoteAllOverloadCandidates(SrcExpr.get());
10283 
10284       SrcExpr = ExprError();
10285       return true;
10286     }
10287 
10288     return false;
10289   }
10290 
10291   SrcExpr = SingleFunctionExpression;
10292   return true;
10293 }
10294 
10295 /// \brief Add a single candidate to the overload set.
10296 static void AddOverloadedCallCandidate(Sema &S,
10297                                        DeclAccessPair FoundDecl,
10298                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
10299                                        ArrayRef<Expr *> Args,
10300                                        OverloadCandidateSet &CandidateSet,
10301                                        bool PartialOverloading,
10302                                        bool KnownValid) {
10303   NamedDecl *Callee = FoundDecl.getDecl();
10304   if (isa<UsingShadowDecl>(Callee))
10305     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10306 
10307   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10308     if (ExplicitTemplateArgs) {
10309       assert(!KnownValid && "Explicit template arguments?");
10310       return;
10311     }
10312     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10313                            PartialOverloading);
10314     return;
10315   }
10316 
10317   if (FunctionTemplateDecl *FuncTemplate
10318       = dyn_cast<FunctionTemplateDecl>(Callee)) {
10319     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10320                                    ExplicitTemplateArgs, Args, CandidateSet);
10321     return;
10322   }
10323 
10324   assert(!KnownValid && "unhandled case in overloaded call candidate");
10325 }
10326 
10327 /// \brief Add the overload candidates named by callee and/or found by argument
10328 /// dependent lookup to the given overload set.
10329 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10330                                        ArrayRef<Expr *> Args,
10331                                        OverloadCandidateSet &CandidateSet,
10332                                        bool PartialOverloading) {
10333 
10334 #ifndef NDEBUG
10335   // Verify that ArgumentDependentLookup is consistent with the rules
10336   // in C++0x [basic.lookup.argdep]p3:
10337   //
10338   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10339   //   and let Y be the lookup set produced by argument dependent
10340   //   lookup (defined as follows). If X contains
10341   //
10342   //     -- a declaration of a class member, or
10343   //
10344   //     -- a block-scope function declaration that is not a
10345   //        using-declaration, or
10346   //
10347   //     -- a declaration that is neither a function or a function
10348   //        template
10349   //
10350   //   then Y is empty.
10351 
10352   if (ULE->requiresADL()) {
10353     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10354            E = ULE->decls_end(); I != E; ++I) {
10355       assert(!(*I)->getDeclContext()->isRecord());
10356       assert(isa<UsingShadowDecl>(*I) ||
10357              !(*I)->getDeclContext()->isFunctionOrMethod());
10358       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
10359     }
10360   }
10361 #endif
10362 
10363   // It would be nice to avoid this copy.
10364   TemplateArgumentListInfo TABuffer;
10365   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10366   if (ULE->hasExplicitTemplateArgs()) {
10367     ULE->copyTemplateArgumentsInto(TABuffer);
10368     ExplicitTemplateArgs = &TABuffer;
10369   }
10370 
10371   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10372          E = ULE->decls_end(); I != E; ++I)
10373     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10374                                CandidateSet, PartialOverloading,
10375                                /*KnownValid*/ true);
10376 
10377   if (ULE->requiresADL())
10378     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10379                                          Args, ExplicitTemplateArgs,
10380                                          CandidateSet, PartialOverloading);
10381 }
10382 
10383 /// Determine whether a declaration with the specified name could be moved into
10384 /// a different namespace.
10385 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10386   switch (Name.getCXXOverloadedOperator()) {
10387   case OO_New: case OO_Array_New:
10388   case OO_Delete: case OO_Array_Delete:
10389     return false;
10390 
10391   default:
10392     return true;
10393   }
10394 }
10395 
10396 /// Attempt to recover from an ill-formed use of a non-dependent name in a
10397 /// template, where the non-dependent name was declared after the template
10398 /// was defined. This is common in code written for a compilers which do not
10399 /// correctly implement two-stage name lookup.
10400 ///
10401 /// Returns true if a viable candidate was found and a diagnostic was issued.
10402 static bool
10403 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10404                        const CXXScopeSpec &SS, LookupResult &R,
10405                        OverloadCandidateSet::CandidateSetKind CSK,
10406                        TemplateArgumentListInfo *ExplicitTemplateArgs,
10407                        ArrayRef<Expr *> Args) {
10408   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10409     return false;
10410 
10411   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10412     if (DC->isTransparentContext())
10413       continue;
10414 
10415     SemaRef.LookupQualifiedName(R, DC);
10416 
10417     if (!R.empty()) {
10418       R.suppressDiagnostics();
10419 
10420       if (isa<CXXRecordDecl>(DC)) {
10421         // Don't diagnose names we find in classes; we get much better
10422         // diagnostics for these from DiagnoseEmptyLookup.
10423         R.clear();
10424         return false;
10425       }
10426 
10427       OverloadCandidateSet Candidates(FnLoc, CSK);
10428       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10429         AddOverloadedCallCandidate(SemaRef, I.getPair(),
10430                                    ExplicitTemplateArgs, Args,
10431                                    Candidates, false, /*KnownValid*/ false);
10432 
10433       OverloadCandidateSet::iterator Best;
10434       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10435         // No viable functions. Don't bother the user with notes for functions
10436         // which don't work and shouldn't be found anyway.
10437         R.clear();
10438         return false;
10439       }
10440 
10441       // Find the namespaces where ADL would have looked, and suggest
10442       // declaring the function there instead.
10443       Sema::AssociatedNamespaceSet AssociatedNamespaces;
10444       Sema::AssociatedClassSet AssociatedClasses;
10445       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10446                                                  AssociatedNamespaces,
10447                                                  AssociatedClasses);
10448       Sema::AssociatedNamespaceSet SuggestedNamespaces;
10449       if (canBeDeclaredInNamespace(R.getLookupName())) {
10450         DeclContext *Std = SemaRef.getStdNamespace();
10451         for (Sema::AssociatedNamespaceSet::iterator
10452                it = AssociatedNamespaces.begin(),
10453                end = AssociatedNamespaces.end(); it != end; ++it) {
10454           // Never suggest declaring a function within namespace 'std'.
10455           if (Std && Std->Encloses(*it))
10456             continue;
10457 
10458           // Never suggest declaring a function within a namespace with a
10459           // reserved name, like __gnu_cxx.
10460           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10461           if (NS &&
10462               NS->getQualifiedNameAsString().find("__") != std::string::npos)
10463             continue;
10464 
10465           SuggestedNamespaces.insert(*it);
10466         }
10467       }
10468 
10469       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10470         << R.getLookupName();
10471       if (SuggestedNamespaces.empty()) {
10472         SemaRef.Diag(Best->Function->getLocation(),
10473                      diag::note_not_found_by_two_phase_lookup)
10474           << R.getLookupName() << 0;
10475       } else if (SuggestedNamespaces.size() == 1) {
10476         SemaRef.Diag(Best->Function->getLocation(),
10477                      diag::note_not_found_by_two_phase_lookup)
10478           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10479       } else {
10480         // FIXME: It would be useful to list the associated namespaces here,
10481         // but the diagnostics infrastructure doesn't provide a way to produce
10482         // a localized representation of a list of items.
10483         SemaRef.Diag(Best->Function->getLocation(),
10484                      diag::note_not_found_by_two_phase_lookup)
10485           << R.getLookupName() << 2;
10486       }
10487 
10488       // Try to recover by calling this function.
10489       return true;
10490     }
10491 
10492     R.clear();
10493   }
10494 
10495   return false;
10496 }
10497 
10498 /// Attempt to recover from ill-formed use of a non-dependent operator in a
10499 /// template, where the non-dependent operator was declared after the template
10500 /// was defined.
10501 ///
10502 /// Returns true if a viable candidate was found and a diagnostic was issued.
10503 static bool
10504 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10505                                SourceLocation OpLoc,
10506                                ArrayRef<Expr *> Args) {
10507   DeclarationName OpName =
10508     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10509   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10510   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10511                                 OverloadCandidateSet::CSK_Operator,
10512                                 /*ExplicitTemplateArgs=*/nullptr, Args);
10513 }
10514 
10515 namespace {
10516 class BuildRecoveryCallExprRAII {
10517   Sema &SemaRef;
10518 public:
10519   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10520     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10521     SemaRef.IsBuildingRecoveryCallExpr = true;
10522   }
10523 
10524   ~BuildRecoveryCallExprRAII() {
10525     SemaRef.IsBuildingRecoveryCallExpr = false;
10526   }
10527 };
10528 
10529 }
10530 
10531 static std::unique_ptr<CorrectionCandidateCallback>
10532 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10533               bool HasTemplateArgs, bool AllowTypoCorrection) {
10534   if (!AllowTypoCorrection)
10535     return llvm::make_unique<NoTypoCorrectionCCC>();
10536   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10537                                                   HasTemplateArgs, ME);
10538 }
10539 
10540 /// Attempts to recover from a call where no functions were found.
10541 ///
10542 /// Returns true if new candidates were found.
10543 static ExprResult
10544 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10545                       UnresolvedLookupExpr *ULE,
10546                       SourceLocation LParenLoc,
10547                       MutableArrayRef<Expr *> Args,
10548                       SourceLocation RParenLoc,
10549                       bool EmptyLookup, bool AllowTypoCorrection) {
10550   // Do not try to recover if it is already building a recovery call.
10551   // This stops infinite loops for template instantiations like
10552   //
10553   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10554   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10555   //
10556   if (SemaRef.IsBuildingRecoveryCallExpr)
10557     return ExprError();
10558   BuildRecoveryCallExprRAII RCE(SemaRef);
10559 
10560   CXXScopeSpec SS;
10561   SS.Adopt(ULE->getQualifierLoc());
10562   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10563 
10564   TemplateArgumentListInfo TABuffer;
10565   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10566   if (ULE->hasExplicitTemplateArgs()) {
10567     ULE->copyTemplateArgumentsInto(TABuffer);
10568     ExplicitTemplateArgs = &TABuffer;
10569   }
10570 
10571   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10572                  Sema::LookupOrdinaryName);
10573   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10574                               OverloadCandidateSet::CSK_Normal,
10575                               ExplicitTemplateArgs, Args) &&
10576       (!EmptyLookup ||
10577        SemaRef.DiagnoseEmptyLookup(
10578            S, SS, R,
10579            MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10580                          ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10581            ExplicitTemplateArgs, Args)))
10582     return ExprError();
10583 
10584   assert(!R.empty() && "lookup results empty despite recovery");
10585 
10586   // Build an implicit member call if appropriate.  Just drop the
10587   // casts and such from the call, we don't really care.
10588   ExprResult NewFn = ExprError();
10589   if ((*R.begin())->isCXXClassMember())
10590     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10591                                                     R, ExplicitTemplateArgs);
10592   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10593     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10594                                         ExplicitTemplateArgs);
10595   else
10596     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10597 
10598   if (NewFn.isInvalid())
10599     return ExprError();
10600 
10601   // This shouldn't cause an infinite loop because we're giving it
10602   // an expression with viable lookup results, which should never
10603   // end up here.
10604   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
10605                                MultiExprArg(Args.data(), Args.size()),
10606                                RParenLoc);
10607 }
10608 
10609 /// \brief Constructs and populates an OverloadedCandidateSet from
10610 /// the given function.
10611 /// \returns true when an the ExprResult output parameter has been set.
10612 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10613                                   UnresolvedLookupExpr *ULE,
10614                                   MultiExprArg Args,
10615                                   SourceLocation RParenLoc,
10616                                   OverloadCandidateSet *CandidateSet,
10617                                   ExprResult *Result) {
10618 #ifndef NDEBUG
10619   if (ULE->requiresADL()) {
10620     // To do ADL, we must have found an unqualified name.
10621     assert(!ULE->getQualifier() && "qualified name with ADL");
10622 
10623     // We don't perform ADL for implicit declarations of builtins.
10624     // Verify that this was correctly set up.
10625     FunctionDecl *F;
10626     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10627         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10628         F->getBuiltinID() && F->isImplicit())
10629       llvm_unreachable("performing ADL for builtin");
10630 
10631     // We don't perform ADL in C.
10632     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10633   }
10634 #endif
10635 
10636   UnbridgedCastsSet UnbridgedCasts;
10637   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10638     *Result = ExprError();
10639     return true;
10640   }
10641 
10642   // Add the functions denoted by the callee to the set of candidate
10643   // functions, including those from argument-dependent lookup.
10644   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10645 
10646   // If we found nothing, try to recover.
10647   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10648   // out if it fails.
10649   if (CandidateSet->empty()) {
10650     // In Microsoft mode, if we are inside a template class member function then
10651     // create a type dependent CallExpr. The goal is to postpone name lookup
10652     // to instantiation time to be able to search into type dependent base
10653     // classes.
10654     if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
10655         (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10656       CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10657                                             Context.DependentTy, VK_RValue,
10658                                             RParenLoc);
10659       CE->setTypeDependent(true);
10660       *Result = CE;
10661       return true;
10662     }
10663     return false;
10664   }
10665 
10666   UnbridgedCasts.restore();
10667   return false;
10668 }
10669 
10670 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10671 /// the completed call expression. If overload resolution fails, emits
10672 /// diagnostics and returns ExprError()
10673 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10674                                            UnresolvedLookupExpr *ULE,
10675                                            SourceLocation LParenLoc,
10676                                            MultiExprArg Args,
10677                                            SourceLocation RParenLoc,
10678                                            Expr *ExecConfig,
10679                                            OverloadCandidateSet *CandidateSet,
10680                                            OverloadCandidateSet::iterator *Best,
10681                                            OverloadingResult OverloadResult,
10682                                            bool AllowTypoCorrection) {
10683   if (CandidateSet->empty())
10684     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10685                                  RParenLoc, /*EmptyLookup=*/true,
10686                                  AllowTypoCorrection);
10687 
10688   switch (OverloadResult) {
10689   case OR_Success: {
10690     FunctionDecl *FDecl = (*Best)->Function;
10691     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10692     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10693       return ExprError();
10694     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10695     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10696                                          ExecConfig);
10697   }
10698 
10699   case OR_No_Viable_Function: {
10700     // Try to recover by looking for viable functions which the user might
10701     // have meant to call.
10702     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10703                                                 Args, RParenLoc,
10704                                                 /*EmptyLookup=*/false,
10705                                                 AllowTypoCorrection);
10706     if (!Recovery.isInvalid())
10707       return Recovery;
10708 
10709     SemaRef.Diag(Fn->getLocStart(),
10710          diag::err_ovl_no_viable_function_in_call)
10711       << ULE->getName() << Fn->getSourceRange();
10712     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10713     break;
10714   }
10715 
10716   case OR_Ambiguous:
10717     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10718       << ULE->getName() << Fn->getSourceRange();
10719     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10720     break;
10721 
10722   case OR_Deleted: {
10723     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10724       << (*Best)->Function->isDeleted()
10725       << ULE->getName()
10726       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10727       << Fn->getSourceRange();
10728     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10729 
10730     // We emitted an error for the unvailable/deleted function call but keep
10731     // the call in the AST.
10732     FunctionDecl *FDecl = (*Best)->Function;
10733     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10734     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10735                                          ExecConfig);
10736   }
10737   }
10738 
10739   // Overload resolution failed.
10740   return ExprError();
10741 }
10742 
10743 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10744 /// (which eventually refers to the declaration Func) and the call
10745 /// arguments Args/NumArgs, attempt to resolve the function call down
10746 /// to a specific function. If overload resolution succeeds, returns
10747 /// the call expression produced by overload resolution.
10748 /// Otherwise, emits diagnostics and returns ExprError.
10749 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10750                                          UnresolvedLookupExpr *ULE,
10751                                          SourceLocation LParenLoc,
10752                                          MultiExprArg Args,
10753                                          SourceLocation RParenLoc,
10754                                          Expr *ExecConfig,
10755                                          bool AllowTypoCorrection) {
10756   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10757                                     OverloadCandidateSet::CSK_Normal);
10758   ExprResult result;
10759 
10760   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10761                              &result))
10762     return result;
10763 
10764   OverloadCandidateSet::iterator Best;
10765   OverloadingResult OverloadResult =
10766       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10767 
10768   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10769                                   RParenLoc, ExecConfig, &CandidateSet,
10770                                   &Best, OverloadResult,
10771                                   AllowTypoCorrection);
10772 }
10773 
10774 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10775   return Functions.size() > 1 ||
10776     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10777 }
10778 
10779 /// \brief Create a unary operation that may resolve to an overloaded
10780 /// operator.
10781 ///
10782 /// \param OpLoc The location of the operator itself (e.g., '*').
10783 ///
10784 /// \param OpcIn The UnaryOperator::Opcode that describes this
10785 /// operator.
10786 ///
10787 /// \param Fns The set of non-member functions that will be
10788 /// considered by overload resolution. The caller needs to build this
10789 /// set based on the context using, e.g.,
10790 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10791 /// set should not contain any member functions; those will be added
10792 /// by CreateOverloadedUnaryOp().
10793 ///
10794 /// \param Input The input argument.
10795 ExprResult
10796 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10797                               const UnresolvedSetImpl &Fns,
10798                               Expr *Input) {
10799   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10800 
10801   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10802   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10803   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10804   // TODO: provide better source location info.
10805   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10806 
10807   if (checkPlaceholderForOverload(*this, Input))
10808     return ExprError();
10809 
10810   Expr *Args[2] = { Input, nullptr };
10811   unsigned NumArgs = 1;
10812 
10813   // For post-increment and post-decrement, add the implicit '0' as
10814   // the second argument, so that we know this is a post-increment or
10815   // post-decrement.
10816   if (Opc == UO_PostInc || Opc == UO_PostDec) {
10817     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10818     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10819                                      SourceLocation());
10820     NumArgs = 2;
10821   }
10822 
10823   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10824 
10825   if (Input->isTypeDependent()) {
10826     if (Fns.empty())
10827       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10828                                          VK_RValue, OK_Ordinary, OpLoc);
10829 
10830     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10831     UnresolvedLookupExpr *Fn
10832       = UnresolvedLookupExpr::Create(Context, NamingClass,
10833                                      NestedNameSpecifierLoc(), OpNameInfo,
10834                                      /*ADL*/ true, IsOverloaded(Fns),
10835                                      Fns.begin(), Fns.end());
10836     return new (Context)
10837         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10838                             VK_RValue, OpLoc, false);
10839   }
10840 
10841   // Build an empty overload set.
10842   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
10843 
10844   // Add the candidates from the given function set.
10845   AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
10846 
10847   // Add operator candidates that are member functions.
10848   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10849 
10850   // Add candidates from ADL.
10851   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
10852                                        /*ExplicitTemplateArgs*/nullptr,
10853                                        CandidateSet);
10854 
10855   // Add builtin operator candidates.
10856   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10857 
10858   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10859 
10860   // Perform overload resolution.
10861   OverloadCandidateSet::iterator Best;
10862   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10863   case OR_Success: {
10864     // We found a built-in operator or an overloaded operator.
10865     FunctionDecl *FnDecl = Best->Function;
10866 
10867     if (FnDecl) {
10868       // We matched an overloaded operator. Build a call to that
10869       // operator.
10870 
10871       // Convert the arguments.
10872       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10873         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
10874 
10875         ExprResult InputRes =
10876           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
10877                                               Best->FoundDecl, Method);
10878         if (InputRes.isInvalid())
10879           return ExprError();
10880         Input = InputRes.get();
10881       } else {
10882         // Convert the arguments.
10883         ExprResult InputInit
10884           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10885                                                       Context,
10886                                                       FnDecl->getParamDecl(0)),
10887                                       SourceLocation(),
10888                                       Input);
10889         if (InputInit.isInvalid())
10890           return ExprError();
10891         Input = InputInit.get();
10892       }
10893 
10894       // Build the actual expression node.
10895       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10896                                                 HadMultipleCandidates, OpLoc);
10897       if (FnExpr.isInvalid())
10898         return ExprError();
10899 
10900       // Determine the result type.
10901       QualType ResultTy = FnDecl->getReturnType();
10902       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10903       ResultTy = ResultTy.getNonLValueExprType(Context);
10904 
10905       Args[0] = Input;
10906       CallExpr *TheCall =
10907         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
10908                                           ResultTy, VK, OpLoc, false);
10909 
10910       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
10911         return ExprError();
10912 
10913       return MaybeBindToTemporary(TheCall);
10914     } else {
10915       // We matched a built-in operator. Convert the arguments, then
10916       // break out so that we will build the appropriate built-in
10917       // operator node.
10918       ExprResult InputRes =
10919         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10920                                   Best->Conversions[0], AA_Passing);
10921       if (InputRes.isInvalid())
10922         return ExprError();
10923       Input = InputRes.get();
10924       break;
10925     }
10926   }
10927 
10928   case OR_No_Viable_Function:
10929     // This is an erroneous use of an operator which can be overloaded by
10930     // a non-member function. Check for non-member operators which were
10931     // defined too late to be candidates.
10932     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
10933       // FIXME: Recover by calling the found function.
10934       return ExprError();
10935 
10936     // No viable function; fall through to handling this as a
10937     // built-in operator, which will produce an error message for us.
10938     break;
10939 
10940   case OR_Ambiguous:
10941     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10942         << UnaryOperator::getOpcodeStr(Opc)
10943         << Input->getType()
10944         << Input->getSourceRange();
10945     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
10946                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10947     return ExprError();
10948 
10949   case OR_Deleted:
10950     Diag(OpLoc, diag::err_ovl_deleted_oper)
10951       << Best->Function->isDeleted()
10952       << UnaryOperator::getOpcodeStr(Opc)
10953       << getDeletedOrUnavailableSuffix(Best->Function)
10954       << Input->getSourceRange();
10955     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
10956                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10957     return ExprError();
10958   }
10959 
10960   // Either we found no viable overloaded operator or we matched a
10961   // built-in operator. In either case, fall through to trying to
10962   // build a built-in operation.
10963   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10964 }
10965 
10966 /// \brief Create a binary operation that may resolve to an overloaded
10967 /// operator.
10968 ///
10969 /// \param OpLoc The location of the operator itself (e.g., '+').
10970 ///
10971 /// \param OpcIn The BinaryOperator::Opcode that describes this
10972 /// operator.
10973 ///
10974 /// \param Fns The set of non-member functions that will be
10975 /// considered by overload resolution. The caller needs to build this
10976 /// set based on the context using, e.g.,
10977 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10978 /// set should not contain any member functions; those will be added
10979 /// by CreateOverloadedBinOp().
10980 ///
10981 /// \param LHS Left-hand argument.
10982 /// \param RHS Right-hand argument.
10983 ExprResult
10984 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10985                             unsigned OpcIn,
10986                             const UnresolvedSetImpl &Fns,
10987                             Expr *LHS, Expr *RHS) {
10988   Expr *Args[2] = { LHS, RHS };
10989   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
10990 
10991   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10992   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10993   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10994 
10995   // If either side is type-dependent, create an appropriate dependent
10996   // expression.
10997   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10998     if (Fns.empty()) {
10999       // If there are no functions to store, just build a dependent
11000       // BinaryOperator or CompoundAssignment.
11001       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11002         return new (Context) BinaryOperator(
11003             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11004             OpLoc, FPFeatures.fp_contract);
11005 
11006       return new (Context) CompoundAssignOperator(
11007           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11008           Context.DependentTy, Context.DependentTy, OpLoc,
11009           FPFeatures.fp_contract);
11010     }
11011 
11012     // FIXME: save results of ADL from here?
11013     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11014     // TODO: provide better source location info in DNLoc component.
11015     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11016     UnresolvedLookupExpr *Fn
11017       = UnresolvedLookupExpr::Create(Context, NamingClass, 
11018                                      NestedNameSpecifierLoc(), OpNameInfo, 
11019                                      /*ADL*/ true, IsOverloaded(Fns),
11020                                      Fns.begin(), Fns.end());
11021     return new (Context)
11022         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11023                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11024   }
11025 
11026   // Always do placeholder-like conversions on the RHS.
11027   if (checkPlaceholderForOverload(*this, Args[1]))
11028     return ExprError();
11029 
11030   // Do placeholder-like conversion on the LHS; note that we should
11031   // not get here with a PseudoObject LHS.
11032   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11033   if (checkPlaceholderForOverload(*this, Args[0]))
11034     return ExprError();
11035 
11036   // If this is the assignment operator, we only perform overload resolution
11037   // if the left-hand side is a class or enumeration type. This is actually
11038   // a hack. The standard requires that we do overload resolution between the
11039   // various built-in candidates, but as DR507 points out, this can lead to
11040   // problems. So we do it this way, which pretty much follows what GCC does.
11041   // Note that we go the traditional code path for compound assignment forms.
11042   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11043     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11044 
11045   // If this is the .* operator, which is not overloadable, just
11046   // create a built-in binary operator.
11047   if (Opc == BO_PtrMemD)
11048     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11049 
11050   // Build an empty overload set.
11051   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11052 
11053   // Add the candidates from the given function set.
11054   AddFunctionCandidates(Fns, Args, CandidateSet, false);
11055 
11056   // Add operator candidates that are member functions.
11057   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11058 
11059   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11060   // performed for an assignment operator (nor for operator[] nor operator->,
11061   // which don't get here).
11062   if (Opc != BO_Assign)
11063     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11064                                          /*ExplicitTemplateArgs*/ nullptr,
11065                                          CandidateSet);
11066 
11067   // Add builtin operator candidates.
11068   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11069 
11070   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11071 
11072   // Perform overload resolution.
11073   OverloadCandidateSet::iterator Best;
11074   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11075     case OR_Success: {
11076       // We found a built-in operator or an overloaded operator.
11077       FunctionDecl *FnDecl = Best->Function;
11078 
11079       if (FnDecl) {
11080         // We matched an overloaded operator. Build a call to that
11081         // operator.
11082 
11083         // Convert the arguments.
11084         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11085           // Best->Access is only meaningful for class members.
11086           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11087 
11088           ExprResult Arg1 =
11089             PerformCopyInitialization(
11090               InitializedEntity::InitializeParameter(Context,
11091                                                      FnDecl->getParamDecl(0)),
11092               SourceLocation(), Args[1]);
11093           if (Arg1.isInvalid())
11094             return ExprError();
11095 
11096           ExprResult Arg0 =
11097             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11098                                                 Best->FoundDecl, Method);
11099           if (Arg0.isInvalid())
11100             return ExprError();
11101           Args[0] = Arg0.getAs<Expr>();
11102           Args[1] = RHS = Arg1.getAs<Expr>();
11103         } else {
11104           // Convert the arguments.
11105           ExprResult Arg0 = PerformCopyInitialization(
11106             InitializedEntity::InitializeParameter(Context,
11107                                                    FnDecl->getParamDecl(0)),
11108             SourceLocation(), Args[0]);
11109           if (Arg0.isInvalid())
11110             return ExprError();
11111 
11112           ExprResult Arg1 =
11113             PerformCopyInitialization(
11114               InitializedEntity::InitializeParameter(Context,
11115                                                      FnDecl->getParamDecl(1)),
11116               SourceLocation(), Args[1]);
11117           if (Arg1.isInvalid())
11118             return ExprError();
11119           Args[0] = LHS = Arg0.getAs<Expr>();
11120           Args[1] = RHS = Arg1.getAs<Expr>();
11121         }
11122 
11123         // Build the actual expression node.
11124         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11125                                                   Best->FoundDecl,
11126                                                   HadMultipleCandidates, OpLoc);
11127         if (FnExpr.isInvalid())
11128           return ExprError();
11129 
11130         // Determine the result type.
11131         QualType ResultTy = FnDecl->getReturnType();
11132         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11133         ResultTy = ResultTy.getNonLValueExprType(Context);
11134 
11135         CXXOperatorCallExpr *TheCall =
11136           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11137                                             Args, ResultTy, VK, OpLoc,
11138                                             FPFeatures.fp_contract);
11139 
11140         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11141                                 FnDecl))
11142           return ExprError();
11143 
11144         ArrayRef<const Expr *> ArgsArray(Args, 2);
11145         // Cut off the implicit 'this'.
11146         if (isa<CXXMethodDecl>(FnDecl))
11147           ArgsArray = ArgsArray.slice(1);
11148         checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 
11149                   TheCall->getSourceRange(), VariadicDoesNotApply);
11150 
11151         return MaybeBindToTemporary(TheCall);
11152       } else {
11153         // We matched a built-in operator. Convert the arguments, then
11154         // break out so that we will build the appropriate built-in
11155         // operator node.
11156         ExprResult ArgsRes0 =
11157           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11158                                     Best->Conversions[0], AA_Passing);
11159         if (ArgsRes0.isInvalid())
11160           return ExprError();
11161         Args[0] = ArgsRes0.get();
11162 
11163         ExprResult ArgsRes1 =
11164           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11165                                     Best->Conversions[1], AA_Passing);
11166         if (ArgsRes1.isInvalid())
11167           return ExprError();
11168         Args[1] = ArgsRes1.get();
11169         break;
11170       }
11171     }
11172 
11173     case OR_No_Viable_Function: {
11174       // C++ [over.match.oper]p9:
11175       //   If the operator is the operator , [...] and there are no
11176       //   viable functions, then the operator is assumed to be the
11177       //   built-in operator and interpreted according to clause 5.
11178       if (Opc == BO_Comma)
11179         break;
11180 
11181       // For class as left operand for assignment or compound assigment
11182       // operator do not fall through to handling in built-in, but report that
11183       // no overloaded assignment operator found
11184       ExprResult Result = ExprError();
11185       if (Args[0]->getType()->isRecordType() &&
11186           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11187         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11188              << BinaryOperator::getOpcodeStr(Opc)
11189              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11190         if (Args[0]->getType()->isIncompleteType()) {
11191           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11192             << Args[0]->getType()
11193             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11194         }
11195       } else {
11196         // This is an erroneous use of an operator which can be overloaded by
11197         // a non-member function. Check for non-member operators which were
11198         // defined too late to be candidates.
11199         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11200           // FIXME: Recover by calling the found function.
11201           return ExprError();
11202 
11203         // No viable function; try to create a built-in operation, which will
11204         // produce an error. Then, show the non-viable candidates.
11205         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11206       }
11207       assert(Result.isInvalid() &&
11208              "C++ binary operator overloading is missing candidates!");
11209       if (Result.isInvalid())
11210         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11211                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11212       return Result;
11213     }
11214 
11215     case OR_Ambiguous:
11216       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11217           << BinaryOperator::getOpcodeStr(Opc)
11218           << Args[0]->getType() << Args[1]->getType()
11219           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11220       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11221                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11222       return ExprError();
11223 
11224     case OR_Deleted:
11225       if (isImplicitlyDeleted(Best->Function)) {
11226         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11227         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11228           << Context.getRecordType(Method->getParent())
11229           << getSpecialMember(Method);
11230 
11231         // The user probably meant to call this special member. Just
11232         // explain why it's deleted.
11233         NoteDeletedFunction(Method);
11234         return ExprError();
11235       } else {
11236         Diag(OpLoc, diag::err_ovl_deleted_oper)
11237           << Best->Function->isDeleted()
11238           << BinaryOperator::getOpcodeStr(Opc)
11239           << getDeletedOrUnavailableSuffix(Best->Function)
11240           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11241       }
11242       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11243                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11244       return ExprError();
11245   }
11246 
11247   // We matched a built-in operator; build it.
11248   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11249 }
11250 
11251 ExprResult
11252 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11253                                          SourceLocation RLoc,
11254                                          Expr *Base, Expr *Idx) {
11255   Expr *Args[2] = { Base, Idx };
11256   DeclarationName OpName =
11257       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11258 
11259   // If either side is type-dependent, create an appropriate dependent
11260   // expression.
11261   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11262 
11263     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11264     // CHECKME: no 'operator' keyword?
11265     DeclarationNameInfo OpNameInfo(OpName, LLoc);
11266     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11267     UnresolvedLookupExpr *Fn
11268       = UnresolvedLookupExpr::Create(Context, NamingClass,
11269                                      NestedNameSpecifierLoc(), OpNameInfo,
11270                                      /*ADL*/ true, /*Overloaded*/ false,
11271                                      UnresolvedSetIterator(),
11272                                      UnresolvedSetIterator());
11273     // Can't add any actual overloads yet
11274 
11275     return new (Context)
11276         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11277                             Context.DependentTy, VK_RValue, RLoc, false);
11278   }
11279 
11280   // Handle placeholders on both operands.
11281   if (checkPlaceholderForOverload(*this, Args[0]))
11282     return ExprError();
11283   if (checkPlaceholderForOverload(*this, Args[1]))
11284     return ExprError();
11285 
11286   // Build an empty overload set.
11287   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11288 
11289   // Subscript can only be overloaded as a member function.
11290 
11291   // Add operator candidates that are member functions.
11292   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11293 
11294   // Add builtin operator candidates.
11295   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11296 
11297   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11298 
11299   // Perform overload resolution.
11300   OverloadCandidateSet::iterator Best;
11301   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11302     case OR_Success: {
11303       // We found a built-in operator or an overloaded operator.
11304       FunctionDecl *FnDecl = Best->Function;
11305 
11306       if (FnDecl) {
11307         // We matched an overloaded operator. Build a call to that
11308         // operator.
11309 
11310         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11311 
11312         // Convert the arguments.
11313         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11314         ExprResult Arg0 =
11315           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11316                                               Best->FoundDecl, Method);
11317         if (Arg0.isInvalid())
11318           return ExprError();
11319         Args[0] = Arg0.get();
11320 
11321         // Convert the arguments.
11322         ExprResult InputInit
11323           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11324                                                       Context,
11325                                                       FnDecl->getParamDecl(0)),
11326                                       SourceLocation(),
11327                                       Args[1]);
11328         if (InputInit.isInvalid())
11329           return ExprError();
11330 
11331         Args[1] = InputInit.getAs<Expr>();
11332 
11333         // Build the actual expression node.
11334         DeclarationNameInfo OpLocInfo(OpName, LLoc);
11335         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11336         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11337                                                   Best->FoundDecl,
11338                                                   HadMultipleCandidates,
11339                                                   OpLocInfo.getLoc(),
11340                                                   OpLocInfo.getInfo());
11341         if (FnExpr.isInvalid())
11342           return ExprError();
11343 
11344         // Determine the result type
11345         QualType ResultTy = FnDecl->getReturnType();
11346         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11347         ResultTy = ResultTy.getNonLValueExprType(Context);
11348 
11349         CXXOperatorCallExpr *TheCall =
11350           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11351                                             FnExpr.get(), Args,
11352                                             ResultTy, VK, RLoc,
11353                                             false);
11354 
11355         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11356           return ExprError();
11357 
11358         return MaybeBindToTemporary(TheCall);
11359       } else {
11360         // We matched a built-in operator. Convert the arguments, then
11361         // break out so that we will build the appropriate built-in
11362         // operator node.
11363         ExprResult ArgsRes0 =
11364           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11365                                     Best->Conversions[0], AA_Passing);
11366         if (ArgsRes0.isInvalid())
11367           return ExprError();
11368         Args[0] = ArgsRes0.get();
11369 
11370         ExprResult ArgsRes1 =
11371           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11372                                     Best->Conversions[1], AA_Passing);
11373         if (ArgsRes1.isInvalid())
11374           return ExprError();
11375         Args[1] = ArgsRes1.get();
11376 
11377         break;
11378       }
11379     }
11380 
11381     case OR_No_Viable_Function: {
11382       if (CandidateSet.empty())
11383         Diag(LLoc, diag::err_ovl_no_oper)
11384           << Args[0]->getType() << /*subscript*/ 0
11385           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11386       else
11387         Diag(LLoc, diag::err_ovl_no_viable_subscript)
11388           << Args[0]->getType()
11389           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11390       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11391                                   "[]", LLoc);
11392       return ExprError();
11393     }
11394 
11395     case OR_Ambiguous:
11396       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
11397           << "[]"
11398           << Args[0]->getType() << Args[1]->getType()
11399           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11400       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11401                                   "[]", LLoc);
11402       return ExprError();
11403 
11404     case OR_Deleted:
11405       Diag(LLoc, diag::err_ovl_deleted_oper)
11406         << Best->Function->isDeleted() << "[]"
11407         << getDeletedOrUnavailableSuffix(Best->Function)
11408         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11409       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11410                                   "[]", LLoc);
11411       return ExprError();
11412     }
11413 
11414   // We matched a built-in operator; build it.
11415   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11416 }
11417 
11418 /// BuildCallToMemberFunction - Build a call to a member
11419 /// function. MemExpr is the expression that refers to the member
11420 /// function (and includes the object parameter), Args/NumArgs are the
11421 /// arguments to the function call (not including the object
11422 /// parameter). The caller needs to validate that the member
11423 /// expression refers to a non-static member function or an overloaded
11424 /// member function.
11425 ExprResult
11426 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11427                                 SourceLocation LParenLoc,
11428                                 MultiExprArg Args,
11429                                 SourceLocation RParenLoc) {
11430   assert(MemExprE->getType() == Context.BoundMemberTy ||
11431          MemExprE->getType() == Context.OverloadTy);
11432 
11433   // Dig out the member expression. This holds both the object
11434   // argument and the member function we're referring to.
11435   Expr *NakedMemExpr = MemExprE->IgnoreParens();
11436 
11437   // Determine whether this is a call to a pointer-to-member function.
11438   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11439     assert(op->getType() == Context.BoundMemberTy);
11440     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11441 
11442     QualType fnType =
11443       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11444 
11445     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11446     QualType resultType = proto->getCallResultType(Context);
11447     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
11448 
11449     // Check that the object type isn't more qualified than the
11450     // member function we're calling.
11451     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11452 
11453     QualType objectType = op->getLHS()->getType();
11454     if (op->getOpcode() == BO_PtrMemI)
11455       objectType = objectType->castAs<PointerType>()->getPointeeType();
11456     Qualifiers objectQuals = objectType.getQualifiers();
11457 
11458     Qualifiers difference = objectQuals - funcQuals;
11459     difference.removeObjCGCAttr();
11460     difference.removeAddressSpace();
11461     if (difference) {
11462       std::string qualsString = difference.getAsString();
11463       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11464         << fnType.getUnqualifiedType()
11465         << qualsString
11466         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11467     }
11468 
11469     if (resultType->isMemberPointerType())
11470       if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11471         RequireCompleteType(LParenLoc, resultType, 0);
11472 
11473     CXXMemberCallExpr *call
11474       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11475                                         resultType, valueKind, RParenLoc);
11476 
11477     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
11478                             call, nullptr))
11479       return ExprError();
11480 
11481     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
11482       return ExprError();
11483 
11484     if (CheckOtherCall(call, proto))
11485       return ExprError();
11486 
11487     return MaybeBindToTemporary(call);
11488   }
11489 
11490   UnbridgedCastsSet UnbridgedCasts;
11491   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11492     return ExprError();
11493 
11494   MemberExpr *MemExpr;
11495   CXXMethodDecl *Method = nullptr;
11496   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11497   NestedNameSpecifier *Qualifier = nullptr;
11498   if (isa<MemberExpr>(NakedMemExpr)) {
11499     MemExpr = cast<MemberExpr>(NakedMemExpr);
11500     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11501     FoundDecl = MemExpr->getFoundDecl();
11502     Qualifier = MemExpr->getQualifier();
11503     UnbridgedCasts.restore();
11504   } else {
11505     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11506     Qualifier = UnresExpr->getQualifier();
11507 
11508     QualType ObjectType = UnresExpr->getBaseType();
11509     Expr::Classification ObjectClassification
11510       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11511                             : UnresExpr->getBase()->Classify(Context);
11512 
11513     // Add overload candidates
11514     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11515                                       OverloadCandidateSet::CSK_Normal);
11516 
11517     // FIXME: avoid copy.
11518     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
11519     if (UnresExpr->hasExplicitTemplateArgs()) {
11520       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11521       TemplateArgs = &TemplateArgsBuffer;
11522     }
11523 
11524     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11525            E = UnresExpr->decls_end(); I != E; ++I) {
11526 
11527       NamedDecl *Func = *I;
11528       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11529       if (isa<UsingShadowDecl>(Func))
11530         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11531 
11532 
11533       // Microsoft supports direct constructor calls.
11534       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11535         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11536                              Args, CandidateSet);
11537       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11538         // If explicit template arguments were provided, we can't call a
11539         // non-template member function.
11540         if (TemplateArgs)
11541           continue;
11542 
11543         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11544                            ObjectClassification, Args, CandidateSet,
11545                            /*SuppressUserConversions=*/false);
11546       } else {
11547         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11548                                    I.getPair(), ActingDC, TemplateArgs,
11549                                    ObjectType,  ObjectClassification,
11550                                    Args, CandidateSet,
11551                                    /*SuppressUsedConversions=*/false);
11552       }
11553     }
11554 
11555     DeclarationName DeclName = UnresExpr->getMemberName();
11556 
11557     UnbridgedCasts.restore();
11558 
11559     OverloadCandidateSet::iterator Best;
11560     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11561                                             Best)) {
11562     case OR_Success:
11563       Method = cast<CXXMethodDecl>(Best->Function);
11564       FoundDecl = Best->FoundDecl;
11565       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11566       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11567         return ExprError();
11568       // If FoundDecl is different from Method (such as if one is a template
11569       // and the other a specialization), make sure DiagnoseUseOfDecl is 
11570       // called on both.
11571       // FIXME: This would be more comprehensively addressed by modifying
11572       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11573       // being used.
11574       if (Method != FoundDecl.getDecl() && 
11575                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11576         return ExprError();
11577       break;
11578 
11579     case OR_No_Viable_Function:
11580       Diag(UnresExpr->getMemberLoc(),
11581            diag::err_ovl_no_viable_member_function_in_call)
11582         << DeclName << MemExprE->getSourceRange();
11583       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11584       // FIXME: Leaking incoming expressions!
11585       return ExprError();
11586 
11587     case OR_Ambiguous:
11588       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11589         << DeclName << MemExprE->getSourceRange();
11590       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11591       // FIXME: Leaking incoming expressions!
11592       return ExprError();
11593 
11594     case OR_Deleted:
11595       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11596         << Best->Function->isDeleted()
11597         << DeclName 
11598         << getDeletedOrUnavailableSuffix(Best->Function)
11599         << MemExprE->getSourceRange();
11600       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11601       // FIXME: Leaking incoming expressions!
11602       return ExprError();
11603     }
11604 
11605     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11606 
11607     // If overload resolution picked a static member, build a
11608     // non-member call based on that function.
11609     if (Method->isStatic()) {
11610       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11611                                    RParenLoc);
11612     }
11613 
11614     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11615   }
11616 
11617   QualType ResultType = Method->getReturnType();
11618   ExprValueKind VK = Expr::getValueKindForType(ResultType);
11619   ResultType = ResultType.getNonLValueExprType(Context);
11620 
11621   assert(Method && "Member call to something that isn't a method?");
11622   CXXMemberCallExpr *TheCall =
11623     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11624                                     ResultType, VK, RParenLoc);
11625 
11626   // (CUDA B.1): Check for invalid calls between targets.
11627   if (getLangOpts().CUDA) {
11628     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11629       if (CheckCUDATarget(Caller, Method)) {
11630         Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11631             << IdentifyCUDATarget(Method) << Method->getIdentifier()
11632             << IdentifyCUDATarget(Caller);
11633         return ExprError();
11634       }
11635     }
11636   }
11637 
11638   // Check for a valid return type.
11639   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
11640                           TheCall, Method))
11641     return ExprError();
11642 
11643   // Convert the object argument (for a non-static member function call).
11644   // We only need to do this if there was actually an overload; otherwise
11645   // it was done at lookup.
11646   if (!Method->isStatic()) {
11647     ExprResult ObjectArg =
11648       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11649                                           FoundDecl, Method);
11650     if (ObjectArg.isInvalid())
11651       return ExprError();
11652     MemExpr->setBase(ObjectArg.get());
11653   }
11654 
11655   // Convert the rest of the arguments
11656   const FunctionProtoType *Proto =
11657     Method->getType()->getAs<FunctionProtoType>();
11658   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11659                               RParenLoc))
11660     return ExprError();
11661 
11662   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11663 
11664   if (CheckFunctionCall(Method, TheCall, Proto))
11665     return ExprError();
11666 
11667   if ((isa<CXXConstructorDecl>(CurContext) || 
11668        isa<CXXDestructorDecl>(CurContext)) && 
11669       TheCall->getMethodDecl()->isPure()) {
11670     const CXXMethodDecl *MD = TheCall->getMethodDecl();
11671 
11672     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11673       Diag(MemExpr->getLocStart(), 
11674            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11675         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11676         << MD->getParent()->getDeclName();
11677 
11678       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11679     }
11680   }
11681   return MaybeBindToTemporary(TheCall);
11682 }
11683 
11684 /// BuildCallToObjectOfClassType - Build a call to an object of class
11685 /// type (C++ [over.call.object]), which can end up invoking an
11686 /// overloaded function call operator (@c operator()) or performing a
11687 /// user-defined conversion on the object argument.
11688 ExprResult
11689 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11690                                    SourceLocation LParenLoc,
11691                                    MultiExprArg Args,
11692                                    SourceLocation RParenLoc) {
11693   if (checkPlaceholderForOverload(*this, Obj))
11694     return ExprError();
11695   ExprResult Object = Obj;
11696 
11697   UnbridgedCastsSet UnbridgedCasts;
11698   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11699     return ExprError();
11700 
11701   assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11702   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11703 
11704   // C++ [over.call.object]p1:
11705   //  If the primary-expression E in the function call syntax
11706   //  evaluates to a class object of type "cv T", then the set of
11707   //  candidate functions includes at least the function call
11708   //  operators of T. The function call operators of T are obtained by
11709   //  ordinary lookup of the name operator() in the context of
11710   //  (E).operator().
11711   OverloadCandidateSet CandidateSet(LParenLoc,
11712                                     OverloadCandidateSet::CSK_Operator);
11713   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11714 
11715   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11716                           diag::err_incomplete_object_call, Object.get()))
11717     return true;
11718 
11719   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11720   LookupQualifiedName(R, Record->getDecl());
11721   R.suppressDiagnostics();
11722 
11723   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11724        Oper != OperEnd; ++Oper) {
11725     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11726                        Object.get()->Classify(Context),
11727                        Args, CandidateSet,
11728                        /*SuppressUserConversions=*/ false);
11729   }
11730 
11731   // C++ [over.call.object]p2:
11732   //   In addition, for each (non-explicit in C++0x) conversion function 
11733   //   declared in T of the form
11734   //
11735   //        operator conversion-type-id () cv-qualifier;
11736   //
11737   //   where cv-qualifier is the same cv-qualification as, or a
11738   //   greater cv-qualification than, cv, and where conversion-type-id
11739   //   denotes the type "pointer to function of (P1,...,Pn) returning
11740   //   R", or the type "reference to pointer to function of
11741   //   (P1,...,Pn) returning R", or the type "reference to function
11742   //   of (P1,...,Pn) returning R", a surrogate call function [...]
11743   //   is also considered as a candidate function. Similarly,
11744   //   surrogate call functions are added to the set of candidate
11745   //   functions for each conversion function declared in an
11746   //   accessible base class provided the function is not hidden
11747   //   within T by another intervening declaration.
11748   std::pair<CXXRecordDecl::conversion_iterator,
11749             CXXRecordDecl::conversion_iterator> Conversions
11750     = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11751   for (CXXRecordDecl::conversion_iterator
11752          I = Conversions.first, E = Conversions.second; I != E; ++I) {
11753     NamedDecl *D = *I;
11754     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11755     if (isa<UsingShadowDecl>(D))
11756       D = cast<UsingShadowDecl>(D)->getTargetDecl();
11757 
11758     // Skip over templated conversion functions; they aren't
11759     // surrogates.
11760     if (isa<FunctionTemplateDecl>(D))
11761       continue;
11762 
11763     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11764     if (!Conv->isExplicit()) {
11765       // Strip the reference type (if any) and then the pointer type (if
11766       // any) to get down to what might be a function type.
11767       QualType ConvType = Conv->getConversionType().getNonReferenceType();
11768       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11769         ConvType = ConvPtrType->getPointeeType();
11770 
11771       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11772       {
11773         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11774                               Object.get(), Args, CandidateSet);
11775       }
11776     }
11777   }
11778 
11779   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11780 
11781   // Perform overload resolution.
11782   OverloadCandidateSet::iterator Best;
11783   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11784                              Best)) {
11785   case OR_Success:
11786     // Overload resolution succeeded; we'll build the appropriate call
11787     // below.
11788     break;
11789 
11790   case OR_No_Viable_Function:
11791     if (CandidateSet.empty())
11792       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11793         << Object.get()->getType() << /*call*/ 1
11794         << Object.get()->getSourceRange();
11795     else
11796       Diag(Object.get()->getLocStart(),
11797            diag::err_ovl_no_viable_object_call)
11798         << Object.get()->getType() << Object.get()->getSourceRange();
11799     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11800     break;
11801 
11802   case OR_Ambiguous:
11803     Diag(Object.get()->getLocStart(),
11804          diag::err_ovl_ambiguous_object_call)
11805       << Object.get()->getType() << Object.get()->getSourceRange();
11806     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11807     break;
11808 
11809   case OR_Deleted:
11810     Diag(Object.get()->getLocStart(),
11811          diag::err_ovl_deleted_object_call)
11812       << Best->Function->isDeleted()
11813       << Object.get()->getType() 
11814       << getDeletedOrUnavailableSuffix(Best->Function)
11815       << Object.get()->getSourceRange();
11816     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11817     break;
11818   }
11819 
11820   if (Best == CandidateSet.end())
11821     return true;
11822 
11823   UnbridgedCasts.restore();
11824 
11825   if (Best->Function == nullptr) {
11826     // Since there is no function declaration, this is one of the
11827     // surrogate candidates. Dig out the conversion function.
11828     CXXConversionDecl *Conv
11829       = cast<CXXConversionDecl>(
11830                          Best->Conversions[0].UserDefined.ConversionFunction);
11831 
11832     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11833                               Best->FoundDecl);
11834     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11835       return ExprError();
11836     assert(Conv == Best->FoundDecl.getDecl() && 
11837              "Found Decl & conversion-to-functionptr should be same, right?!");
11838     // We selected one of the surrogate functions that converts the
11839     // object parameter to a function pointer. Perform the conversion
11840     // on the object argument, then let ActOnCallExpr finish the job.
11841 
11842     // Create an implicit member expr to refer to the conversion operator.
11843     // and then call it.
11844     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11845                                              Conv, HadMultipleCandidates);
11846     if (Call.isInvalid())
11847       return ExprError();
11848     // Record usage of conversion in an implicit cast.
11849     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11850                                     CK_UserDefinedConversion, Call.get(),
11851                                     nullptr, VK_RValue);
11852 
11853     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11854   }
11855 
11856   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
11857 
11858   // We found an overloaded operator(). Build a CXXOperatorCallExpr
11859   // that calls this method, using Object for the implicit object
11860   // parameter and passing along the remaining arguments.
11861   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11862 
11863   // An error diagnostic has already been printed when parsing the declaration.
11864   if (Method->isInvalidDecl())
11865     return ExprError();
11866 
11867   const FunctionProtoType *Proto =
11868     Method->getType()->getAs<FunctionProtoType>();
11869 
11870   unsigned NumParams = Proto->getNumParams();
11871 
11872   DeclarationNameInfo OpLocInfo(
11873                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11874   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11875   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11876                                            HadMultipleCandidates,
11877                                            OpLocInfo.getLoc(),
11878                                            OpLocInfo.getInfo());
11879   if (NewFn.isInvalid())
11880     return true;
11881 
11882   // Build the full argument list for the method call (the implicit object
11883   // parameter is placed at the beginning of the list).
11884   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
11885   MethodArgs[0] = Object.get();
11886   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11887 
11888   // Once we've built TheCall, all of the expressions are properly
11889   // owned.
11890   QualType ResultTy = Method->getReturnType();
11891   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11892   ResultTy = ResultTy.getNonLValueExprType(Context);
11893 
11894   CXXOperatorCallExpr *TheCall = new (Context)
11895       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
11896                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11897                           ResultTy, VK, RParenLoc, false);
11898   MethodArgs.reset();
11899 
11900   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
11901     return true;
11902 
11903   // We may have default arguments. If so, we need to allocate more
11904   // slots in the call for them.
11905   if (Args.size() < NumParams)
11906     TheCall->setNumArgs(Context, NumParams + 1);
11907 
11908   bool IsError = false;
11909 
11910   // Initialize the implicit object parameter.
11911   ExprResult ObjRes =
11912     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
11913                                         Best->FoundDecl, Method);
11914   if (ObjRes.isInvalid())
11915     IsError = true;
11916   else
11917     Object = ObjRes;
11918   TheCall->setArg(0, Object.get());
11919 
11920   // Check the argument types.
11921   for (unsigned i = 0; i != NumParams; i++) {
11922     Expr *Arg;
11923     if (i < Args.size()) {
11924       Arg = Args[i];
11925 
11926       // Pass the argument.
11927 
11928       ExprResult InputInit
11929         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11930                                                     Context,
11931                                                     Method->getParamDecl(i)),
11932                                     SourceLocation(), Arg);
11933 
11934       IsError |= InputInit.isInvalid();
11935       Arg = InputInit.getAs<Expr>();
11936     } else {
11937       ExprResult DefArg
11938         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11939       if (DefArg.isInvalid()) {
11940         IsError = true;
11941         break;
11942       }
11943 
11944       Arg = DefArg.getAs<Expr>();
11945     }
11946 
11947     TheCall->setArg(i + 1, Arg);
11948   }
11949 
11950   // If this is a variadic call, handle args passed through "...".
11951   if (Proto->isVariadic()) {
11952     // Promote the arguments (C99 6.5.2.2p7).
11953     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
11954       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
11955                                                         nullptr);
11956       IsError |= Arg.isInvalid();
11957       TheCall->setArg(i + 1, Arg.get());
11958     }
11959   }
11960 
11961   if (IsError) return true;
11962 
11963   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11964 
11965   if (CheckFunctionCall(Method, TheCall, Proto))
11966     return true;
11967 
11968   return MaybeBindToTemporary(TheCall);
11969 }
11970 
11971 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11972 ///  (if one exists), where @c Base is an expression of class type and
11973 /// @c Member is the name of the member we're trying to find.
11974 ExprResult
11975 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11976                                bool *NoArrowOperatorFound) {
11977   assert(Base->getType()->isRecordType() &&
11978          "left-hand side must have class type");
11979 
11980   if (checkPlaceholderForOverload(*this, Base))
11981     return ExprError();
11982 
11983   SourceLocation Loc = Base->getExprLoc();
11984 
11985   // C++ [over.ref]p1:
11986   //
11987   //   [...] An expression x->m is interpreted as (x.operator->())->m
11988   //   for a class object x of type T if T::operator->() exists and if
11989   //   the operator is selected as the best match function by the
11990   //   overload resolution mechanism (13.3).
11991   DeclarationName OpName =
11992     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11993   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
11994   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11995 
11996   if (RequireCompleteType(Loc, Base->getType(),
11997                           diag::err_typecheck_incomplete_tag, Base))
11998     return ExprError();
11999 
12000   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12001   LookupQualifiedName(R, BaseRecord->getDecl());
12002   R.suppressDiagnostics();
12003 
12004   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12005        Oper != OperEnd; ++Oper) {
12006     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12007                        None, CandidateSet, /*SuppressUserConversions=*/false);
12008   }
12009 
12010   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12011 
12012   // Perform overload resolution.
12013   OverloadCandidateSet::iterator Best;
12014   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12015   case OR_Success:
12016     // Overload resolution succeeded; we'll build the call below.
12017     break;
12018 
12019   case OR_No_Viable_Function:
12020     if (CandidateSet.empty()) {
12021       QualType BaseType = Base->getType();
12022       if (NoArrowOperatorFound) {
12023         // Report this specific error to the caller instead of emitting a
12024         // diagnostic, as requested.
12025         *NoArrowOperatorFound = true;
12026         return ExprError();
12027       }
12028       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12029         << BaseType << Base->getSourceRange();
12030       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12031         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12032           << FixItHint::CreateReplacement(OpLoc, ".");
12033       }
12034     } else
12035       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12036         << "operator->" << Base->getSourceRange();
12037     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12038     return ExprError();
12039 
12040   case OR_Ambiguous:
12041     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12042       << "->" << Base->getType() << Base->getSourceRange();
12043     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12044     return ExprError();
12045 
12046   case OR_Deleted:
12047     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12048       << Best->Function->isDeleted()
12049       << "->" 
12050       << getDeletedOrUnavailableSuffix(Best->Function)
12051       << Base->getSourceRange();
12052     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12053     return ExprError();
12054   }
12055 
12056   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12057 
12058   // Convert the object parameter.
12059   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12060   ExprResult BaseResult =
12061     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12062                                         Best->FoundDecl, Method);
12063   if (BaseResult.isInvalid())
12064     return ExprError();
12065   Base = BaseResult.get();
12066 
12067   // Build the operator call.
12068   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12069                                             HadMultipleCandidates, OpLoc);
12070   if (FnExpr.isInvalid())
12071     return ExprError();
12072 
12073   QualType ResultTy = Method->getReturnType();
12074   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12075   ResultTy = ResultTy.getNonLValueExprType(Context);
12076   CXXOperatorCallExpr *TheCall =
12077     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12078                                       Base, ResultTy, VK, OpLoc, false);
12079 
12080   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12081           return ExprError();
12082 
12083   return MaybeBindToTemporary(TheCall);
12084 }
12085 
12086 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12087 /// a literal operator described by the provided lookup results.
12088 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12089                                           DeclarationNameInfo &SuffixInfo,
12090                                           ArrayRef<Expr*> Args,
12091                                           SourceLocation LitEndLoc,
12092                                        TemplateArgumentListInfo *TemplateArgs) {
12093   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12094 
12095   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12096                                     OverloadCandidateSet::CSK_Normal);
12097   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
12098                         TemplateArgs);
12099 
12100   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12101 
12102   // Perform overload resolution. This will usually be trivial, but might need
12103   // to perform substitutions for a literal operator template.
12104   OverloadCandidateSet::iterator Best;
12105   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12106   case OR_Success:
12107   case OR_Deleted:
12108     break;
12109 
12110   case OR_No_Viable_Function:
12111     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12112       << R.getLookupName();
12113     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12114     return ExprError();
12115 
12116   case OR_Ambiguous:
12117     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12118     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12119     return ExprError();
12120   }
12121 
12122   FunctionDecl *FD = Best->Function;
12123   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12124                                         HadMultipleCandidates,
12125                                         SuffixInfo.getLoc(),
12126                                         SuffixInfo.getInfo());
12127   if (Fn.isInvalid())
12128     return true;
12129 
12130   // Check the argument types. This should almost always be a no-op, except
12131   // that array-to-pointer decay is applied to string literals.
12132   Expr *ConvArgs[2];
12133   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12134     ExprResult InputInit = PerformCopyInitialization(
12135       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12136       SourceLocation(), Args[ArgIdx]);
12137     if (InputInit.isInvalid())
12138       return true;
12139     ConvArgs[ArgIdx] = InputInit.get();
12140   }
12141 
12142   QualType ResultTy = FD->getReturnType();
12143   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12144   ResultTy = ResultTy.getNonLValueExprType(Context);
12145 
12146   UserDefinedLiteral *UDL =
12147     new (Context) UserDefinedLiteral(Context, Fn.get(),
12148                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12149                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12150 
12151   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12152     return ExprError();
12153 
12154   if (CheckFunctionCall(FD, UDL, nullptr))
12155     return ExprError();
12156 
12157   return MaybeBindToTemporary(UDL);
12158 }
12159 
12160 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12161 /// given LookupResult is non-empty, it is assumed to describe a member which
12162 /// will be invoked. Otherwise, the function will be found via argument
12163 /// dependent lookup.
12164 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12165 /// otherwise CallExpr is set to ExprError() and some non-success value
12166 /// is returned.
12167 Sema::ForRangeStatus
12168 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12169                                 SourceLocation RangeLoc, VarDecl *Decl,
12170                                 BeginEndFunction BEF,
12171                                 const DeclarationNameInfo &NameInfo,
12172                                 LookupResult &MemberLookup,
12173                                 OverloadCandidateSet *CandidateSet,
12174                                 Expr *Range, ExprResult *CallExpr) {
12175   CandidateSet->clear();
12176   if (!MemberLookup.empty()) {
12177     ExprResult MemberRef =
12178         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12179                                  /*IsPtr=*/false, CXXScopeSpec(),
12180                                  /*TemplateKWLoc=*/SourceLocation(),
12181                                  /*FirstQualifierInScope=*/nullptr,
12182                                  MemberLookup,
12183                                  /*TemplateArgs=*/nullptr);
12184     if (MemberRef.isInvalid()) {
12185       *CallExpr = ExprError();
12186       Diag(Range->getLocStart(), diag::note_in_for_range)
12187           << RangeLoc << BEF << Range->getType();
12188       return FRS_DiagnosticIssued;
12189     }
12190     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12191     if (CallExpr->isInvalid()) {
12192       *CallExpr = ExprError();
12193       Diag(Range->getLocStart(), diag::note_in_for_range)
12194           << RangeLoc << BEF << Range->getType();
12195       return FRS_DiagnosticIssued;
12196     }
12197   } else {
12198     UnresolvedSet<0> FoundNames;
12199     UnresolvedLookupExpr *Fn =
12200       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12201                                    NestedNameSpecifierLoc(), NameInfo,
12202                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12203                                    FoundNames.begin(), FoundNames.end());
12204 
12205     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12206                                                     CandidateSet, CallExpr);
12207     if (CandidateSet->empty() || CandidateSetError) {
12208       *CallExpr = ExprError();
12209       return FRS_NoViableFunction;
12210     }
12211     OverloadCandidateSet::iterator Best;
12212     OverloadingResult OverloadResult =
12213         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12214 
12215     if (OverloadResult == OR_No_Viable_Function) {
12216       *CallExpr = ExprError();
12217       return FRS_NoViableFunction;
12218     }
12219     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12220                                          Loc, nullptr, CandidateSet, &Best,
12221                                          OverloadResult,
12222                                          /*AllowTypoCorrection=*/false);
12223     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12224       *CallExpr = ExprError();
12225       Diag(Range->getLocStart(), diag::note_in_for_range)
12226           << RangeLoc << BEF << Range->getType();
12227       return FRS_DiagnosticIssued;
12228     }
12229   }
12230   return FRS_Success;
12231 }
12232 
12233 
12234 /// FixOverloadedFunctionReference - E is an expression that refers to
12235 /// a C++ overloaded function (possibly with some parentheses and
12236 /// perhaps a '&' around it). We have resolved the overloaded function
12237 /// to the function declaration Fn, so patch up the expression E to
12238 /// refer (possibly indirectly) to Fn. Returns the new expr.
12239 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12240                                            FunctionDecl *Fn) {
12241   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12242     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12243                                                    Found, Fn);
12244     if (SubExpr == PE->getSubExpr())
12245       return PE;
12246 
12247     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12248   }
12249 
12250   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12251     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12252                                                    Found, Fn);
12253     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12254                                SubExpr->getType()) &&
12255            "Implicit cast type cannot be determined from overload");
12256     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12257     if (SubExpr == ICE->getSubExpr())
12258       return ICE;
12259 
12260     return ImplicitCastExpr::Create(Context, ICE->getType(),
12261                                     ICE->getCastKind(),
12262                                     SubExpr, nullptr,
12263                                     ICE->getValueKind());
12264   }
12265 
12266   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12267     assert(UnOp->getOpcode() == UO_AddrOf &&
12268            "Can only take the address of an overloaded function");
12269     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12270       if (Method->isStatic()) {
12271         // Do nothing: static member functions aren't any different
12272         // from non-member functions.
12273       } else {
12274         // Fix the subexpression, which really has to be an
12275         // UnresolvedLookupExpr holding an overloaded member function
12276         // or template.
12277         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12278                                                        Found, Fn);
12279         if (SubExpr == UnOp->getSubExpr())
12280           return UnOp;
12281 
12282         assert(isa<DeclRefExpr>(SubExpr)
12283                && "fixed to something other than a decl ref");
12284         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12285                && "fixed to a member ref with no nested name qualifier");
12286 
12287         // We have taken the address of a pointer to member
12288         // function. Perform the computation here so that we get the
12289         // appropriate pointer to member type.
12290         QualType ClassType
12291           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12292         QualType MemPtrType
12293           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12294 
12295         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12296                                            VK_RValue, OK_Ordinary,
12297                                            UnOp->getOperatorLoc());
12298       }
12299     }
12300     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12301                                                    Found, Fn);
12302     if (SubExpr == UnOp->getSubExpr())
12303       return UnOp;
12304 
12305     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12306                                      Context.getPointerType(SubExpr->getType()),
12307                                        VK_RValue, OK_Ordinary,
12308                                        UnOp->getOperatorLoc());
12309   }
12310 
12311   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12312     // FIXME: avoid copy.
12313     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12314     if (ULE->hasExplicitTemplateArgs()) {
12315       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12316       TemplateArgs = &TemplateArgsBuffer;
12317     }
12318 
12319     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12320                                            ULE->getQualifierLoc(),
12321                                            ULE->getTemplateKeywordLoc(),
12322                                            Fn,
12323                                            /*enclosing*/ false, // FIXME?
12324                                            ULE->getNameLoc(),
12325                                            Fn->getType(),
12326                                            VK_LValue,
12327                                            Found.getDecl(),
12328                                            TemplateArgs);
12329     MarkDeclRefReferenced(DRE);
12330     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12331     return DRE;
12332   }
12333 
12334   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12335     // FIXME: avoid copy.
12336     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12337     if (MemExpr->hasExplicitTemplateArgs()) {
12338       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12339       TemplateArgs = &TemplateArgsBuffer;
12340     }
12341 
12342     Expr *Base;
12343 
12344     // If we're filling in a static method where we used to have an
12345     // implicit member access, rewrite to a simple decl ref.
12346     if (MemExpr->isImplicitAccess()) {
12347       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12348         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12349                                                MemExpr->getQualifierLoc(),
12350                                                MemExpr->getTemplateKeywordLoc(),
12351                                                Fn,
12352                                                /*enclosing*/ false,
12353                                                MemExpr->getMemberLoc(),
12354                                                Fn->getType(),
12355                                                VK_LValue,
12356                                                Found.getDecl(),
12357                                                TemplateArgs);
12358         MarkDeclRefReferenced(DRE);
12359         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12360         return DRE;
12361       } else {
12362         SourceLocation Loc = MemExpr->getMemberLoc();
12363         if (MemExpr->getQualifier())
12364           Loc = MemExpr->getQualifierLoc().getBeginLoc();
12365         CheckCXXThisCapture(Loc);
12366         Base = new (Context) CXXThisExpr(Loc,
12367                                          MemExpr->getBaseType(),
12368                                          /*isImplicit=*/true);
12369       }
12370     } else
12371       Base = MemExpr->getBase();
12372 
12373     ExprValueKind valueKind;
12374     QualType type;
12375     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12376       valueKind = VK_LValue;
12377       type = Fn->getType();
12378     } else {
12379       valueKind = VK_RValue;
12380       type = Context.BoundMemberTy;
12381     }
12382 
12383     MemberExpr *ME = MemberExpr::Create(Context, Base,
12384                                         MemExpr->isArrow(),
12385                                         MemExpr->getQualifierLoc(),
12386                                         MemExpr->getTemplateKeywordLoc(),
12387                                         Fn,
12388                                         Found,
12389                                         MemExpr->getMemberNameInfo(),
12390                                         TemplateArgs,
12391                                         type, valueKind, OK_Ordinary);
12392     ME->setHadMultipleCandidates(true);
12393     MarkMemberReferenced(ME);
12394     return ME;
12395   }
12396 
12397   llvm_unreachable("Invalid reference to overloaded function");
12398 }
12399 
12400 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12401                                                 DeclAccessPair Found,
12402                                                 FunctionDecl *Fn) {
12403   return FixOverloadedFunctionReference(E.get(), Found, Fn);
12404 }