clang API Documentation

SemaOverload.cpp
Go to the documentation of this file.
00001 //===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
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/SemaInternal.h"
00015 #include "clang/Sema/Lookup.h"
00016 #include "clang/Sema/Initialization.h"
00017 #include "clang/Sema/Template.h"
00018 #include "clang/Sema/TemplateDeduction.h"
00019 #include "clang/Basic/Diagnostic.h"
00020 #include "clang/Lex/Preprocessor.h"
00021 #include "clang/AST/ASTContext.h"
00022 #include "clang/AST/CXXInheritance.h"
00023 #include "clang/AST/DeclObjC.h"
00024 #include "clang/AST/Expr.h"
00025 #include "clang/AST/ExprCXX.h"
00026 #include "clang/AST/ExprObjC.h"
00027 #include "clang/AST/TypeOrdering.h"
00028 #include "clang/Basic/PartialDiagnostic.h"
00029 #include "llvm/ADT/DenseSet.h"
00030 #include "llvm/ADT/SmallPtrSet.h"
00031 #include "llvm/ADT/SmallString.h"
00032 #include "llvm/ADT/STLExtras.h"
00033 #include <algorithm>
00034 
00035 namespace clang {
00036 using namespace sema;
00037 
00038 /// A convenience routine for creating a decayed reference to a
00039 /// function.
00040 static ExprResult
00041 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
00042                       SourceLocation Loc = SourceLocation(), 
00043                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
00044   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
00045                                                  VK_LValue, Loc, LocInfo);
00046   if (HadMultipleCandidates)
00047     DRE->setHadMultipleCandidates(true);
00048   ExprResult E = S.Owned(DRE);
00049   E = S.DefaultFunctionArrayConversion(E.take());
00050   if (E.isInvalid())
00051     return ExprError();
00052   return move(E);
00053 }
00054 
00055 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
00056                                  bool InOverloadResolution,
00057                                  StandardConversionSequence &SCS,
00058                                  bool CStyle,
00059                                  bool AllowObjCWritebackConversion);
00060   
00061 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 
00062                                                  QualType &ToType,
00063                                                  bool InOverloadResolution,
00064                                                  StandardConversionSequence &SCS,
00065                                                  bool CStyle);
00066 static OverloadingResult
00067 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
00068                         UserDefinedConversionSequence& User,
00069                         OverloadCandidateSet& Conversions,
00070                         bool AllowExplicit);
00071 
00072 
00073 static ImplicitConversionSequence::CompareKind
00074 CompareStandardConversionSequences(Sema &S,
00075                                    const StandardConversionSequence& SCS1,
00076                                    const StandardConversionSequence& SCS2);
00077 
00078 static ImplicitConversionSequence::CompareKind
00079 CompareQualificationConversions(Sema &S,
00080                                 const StandardConversionSequence& SCS1,
00081                                 const StandardConversionSequence& SCS2);
00082 
00083 static ImplicitConversionSequence::CompareKind
00084 CompareDerivedToBaseConversions(Sema &S,
00085                                 const StandardConversionSequence& SCS1,
00086                                 const StandardConversionSequence& SCS2);
00087 
00088 
00089 
00090 /// GetConversionCategory - Retrieve the implicit conversion
00091 /// category corresponding to the given implicit conversion kind.
00092 ImplicitConversionCategory
00093 GetConversionCategory(ImplicitConversionKind Kind) {
00094   static const ImplicitConversionCategory
00095     Category[(int)ICK_Num_Conversion_Kinds] = {
00096     ICC_Identity,
00097     ICC_Lvalue_Transformation,
00098     ICC_Lvalue_Transformation,
00099     ICC_Lvalue_Transformation,
00100     ICC_Identity,
00101     ICC_Qualification_Adjustment,
00102     ICC_Promotion,
00103     ICC_Promotion,
00104     ICC_Promotion,
00105     ICC_Conversion,
00106     ICC_Conversion,
00107     ICC_Conversion,
00108     ICC_Conversion,
00109     ICC_Conversion,
00110     ICC_Conversion,
00111     ICC_Conversion,
00112     ICC_Conversion,
00113     ICC_Conversion,
00114     ICC_Conversion,
00115     ICC_Conversion,
00116     ICC_Conversion,
00117     ICC_Conversion
00118   };
00119   return Category[(int)Kind];
00120 }
00121 
00122 /// GetConversionRank - Retrieve the implicit conversion rank
00123 /// corresponding to the given implicit conversion kind.
00124 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
00125   static const ImplicitConversionRank
00126     Rank[(int)ICK_Num_Conversion_Kinds] = {
00127     ICR_Exact_Match,
00128     ICR_Exact_Match,
00129     ICR_Exact_Match,
00130     ICR_Exact_Match,
00131     ICR_Exact_Match,
00132     ICR_Exact_Match,
00133     ICR_Promotion,
00134     ICR_Promotion,
00135     ICR_Promotion,
00136     ICR_Conversion,
00137     ICR_Conversion,
00138     ICR_Conversion,
00139     ICR_Conversion,
00140     ICR_Conversion,
00141     ICR_Conversion,
00142     ICR_Conversion,
00143     ICR_Conversion,
00144     ICR_Conversion,
00145     ICR_Conversion,
00146     ICR_Conversion,
00147     ICR_Complex_Real_Conversion,
00148     ICR_Conversion,
00149     ICR_Conversion,
00150     ICR_Writeback_Conversion
00151   };
00152   return Rank[(int)Kind];
00153 }
00154 
00155 /// GetImplicitConversionName - Return the name of this kind of
00156 /// implicit conversion.
00157 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
00158   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
00159     "No conversion",
00160     "Lvalue-to-rvalue",
00161     "Array-to-pointer",
00162     "Function-to-pointer",
00163     "Noreturn adjustment",
00164     "Qualification",
00165     "Integral promotion",
00166     "Floating point promotion",
00167     "Complex promotion",
00168     "Integral conversion",
00169     "Floating conversion",
00170     "Complex conversion",
00171     "Floating-integral conversion",
00172     "Pointer conversion",
00173     "Pointer-to-member conversion",
00174     "Boolean conversion",
00175     "Compatible-types conversion",
00176     "Derived-to-base conversion",
00177     "Vector conversion",
00178     "Vector splat",
00179     "Complex-real conversion",
00180     "Block Pointer conversion",
00181     "Transparent Union Conversion"
00182     "Writeback conversion"
00183   };
00184   return Name[Kind];
00185 }
00186 
00187 /// StandardConversionSequence - Set the standard conversion
00188 /// sequence to the identity conversion.
00189 void StandardConversionSequence::setAsIdentityConversion() {
00190   First = ICK_Identity;
00191   Second = ICK_Identity;
00192   Third = ICK_Identity;
00193   DeprecatedStringLiteralToCharPtr = false;
00194   QualificationIncludesObjCLifetime = false;
00195   ReferenceBinding = false;
00196   DirectBinding = false;
00197   IsLvalueReference = true;
00198   BindsToFunctionLvalue = false;
00199   BindsToRvalue = false;
00200   BindsImplicitObjectArgumentWithoutRefQualifier = false;
00201   ObjCLifetimeConversionBinding = false;
00202   CopyConstructor = 0;
00203 }
00204 
00205 /// getRank - Retrieve the rank of this standard conversion sequence
00206 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
00207 /// implicit conversions.
00208 ImplicitConversionRank StandardConversionSequence::getRank() const {
00209   ImplicitConversionRank Rank = ICR_Exact_Match;
00210   if  (GetConversionRank(First) > Rank)
00211     Rank = GetConversionRank(First);
00212   if  (GetConversionRank(Second) > Rank)
00213     Rank = GetConversionRank(Second);
00214   if  (GetConversionRank(Third) > Rank)
00215     Rank = GetConversionRank(Third);
00216   return Rank;
00217 }
00218 
00219 /// isPointerConversionToBool - Determines whether this conversion is
00220 /// a conversion of a pointer or pointer-to-member to bool. This is
00221 /// used as part of the ranking of standard conversion sequences
00222 /// (C++ 13.3.3.2p4).
00223 bool StandardConversionSequence::isPointerConversionToBool() const {
00224   // Note that FromType has not necessarily been transformed by the
00225   // array-to-pointer or function-to-pointer implicit conversions, so
00226   // check for their presence as well as checking whether FromType is
00227   // a pointer.
00228   if (getToType(1)->isBooleanType() &&
00229       (getFromType()->isPointerType() ||
00230        getFromType()->isObjCObjectPointerType() ||
00231        getFromType()->isBlockPointerType() ||
00232        getFromType()->isNullPtrType() ||
00233        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
00234     return true;
00235 
00236   return false;
00237 }
00238 
00239 /// isPointerConversionToVoidPointer - Determines whether this
00240 /// conversion is a conversion of a pointer to a void pointer. This is
00241 /// used as part of the ranking of standard conversion sequences (C++
00242 /// 13.3.3.2p4).
00243 bool
00244 StandardConversionSequence::
00245 isPointerConversionToVoidPointer(ASTContext& Context) const {
00246   QualType FromType = getFromType();
00247   QualType ToType = getToType(1);
00248 
00249   // Note that FromType has not necessarily been transformed by the
00250   // array-to-pointer implicit conversion, so check for its presence
00251   // and redo the conversion to get a pointer.
00252   if (First == ICK_Array_To_Pointer)
00253     FromType = Context.getArrayDecayedType(FromType);
00254 
00255   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
00256     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
00257       return ToPtrType->getPointeeType()->isVoidType();
00258 
00259   return false;
00260 }
00261 
00262 /// Skip any implicit casts which could be either part of a narrowing conversion
00263 /// or after one in an implicit conversion.
00264 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
00265   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
00266     switch (ICE->getCastKind()) {
00267     case CK_NoOp:
00268     case CK_IntegralCast:
00269     case CK_IntegralToBoolean:
00270     case CK_IntegralToFloating:
00271     case CK_FloatingToIntegral:
00272     case CK_FloatingToBoolean:
00273     case CK_FloatingCast:
00274       Converted = ICE->getSubExpr();
00275       continue;
00276 
00277     default:
00278       return Converted;
00279     }
00280   }
00281 
00282   return Converted;
00283 }
00284 
00285 /// Check if this standard conversion sequence represents a narrowing
00286 /// conversion, according to C++11 [dcl.init.list]p7.
00287 ///
00288 /// \param Ctx  The AST context.
00289 /// \param Converted  The result of applying this standard conversion sequence.
00290 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
00291 ///        value of the expression prior to the narrowing conversion.
00292 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
00293 ///        type of the expression prior to the narrowing conversion.
00294 NarrowingKind
00295 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
00296                                              const Expr *Converted,
00297                                              APValue &ConstantValue,
00298                                              QualType &ConstantType) const {
00299   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
00300 
00301   // C++11 [dcl.init.list]p7:
00302   //   A narrowing conversion is an implicit conversion ...
00303   QualType FromType = getToType(0);
00304   QualType ToType = getToType(1);
00305   switch (Second) {
00306   // -- from a floating-point type to an integer type, or
00307   //
00308   // -- from an integer type or unscoped enumeration type to a floating-point
00309   //    type, except where the source is a constant expression and the actual
00310   //    value after conversion will fit into the target type and will produce
00311   //    the original value when converted back to the original type, or
00312   case ICK_Floating_Integral:
00313     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
00314       return NK_Type_Narrowing;
00315     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
00316       llvm::APSInt IntConstantValue;
00317       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
00318       if (Initializer &&
00319           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
00320         // Convert the integer to the floating type.
00321         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
00322         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
00323                                 llvm::APFloat::rmNearestTiesToEven);
00324         // And back.
00325         llvm::APSInt ConvertedValue = IntConstantValue;
00326         bool ignored;
00327         Result.convertToInteger(ConvertedValue,
00328                                 llvm::APFloat::rmTowardZero, &ignored);
00329         // If the resulting value is different, this was a narrowing conversion.
00330         if (IntConstantValue != ConvertedValue) {
00331           ConstantValue = APValue(IntConstantValue);
00332           ConstantType = Initializer->getType();
00333           return NK_Constant_Narrowing;
00334         }
00335       } else {
00336         // Variables are always narrowings.
00337         return NK_Variable_Narrowing;
00338       }
00339     }
00340     return NK_Not_Narrowing;
00341 
00342   // -- from long double to double or float, or from double to float, except
00343   //    where the source is a constant expression and the actual value after
00344   //    conversion is within the range of values that can be represented (even
00345   //    if it cannot be represented exactly), or
00346   case ICK_Floating_Conversion:
00347     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
00348         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
00349       // FromType is larger than ToType.
00350       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
00351       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
00352         // Constant!
00353         assert(ConstantValue.isFloat());
00354         llvm::APFloat FloatVal = ConstantValue.getFloat();
00355         // Convert the source value into the target type.
00356         bool ignored;
00357         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
00358           Ctx.getFloatTypeSemantics(ToType),
00359           llvm::APFloat::rmNearestTiesToEven, &ignored);
00360         // If there was no overflow, the source value is within the range of
00361         // values that can be represented.
00362         if (ConvertStatus & llvm::APFloat::opOverflow) {
00363           ConstantType = Initializer->getType();
00364           return NK_Constant_Narrowing;
00365         }
00366       } else {
00367         return NK_Variable_Narrowing;
00368       }
00369     }
00370     return NK_Not_Narrowing;
00371 
00372   // -- from an integer type or unscoped enumeration type to an integer type
00373   //    that cannot represent all the values of the original type, except where
00374   //    the source is a constant expression and the actual value after
00375   //    conversion will fit into the target type and will produce the original
00376   //    value when converted back to the original type.
00377   case ICK_Boolean_Conversion:  // Bools are integers too.
00378     if (!FromType->isIntegralOrUnscopedEnumerationType()) {
00379       // Boolean conversions can be from pointers and pointers to members
00380       // [conv.bool], and those aren't considered narrowing conversions.
00381       return NK_Not_Narrowing;
00382     }  // Otherwise, fall through to the integral case.
00383   case ICK_Integral_Conversion: {
00384     assert(FromType->isIntegralOrUnscopedEnumerationType());
00385     assert(ToType->isIntegralOrUnscopedEnumerationType());
00386     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
00387     const unsigned FromWidth = Ctx.getIntWidth(FromType);
00388     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
00389     const unsigned ToWidth = Ctx.getIntWidth(ToType);
00390 
00391     if (FromWidth > ToWidth ||
00392         (FromWidth == ToWidth && FromSigned != ToSigned)) {
00393       // Not all values of FromType can be represented in ToType.
00394       llvm::APSInt InitializerValue;
00395       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
00396       if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
00397         ConstantValue = APValue(InitializerValue);
00398 
00399         // Add a bit to the InitializerValue so we don't have to worry about
00400         // signed vs. unsigned comparisons.
00401         InitializerValue = InitializerValue.extend(
00402           InitializerValue.getBitWidth() + 1);
00403         // Convert the initializer to and from the target width and signed-ness.
00404         llvm::APSInt ConvertedValue = InitializerValue;
00405         ConvertedValue = ConvertedValue.trunc(ToWidth);
00406         ConvertedValue.setIsSigned(ToSigned);
00407         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
00408         ConvertedValue.setIsSigned(InitializerValue.isSigned());
00409         // If the result is different, this was a narrowing conversion.
00410         if (ConvertedValue != InitializerValue) {
00411           ConstantType = Initializer->getType();
00412           return NK_Constant_Narrowing;
00413         }
00414       } else {
00415         // Variables are always narrowings.
00416         return NK_Variable_Narrowing;
00417       }
00418     }
00419     return NK_Not_Narrowing;
00420   }
00421 
00422   default:
00423     // Other kinds of conversions are not narrowings.
00424     return NK_Not_Narrowing;
00425   }
00426 }
00427 
00428 /// DebugPrint - Print this standard conversion sequence to standard
00429 /// error. Useful for debugging overloading issues.
00430 void StandardConversionSequence::DebugPrint() const {
00431   raw_ostream &OS = llvm::errs();
00432   bool PrintedSomething = false;
00433   if (First != ICK_Identity) {
00434     OS << GetImplicitConversionName(First);
00435     PrintedSomething = true;
00436   }
00437 
00438   if (Second != ICK_Identity) {
00439     if (PrintedSomething) {
00440       OS << " -> ";
00441     }
00442     OS << GetImplicitConversionName(Second);
00443 
00444     if (CopyConstructor) {
00445       OS << " (by copy constructor)";
00446     } else if (DirectBinding) {
00447       OS << " (direct reference binding)";
00448     } else if (ReferenceBinding) {
00449       OS << " (reference binding)";
00450     }
00451     PrintedSomething = true;
00452   }
00453 
00454   if (Third != ICK_Identity) {
00455     if (PrintedSomething) {
00456       OS << " -> ";
00457     }
00458     OS << GetImplicitConversionName(Third);
00459     PrintedSomething = true;
00460   }
00461 
00462   if (!PrintedSomething) {
00463     OS << "No conversions required";
00464   }
00465 }
00466 
00467 /// DebugPrint - Print this user-defined conversion sequence to standard
00468 /// error. Useful for debugging overloading issues.
00469 void UserDefinedConversionSequence::DebugPrint() const {
00470   raw_ostream &OS = llvm::errs();
00471   if (Before.First || Before.Second || Before.Third) {
00472     Before.DebugPrint();
00473     OS << " -> ";
00474   }
00475   if (ConversionFunction)
00476     OS << '\'' << *ConversionFunction << '\'';
00477   else
00478     OS << "aggregate initialization";
00479   if (After.First || After.Second || After.Third) {
00480     OS << " -> ";
00481     After.DebugPrint();
00482   }
00483 }
00484 
00485 /// DebugPrint - Print this implicit conversion sequence to standard
00486 /// error. Useful for debugging overloading issues.
00487 void ImplicitConversionSequence::DebugPrint() const {
00488   raw_ostream &OS = llvm::errs();
00489   switch (ConversionKind) {
00490   case StandardConversion:
00491     OS << "Standard conversion: ";
00492     Standard.DebugPrint();
00493     break;
00494   case UserDefinedConversion:
00495     OS << "User-defined conversion: ";
00496     UserDefined.DebugPrint();
00497     break;
00498   case EllipsisConversion:
00499     OS << "Ellipsis conversion";
00500     break;
00501   case AmbiguousConversion:
00502     OS << "Ambiguous conversion";
00503     break;
00504   case BadConversion:
00505     OS << "Bad conversion";
00506     break;
00507   }
00508 
00509   OS << "\n";
00510 }
00511 
00512 void AmbiguousConversionSequence::construct() {
00513   new (&conversions()) ConversionSet();
00514 }
00515 
00516 void AmbiguousConversionSequence::destruct() {
00517   conversions().~ConversionSet();
00518 }
00519 
00520 void
00521 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
00522   FromTypePtr = O.FromTypePtr;
00523   ToTypePtr = O.ToTypePtr;
00524   new (&conversions()) ConversionSet(O.conversions());
00525 }
00526 
00527 namespace {
00528   // Structure used by OverloadCandidate::DeductionFailureInfo to store
00529   // template parameter and template argument information.
00530   struct DFIParamWithArguments {
00531     TemplateParameter Param;
00532     TemplateArgument FirstArg;
00533     TemplateArgument SecondArg;
00534   };
00535 }
00536 
00537 /// \brief Convert from Sema's representation of template deduction information
00538 /// to the form used in overload-candidate information.
00539 OverloadCandidate::DeductionFailureInfo
00540 static MakeDeductionFailureInfo(ASTContext &Context,
00541                                 Sema::TemplateDeductionResult TDK,
00542                                 TemplateDeductionInfo &Info) {
00543   OverloadCandidate::DeductionFailureInfo Result;
00544   Result.Result = static_cast<unsigned>(TDK);
00545   Result.HasDiagnostic = false;
00546   Result.Data = 0;
00547   switch (TDK) {
00548   case Sema::TDK_Success:
00549   case Sema::TDK_InstantiationDepth:
00550   case Sema::TDK_TooManyArguments:
00551   case Sema::TDK_TooFewArguments:
00552     break;
00553 
00554   case Sema::TDK_Incomplete:
00555   case Sema::TDK_InvalidExplicitArguments:
00556     Result.Data = Info.Param.getOpaqueValue();
00557     break;
00558 
00559   case Sema::TDK_Inconsistent:
00560   case Sema::TDK_Underqualified: {
00561     // FIXME: Should allocate from normal heap so that we can free this later.
00562     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
00563     Saved->Param = Info.Param;
00564     Saved->FirstArg = Info.FirstArg;
00565     Saved->SecondArg = Info.SecondArg;
00566     Result.Data = Saved;
00567     break;
00568   }
00569 
00570   case Sema::TDK_SubstitutionFailure:
00571     Result.Data = Info.take();
00572     if (Info.hasSFINAEDiagnostic()) {
00573       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
00574           SourceLocation(), PartialDiagnostic::NullDiagnostic());
00575       Info.takeSFINAEDiagnostic(*Diag);
00576       Result.HasDiagnostic = true;
00577     }
00578     break;
00579 
00580   case Sema::TDK_NonDeducedMismatch:
00581   case Sema::TDK_FailedOverloadResolution:
00582     break;
00583   }
00584 
00585   return Result;
00586 }
00587 
00588 void OverloadCandidate::DeductionFailureInfo::Destroy() {
00589   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
00590   case Sema::TDK_Success:
00591   case Sema::TDK_InstantiationDepth:
00592   case Sema::TDK_Incomplete:
00593   case Sema::TDK_TooManyArguments:
00594   case Sema::TDK_TooFewArguments:
00595   case Sema::TDK_InvalidExplicitArguments:
00596     break;
00597 
00598   case Sema::TDK_Inconsistent:
00599   case Sema::TDK_Underqualified:
00600     // FIXME: Destroy the data?
00601     Data = 0;
00602     break;
00603 
00604   case Sema::TDK_SubstitutionFailure:
00605     // FIXME: Destroy the template argument list?
00606     Data = 0;
00607     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
00608       Diag->~PartialDiagnosticAt();
00609       HasDiagnostic = false;
00610     }
00611     break;
00612 
00613   // Unhandled
00614   case Sema::TDK_NonDeducedMismatch:
00615   case Sema::TDK_FailedOverloadResolution:
00616     break;
00617   }
00618 }
00619 
00620 PartialDiagnosticAt *
00621 OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
00622   if (HasDiagnostic)
00623     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
00624   return 0;
00625 }
00626 
00627 TemplateParameter
00628 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
00629   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
00630   case Sema::TDK_Success:
00631   case Sema::TDK_InstantiationDepth:
00632   case Sema::TDK_TooManyArguments:
00633   case Sema::TDK_TooFewArguments:
00634   case Sema::TDK_SubstitutionFailure:
00635     return TemplateParameter();
00636 
00637   case Sema::TDK_Incomplete:
00638   case Sema::TDK_InvalidExplicitArguments:
00639     return TemplateParameter::getFromOpaqueValue(Data);
00640 
00641   case Sema::TDK_Inconsistent:
00642   case Sema::TDK_Underqualified:
00643     return static_cast<DFIParamWithArguments*>(Data)->Param;
00644 
00645   // Unhandled
00646   case Sema::TDK_NonDeducedMismatch:
00647   case Sema::TDK_FailedOverloadResolution:
00648     break;
00649   }
00650 
00651   return TemplateParameter();
00652 }
00653 
00654 TemplateArgumentList *
00655 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
00656   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
00657     case Sema::TDK_Success:
00658     case Sema::TDK_InstantiationDepth:
00659     case Sema::TDK_TooManyArguments:
00660     case Sema::TDK_TooFewArguments:
00661     case Sema::TDK_Incomplete:
00662     case Sema::TDK_InvalidExplicitArguments:
00663     case Sema::TDK_Inconsistent:
00664     case Sema::TDK_Underqualified:
00665       return 0;
00666 
00667     case Sema::TDK_SubstitutionFailure:
00668       return static_cast<TemplateArgumentList*>(Data);
00669 
00670     // Unhandled
00671     case Sema::TDK_NonDeducedMismatch:
00672     case Sema::TDK_FailedOverloadResolution:
00673       break;
00674   }
00675 
00676   return 0;
00677 }
00678 
00679 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
00680   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
00681   case Sema::TDK_Success:
00682   case Sema::TDK_InstantiationDepth:
00683   case Sema::TDK_Incomplete:
00684   case Sema::TDK_TooManyArguments:
00685   case Sema::TDK_TooFewArguments:
00686   case Sema::TDK_InvalidExplicitArguments:
00687   case Sema::TDK_SubstitutionFailure:
00688     return 0;
00689 
00690   case Sema::TDK_Inconsistent:
00691   case Sema::TDK_Underqualified:
00692     return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
00693 
00694   // Unhandled
00695   case Sema::TDK_NonDeducedMismatch:
00696   case Sema::TDK_FailedOverloadResolution:
00697     break;
00698   }
00699 
00700   return 0;
00701 }
00702 
00703 const TemplateArgument *
00704 OverloadCandidate::DeductionFailureInfo::getSecondArg() {
00705   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
00706   case Sema::TDK_Success:
00707   case Sema::TDK_InstantiationDepth:
00708   case Sema::TDK_Incomplete:
00709   case Sema::TDK_TooManyArguments:
00710   case Sema::TDK_TooFewArguments:
00711   case Sema::TDK_InvalidExplicitArguments:
00712   case Sema::TDK_SubstitutionFailure:
00713     return 0;
00714 
00715   case Sema::TDK_Inconsistent:
00716   case Sema::TDK_Underqualified:
00717     return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
00718 
00719   // Unhandled
00720   case Sema::TDK_NonDeducedMismatch:
00721   case Sema::TDK_FailedOverloadResolution:
00722     break;
00723   }
00724 
00725   return 0;
00726 }
00727 
00728 void OverloadCandidateSet::clear() {
00729   for (iterator i = begin(), e = end(); i != e; ++i)
00730     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
00731       i->Conversions[ii].~ImplicitConversionSequence();
00732   NumInlineSequences = 0;
00733   Candidates.clear();
00734   Functions.clear();
00735 }
00736 
00737 namespace {
00738   class UnbridgedCastsSet {
00739     struct Entry {
00740       Expr **Addr;
00741       Expr *Saved;
00742     };
00743     SmallVector<Entry, 2> Entries;
00744     
00745   public:
00746     void save(Sema &S, Expr *&E) {
00747       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
00748       Entry entry = { &E, E };
00749       Entries.push_back(entry);
00750       E = S.stripARCUnbridgedCast(E);
00751     }
00752 
00753     void restore() {
00754       for (SmallVectorImpl<Entry>::iterator
00755              i = Entries.begin(), e = Entries.end(); i != e; ++i) 
00756         *i->Addr = i->Saved;
00757     }
00758   };
00759 }
00760 
00761 /// checkPlaceholderForOverload - Do any interesting placeholder-like
00762 /// preprocessing on the given expression.
00763 ///
00764 /// \param unbridgedCasts a collection to which to add unbridged casts;
00765 ///   without this, they will be immediately diagnosed as errors
00766 ///
00767 /// Return true on unrecoverable error.
00768 static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
00769                                         UnbridgedCastsSet *unbridgedCasts = 0) {
00770   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
00771     // We can't handle overloaded expressions here because overload
00772     // resolution might reasonably tweak them.
00773     if (placeholder->getKind() == BuiltinType::Overload) return false;
00774 
00775     // If the context potentially accepts unbridged ARC casts, strip
00776     // the unbridged cast and add it to the collection for later restoration.
00777     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
00778         unbridgedCasts) {
00779       unbridgedCasts->save(S, E);
00780       return false;
00781     }
00782 
00783     // Go ahead and check everything else.
00784     ExprResult result = S.CheckPlaceholderExpr(E);
00785     if (result.isInvalid())
00786       return true;
00787 
00788     E = result.take();
00789     return false;
00790   }
00791 
00792   // Nothing to do.
00793   return false;
00794 }
00795 
00796 /// checkArgPlaceholdersForOverload - Check a set of call operands for
00797 /// placeholders.
00798 static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
00799                                             unsigned numArgs,
00800                                             UnbridgedCastsSet &unbridged) {
00801   for (unsigned i = 0; i != numArgs; ++i)
00802     if (checkPlaceholderForOverload(S, args[i], &unbridged))
00803       return true;
00804 
00805   return false;
00806 }
00807 
00808 // IsOverload - Determine whether the given New declaration is an
00809 // overload of the declarations in Old. This routine returns false if
00810 // New and Old cannot be overloaded, e.g., if New has the same
00811 // signature as some function in Old (C++ 1.3.10) or if the Old
00812 // declarations aren't functions (or function templates) at all. When
00813 // it does return false, MatchedDecl will point to the decl that New
00814 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
00815 // top of the underlying declaration.
00816 //
00817 // Example: Given the following input:
00818 //
00819 //   void f(int, float); // #1
00820 //   void f(int, int); // #2
00821 //   int f(int, int); // #3
00822 //
00823 // When we process #1, there is no previous declaration of "f",
00824 // so IsOverload will not be used.
00825 //
00826 // When we process #2, Old contains only the FunctionDecl for #1.  By
00827 // comparing the parameter types, we see that #1 and #2 are overloaded
00828 // (since they have different signatures), so this routine returns
00829 // false; MatchedDecl is unchanged.
00830 //
00831 // When we process #3, Old is an overload set containing #1 and #2. We
00832 // compare the signatures of #3 to #1 (they're overloaded, so we do
00833 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
00834 // identical (return types of functions are not part of the
00835 // signature), IsOverload returns false and MatchedDecl will be set to
00836 // point to the FunctionDecl for #2.
00837 //
00838 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
00839 // into a class by a using declaration.  The rules for whether to hide
00840 // shadow declarations ignore some properties which otherwise figure
00841 // into a function template's signature.
00842 Sema::OverloadKind
00843 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
00844                     NamedDecl *&Match, bool NewIsUsingDecl) {
00845   for (LookupResult::iterator I = Old.begin(), E = Old.end();
00846          I != E; ++I) {
00847     NamedDecl *OldD = *I;
00848 
00849     bool OldIsUsingDecl = false;
00850     if (isa<UsingShadowDecl>(OldD)) {
00851       OldIsUsingDecl = true;
00852 
00853       // We can always introduce two using declarations into the same
00854       // context, even if they have identical signatures.
00855       if (NewIsUsingDecl) continue;
00856 
00857       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
00858     }
00859 
00860     // If either declaration was introduced by a using declaration,
00861     // we'll need to use slightly different rules for matching.
00862     // Essentially, these rules are the normal rules, except that
00863     // function templates hide function templates with different
00864     // return types or template parameter lists.
00865     bool UseMemberUsingDeclRules =
00866       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
00867 
00868     if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
00869       if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
00870         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
00871           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
00872           continue;
00873         }
00874 
00875         Match = *I;
00876         return Ovl_Match;
00877       }
00878     } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
00879       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
00880         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
00881           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
00882           continue;
00883         }
00884 
00885         Match = *I;
00886         return Ovl_Match;
00887       }
00888     } else if (isa<UsingDecl>(OldD)) {
00889       // We can overload with these, which can show up when doing
00890       // redeclaration checks for UsingDecls.
00891       assert(Old.getLookupKind() == LookupUsingDeclName);
00892     } else if (isa<TagDecl>(OldD)) {
00893       // We can always overload with tags by hiding them.
00894     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
00895       // Optimistically assume that an unresolved using decl will
00896       // overload; if it doesn't, we'll have to diagnose during
00897       // template instantiation.
00898     } else {
00899       // (C++ 13p1):
00900       //   Only function declarations can be overloaded; object and type
00901       //   declarations cannot be overloaded.
00902       Match = *I;
00903       return Ovl_NonFunction;
00904     }
00905   }
00906 
00907   return Ovl_Overload;
00908 }
00909 
00910 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
00911                       bool UseUsingDeclRules) {
00912   // If both of the functions are extern "C", then they are not
00913   // overloads.
00914   if (Old->isExternC() && New->isExternC())
00915     return false;
00916 
00917   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
00918   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
00919 
00920   // C++ [temp.fct]p2:
00921   //   A function template can be overloaded with other function templates
00922   //   and with normal (non-template) functions.
00923   if ((OldTemplate == 0) != (NewTemplate == 0))
00924     return true;
00925 
00926   // Is the function New an overload of the function Old?
00927   QualType OldQType = Context.getCanonicalType(Old->getType());
00928   QualType NewQType = Context.getCanonicalType(New->getType());
00929 
00930   // Compare the signatures (C++ 1.3.10) of the two functions to
00931   // determine whether they are overloads. If we find any mismatch
00932   // in the signature, they are overloads.
00933 
00934   // If either of these functions is a K&R-style function (no
00935   // prototype), then we consider them to have matching signatures.
00936   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
00937       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
00938     return false;
00939 
00940   const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
00941   const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
00942 
00943   // The signature of a function includes the types of its
00944   // parameters (C++ 1.3.10), which includes the presence or absence
00945   // of the ellipsis; see C++ DR 357).
00946   if (OldQType != NewQType &&
00947       (OldType->getNumArgs() != NewType->getNumArgs() ||
00948        OldType->isVariadic() != NewType->isVariadic() ||
00949        !FunctionArgTypesAreEqual(OldType, NewType)))
00950     return true;
00951 
00952   // C++ [temp.over.link]p4:
00953   //   The signature of a function template consists of its function
00954   //   signature, its return type and its template parameter list. The names
00955   //   of the template parameters are significant only for establishing the
00956   //   relationship between the template parameters and the rest of the
00957   //   signature.
00958   //
00959   // We check the return type and template parameter lists for function
00960   // templates first; the remaining checks follow.
00961   //
00962   // However, we don't consider either of these when deciding whether
00963   // a member introduced by a shadow declaration is hidden.
00964   if (!UseUsingDeclRules && NewTemplate &&
00965       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
00966                                        OldTemplate->getTemplateParameters(),
00967                                        false, TPL_TemplateMatch) ||
00968        OldType->getResultType() != NewType->getResultType()))
00969     return true;
00970 
00971   // If the function is a class member, its signature includes the
00972   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
00973   //
00974   // As part of this, also check whether one of the member functions
00975   // is static, in which case they are not overloads (C++
00976   // 13.1p2). While not part of the definition of the signature,
00977   // this check is important to determine whether these functions
00978   // can be overloaded.
00979   CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
00980   CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
00981   if (OldMethod && NewMethod &&
00982       !OldMethod->isStatic() && !NewMethod->isStatic() &&
00983       (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
00984        OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
00985     if (!UseUsingDeclRules &&
00986         OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
00987         (OldMethod->getRefQualifier() == RQ_None ||
00988          NewMethod->getRefQualifier() == RQ_None)) {
00989       // C++0x [over.load]p2:
00990       //   - Member function declarations with the same name and the same
00991       //     parameter-type-list as well as member function template
00992       //     declarations with the same name, the same parameter-type-list, and
00993       //     the same template parameter lists cannot be overloaded if any of
00994       //     them, but not all, have a ref-qualifier (8.3.5).
00995       Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
00996         << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
00997       Diag(OldMethod->getLocation(), diag::note_previous_declaration);
00998     }
00999 
01000     return true;
01001   }
01002 
01003   // The signatures match; this is not an overload.
01004   return false;
01005 }
01006 
01007 /// \brief Checks availability of the function depending on the current
01008 /// function context. Inside an unavailable function, unavailability is ignored.
01009 ///
01010 /// \returns true if \arg FD is unavailable and current context is inside
01011 /// an available function, false otherwise.
01012 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
01013   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
01014 }
01015 
01016 /// \brief Tries a user-defined conversion from From to ToType.
01017 ///
01018 /// Produces an implicit conversion sequence for when a standard conversion
01019 /// is not an option. See TryImplicitConversion for more information.
01020 static ImplicitConversionSequence
01021 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
01022                          bool SuppressUserConversions,
01023                          bool AllowExplicit,
01024                          bool InOverloadResolution,
01025                          bool CStyle,
01026                          bool AllowObjCWritebackConversion) {
01027   ImplicitConversionSequence ICS;
01028 
01029   if (SuppressUserConversions) {
01030     // We're not in the case above, so there is no conversion that
01031     // we can perform.
01032     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
01033     return ICS;
01034   }
01035 
01036   // Attempt user-defined conversion.
01037   OverloadCandidateSet Conversions(From->getExprLoc());
01038   OverloadingResult UserDefResult
01039     = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
01040                               AllowExplicit);
01041 
01042   if (UserDefResult == OR_Success) {
01043     ICS.setUserDefined();
01044     // C++ [over.ics.user]p4:
01045     //   A conversion of an expression of class type to the same class
01046     //   type is given Exact Match rank, and a conversion of an
01047     //   expression of class type to a base class of that type is
01048     //   given Conversion rank, in spite of the fact that a copy
01049     //   constructor (i.e., a user-defined conversion function) is
01050     //   called for those cases.
01051     if (CXXConstructorDecl *Constructor
01052           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
01053       QualType FromCanon
01054         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
01055       QualType ToCanon
01056         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
01057       if (Constructor->isCopyConstructor() &&
01058           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
01059         // Turn this into a "standard" conversion sequence, so that it
01060         // gets ranked with standard conversion sequences.
01061         ICS.setStandard();
01062         ICS.Standard.setAsIdentityConversion();
01063         ICS.Standard.setFromType(From->getType());
01064         ICS.Standard.setAllToTypes(ToType);
01065         ICS.Standard.CopyConstructor = Constructor;
01066         if (ToCanon != FromCanon)
01067           ICS.Standard.Second = ICK_Derived_To_Base;
01068       }
01069     }
01070 
01071     // C++ [over.best.ics]p4:
01072     //   However, when considering the argument of a user-defined
01073     //   conversion function that is a candidate by 13.3.1.3 when
01074     //   invoked for the copying of the temporary in the second step
01075     //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
01076     //   13.3.1.6 in all cases, only standard conversion sequences and
01077     //   ellipsis conversion sequences are allowed.
01078     if (SuppressUserConversions && ICS.isUserDefined()) {
01079       ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
01080     }
01081   } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
01082     ICS.setAmbiguous();
01083     ICS.Ambiguous.setFromType(From->getType());
01084     ICS.Ambiguous.setToType(ToType);
01085     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
01086          Cand != Conversions.end(); ++Cand)
01087       if (Cand->Viable)
01088         ICS.Ambiguous.addConversion(Cand->Function);
01089   } else {
01090     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
01091   }
01092 
01093   return ICS;
01094 }
01095 
01096 /// TryImplicitConversion - Attempt to perform an implicit conversion
01097 /// from the given expression (Expr) to the given type (ToType). This
01098 /// function returns an implicit conversion sequence that can be used
01099 /// to perform the initialization. Given
01100 ///
01101 ///   void f(float f);
01102 ///   void g(int i) { f(i); }
01103 ///
01104 /// this routine would produce an implicit conversion sequence to
01105 /// describe the initialization of f from i, which will be a standard
01106 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
01107 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
01108 //
01109 /// Note that this routine only determines how the conversion can be
01110 /// performed; it does not actually perform the conversion. As such,
01111 /// it will not produce any diagnostics if no conversion is available,
01112 /// but will instead return an implicit conversion sequence of kind
01113 /// "BadConversion".
01114 ///
01115 /// If @p SuppressUserConversions, then user-defined conversions are
01116 /// not permitted.
01117 /// If @p AllowExplicit, then explicit user-defined conversions are
01118 /// permitted.
01119 ///
01120 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
01121 /// writeback conversion, which allows __autoreleasing id* parameters to
01122 /// be initialized with __strong id* or __weak id* arguments.
01123 static ImplicitConversionSequence
01124 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
01125                       bool SuppressUserConversions,
01126                       bool AllowExplicit,
01127                       bool InOverloadResolution,
01128                       bool CStyle,
01129                       bool AllowObjCWritebackConversion) {
01130   ImplicitConversionSequence ICS;
01131   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
01132                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
01133     ICS.setStandard();
01134     return ICS;
01135   }
01136 
01137   if (!S.getLangOpts().CPlusPlus) {
01138     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
01139     return ICS;
01140   }
01141 
01142   // C++ [over.ics.user]p4:
01143   //   A conversion of an expression of class type to the same class
01144   //   type is given Exact Match rank, and a conversion of an
01145   //   expression of class type to a base class of that type is
01146   //   given Conversion rank, in spite of the fact that a copy/move
01147   //   constructor (i.e., a user-defined conversion function) is
01148   //   called for those cases.
01149   QualType FromType = From->getType();
01150   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
01151       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
01152        S.IsDerivedFrom(FromType, ToType))) {
01153     ICS.setStandard();
01154     ICS.Standard.setAsIdentityConversion();
01155     ICS.Standard.setFromType(FromType);
01156     ICS.Standard.setAllToTypes(ToType);
01157 
01158     // We don't actually check at this point whether there is a valid
01159     // copy/move constructor, since overloading just assumes that it
01160     // exists. When we actually perform initialization, we'll find the
01161     // appropriate constructor to copy the returned object, if needed.
01162     ICS.Standard.CopyConstructor = 0;
01163 
01164     // Determine whether this is considered a derived-to-base conversion.
01165     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
01166       ICS.Standard.Second = ICK_Derived_To_Base;
01167 
01168     return ICS;
01169   }
01170 
01171   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
01172                                   AllowExplicit, InOverloadResolution, CStyle,
01173                                   AllowObjCWritebackConversion);
01174 }
01175 
01176 ImplicitConversionSequence
01177 Sema::TryImplicitConversion(Expr *From, QualType ToType,
01178                             bool SuppressUserConversions,
01179                             bool AllowExplicit,
01180                             bool InOverloadResolution,
01181                             bool CStyle,
01182                             bool AllowObjCWritebackConversion) {
01183   return clang::TryImplicitConversion(*this, From, ToType, 
01184                                       SuppressUserConversions, AllowExplicit,
01185                                       InOverloadResolution, CStyle, 
01186                                       AllowObjCWritebackConversion);
01187 }
01188 
01189 /// PerformImplicitConversion - Perform an implicit conversion of the
01190 /// expression From to the type ToType. Returns the
01191 /// converted expression. Flavor is the kind of conversion we're
01192 /// performing, used in the error message. If @p AllowExplicit,
01193 /// explicit user-defined conversions are permitted.
01194 ExprResult
01195 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
01196                                 AssignmentAction Action, bool AllowExplicit) {
01197   ImplicitConversionSequence ICS;
01198   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
01199 }
01200 
01201 ExprResult
01202 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
01203                                 AssignmentAction Action, bool AllowExplicit,
01204                                 ImplicitConversionSequence& ICS) {
01205   if (checkPlaceholderForOverload(*this, From))
01206     return ExprError();
01207 
01208   // Objective-C ARC: Determine whether we will allow the writeback conversion.
01209   bool AllowObjCWritebackConversion
01210     = getLangOpts().ObjCAutoRefCount && 
01211       (Action == AA_Passing || Action == AA_Sending);
01212 
01213   ICS = clang::TryImplicitConversion(*this, From, ToType,
01214                                      /*SuppressUserConversions=*/false,
01215                                      AllowExplicit,
01216                                      /*InOverloadResolution=*/false,
01217                                      /*CStyle=*/false,
01218                                      AllowObjCWritebackConversion);
01219   return PerformImplicitConversion(From, ToType, ICS, Action);
01220 }
01221 
01222 /// \brief Determine whether the conversion from FromType to ToType is a valid
01223 /// conversion that strips "noreturn" off the nested function type.
01224 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
01225                                 QualType &ResultTy) {
01226   if (Context.hasSameUnqualifiedType(FromType, ToType))
01227     return false;
01228 
01229   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
01230   // where F adds one of the following at most once:
01231   //   - a pointer
01232   //   - a member pointer
01233   //   - a block pointer
01234   CanQualType CanTo = Context.getCanonicalType(ToType);
01235   CanQualType CanFrom = Context.getCanonicalType(FromType);
01236   Type::TypeClass TyClass = CanTo->getTypeClass();
01237   if (TyClass != CanFrom->getTypeClass()) return false;
01238   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
01239     if (TyClass == Type::Pointer) {
01240       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
01241       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
01242     } else if (TyClass == Type::BlockPointer) {
01243       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
01244       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
01245     } else if (TyClass == Type::MemberPointer) {
01246       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
01247       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
01248     } else {
01249       return false;
01250     }
01251 
01252     TyClass = CanTo->getTypeClass();
01253     if (TyClass != CanFrom->getTypeClass()) return false;
01254     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
01255       return false;
01256   }
01257 
01258   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
01259   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
01260   if (!EInfo.getNoReturn()) return false;
01261 
01262   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
01263   assert(QualType(FromFn, 0).isCanonical());
01264   if (QualType(FromFn, 0) != CanTo) return false;
01265 
01266   ResultTy = ToType;
01267   return true;
01268 }
01269 
01270 /// \brief Determine whether the conversion from FromType to ToType is a valid
01271 /// vector conversion.
01272 ///
01273 /// \param ICK Will be set to the vector conversion kind, if this is a vector
01274 /// conversion.
01275 static bool IsVectorConversion(ASTContext &Context, QualType FromType,
01276                                QualType ToType, ImplicitConversionKind &ICK) {
01277   // We need at least one of these types to be a vector type to have a vector
01278   // conversion.
01279   if (!ToType->isVectorType() && !FromType->isVectorType())
01280     return false;
01281 
01282   // Identical types require no conversions.
01283   if (Context.hasSameUnqualifiedType(FromType, ToType))
01284     return false;
01285 
01286   // There are no conversions between extended vector types, only identity.
01287   if (ToType->isExtVectorType()) {
01288     // There are no conversions between extended vector types other than the
01289     // identity conversion.
01290     if (FromType->isExtVectorType())
01291       return false;
01292 
01293     // Vector splat from any arithmetic type to a vector.
01294     if (FromType->isArithmeticType()) {
01295       ICK = ICK_Vector_Splat;
01296       return true;
01297     }
01298   }
01299 
01300   // We can perform the conversion between vector types in the following cases:
01301   // 1)vector types are equivalent AltiVec and GCC vector types
01302   // 2)lax vector conversions are permitted and the vector types are of the
01303   //   same size
01304   if (ToType->isVectorType() && FromType->isVectorType()) {
01305     if (Context.areCompatibleVectorTypes(FromType, ToType) ||
01306         (Context.getLangOpts().LaxVectorConversions &&
01307          (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
01308       ICK = ICK_Vector_Conversion;
01309       return true;
01310     }
01311   }
01312 
01313   return false;
01314 }
01315 
01316 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
01317                                 bool InOverloadResolution,
01318                                 StandardConversionSequence &SCS,
01319                                 bool CStyle);
01320   
01321 /// IsStandardConversion - Determines whether there is a standard
01322 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
01323 /// expression From to the type ToType. Standard conversion sequences
01324 /// only consider non-class types; for conversions that involve class
01325 /// types, use TryImplicitConversion. If a conversion exists, SCS will
01326 /// contain the standard conversion sequence required to perform this
01327 /// conversion and this routine will return true. Otherwise, this
01328 /// routine will return false and the value of SCS is unspecified.
01329 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
01330                                  bool InOverloadResolution,
01331                                  StandardConversionSequence &SCS,
01332                                  bool CStyle,
01333                                  bool AllowObjCWritebackConversion) {
01334   QualType FromType = From->getType();
01335 
01336   // Standard conversions (C++ [conv])
01337   SCS.setAsIdentityConversion();
01338   SCS.DeprecatedStringLiteralToCharPtr = false;
01339   SCS.IncompatibleObjC = false;
01340   SCS.setFromType(FromType);
01341   SCS.CopyConstructor = 0;
01342 
01343   // There are no standard conversions for class types in C++, so
01344   // abort early. When overloading in C, however, we do permit
01345   if (FromType->isRecordType() || ToType->isRecordType()) {
01346     if (S.getLangOpts().CPlusPlus)
01347       return false;
01348 
01349     // When we're overloading in C, we allow, as standard conversions,
01350   }
01351 
01352   // The first conversion can be an lvalue-to-rvalue conversion,
01353   // array-to-pointer conversion, or function-to-pointer conversion
01354   // (C++ 4p1).
01355 
01356   if (FromType == S.Context.OverloadTy) {
01357     DeclAccessPair AccessPair;
01358     if (FunctionDecl *Fn
01359           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
01360                                                  AccessPair)) {
01361       // We were able to resolve the address of the overloaded function,
01362       // so we can convert to the type of that function.
01363       FromType = Fn->getType();
01364 
01365       // we can sometimes resolve &foo<int> regardless of ToType, so check
01366       // if the type matches (identity) or we are converting to bool
01367       if (!S.Context.hasSameUnqualifiedType(
01368                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
01369         QualType resultTy;
01370         // if the function type matches except for [[noreturn]], it's ok
01371         if (!S.IsNoReturnConversion(FromType,
01372               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
01373           // otherwise, only a boolean conversion is standard   
01374           if (!ToType->isBooleanType()) 
01375             return false; 
01376       }
01377 
01378       // Check if the "from" expression is taking the address of an overloaded
01379       // function and recompute the FromType accordingly. Take advantage of the
01380       // fact that non-static member functions *must* have such an address-of
01381       // expression. 
01382       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
01383       if (Method && !Method->isStatic()) {
01384         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
01385                "Non-unary operator on non-static member address");
01386         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
01387                == UO_AddrOf &&
01388                "Non-address-of operator on non-static member address");
01389         const Type *ClassType
01390           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
01391         FromType = S.Context.getMemberPointerType(FromType, ClassType);
01392       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
01393         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
01394                UO_AddrOf &&
01395                "Non-address-of operator for overloaded function expression");
01396         FromType = S.Context.getPointerType(FromType);
01397       }
01398 
01399       // Check that we've computed the proper type after overload resolution.
01400       assert(S.Context.hasSameType(
01401         FromType,
01402         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
01403     } else {
01404       return false;
01405     }
01406   }
01407   // Lvalue-to-rvalue conversion (C++11 4.1):
01408   //   A glvalue (3.10) of a non-function, non-array type T can
01409   //   be converted to a prvalue.
01410   bool argIsLValue = From->isGLValue();
01411   if (argIsLValue &&
01412       !FromType->isFunctionType() && !FromType->isArrayType() &&
01413       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
01414     SCS.First = ICK_Lvalue_To_Rvalue;
01415 
01416     // C11 6.3.2.1p2:
01417     //   ... if the lvalue has atomic type, the value has the non-atomic version 
01418     //   of the type of the lvalue ...
01419     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
01420       FromType = Atomic->getValueType();
01421 
01422     // If T is a non-class type, the type of the rvalue is the
01423     // cv-unqualified version of T. Otherwise, the type of the rvalue
01424     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
01425     // just strip the qualifiers because they don't matter.
01426     FromType = FromType.getUnqualifiedType();
01427   } else if (FromType->isArrayType()) {
01428     // Array-to-pointer conversion (C++ 4.2)
01429     SCS.First = ICK_Array_To_Pointer;
01430 
01431     // An lvalue or rvalue of type "array of N T" or "array of unknown
01432     // bound of T" can be converted to an rvalue of type "pointer to
01433     // T" (C++ 4.2p1).
01434     FromType = S.Context.getArrayDecayedType(FromType);
01435 
01436     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
01437       // This conversion is deprecated. (C++ D.4).
01438       SCS.DeprecatedStringLiteralToCharPtr = true;
01439 
01440       // For the purpose of ranking in overload resolution
01441       // (13.3.3.1.1), this conversion is considered an
01442       // array-to-pointer conversion followed by a qualification
01443       // conversion (4.4). (C++ 4.2p2)
01444       SCS.Second = ICK_Identity;
01445       SCS.Third = ICK_Qualification;
01446       SCS.QualificationIncludesObjCLifetime = false;
01447       SCS.setAllToTypes(FromType);
01448       return true;
01449     }
01450   } else if (FromType->isFunctionType() && argIsLValue) {
01451     // Function-to-pointer conversion (C++ 4.3).
01452     SCS.First = ICK_Function_To_Pointer;
01453 
01454     // An lvalue of function type T can be converted to an rvalue of
01455     // type "pointer to T." The result is a pointer to the
01456     // function. (C++ 4.3p1).
01457     FromType = S.Context.getPointerType(FromType);
01458   } else {
01459     // We don't require any conversions for the first step.
01460     SCS.First = ICK_Identity;
01461   }
01462   SCS.setToType(0, FromType);
01463 
01464   // The second conversion can be an integral promotion, floating
01465   // point promotion, integral conversion, floating point conversion,
01466   // floating-integral conversion, pointer conversion,
01467   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
01468   // For overloading in C, this can also be a "compatible-type"
01469   // conversion.
01470   bool IncompatibleObjC = false;
01471   ImplicitConversionKind SecondICK = ICK_Identity;
01472   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
01473     // The unqualified versions of the types are the same: there's no
01474     // conversion to do.
01475     SCS.Second = ICK_Identity;
01476   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
01477     // Integral promotion (C++ 4.5).
01478     SCS.Second = ICK_Integral_Promotion;
01479     FromType = ToType.getUnqualifiedType();
01480   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
01481     // Floating point promotion (C++ 4.6).
01482     SCS.Second = ICK_Floating_Promotion;
01483     FromType = ToType.getUnqualifiedType();
01484   } else if (S.IsComplexPromotion(FromType, ToType)) {
01485     // Complex promotion (Clang extension)
01486     SCS.Second = ICK_Complex_Promotion;
01487     FromType = ToType.getUnqualifiedType();
01488   } else if (ToType->isBooleanType() &&
01489              (FromType->isArithmeticType() ||
01490               FromType->isAnyPointerType() ||
01491               FromType->isBlockPointerType() ||
01492               FromType->isMemberPointerType() ||
01493               FromType->isNullPtrType())) {
01494     // Boolean conversions (C++ 4.12).
01495     SCS.Second = ICK_Boolean_Conversion;
01496     FromType = S.Context.BoolTy;
01497   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
01498              ToType->isIntegralType(S.Context)) {
01499     // Integral conversions (C++ 4.7).
01500     SCS.Second = ICK_Integral_Conversion;
01501     FromType = ToType.getUnqualifiedType();
01502   } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
01503     // Complex conversions (C99 6.3.1.6)
01504     SCS.Second = ICK_Complex_Conversion;
01505     FromType = ToType.getUnqualifiedType();
01506   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
01507              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
01508     // Complex-real conversions (C99 6.3.1.7)
01509     SCS.Second = ICK_Complex_Real;
01510     FromType = ToType.getUnqualifiedType();
01511   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
01512     // Floating point conversions (C++ 4.8).
01513     SCS.Second = ICK_Floating_Conversion;
01514     FromType = ToType.getUnqualifiedType();
01515   } else if ((FromType->isRealFloatingType() &&
01516               ToType->isIntegralType(S.Context)) ||
01517              (FromType->isIntegralOrUnscopedEnumerationType() &&
01518               ToType->isRealFloatingType())) {
01519     // Floating-integral conversions (C++ 4.9).
01520     SCS.Second = ICK_Floating_Integral;
01521     FromType = ToType.getUnqualifiedType();
01522   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
01523     SCS.Second = ICK_Block_Pointer_Conversion;
01524   } else if (AllowObjCWritebackConversion &&
01525              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
01526     SCS.Second = ICK_Writeback_Conversion;
01527   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
01528                                    FromType, IncompatibleObjC)) {
01529     // Pointer conversions (C++ 4.10).
01530     SCS.Second = ICK_Pointer_Conversion;
01531     SCS.IncompatibleObjC = IncompatibleObjC;
01532     FromType = FromType.getUnqualifiedType();
01533   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
01534                                          InOverloadResolution, FromType)) {
01535     // Pointer to member conversions (4.11).
01536     SCS.Second = ICK_Pointer_Member;
01537   } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
01538     SCS.Second = SecondICK;
01539     FromType = ToType.getUnqualifiedType();
01540   } else if (!S.getLangOpts().CPlusPlus &&
01541              S.Context.typesAreCompatible(ToType, FromType)) {
01542     // Compatible conversions (Clang extension for C function overloading)
01543     SCS.Second = ICK_Compatible_Conversion;
01544     FromType = ToType.getUnqualifiedType();
01545   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
01546     // Treat a conversion that strips "noreturn" as an identity conversion.
01547     SCS.Second = ICK_NoReturn_Adjustment;
01548   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
01549                                              InOverloadResolution,
01550                                              SCS, CStyle)) {
01551     SCS.Second = ICK_TransparentUnionConversion;
01552     FromType = ToType;
01553   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
01554                                  CStyle)) {
01555     // tryAtomicConversion has updated the standard conversion sequence
01556     // appropriately.
01557     return true;
01558   } else {
01559     // No second conversion required.
01560     SCS.Second = ICK_Identity;
01561   }
01562   SCS.setToType(1, FromType);
01563 
01564   QualType CanonFrom;
01565   QualType CanonTo;
01566   // The third conversion can be a qualification conversion (C++ 4p1).
01567   bool ObjCLifetimeConversion;
01568   if (S.IsQualificationConversion(FromType, ToType, CStyle, 
01569                                   ObjCLifetimeConversion)) {
01570     SCS.Third = ICK_Qualification;
01571     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
01572     FromType = ToType;
01573     CanonFrom = S.Context.getCanonicalType(FromType);
01574     CanonTo = S.Context.getCanonicalType(ToType);
01575   } else {
01576     // No conversion required
01577     SCS.Third = ICK_Identity;
01578 
01579     // C++ [over.best.ics]p6:
01580     //   [...] Any difference in top-level cv-qualification is
01581     //   subsumed by the initialization itself and does not constitute
01582     //   a conversion. [...]
01583     CanonFrom = S.Context.getCanonicalType(FromType);
01584     CanonTo = S.Context.getCanonicalType(ToType);
01585     if (CanonFrom.getLocalUnqualifiedType()
01586                                        == CanonTo.getLocalUnqualifiedType() &&
01587         (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
01588          || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
01589          || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
01590       FromType = ToType;
01591       CanonFrom = CanonTo;
01592     }
01593   }
01594   SCS.setToType(2, FromType);
01595 
01596   // If we have not converted the argument type to the parameter type,
01597   // this is a bad conversion sequence.
01598   if (CanonFrom != CanonTo)
01599     return false;
01600 
01601   return true;
01602 }
01603   
01604 static bool
01605 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 
01606                                      QualType &ToType,
01607                                      bool InOverloadResolution,
01608                                      StandardConversionSequence &SCS,
01609                                      bool CStyle) {
01610     
01611   const RecordType *UT = ToType->getAsUnionType();
01612   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
01613     return false;
01614   // The field to initialize within the transparent union.
01615   RecordDecl *UD = UT->getDecl();
01616   // It's compatible if the expression matches any of the fields.
01617   for (RecordDecl::field_iterator it = UD->field_begin(),
01618        itend = UD->field_end();
01619        it != itend; ++it) {
01620     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
01621                              CStyle, /*ObjCWritebackConversion=*/false)) {
01622       ToType = it->getType();
01623       return true;
01624     }
01625   }
01626   return false;
01627 }
01628 
01629 /// IsIntegralPromotion - Determines whether the conversion from the
01630 /// expression From (whose potentially-adjusted type is FromType) to
01631 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
01632 /// sets PromotedType to the promoted type.
01633 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
01634   const BuiltinType *To = ToType->getAs<BuiltinType>();
01635   // All integers are built-in.
01636   if (!To) {
01637     return false;
01638   }
01639 
01640   // An rvalue of type char, signed char, unsigned char, short int, or
01641   // unsigned short int can be converted to an rvalue of type int if
01642   // int can represent all the values of the source type; otherwise,
01643   // the source rvalue can be converted to an rvalue of type unsigned
01644   // int (C++ 4.5p1).
01645   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
01646       !FromType->isEnumeralType()) {
01647     if (// We can promote any signed, promotable integer type to an int
01648         (FromType->isSignedIntegerType() ||
01649          // We can promote any unsigned integer type whose size is
01650          // less than int to an int.
01651          (!FromType->isSignedIntegerType() &&
01652           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
01653       return To->getKind() == BuiltinType::Int;
01654     }
01655 
01656     return To->getKind() == BuiltinType::UInt;
01657   }
01658 
01659   // C++0x [conv.prom]p3:
01660   //   A prvalue of an unscoped enumeration type whose underlying type is not
01661   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
01662   //   following types that can represent all the values of the enumeration
01663   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
01664   //   unsigned int, long int, unsigned long int, long long int, or unsigned
01665   //   long long int. If none of the types in that list can represent all the
01666   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
01667   //   type can be converted to an rvalue a prvalue of the extended integer type
01668   //   with lowest integer conversion rank (4.13) greater than the rank of long
01669   //   long in which all the values of the enumeration can be represented. If
01670   //   there are two such extended types, the signed one is chosen.
01671   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
01672     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
01673     // provided for a scoped enumeration.
01674     if (FromEnumType->getDecl()->isScoped())
01675       return false;
01676 
01677     // We have already pre-calculated the promotion type, so this is trivial.
01678     if (ToType->isIntegerType() &&
01679         !RequireCompleteType(From->getLocStart(), FromType, 0))
01680       return Context.hasSameUnqualifiedType(ToType,
01681                                 FromEnumType->getDecl()->getPromotionType());
01682   }
01683 
01684   // C++0x [conv.prom]p2:
01685   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
01686   //   to an rvalue a prvalue of the first of the following types that can
01687   //   represent all the values of its underlying type: int, unsigned int,
01688   //   long int, unsigned long int, long long int, or unsigned long long int.
01689   //   If none of the types in that list can represent all the values of its
01690   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
01691   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
01692   //   type.
01693   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
01694       ToType->isIntegerType()) {
01695     // Determine whether the type we're converting from is signed or
01696     // unsigned.
01697     bool FromIsSigned = FromType->isSignedIntegerType();
01698     uint64_t FromSize = Context.getTypeSize(FromType);
01699 
01700     // The types we'll try to promote to, in the appropriate
01701     // order. Try each of these types.
01702     QualType PromoteTypes[6] = {
01703       Context.IntTy, Context.UnsignedIntTy,
01704       Context.LongTy, Context.UnsignedLongTy ,
01705       Context.LongLongTy, Context.UnsignedLongLongTy
01706     };
01707     for (int Idx = 0; Idx < 6; ++Idx) {
01708       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
01709       if (FromSize < ToSize ||
01710           (FromSize == ToSize &&
01711            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
01712         // We found the type that we can promote to. If this is the
01713         // type we wanted, we have a promotion. Otherwise, no
01714         // promotion.
01715         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
01716       }
01717     }
01718   }
01719 
01720   // An rvalue for an integral bit-field (9.6) can be converted to an
01721   // rvalue of type int if int can represent all the values of the
01722   // bit-field; otherwise, it can be converted to unsigned int if
01723   // unsigned int can represent all the values of the bit-field. If
01724   // the bit-field is larger yet, no integral promotion applies to
01725   // it. If the bit-field has an enumerated type, it is treated as any
01726   // other value of that type for promotion purposes (C++ 4.5p3).
01727   // FIXME: We should delay checking of bit-fields until we actually perform the
01728   // conversion.
01729   using llvm::APSInt;
01730   if (From)
01731     if (FieldDecl *MemberDecl = From->getBitField()) {
01732       APSInt BitWidth;
01733       if (FromType->isIntegralType(Context) &&
01734           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
01735         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
01736         ToSize = Context.getTypeSize(ToType);
01737 
01738         // Are we promoting to an int from a bitfield that fits in an int?
01739         if (BitWidth < ToSize ||
01740             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
01741           return To->getKind() == BuiltinType::Int;
01742         }
01743 
01744         // Are we promoting to an unsigned int from an unsigned bitfield
01745         // that fits into an unsigned int?
01746         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
01747           return To->getKind() == BuiltinType::UInt;
01748         }
01749 
01750         return false;
01751       }
01752     }
01753 
01754   // An rvalue of type bool can be converted to an rvalue of type int,
01755   // with false becoming zero and true becoming one (C++ 4.5p4).
01756   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
01757     return true;
01758   }
01759 
01760   return false;
01761 }
01762 
01763 /// IsFloatingPointPromotion - Determines whether the conversion from
01764 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
01765 /// returns true and sets PromotedType to the promoted type.
01766 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
01767   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
01768     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
01769       /// An rvalue of type float can be converted to an rvalue of type
01770       /// double. (C++ 4.6p1).
01771       if (FromBuiltin->getKind() == BuiltinType::Float &&
01772           ToBuiltin->getKind() == BuiltinType::Double)
01773         return true;
01774 
01775       // C99 6.3.1.5p1:
01776       //   When a float is promoted to double or long double, or a
01777       //   double is promoted to long double [...].
01778       if (!getLangOpts().CPlusPlus &&
01779           (FromBuiltin->getKind() == BuiltinType::Float ||
01780            FromBuiltin->getKind() == BuiltinType::Double) &&
01781           (ToBuiltin->getKind() == BuiltinType::LongDouble))
01782         return true;
01783 
01784       // Half can be promoted to float.
01785       if (FromBuiltin->getKind() == BuiltinType::Half &&
01786           ToBuiltin->getKind() == BuiltinType::Float)
01787         return true;
01788     }
01789 
01790   return false;
01791 }
01792 
01793 /// \brief Determine if a conversion is a complex promotion.
01794 ///
01795 /// A complex promotion is defined as a complex -> complex conversion
01796 /// where the conversion between the underlying real types is a
01797 /// floating-point or integral promotion.
01798 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
01799   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
01800   if (!FromComplex)
01801     return false;
01802 
01803   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
01804   if (!ToComplex)
01805     return false;
01806 
01807   return IsFloatingPointPromotion(FromComplex->getElementType(),
01808                                   ToComplex->getElementType()) ||
01809     IsIntegralPromotion(0, FromComplex->getElementType(),
01810                         ToComplex->getElementType());
01811 }
01812 
01813 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
01814 /// the pointer type FromPtr to a pointer to type ToPointee, with the
01815 /// same type qualifiers as FromPtr has on its pointee type. ToType,
01816 /// if non-empty, will be a pointer to ToType that may or may not have
01817 /// the right set of qualifiers on its pointee.
01818 ///
01819 static QualType
01820 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
01821                                    QualType ToPointee, QualType ToType,
01822                                    ASTContext &Context,
01823                                    bool StripObjCLifetime = false) {
01824   assert((FromPtr->getTypeClass() == Type::Pointer ||
01825           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
01826          "Invalid similarly-qualified pointer type");
01827 
01828   /// Conversions to 'id' subsume cv-qualifier conversions.
01829   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 
01830     return ToType.getUnqualifiedType();
01831 
01832   QualType CanonFromPointee
01833     = Context.getCanonicalType(FromPtr->getPointeeType());
01834   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
01835   Qualifiers Quals = CanonFromPointee.getQualifiers();
01836 
01837   if (StripObjCLifetime)
01838     Quals.removeObjCLifetime();
01839   
01840   // Exact qualifier match -> return the pointer type we're converting to.
01841   if (CanonToPointee.getLocalQualifiers() == Quals) {
01842     // ToType is exactly what we need. Return it.
01843     if (!ToType.isNull())
01844       return ToType.getUnqualifiedType();
01845 
01846     // Build a pointer to ToPointee. It has the right qualifiers
01847     // already.
01848     if (isa<ObjCObjectPointerType>(ToType))
01849       return Context.getObjCObjectPointerType(ToPointee);
01850     return Context.getPointerType(ToPointee);
01851   }
01852 
01853   // Just build a canonical type that has the right qualifiers.
01854   QualType QualifiedCanonToPointee
01855     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
01856 
01857   if (isa<ObjCObjectPointerType>(ToType))
01858     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
01859   return Context.getPointerType(QualifiedCanonToPointee);
01860 }
01861 
01862 static bool isNullPointerConstantForConversion(Expr *Expr,
01863                                                bool InOverloadResolution,
01864                                                ASTContext &Context) {
01865   // Handle value-dependent integral null pointer constants correctly.
01866   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
01867   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
01868       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
01869     return !InOverloadResolution;
01870 
01871   return Expr->isNullPointerConstant(Context,
01872                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
01873                                         : Expr::NPC_ValueDependentIsNull);
01874 }
01875 
01876 /// IsPointerConversion - Determines whether the conversion of the
01877 /// expression From, which has the (possibly adjusted) type FromType,
01878 /// can be converted to the type ToType via a pointer conversion (C++
01879 /// 4.10). If so, returns true and places the converted type (that
01880 /// might differ from ToType in its cv-qualifiers at some level) into
01881 /// ConvertedType.
01882 ///
01883 /// This routine also supports conversions to and from block pointers
01884 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
01885 /// pointers to interfaces. FIXME: Once we've determined the
01886 /// appropriate overloading rules for Objective-C, we may want to
01887 /// split the Objective-C checks into a different routine; however,
01888 /// GCC seems to consider all of these conversions to be pointer
01889 /// conversions, so for now they live here. IncompatibleObjC will be
01890 /// set if the conversion is an allowed Objective-C conversion that
01891 /// should result in a warning.
01892 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
01893                                bool InOverloadResolution,
01894                                QualType& ConvertedType,
01895                                bool &IncompatibleObjC) {
01896   IncompatibleObjC = false;
01897   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
01898                               IncompatibleObjC))
01899     return true;
01900 
01901   // Conversion from a null pointer constant to any Objective-C pointer type.
01902   if (ToType->isObjCObjectPointerType() &&
01903       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
01904     ConvertedType = ToType;
01905     return true;
01906   }
01907 
01908   // Blocks: Block pointers can be converted to void*.
01909   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
01910       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
01911     ConvertedType = ToType;
01912     return true;
01913   }
01914   // Blocks: A null pointer constant can be converted to a block
01915   // pointer type.
01916   if (ToType->isBlockPointerType() &&
01917       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
01918     ConvertedType = ToType;
01919     return true;
01920   }
01921 
01922   // If the left-hand-side is nullptr_t, the right side can be a null
01923   // pointer constant.
01924   if (ToType->isNullPtrType() &&
01925       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
01926     ConvertedType = ToType;
01927     return true;
01928   }
01929 
01930   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
01931   if (!ToTypePtr)
01932     return false;
01933 
01934   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
01935   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
01936     ConvertedType = ToType;
01937     return true;
01938   }
01939 
01940   // Beyond this point, both types need to be pointers
01941   // , including objective-c pointers.
01942   QualType ToPointeeType = ToTypePtr->getPointeeType();
01943   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
01944       !getLangOpts().ObjCAutoRefCount) {
01945     ConvertedType = BuildSimilarlyQualifiedPointerType(
01946                                       FromType->getAs<ObjCObjectPointerType>(),
01947                                                        ToPointeeType,
01948                                                        ToType, Context);
01949     return true;
01950   }
01951   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
01952   if (!FromTypePtr)
01953     return false;
01954 
01955   QualType FromPointeeType = FromTypePtr->getPointeeType();
01956 
01957   // If the unqualified pointee types are the same, this can't be a
01958   // pointer conversion, so don't do all of the work below.
01959   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
01960     return false;
01961 
01962   // An rvalue of type "pointer to cv T," where T is an object type,
01963   // can be converted to an rvalue of type "pointer to cv void" (C++
01964   // 4.10p2).
01965   if (FromPointeeType->isIncompleteOrObjectType() &&
01966       ToPointeeType->isVoidType()) {
01967     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
01968                                                        ToPointeeType,
01969                                                        ToType, Context,
01970                                                    /*StripObjCLifetime=*/true);
01971     return true;
01972   }
01973 
01974   // MSVC allows implicit function to void* type conversion.
01975   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
01976       ToPointeeType->isVoidType()) {
01977     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
01978                                                        ToPointeeType,
01979                                                        ToType, Context);
01980     return true;
01981   }
01982 
01983   // When we're overloading in C, we allow a special kind of pointer
01984   // conversion for compatible-but-not-identical pointee types.
01985   if (!getLangOpts().CPlusPlus &&
01986       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
01987     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
01988                                                        ToPointeeType,
01989                                                        ToType, Context);
01990     return true;
01991   }
01992 
01993   // C++ [conv.ptr]p3:
01994   //
01995   //   An rvalue of type "pointer to cv D," where D is a class type,
01996   //   can be converted to an rvalue of type "pointer to cv B," where
01997   //   B is a base class (clause 10) of D. If B is an inaccessible
01998   //   (clause 11) or ambiguous (10.2) base class of D, a program that
01999   //   necessitates this conversion is ill-formed. The result of the
02000   //   conversion is a pointer to the base class sub-object of the
02001   //   derived class object. The null pointer value is converted to
02002   //   the null pointer value of the destination type.
02003   //
02004   // Note that we do not check for ambiguity or inaccessibility
02005   // here. That is handled by CheckPointerConversion.
02006   if (getLangOpts().CPlusPlus &&
02007       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
02008       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
02009       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
02010       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
02011     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
02012                                                        ToPointeeType,
02013                                                        ToType, Context);
02014     return true;
02015   }
02016 
02017   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
02018       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
02019     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
02020                                                        ToPointeeType,
02021                                                        ToType, Context);
02022     return true;
02023   }
02024   
02025   return false;
02026 }
02027  
02028 /// \brief Adopt the given qualifiers for the given type.
02029 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
02030   Qualifiers TQs = T.getQualifiers();
02031   
02032   // Check whether qualifiers already match.
02033   if (TQs == Qs)
02034     return T;
02035   
02036   if (Qs.compatiblyIncludes(TQs))
02037     return Context.getQualifiedType(T, Qs);
02038   
02039   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
02040 }
02041 
02042 /// isObjCPointerConversion - Determines whether this is an
02043 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
02044 /// with the same arguments and return values.
02045 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
02046                                    QualType& ConvertedType,
02047                                    bool &IncompatibleObjC) {
02048   if (!getLangOpts().ObjC1)
02049     return false;
02050 
02051   // The set of qualifiers on the type we're converting from.
02052   Qualifiers FromQualifiers = FromType.getQualifiers();
02053   
02054   // First, we handle all conversions on ObjC object pointer types.
02055   const ObjCObjectPointerType* ToObjCPtr =
02056     ToType->getAs<ObjCObjectPointerType>();
02057   const ObjCObjectPointerType *FromObjCPtr =
02058     FromType->getAs<ObjCObjectPointerType>();
02059 
02060   if (ToObjCPtr && FromObjCPtr) {
02061     // If the pointee types are the same (ignoring qualifications),
02062     // then this is not a pointer conversion.
02063     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
02064                                        FromObjCPtr->getPointeeType()))
02065       return false;
02066 
02067     // Check for compatible 
02068     // Objective C++: We're able to convert between "id" or "Class" and a
02069     // pointer to any interface (in both directions).
02070     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
02071       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
02072       return true;
02073     }
02074     // Conversions with Objective-C's id<...>.
02075     if ((FromObjCPtr->isObjCQualifiedIdType() ||
02076          ToObjCPtr->isObjCQualifiedIdType()) &&
02077         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
02078                                                   /*compare=*/false)) {
02079       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
02080       return true;
02081     }
02082     // Objective C++: We're able to convert from a pointer to an
02083     // interface to a pointer to a different interface.
02084     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
02085       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
02086       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
02087       if (getLangOpts().CPlusPlus && LHS && RHS &&
02088           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
02089                                                 FromObjCPtr->getPointeeType()))
02090         return false;
02091       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
02092                                                    ToObjCPtr->getPointeeType(),
02093                                                          ToType, Context);
02094       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
02095       return true;
02096     }
02097 
02098     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
02099       // Okay: this is some kind of implicit downcast of Objective-C
02100       // interfaces, which is permitted. However, we're going to
02101       // complain about it.
02102       IncompatibleObjC = true;
02103       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
02104                                                    ToObjCPtr->getPointeeType(),
02105                                                          ToType, Context);
02106       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
02107       return true;
02108     }
02109   }
02110   // Beyond this point, both types need to be C pointers or block pointers.
02111   QualType ToPointeeType;
02112   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
02113     ToPointeeType = ToCPtr->getPointeeType();
02114   else if (const BlockPointerType *ToBlockPtr =
02115             ToType->getAs<BlockPointerType>()) {
02116     // Objective C++: We're able to convert from a pointer to any object
02117     // to a block pointer type.
02118     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
02119       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
02120       return true;
02121     }
02122     ToPointeeType = ToBlockPtr->getPointeeType();
02123   }
02124   else if (FromType->getAs<BlockPointerType>() &&
02125            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
02126     // Objective C++: We're able to convert from a block pointer type to a
02127     // pointer to any object.
02128     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
02129     return true;
02130   }
02131   else
02132     return false;
02133 
02134   QualType FromPointeeType;
02135   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
02136     FromPointeeType = FromCPtr->getPointeeType();
02137   else if (const BlockPointerType *FromBlockPtr =
02138            FromType->getAs<BlockPointerType>())
02139     FromPointeeType = FromBlockPtr->getPointeeType();
02140   else
02141     return false;
02142 
02143   // If we have pointers to pointers, recursively check whether this
02144   // is an Objective-C conversion.
02145   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
02146       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
02147                               IncompatibleObjC)) {
02148     // We always complain about this conversion.
02149     IncompatibleObjC = true;
02150     ConvertedType = Context.getPointerType(ConvertedType);
02151     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
02152     return true;
02153   }
02154   // Allow conversion of pointee being objective-c pointer to another one;
02155   // as in I* to id.
02156   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
02157       ToPointeeType->getAs<ObjCObjectPointerType>() &&
02158       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
02159                               IncompatibleObjC)) {
02160         
02161     ConvertedType = Context.getPointerType(ConvertedType);
02162     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
02163     return true;
02164   }
02165 
02166   // If we have pointers to functions or blocks, check whether the only
02167   // differences in the argument and result types are in Objective-C
02168   // pointer conversions. If so, we permit the conversion (but
02169   // complain about it).
02170   const FunctionProtoType *FromFunctionType
02171     = FromPointeeType->getAs<FunctionProtoType>();
02172   const FunctionProtoType *ToFunctionType
02173     = ToPointeeType->getAs<FunctionProtoType>();
02174   if (FromFunctionType && ToFunctionType) {
02175     // If the function types are exactly the same, this isn't an
02176     // Objective-C pointer conversion.
02177     if (Context.getCanonicalType(FromPointeeType)
02178           == Context.getCanonicalType(ToPointeeType))
02179       return false;
02180 
02181     // Perform the quick checks that will tell us whether these
02182     // function types are obviously different.
02183     if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
02184         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
02185         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
02186       return false;
02187 
02188     bool HasObjCConversion = false;
02189     if (Context.getCanonicalType(FromFunctionType->getResultType())
02190           == Context.getCanonicalType(ToFunctionType->getResultType())) {
02191       // Okay, the types match exactly. Nothing to do.
02192     } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
02193                                        ToFunctionType->getResultType(),
02194                                        ConvertedType, IncompatibleObjC)) {
02195       // Okay, we have an Objective-C pointer conversion.
02196       HasObjCConversion = true;
02197     } else {
02198       // Function types are too different. Abort.
02199       return false;
02200     }
02201 
02202     // Check argument types.
02203     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
02204          ArgIdx != NumArgs; ++ArgIdx) {
02205       QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
02206       QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
02207       if (Context.getCanonicalType(FromArgType)
02208             == Context.getCanonicalType(ToArgType)) {
02209         // Okay, the types match exactly. Nothing to do.
02210       } else if (isObjCPointerConversion(FromArgType, ToArgType,
02211                                          ConvertedType, IncompatibleObjC)) {
02212         // Okay, we have an Objective-C pointer conversion.
02213         HasObjCConversion = true;
02214       } else {
02215         // Argument types are too different. Abort.
02216         return false;
02217       }
02218     }
02219 
02220     if (HasObjCConversion) {
02221       // We had an Objective-C conversion. Allow this pointer
02222       // conversion, but complain about it.
02223       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
02224       IncompatibleObjC = true;
02225       return true;
02226     }
02227   }
02228 
02229   return false;
02230 }
02231 
02232 /// \brief Determine whether this is an Objective-C writeback conversion,
02233 /// used for parameter passing when performing automatic reference counting.
02234 ///
02235 /// \param FromType The type we're converting form.
02236 ///
02237 /// \param ToType The type we're converting to.
02238 ///
02239 /// \param ConvertedType The type that will be produced after applying
02240 /// this conversion.
02241 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
02242                                      QualType &ConvertedType) {
02243   if (!getLangOpts().ObjCAutoRefCount || 
02244       Context.hasSameUnqualifiedType(FromType, ToType))
02245     return false;
02246   
02247   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
02248   QualType ToPointee;
02249   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
02250     ToPointee = ToPointer->getPointeeType();
02251   else
02252     return false;
02253   
02254   Qualifiers ToQuals = ToPointee.getQualifiers();
02255   if (!ToPointee->isObjCLifetimeType() || 
02256       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
02257       !ToQuals.withoutObjCLifetime().empty())
02258     return false;
02259   
02260   // Argument must be a pointer to __strong to __weak.
02261   QualType FromPointee;
02262   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
02263     FromPointee = FromPointer->getPointeeType();
02264   else
02265     return false;
02266   
02267   Qualifiers FromQuals = FromPointee.getQualifiers();
02268   if (!FromPointee->isObjCLifetimeType() ||
02269       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
02270        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
02271     return false;
02272   
02273   // Make sure that we have compatible qualifiers.
02274   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
02275   if (!ToQuals.compatiblyIncludes(FromQuals))
02276     return false;
02277   
02278   // Remove qualifiers from the pointee type we're converting from; they
02279   // aren't used in the compatibility check belong, and we'll be adding back
02280   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
02281   FromPointee = FromPointee.getUnqualifiedType();
02282   
02283   // The unqualified form of the pointee types must be compatible.
02284   ToPointee = ToPointee.getUnqualifiedType();
02285   bool IncompatibleObjC;
02286   if (Context.typesAreCompatible(FromPointee, ToPointee))
02287     FromPointee = ToPointee;
02288   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
02289                                     IncompatibleObjC))
02290     return false;
02291   
02292   /// \brief Construct the type we're converting to, which is a pointer to
02293   /// __autoreleasing pointee.
02294   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
02295   ConvertedType = Context.getPointerType(FromPointee);
02296   return true;
02297 }
02298 
02299 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
02300                                     QualType& ConvertedType) {
02301   QualType ToPointeeType;
02302   if (const BlockPointerType *ToBlockPtr =
02303         ToType->getAs<BlockPointerType>())
02304     ToPointeeType = ToBlockPtr->getPointeeType();
02305   else
02306     return false;
02307   
02308   QualType FromPointeeType;
02309   if (const BlockPointerType *FromBlockPtr =
02310       FromType->getAs<BlockPointerType>())
02311     FromPointeeType = FromBlockPtr->getPointeeType();
02312   else
02313     return false;
02314   // We have pointer to blocks, check whether the only
02315   // differences in the argument and result types are in Objective-C
02316   // pointer conversions. If so, we permit the conversion.
02317   
02318   const FunctionProtoType *FromFunctionType
02319     = FromPointeeType->getAs<FunctionProtoType>();
02320   const FunctionProtoType *ToFunctionType
02321     = ToPointeeType->getAs<FunctionProtoType>();
02322   
02323   if (!FromFunctionType || !ToFunctionType)
02324     return false;
02325 
02326   if (Context.hasSameType(FromPointeeType, ToPointeeType))
02327     return true;
02328     
02329   // Perform the quick checks that will tell us whether these
02330   // function types are obviously different.
02331   if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
02332       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
02333     return false;
02334     
02335   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
02336   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
02337   if (FromEInfo != ToEInfo)
02338     return false;
02339 
02340   bool IncompatibleObjC = false;
02341   if (Context.hasSameType(FromFunctionType->getResultType(), 
02342                           ToFunctionType->getResultType())) {
02343     // Okay, the types match exactly. Nothing to do.
02344   } else {
02345     QualType RHS = FromFunctionType->getResultType();
02346     QualType LHS = ToFunctionType->getResultType();
02347     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
02348         !RHS.hasQualifiers() && LHS.hasQualifiers())
02349        LHS = LHS.getUnqualifiedType();
02350 
02351      if (Context.hasSameType(RHS,LHS)) {
02352        // OK exact match.
02353      } else if (isObjCPointerConversion(RHS, LHS,
02354                                         ConvertedType, IncompatibleObjC)) {
02355      if (IncompatibleObjC)
02356        return false;
02357      // Okay, we have an Objective-C pointer conversion.
02358      }
02359      else
02360        return false;
02361    }
02362     
02363    // Check argument types.
02364    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
02365         ArgIdx != NumArgs; ++ArgIdx) {
02366      IncompatibleObjC = false;
02367      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
02368      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
02369      if (Context.hasSameType(FromArgType, ToArgType)) {
02370        // Okay, the types match exactly. Nothing to do.
02371      } else if (isObjCPointerConversion(ToArgType, FromArgType,
02372                                         ConvertedType, IncompatibleObjC)) {
02373        if (IncompatibleObjC)
02374          return false;
02375        // Okay, we have an Objective-C pointer conversion.
02376      } else
02377        // Argument types are too different. Abort.
02378        return false;
02379    }
02380    if (LangOpts.ObjCAutoRefCount && 
02381        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 
02382                                                     ToFunctionType))
02383      return false;
02384    
02385    ConvertedType = ToType;
02386    return true;
02387 }
02388 
02389 enum {
02390   ft_default,
02391   ft_different_class,
02392   ft_parameter_arity,
02393   ft_parameter_mismatch,
02394   ft_return_type,
02395   ft_qualifer_mismatch
02396 };
02397 
02398 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
02399 /// function types.  Catches different number of parameter, mismatch in
02400 /// parameter types, and different return types.
02401 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
02402                                       QualType FromType, QualType ToType) {
02403   // If either type is not valid, include no extra info.
02404   if (FromType.isNull() || ToType.isNull()) {
02405     PDiag << ft_default;
02406     return;
02407   }
02408 
02409   // Get the function type from the pointers.
02410   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
02411     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
02412                             *ToMember = ToType->getAs<MemberPointerType>();
02413     if (FromMember->getClass() != ToMember->getClass()) {
02414       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
02415             << QualType(FromMember->getClass(), 0);
02416       return;
02417     }
02418     FromType = FromMember->getPointeeType();
02419     ToType = ToMember->getPointeeType();
02420   }
02421 
02422   if (FromType->isPointerType())
02423     FromType = FromType->getPointeeType();
02424   if (ToType->isPointerType())
02425     ToType = ToType->getPointeeType();
02426 
02427   // Remove references.
02428   FromType = FromType.getNonReferenceType();
02429   ToType = ToType.getNonReferenceType();
02430 
02431   // Don't print extra info for non-specialized template functions.
02432   if (FromType->isInstantiationDependentType() &&
02433       !FromType->getAs<TemplateSpecializationType>()) {
02434     PDiag << ft_default;
02435     return;
02436   }
02437 
02438   // No extra info for same types.
02439   if (Context.hasSameType(FromType, ToType)) {
02440     PDiag << ft_default;
02441     return;
02442   }
02443 
02444   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
02445                           *ToFunction = ToType->getAs<FunctionProtoType>();
02446 
02447   // Both types need to be function types.
02448   if (!FromFunction || !ToFunction) {
02449     PDiag << ft_default;
02450     return;
02451   }
02452 
02453   if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
02454     PDiag << ft_parameter_arity << ToFunction->getNumArgs()
02455           << FromFunction->getNumArgs();
02456     return;
02457   }
02458 
02459   // Handle different parameter types.
02460   unsigned ArgPos;
02461   if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
02462     PDiag << ft_parameter_mismatch << ArgPos + 1
02463           << ToFunction->getArgType(ArgPos)
02464           << FromFunction->getArgType(ArgPos);
02465     return;
02466   }
02467 
02468   // Handle different return type.
02469   if (!Context.hasSameType(FromFunction->getResultType(),
02470                            ToFunction->getResultType())) {
02471     PDiag << ft_return_type << ToFunction->getResultType()
02472           << FromFunction->getResultType();
02473     return;
02474   }
02475 
02476   unsigned FromQuals = FromFunction->getTypeQuals(),
02477            ToQuals = ToFunction->getTypeQuals();
02478   if (FromQuals != ToQuals) {
02479     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
02480     return;
02481   }
02482 
02483   // Unable to find a difference, so add no extra info.
02484   PDiag << ft_default;
02485 }
02486 
02487 /// FunctionArgTypesAreEqual - This routine checks two function proto types
02488 /// for equality of their argument types. Caller has already checked that
02489 /// they have same number of arguments. This routine assumes that Objective-C
02490 /// pointer types which only differ in their protocol qualifiers are equal.
02491 /// If the parameters are different, ArgPos will have the the parameter index
02492 /// of the first different parameter.
02493 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
02494                                     const FunctionProtoType *NewType,
02495                                     unsigned *ArgPos) {
02496   if (!getLangOpts().ObjC1) {
02497     for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
02498          N = NewType->arg_type_begin(),
02499          E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
02500       if (!Context.hasSameType(*O, *N)) {
02501         if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
02502         return false;
02503       }
02504     }
02505     return true;
02506   }
02507 
02508   for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
02509        N = NewType->arg_type_begin(),
02510        E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
02511     QualType ToType = (*O);
02512     QualType FromType = (*N);
02513     if (!Context.hasSameType(ToType, FromType)) {
02514       if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
02515         if (const PointerType *PTFr = FromType->getAs<PointerType>())
02516           if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
02517                PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
02518               (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
02519                PTFr->getPointeeType()->isObjCQualifiedClassType()))
02520             continue;
02521       }
02522       else if (const ObjCObjectPointerType *PTTo =
02523                  ToType->getAs<ObjCObjectPointerType>()) {
02524         if (const ObjCObjectPointerType *PTFr =
02525               FromType->getAs<ObjCObjectPointerType>())
02526           if (Context.hasSameUnqualifiedType(
02527                 PTTo->getObjectType()->getBaseType(),
02528                 PTFr->getObjectType()->getBaseType()))
02529             continue;
02530       }
02531       if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
02532       return false;
02533     }
02534   }
02535   return true;
02536 }
02537 
02538 /// CheckPointerConversion - Check the pointer conversion from the
02539 /// expression From to the type ToType. This routine checks for
02540 /// ambiguous or inaccessible derived-to-base pointer
02541 /// conversions for which IsPointerConversion has already returned
02542 /// true. It returns true and produces a diagnostic if there was an
02543 /// error, or returns false otherwise.
02544 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
02545                                   CastKind &Kind,
02546                                   CXXCastPath& BasePath,
02547                                   bool IgnoreBaseAccess) {
02548   QualType FromType = From->getType();
02549   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
02550 
02551   Kind = CK_BitCast;
02552 
02553   if (!IsCStyleOrFunctionalCast &&
02554       Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
02555       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
02556     DiagRuntimeBehavior(From->getExprLoc(), From,
02557                         PDiag(diag::warn_impcast_bool_to_null_pointer)
02558                           << ToType << From->getSourceRange());
02559 
02560   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
02561     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
02562       QualType FromPointeeType = FromPtrType->getPointeeType(),
02563                ToPointeeType   = ToPtrType->getPointeeType();
02564 
02565       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
02566           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
02567         // We must have a derived-to-base conversion. Check an
02568         // ambiguous or inaccessible conversion.
02569         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
02570                                          From->getExprLoc(),
02571                                          From->getSourceRange(), &BasePath,
02572                                          IgnoreBaseAccess))
02573           return true;
02574 
02575         // The conversion was successful.
02576         Kind = CK_DerivedToBase;
02577       }
02578     }
02579   } else if (const ObjCObjectPointerType *ToPtrType =
02580                ToType->getAs<ObjCObjectPointerType>()) {
02581     if (const ObjCObjectPointerType *FromPtrType =
02582           FromType->getAs<ObjCObjectPointerType>()) {
02583       // Objective-C++ conversions are always okay.
02584       // FIXME: We should have a different class of conversions for the
02585       // Objective-C++ implicit conversions.
02586       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
02587         return false;
02588     } else if (FromType->isBlockPointerType()) {
02589       Kind = CK_BlockPointerToObjCPointerCast;
02590     } else {
02591       Kind = CK_CPointerToObjCPointerCast;
02592     }
02593   } else if (ToType->isBlockPointerType()) {
02594     if (!FromType->isBlockPointerType())
02595       Kind = CK_AnyPointerToBlockPointerCast;
02596   }
02597 
02598   // We shouldn't fall into this case unless it's valid for other
02599   // reasons.
02600   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
02601     Kind = CK_NullToPointer;
02602 
02603   return false;
02604 }
02605 
02606 /// IsMemberPointerConversion - Determines whether the conversion of the
02607 /// expression From, which has the (possibly adjusted) type FromType, can be
02608 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
02609 /// If so, returns true and places the converted type (that might differ from
02610 /// ToType in its cv-qualifiers at some level) into ConvertedType.
02611 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
02612                                      QualType ToType,
02613                                      bool InOverloadResolution,
02614                                      QualType &ConvertedType) {
02615   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
02616   if (!ToTypePtr)
02617     return false;
02618 
02619   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
02620   if (From->isNullPointerConstant(Context,
02621                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
02622                                         : Expr::NPC_ValueDependentIsNull)) {
02623     ConvertedType = ToType;
02624     return true;
02625   }
02626 
02627   // Otherwise, both types have to be member pointers.
02628   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
02629   if (!FromTypePtr)
02630     return false;
02631 
02632   // A pointer to member of B can be converted to a pointer to member of D,
02633   // where D is derived from B (C++ 4.11p2).
02634   QualType FromClass(FromTypePtr->getClass(), 0);
02635   QualType ToClass(ToTypePtr->getClass(), 0);
02636 
02637   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
02638       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
02639       IsDerivedFrom(ToClass, FromClass)) {
02640     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
02641                                                  ToClass.getTypePtr());
02642     return true;
02643   }
02644 
02645   return false;
02646 }
02647 
02648 /// CheckMemberPointerConversion - Check the member pointer conversion from the
02649 /// expression From to the type ToType. This routine checks for ambiguous or
02650 /// virtual or inaccessible base-to-derived member pointer conversions
02651 /// for which IsMemberPointerConversion has already returned true. It returns
02652 /// true and produces a diagnostic if there was an error, or returns false
02653 /// otherwise.
02654 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
02655                                         CastKind &Kind,
02656                                         CXXCastPath &BasePath,
02657                                         bool IgnoreBaseAccess) {
02658   QualType FromType = From->getType();
02659   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
02660   if (!FromPtrType) {
02661     // This must be a null pointer to member pointer conversion
02662     assert(From->isNullPointerConstant(Context,
02663                                        Expr::NPC_ValueDependentIsNull) &&
02664            "Expr must be null pointer constant!");
02665     Kind = CK_NullToMemberPointer;
02666     return false;
02667   }
02668 
02669   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
02670   assert(ToPtrType && "No member pointer cast has a target type "
02671                       "that is not a member pointer.");
02672 
02673   QualType FromClass = QualType(FromPtrType->getClass(), 0);
02674   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
02675 
02676   // FIXME: What about dependent types?
02677   assert(FromClass->isRecordType() && "Pointer into non-class.");
02678   assert(ToClass->isRecordType() && "Pointer into non-class.");
02679 
02680   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
02681                      /*DetectVirtual=*/true);
02682   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
02683   assert(DerivationOkay &&
02684          "Should not have been called if derivation isn't OK.");
02685   (void)DerivationOkay;
02686 
02687   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
02688                                   getUnqualifiedType())) {
02689     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
02690     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
02691       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
02692     return true;
02693   }
02694 
02695   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
02696     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
02697       << FromClass << ToClass << QualType(VBase, 0)
02698       << From->getSourceRange();
02699     return true;
02700   }
02701 
02702   if (!IgnoreBaseAccess)
02703     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
02704                          Paths.front(),
02705                          diag::err_downcast_from_inaccessible_base);
02706 
02707   // Must be a base to derived member conversion.
02708   BuildBasePathArray(Paths, BasePath);
02709   Kind = CK_BaseToDerivedMemberPointer;
02710   return false;
02711 }
02712 
02713 /// IsQualificationConversion - Determines whether the conversion from
02714 /// an rvalue of type FromType to ToType is a qualification conversion
02715 /// (C++ 4.4).
02716 ///
02717 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
02718 /// when the qualification conversion involves a change in the Objective-C
02719 /// object lifetime.
02720 bool
02721 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
02722                                 bool CStyle, bool &ObjCLifetimeConversion) {
02723   FromType = Context.getCanonicalType(FromType);
02724   ToType = Context.getCanonicalType(ToType);
02725   ObjCLifetimeConversion = false;
02726   
02727   // If FromType and ToType are the same type, this is not a
02728   // qualification conversion.
02729   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
02730     return false;
02731 
02732   // (C++ 4.4p4):
02733   //   A conversion can add cv-qualifiers at levels other than the first
02734   //   in multi-level pointers, subject to the following rules: [...]
02735   bool PreviousToQualsIncludeConst = true;
02736   bool UnwrappedAnyPointer = false;
02737   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
02738     // Within each iteration of the loop, we check the qualifiers to
02739     // determine if this still looks like a qualification
02740     // conversion. Then, if all is well, we unwrap one more level of
02741     // pointers or pointers-to-members and do it all again
02742     // until there are no more pointers or pointers-to-members left to
02743     // unwrap.
02744     UnwrappedAnyPointer = true;
02745 
02746     Qualifiers FromQuals = FromType.getQualifiers();
02747     Qualifiers ToQuals = ToType.getQualifiers();
02748     
02749     // Objective-C ARC:
02750     //   Check Objective-C lifetime conversions.
02751     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
02752         UnwrappedAnyPointer) {
02753       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
02754         ObjCLifetimeConversion = true;
02755         FromQuals.removeObjCLifetime();
02756         ToQuals.removeObjCLifetime();
02757       } else {
02758         // Qualification conversions cannot cast between different
02759         // Objective-C lifetime qualifiers.
02760         return false;
02761       }
02762     }
02763     
02764     // Allow addition/removal of GC attributes but not changing GC attributes.
02765     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
02766         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
02767       FromQuals.removeObjCGCAttr();
02768       ToQuals.removeObjCGCAttr();
02769     }
02770     
02771     //   -- for every j > 0, if const is in cv 1,j then const is in cv
02772     //      2,j, and similarly for volatile.
02773     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
02774       return false;
02775 
02776     //   -- if the cv 1,j and cv 2,j are different, then const is in
02777     //      every cv for 0 < k < j.
02778     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
02779         && !PreviousToQualsIncludeConst)
02780       return false;
02781 
02782     // Keep track of whether all prior cv-qualifiers in the "to" type
02783     // include const.
02784     PreviousToQualsIncludeConst
02785       = PreviousToQualsIncludeConst && ToQuals.hasConst();
02786   }
02787 
02788   // We are left with FromType and ToType being the pointee types
02789   // after unwrapping the original FromType and ToType the same number
02790   // of types. If we unwrapped any pointers, and if FromType and
02791   // ToType have the same unqualified type (since we checked
02792   // qualifiers above), then this is a qualification conversion.
02793   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
02794 }
02795 
02796 /// \brief - Determine whether this is a conversion from a scalar type to an
02797 /// atomic type.
02798 ///
02799 /// If successful, updates \c SCS's second and third steps in the conversion
02800 /// sequence to finish the conversion.
02801 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
02802                                 bool InOverloadResolution,
02803                                 StandardConversionSequence &SCS,
02804                                 bool CStyle) {
02805   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
02806   if (!ToAtomic)
02807     return false;
02808   
02809   StandardConversionSequence InnerSCS;
02810   if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 
02811                             InOverloadResolution, InnerSCS,
02812                             CStyle, /*AllowObjCWritebackConversion=*/false))
02813     return false;
02814   
02815   SCS.Second = InnerSCS.Second;
02816   SCS.setToType(1, InnerSCS.getToType(1));
02817   SCS.Third = InnerSCS.Third;
02818   SCS.QualificationIncludesObjCLifetime
02819     = InnerSCS.QualificationIncludesObjCLifetime;
02820   SCS.setToType(2, InnerSCS.getToType(2));
02821   return true;
02822 }
02823 
02824 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
02825                                               CXXConstructorDecl *Constructor,
02826                                               QualType Type) {
02827   const FunctionProtoType *CtorType =
02828       Constructor->getType()->getAs<FunctionProtoType>();
02829   if (CtorType->getNumArgs() > 0) {
02830     QualType FirstArg = CtorType->getArgType(0);
02831     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
02832       return true;
02833   }
02834   return false;
02835 }
02836 
02837 static OverloadingResult
02838 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
02839                                        CXXRecordDecl *To,
02840                                        UserDefinedConversionSequence &User,
02841                                        OverloadCandidateSet &CandidateSet,
02842                                        bool AllowExplicit) {
02843   DeclContext::lookup_iterator Con, ConEnd;
02844   for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
02845        Con != ConEnd; ++Con) {
02846     NamedDecl *D = *Con;
02847     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
02848 
02849     // Find the constructor (which may be a template).
02850     CXXConstructorDecl *Constructor = 0;
02851     FunctionTemplateDecl *ConstructorTmpl
02852       = dyn_cast<FunctionTemplateDecl>(D);
02853     if (ConstructorTmpl)
02854       Constructor
02855         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
02856     else
02857       Constructor = cast<CXXConstructorDecl>(D);
02858 
02859     bool Usable = !Constructor->isInvalidDecl() &&
02860                   S.isInitListConstructor(Constructor) &&
02861                   (AllowExplicit || !Constructor->isExplicit());
02862     if (Usable) {
02863       // If the first argument is (a reference to) the target type,
02864       // suppress conversions.
02865       bool SuppressUserConversions =
02866           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
02867       if (ConstructorTmpl)
02868         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
02869                                        /*ExplicitArgs*/ 0,
02870                                        From, CandidateSet,
02871                                        SuppressUserConversions);
02872       else
02873         S.AddOverloadCandidate(Constructor, FoundDecl,
02874                                From, CandidateSet,
02875                                SuppressUserConversions);
02876     }
02877   }
02878 
02879   bool HadMultipleCandidates = (CandidateSet.size() > 1);
02880 
02881   OverloadCandidateSet::iterator Best;
02882   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
02883   case OR_Success: {
02884     // Record the standard conversion we used and the conversion function.
02885     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
02886     S.MarkFunctionReferenced(From->getLocStart(), Constructor);
02887 
02888     QualType ThisType = Constructor->getThisType(S.Context);
02889     // Initializer lists don't have conversions as such.
02890     User.Before.setAsIdentityConversion();
02891     User.HadMultipleCandidates = HadMultipleCandidates;
02892     User.ConversionFunction = Constructor;
02893     User.FoundConversionFunction = Best->FoundDecl;
02894     User.After.setAsIdentityConversion();
02895     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
02896     User.After.setAllToTypes(ToType);
02897     return OR_Success;
02898   }
02899 
02900   case OR_No_Viable_Function:
02901     return OR_No_Viable_Function;
02902   case OR_Deleted:
02903     return OR_Deleted;
02904   case OR_Ambiguous:
02905     return OR_Ambiguous;
02906   }
02907 
02908   llvm_unreachable("Invalid OverloadResult!");
02909 }
02910 
02911 /// Determines whether there is a user-defined conversion sequence
02912 /// (C++ [over.ics.user]) that converts expression From to the type
02913 /// ToType. If such a conversion exists, User will contain the
02914 /// user-defined conversion sequence that performs such a conversion
02915 /// and this routine will return true. Otherwise, this routine returns
02916 /// false and User is unspecified.
02917 ///
02918 /// \param AllowExplicit  true if the conversion should consider C++0x
02919 /// "explicit" conversion functions as well as non-explicit conversion
02920 /// functions (C++0x [class.conv.fct]p2).
02921 static OverloadingResult
02922 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
02923                         UserDefinedConversionSequence &User,
02924                         OverloadCandidateSet &CandidateSet,
02925                         bool AllowExplicit) {
02926   // Whether we will only visit constructors.
02927   bool ConstructorsOnly = false;
02928 
02929   // If the type we are conversion to is a class type, enumerate its
02930   // constructors.
02931   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
02932     // C++ [over.match.ctor]p1:
02933     //   When objects of class type are direct-initialized (8.5), or
02934     //   copy-initialized from an expression of the same or a
02935     //   derived class type (8.5), overload resolution selects the
02936     //   constructor. [...] For copy-initialization, the candidate
02937     //   functions are all the converting constructors (12.3.1) of
02938     //   that class. The argument list is the expression-list within
02939     //   the parentheses of the initializer.
02940     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
02941         (From->getType()->getAs<RecordType>() &&
02942          S.IsDerivedFrom(From->getType(), ToType)))
02943       ConstructorsOnly = true;
02944 
02945     S.RequireCompleteType(From->getLocStart(), ToType, 0);
02946     // RequireCompleteType may have returned true due to some invalid decl
02947     // during template instantiation, but ToType may be complete enough now
02948     // to try to recover.
02949     if (ToType->isIncompleteType()) {
02950       // We're not going to find any constructors.
02951     } else if (CXXRecordDecl *ToRecordDecl
02952                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
02953 
02954       Expr **Args = &From;
02955       unsigned NumArgs = 1;
02956       bool ListInitializing = false;
02957       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
02958         // But first, see if there is an init-list-contructor that will work.
02959         OverloadingResult Result = IsInitializerListConstructorConversion(
02960             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
02961         if (Result != OR_No_Viable_Function)
02962           return Result;
02963         // Never mind.
02964         CandidateSet.clear();
02965 
02966         // If we're list-initializing, we pass the individual elements as
02967         // arguments, not the entire list.
02968         Args = InitList->getInits();
02969         NumArgs = InitList->getNumInits();
02970         ListInitializing = true;
02971       }
02972 
02973       DeclContext::lookup_iterator Con, ConEnd;
02974       for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
02975            Con != ConEnd; ++Con) {
02976         NamedDecl *D = *Con;
02977         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
02978 
02979         // Find the constructor (which may be a template).
02980         CXXConstructorDecl *Constructor = 0;
02981         FunctionTemplateDecl *ConstructorTmpl
02982           = dyn_cast<FunctionTemplateDecl>(D);
02983         if (ConstructorTmpl)
02984           Constructor
02985             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
02986         else
02987           Constructor = cast<CXXConstructorDecl>(D);
02988 
02989         bool Usable = !Constructor->isInvalidDecl();
02990         if (ListInitializing)
02991           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
02992         else
02993           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
02994         if (Usable) {
02995           bool SuppressUserConversions = !ConstructorsOnly;
02996           if (SuppressUserConversions && ListInitializing) {
02997             SuppressUserConversions = false;
02998             if (NumArgs == 1) {
02999               // If the first argument is (a reference to) the target type,
03000               // suppress conversions.
03001               SuppressUserConversions = isFirstArgumentCompatibleWithType(
03002                                                 S.Context, Constructor, ToType);
03003             }
03004           }
03005           if (ConstructorTmpl)
03006             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
03007                                            /*ExplicitArgs*/ 0,
03008                                            llvm::makeArrayRef(Args, NumArgs),
03009                                            CandidateSet, SuppressUserConversions);
03010           else
03011             // Allow one user-defined conversion when user specifies a
03012             // From->ToType conversion via an static cast (c-style, etc).
03013             S.AddOverloadCandidate(Constructor, FoundDecl,
03014                                    llvm::makeArrayRef(Args, NumArgs),
03015                                    CandidateSet, SuppressUserConversions);
03016         }
03017       }
03018     }
03019   }
03020 
03021   // Enumerate conversion functions, if we're allowed to.
03022   if (ConstructorsOnly || isa<InitListExpr>(From)) {
03023   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
03024     // No conversion functions from incomplete types.
03025   } else if (const RecordType *FromRecordType
03026                                    = From->getType()->getAs<RecordType>()) {
03027     if (CXXRecordDecl *FromRecordDecl
03028          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
03029       // Add all of the conversion functions as candidates.
03030       const UnresolvedSetImpl *Conversions
03031         = FromRecordDecl->getVisibleConversionFunctions();
03032       for (UnresolvedSetImpl::iterator I = Conversions->begin(),
03033              E = Conversions->end(); I != E; ++I) {
03034         DeclAccessPair FoundDecl = I.getPair();
03035         NamedDecl *D = FoundDecl.getDecl();
03036         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
03037         if (isa<UsingShadowDecl>(D))
03038           D = cast<UsingShadowDecl>(D)->getTargetDecl();
03039 
03040         CXXConversionDecl *Conv;
03041         FunctionTemplateDecl *ConvTemplate;
03042         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
03043           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
03044         else
03045           Conv = cast<CXXConversionDecl>(D);
03046 
03047         if (AllowExplicit || !Conv->isExplicit()) {
03048           if (ConvTemplate)
03049             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
03050                                              ActingContext, From, ToType,
03051                                              CandidateSet);
03052           else
03053             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
03054                                      From, ToType, CandidateSet);
03055         }
03056       }
03057     }
03058   }
03059 
03060   bool HadMultipleCandidates = (CandidateSet.size() > 1);
03061 
03062   OverloadCandidateSet::iterator Best;
03063   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
03064   case OR_Success:
03065     // Record the standard conversion we used and the conversion function.
03066     if (CXXConstructorDecl *Constructor
03067           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
03068       S.MarkFunctionReferenced(From->getLocStart(), Constructor);
03069 
03070       // C++ [over.ics.user]p1:
03071       //   If the user-defined conversion is specified by a
03072       //   constructor (12.3.1), the initial standard conversion
03073       //   sequence converts the source type to the type required by
03074       //   the argument of the constructor.
03075       //
03076       QualType ThisType = Constructor->getThisType(S.Context);
03077       if (isa<InitListExpr>(From)) {
03078         // Initializer lists don't have conversions as such.
03079         User.Before.setAsIdentityConversion();
03080       } else {
03081         if (Best->Conversions[0].isEllipsis())
03082           User.EllipsisConversion = true;
03083         else {
03084           User.Before = Best->Conversions[0].Standard;
03085           User.EllipsisConversion = false;
03086         }
03087       }
03088       User.HadMultipleCandidates = HadMultipleCandidates;
03089       User.ConversionFunction = Constructor;
03090       User.FoundConversionFunction = Best->FoundDecl;
03091       User.After.setAsIdentityConversion();
03092       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
03093       User.After.setAllToTypes(ToType);
03094       return OR_Success;
03095     }
03096     if (CXXConversionDecl *Conversion
03097                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
03098       S.MarkFunctionReferenced(From->getLocStart(), Conversion);
03099 
03100       // C++ [over.ics.user]p1:
03101       //
03102       //   [...] If the user-defined conversion is specified by a
03103       //   conversion function (12.3.2), the initial standard
03104       //   conversion sequence converts the source type to the
03105       //   implicit object parameter of the conversion function.
03106       User.Before = Best->Conversions[0].Standard;
03107       User.HadMultipleCandidates = HadMultipleCandidates;
03108       User.ConversionFunction = Conversion;
03109       User.FoundConversionFunction = Best->FoundDecl;
03110       User.EllipsisConversion = false;
03111 
03112       // C++ [over.ics.user]p2:
03113       //   The second standard conversion sequence converts the
03114       //   result of the user-defined conversion to the target type
03115       //   for the sequence. Since an implicit conversion sequence
03116       //   is an initialization, the special rules for
03117       //   initialization by user-defined conversion apply when
03118       //   selecting the best user-defined conversion for a
03119       //   user-defined conversion sequence (see 13.3.3 and
03120       //   13.3.3.1).
03121       User.After = Best->FinalConversion;
03122       return OR_Success;
03123     }
03124     llvm_unreachable("Not a constructor or conversion function?");
03125 
03126   case OR_No_Viable_Function:
03127     return OR_No_Viable_Function;
03128   case OR_Deleted:
03129     // No conversion here! We're done.
03130     return OR_Deleted;
03131 
03132   case OR_Ambiguous:
03133     return OR_Ambiguous;
03134   }
03135 
03136   llvm_unreachable("Invalid OverloadResult!");
03137 }
03138 
03139 bool
03140 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
03141   ImplicitConversionSequence ICS;
03142   OverloadCandidateSet CandidateSet(From->getExprLoc());
03143   OverloadingResult OvResult =
03144     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
03145                             CandidateSet, false);
03146   if (OvResult == OR_Ambiguous)
03147     Diag(From->getLocStart(),
03148          diag::err_typecheck_ambiguous_condition)
03149           << From->getType() << ToType << From->getSourceRange();
03150   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
03151     Diag(From->getLocStart(),
03152          diag::err_typecheck_nonviable_condition)
03153     << From->getType() << ToType << From->getSourceRange();
03154   else
03155     return false;
03156   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
03157   return true;
03158 }
03159 
03160 /// \brief Compare the user-defined conversion functions or constructors
03161 /// of two user-defined conversion sequences to determine whether any ordering
03162 /// is possible.
03163 static ImplicitConversionSequence::CompareKind
03164 compareConversionFunctions(Sema &S,
03165                            FunctionDecl *Function1,
03166                            FunctionDecl *Function2) {
03167   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
03168     return ImplicitConversionSequence::Indistinguishable;
03169   
03170   // Objective-C++:
03171   //   If both conversion functions are implicitly-declared conversions from
03172   //   a lambda closure type to a function pointer and a block pointer, 
03173   //   respectively, always prefer the conversion to a function pointer,
03174   //   because the function pointer is more lightweight and is more likely
03175   //   to keep code working.
03176   CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
03177   if (!Conv1)
03178     return ImplicitConversionSequence::Indistinguishable;
03179     
03180   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
03181   if (!Conv2)
03182     return ImplicitConversionSequence::Indistinguishable;
03183   
03184   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
03185     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
03186     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
03187     if (Block1 != Block2)
03188       return Block1? ImplicitConversionSequence::Worse 
03189                    : ImplicitConversionSequence::Better;
03190   }
03191 
03192   return ImplicitConversionSequence::Indistinguishable;
03193 }
03194   
03195 /// CompareImplicitConversionSequences - Compare two implicit
03196 /// conversion sequences to determine whether one is better than the
03197 /// other or if they are indistinguishable (C++ 13.3.3.2).
03198 static ImplicitConversionSequence::CompareKind
03199 CompareImplicitConversionSequences(Sema &S,
03200                                    const ImplicitConversionSequence& ICS1,
03201                                    const ImplicitConversionSequence& ICS2)
03202 {
03203   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
03204   // conversion sequences (as defined in 13.3.3.1)
03205   //   -- a standard conversion sequence (13.3.3.1.1) is a better
03206   //      conversion sequence than a user-defined conversion sequence or
03207   //      an ellipsis conversion sequence, and
03208   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
03209   //      conversion sequence than an ellipsis conversion sequence
03210   //      (13.3.3.1.3).
03211   //
03212   // C++0x [over.best.ics]p10:
03213   //   For the purpose of ranking implicit conversion sequences as
03214   //   described in 13.3.3.2, the ambiguous conversion sequence is
03215   //   treated as a user-defined sequence that is indistinguishable
03216   //   from any other user-defined conversion sequence.
03217   if (ICS1.getKindRank() < ICS2.getKindRank())
03218     return ImplicitConversionSequence::Better;
03219   if (ICS2.getKindRank() < ICS1.getKindRank())
03220     return ImplicitConversionSequence::Worse;
03221 
03222   // The following checks require both conversion sequences to be of
03223   // the same kind.
03224   if (ICS1.getKind() != ICS2.getKind())
03225     return ImplicitConversionSequence::Indistinguishable;
03226 
03227   ImplicitConversionSequence::CompareKind Result =
03228       ImplicitConversionSequence::Indistinguishable;
03229 
03230   // Two implicit conversion sequences of the same form are
03231   // indistinguishable conversion sequences unless one of the
03232   // following rules apply: (C++ 13.3.3.2p3):
03233   if (ICS1.isStandard())
03234     Result = CompareStandardConversionSequences(S,
03235                                                 ICS1.Standard, ICS2.Standard);
03236   else if (ICS1.isUserDefined()) {
03237     // User-defined conversion sequence U1 is a better conversion
03238     // sequence than another user-defined conversion sequence U2 if
03239     // they contain the same user-defined conversion function or
03240     // constructor and if the second standard conversion sequence of
03241     // U1 is better than the second standard conversion sequence of
03242     // U2 (C++ 13.3.3.2p3).
03243     if (ICS1.UserDefined.ConversionFunction ==
03244           ICS2.UserDefined.ConversionFunction)
03245       Result = CompareStandardConversionSequences(S,
03246                                                   ICS1.UserDefined.After,
03247                                                   ICS2.UserDefined.After);
03248     else
03249       Result = compareConversionFunctions(S, 
03250                                           ICS1.UserDefined.ConversionFunction,
03251                                           ICS2.UserDefined.ConversionFunction);
03252   }
03253 
03254   // List-initialization sequence L1 is a better conversion sequence than
03255   // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
03256   // for some X and L2 does not.
03257   if (Result == ImplicitConversionSequence::Indistinguishable &&
03258       !ICS1.isBad() &&
03259       ICS1.isListInitializationSequence() &&
03260       ICS2.isListInitializationSequence()) {
03261     if (ICS1.isStdInitializerListElement() &&
03262         !ICS2.isStdInitializerListElement())
03263       return ImplicitConversionSequence::Better;
03264     if (!ICS1.isStdInitializerListElement() &&
03265         ICS2.isStdInitializerListElement())
03266       return ImplicitConversionSequence::Worse;
03267   }
03268 
03269   return Result;
03270 }
03271 
03272 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
03273   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
03274     Qualifiers Quals;
03275     T1 = Context.getUnqualifiedArrayType(T1, Quals);
03276     T2 = Context.getUnqualifiedArrayType(T2, Quals);
03277   }
03278 
03279   return Context.hasSameUnqualifiedType(T1, T2);
03280 }
03281 
03282 // Per 13.3.3.2p3, compare the given standard conversion sequences to
03283 // determine if one is a proper subset of the other.
03284 static ImplicitConversionSequence::CompareKind
03285 compareStandardConversionSubsets(ASTContext &Context,
03286                                  const StandardConversionSequence& SCS1,
03287                                  const StandardConversionSequence& SCS2) {
03288   ImplicitConversionSequence::CompareKind Result
03289     = ImplicitConversionSequence::Indistinguishable;
03290 
03291   // the identity conversion sequence is considered to be a subsequence of
03292   // any non-identity conversion sequence
03293   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
03294     return ImplicitConversionSequence::Better;
03295   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
03296     return ImplicitConversionSequence::Worse;
03297 
03298   if (SCS1.Second != SCS2.Second) {
03299     if (SCS1.Second == ICK_Identity)
03300       Result = ImplicitConversionSequence::Better;
03301     else if (SCS2.Second == ICK_Identity)
03302       Result = ImplicitConversionSequence::Worse;
03303     else
03304       return ImplicitConversionSequence::Indistinguishable;
03305   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
03306     return ImplicitConversionSequence::Indistinguishable;
03307 
03308   if (SCS1.Third == SCS2.Third) {
03309     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
03310                              : ImplicitConversionSequence::Indistinguishable;
03311   }
03312 
03313   if (SCS1.Third == ICK_Identity)
03314     return Result == ImplicitConversionSequence::Worse
03315              ? ImplicitConversionSequence::Indistinguishable
03316              : ImplicitConversionSequence::Better;
03317 
03318   if (SCS2.Third == ICK_Identity)
03319     return Result == ImplicitConversionSequence::Better
03320              ? ImplicitConversionSequence::Indistinguishable
03321              : ImplicitConversionSequence::Worse;
03322 
03323   return ImplicitConversionSequence::Indistinguishable;
03324 }
03325 
03326 /// \brief Determine whether one of the given reference bindings is better
03327 /// than the other based on what kind of bindings they are.
03328 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
03329                                        const StandardConversionSequence &SCS2) {
03330   // C++0x [over.ics.rank]p3b4:
03331   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
03332   //      implicit object parameter of a non-static member function declared
03333   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
03334   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
03335   //      lvalue reference to a function lvalue and S2 binds an rvalue
03336   //      reference*.
03337   //
03338   // FIXME: Rvalue references. We're going rogue with the above edits,
03339   // because the semantics in the current C++0x working paper (N3225 at the
03340   // time of this writing) break the standard definition of std::forward
03341   // and std::reference_wrapper when dealing with references to functions.
03342   // Proposed wording changes submitted to CWG for consideration.
03343   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
03344       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
03345     return false;
03346 
03347   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
03348           SCS2.IsLvalueReference) ||
03349          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
03350           !SCS2.IsLvalueReference);
03351 }
03352 
03353 /// CompareStandardConversionSequences - Compare two standard
03354 /// conversion sequences to determine whether one is better than the
03355 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
03356 static ImplicitConversionSequence::CompareKind
03357 CompareStandardConversionSequences(Sema &S,
03358                                    const StandardConversionSequence& SCS1,
03359                                    const StandardConversionSequence& SCS2)
03360 {
03361   // Standard conversion sequence S1 is a better conversion sequence
03362   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
03363 
03364   //  -- S1 is a proper subsequence of S2 (comparing the conversion
03365   //     sequences in the canonical form defined by 13.3.3.1.1,
03366   //     excluding any Lvalue Transformation; the identity conversion
03367   //     sequence is considered to be a subsequence of any
03368   //     non-identity conversion sequence) or, if not that,
03369   if (ImplicitConversionSequence::CompareKind CK
03370         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
03371     return CK;
03372 
03373   //  -- the rank of S1 is better than the rank of S2 (by the rules
03374   //     defined below), or, if not that,
03375   ImplicitConversionRank Rank1 = SCS1.getRank();
03376   ImplicitConversionRank Rank2 = SCS2.getRank();
03377   if (Rank1 < Rank2)
03378     return ImplicitConversionSequence::Better;
03379   else if (Rank2 < Rank1)
03380     return ImplicitConversionSequence::Worse;
03381 
03382   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
03383   // are indistinguishable unless one of the following rules
03384   // applies:
03385 
03386   //   A conversion that is not a conversion of a pointer, or
03387   //   pointer to member, to bool is better than another conversion
03388   //   that is such a conversion.
03389   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
03390     return SCS2.isPointerConversionToBool()
03391              ? ImplicitConversionSequence::Better
03392              : ImplicitConversionSequence::Worse;
03393 
03394   // C++ [over.ics.rank]p4b2:
03395   //
03396   //   If class B is derived directly or indirectly from class A,
03397   //   conversion of B* to A* is better than conversion of B* to
03398   //   void*, and conversion of A* to void* is better than conversion
03399   //   of B* to void*.
03400   bool SCS1ConvertsToVoid
03401     = SCS1.isPointerConversionToVoidPointer(S.Context);
03402   bool SCS2ConvertsToVoid
03403     = SCS2.isPointerConversionToVoidPointer(S.Context);
03404   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
03405     // Exactly one of the conversion sequences is a conversion to
03406     // a void pointer; it's the worse conversion.
03407     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
03408                               : ImplicitConversionSequence::Worse;
03409   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
03410     // Neither conversion sequence converts to a void pointer; compare
03411     // their derived-to-base conversions.
03412     if (ImplicitConversionSequence::CompareKind DerivedCK
03413           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
03414       return DerivedCK;
03415   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
03416              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
03417     // Both conversion sequences are conversions to void
03418     // pointers. Compare the source types to determine if there's an
03419     // inheritance relationship in their sources.
03420     QualType FromType1 = SCS1.getFromType();
03421     QualType FromType2 = SCS2.getFromType();
03422 
03423     // Adjust the types we're converting from via the array-to-pointer
03424     // conversion, if we need to.
03425     if (SCS1.First == ICK_Array_To_Pointer)
03426       FromType1 = S.Context.getArrayDecayedType(FromType1);
03427     if (SCS2.First == ICK_Array_To_Pointer)
03428       FromType2 = S.Context.getArrayDecayedType(FromType2);
03429 
03430     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
03431     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
03432 
03433     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
03434       return ImplicitConversionSequence::Better;
03435     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
03436       return ImplicitConversionSequence::Worse;
03437 
03438     // Objective-C++: If one interface is more specific than the
03439     // other, it is the better one.
03440     const ObjCObjectPointerType* FromObjCPtr1
03441       = FromType1->getAs<ObjCObjectPointerType>();
03442     const ObjCObjectPointerType* FromObjCPtr2
03443       = FromType2->getAs<ObjCObjectPointerType>();
03444     if (FromObjCPtr1 && FromObjCPtr2) {
03445       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 
03446                                                           FromObjCPtr2);
03447       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 
03448                                                            FromObjCPtr1);
03449       if (AssignLeft != AssignRight) {
03450         return AssignLeft? ImplicitConversionSequence::Better
03451                          : ImplicitConversionSequence::Worse;
03452       }
03453     }
03454   }
03455 
03456   // Compare based on qualification conversions (C++ 13.3.3.2p3,
03457   // bullet 3).
03458   if (ImplicitConversionSequence::CompareKind QualCK
03459         = CompareQualificationConversions(S, SCS1, SCS2))
03460     return QualCK;
03461 
03462   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
03463     // Check for a better reference binding based on the kind of bindings.
03464     if (isBetterReferenceBindingKind(SCS1, SCS2))
03465       return ImplicitConversionSequence::Better;
03466     else if (isBetterReferenceBindingKind(SCS2, SCS1))
03467       return ImplicitConversionSequence::Worse;
03468 
03469     // C++ [over.ics.rank]p3b4:
03470     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
03471     //      which the references refer are the same type except for
03472     //      top-level cv-qualifiers, and the type to which the reference
03473     //      initialized by S2 refers is more cv-qualified than the type
03474     //      to which the reference initialized by S1 refers.
03475     QualType T1 = SCS1.getToType(2);
03476     QualType T2 = SCS2.getToType(2);
03477     T1 = S.Context.getCanonicalType(T1);
03478     T2 = S.Context.getCanonicalType(T2);
03479     Qualifiers T1Quals, T2Quals;
03480     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
03481     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
03482     if (UnqualT1 == UnqualT2) {
03483       // Objective-C++ ARC: If the references refer to objects with different
03484       // lifetimes, prefer bindings that don't change lifetime.
03485       if (SCS1.ObjCLifetimeConversionBinding != 
03486                                           SCS2.ObjCLifetimeConversionBinding) {
03487         return SCS1.ObjCLifetimeConversionBinding
03488                                            ? ImplicitConversionSequence::Worse
03489                                            : ImplicitConversionSequence::Better;
03490       }
03491       
03492       // If the type is an array type, promote the element qualifiers to the
03493       // type for comparison.
03494       if (isa<ArrayType>(T1) && T1Quals)
03495         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
03496       if (isa<ArrayType>(T2) && T2Quals)
03497         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
03498       if (T2.isMoreQualifiedThan(T1))
03499         return ImplicitConversionSequence::Better;
03500       else if (T1.isMoreQualifiedThan(T2))
03501         return ImplicitConversionSequence::Worse;      
03502     }
03503   }
03504 
03505   // In Microsoft mode, prefer an integral conversion to a
03506   // floating-to-integral conversion if the integral conversion
03507   // is between types of the same size.
03508   // For example:
03509   // void f(float);
03510   // void f(int);
03511   // int main {
03512   //    long a;
03513   //    f(a);
03514   // }
03515   // Here, MSVC will call f(int) instead of generating a compile error
03516   // as clang will do in standard mode.
03517   if (S.getLangOpts().MicrosoftMode &&
03518       SCS1.Second == ICK_Integral_Conversion &&
03519       SCS2.Second == ICK_Floating_Integral && 
03520       S.Context.getTypeSize(SCS1.getFromType()) ==
03521       S.Context.getTypeSize(SCS1.getToType(2)))
03522     return ImplicitConversionSequence::Better;
03523 
03524   return ImplicitConversionSequence::Indistinguishable;
03525 }
03526 
03527 /// CompareQualificationConversions - Compares two standard conversion
03528 /// sequences to determine whether they can be ranked based on their
03529 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
03530 ImplicitConversionSequence::CompareKind
03531 CompareQualificationConversions(Sema &S,
03532                                 const StandardConversionSequence& SCS1,
03533                                 const StandardConversionSequence& SCS2) {
03534   // C++ 13.3.3.2p3:
03535   //  -- S1 and S2 differ only in their qualification conversion and
03536   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
03537   //     cv-qualification signature of type T1 is a proper subset of
03538   //     the cv-qualification signature of type T2, and S1 is not the
03539   //     deprecated string literal array-to-pointer conversion (4.2).
03540   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
03541       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
03542     return ImplicitConversionSequence::Indistinguishable;
03543 
03544   // FIXME: the example in the standard doesn't use a qualification
03545   // conversion (!)
03546   QualType T1 = SCS1.getToType(2);
03547   QualType T2 = SCS2.getToType(2);
03548   T1 = S.Context.getCanonicalType(T1);
03549   T2 = S.Context.getCanonicalType(T2);
03550   Qualifiers T1Quals, T2Quals;
03551   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
03552   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
03553 
03554   // If the types are the same, we won't learn anything by unwrapped
03555   // them.
03556   if (UnqualT1 == UnqualT2)
03557     return ImplicitConversionSequence::Indistinguishable;
03558 
03559   // If the type is an array type, promote the element qualifiers to the type
03560   // for comparison.
03561   if (isa<ArrayType>(T1) && T1Quals)
03562     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
03563   if (isa<ArrayType>(T2) && T2Quals)
03564     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
03565 
03566   ImplicitConversionSequence::CompareKind Result
03567     = ImplicitConversionSequence::Indistinguishable;
03568   
03569   // Objective-C++ ARC:
03570   //   Prefer qualification conversions not involving a change in lifetime
03571   //   to qualification conversions that do not change lifetime.
03572   if (SCS1.QualificationIncludesObjCLifetime != 
03573                                       SCS2.QualificationIncludesObjCLifetime) {
03574     Result = SCS1.QualificationIncludesObjCLifetime
03575                ? ImplicitConversionSequence::Worse
03576                : ImplicitConversionSequence::Better;
03577   }
03578   
03579   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
03580     // Within each iteration of the loop, we check the qualifiers to
03581     // determine if this still looks like a qualification
03582     // conversion. Then, if all is well, we unwrap one more level of
03583     // pointers or pointers-to-members and do it all again
03584     // until there are no more pointers or pointers-to-members left
03585     // to unwrap. This essentially mimics what
03586     // IsQualificationConversion does, but here we're checking for a
03587     // strict subset of qualifiers.
03588     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
03589       // The qualifiers are the same, so this doesn't tell us anything
03590       // about how the sequences rank.
03591       ;
03592     else if (T2.isMoreQualifiedThan(T1)) {
03593       // T1 has fewer qualifiers, so it could be the better sequence.
03594       if (Result == ImplicitConversionSequence::Worse)
03595         // Neither has qualifiers that are a subset of the other's
03596         // qualifiers.
03597         return ImplicitConversionSequence::Indistinguishable;
03598 
03599       Result = ImplicitConversionSequence::Better;
03600     } else if (T1.isMoreQualifiedThan(T2)) {
03601       // T2 has fewer qualifiers, so it could be the better sequence.
03602       if (Result == ImplicitConversionSequence::Better)
03603         // Neither has qualifiers that are a subset of the other's
03604         // qualifiers.
03605         return ImplicitConversionSequence::Indistinguishable;
03606 
03607       Result = ImplicitConversionSequence::Worse;
03608     } else {
03609       // Qualifiers are disjoint.
03610       return ImplicitConversionSequence::Indistinguishable;
03611     }
03612 
03613     // If the types after this point are equivalent, we're done.
03614     if (S.Context.hasSameUnqualifiedType(T1, T2))
03615       break;
03616   }
03617 
03618   // Check that the winning standard conversion sequence isn't using
03619   // the deprecated string literal array to pointer conversion.
03620   switch (Result) {
03621   case ImplicitConversionSequence::Better:
03622     if (SCS1.DeprecatedStringLiteralToCharPtr)
03623       Result = ImplicitConversionSequence::Indistinguishable;
03624     break;
03625 
03626   case ImplicitConversionSequence::Indistinguishable:
03627     break;
03628 
03629   case ImplicitConversionSequence::Worse:
03630     if (SCS2.DeprecatedStringLiteralToCharPtr)
03631       Result = ImplicitConversionSequence::Indistinguishable;
03632     break;
03633   }
03634 
03635   return Result;
03636 }
03637 
03638 /// CompareDerivedToBaseConversions - Compares two standard conversion
03639 /// sequences to determine whether they can be ranked based on their
03640 /// various kinds of derived-to-base conversions (C++
03641 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
03642 /// conversions between Objective-C interface types.
03643 ImplicitConversionSequence::CompareKind
03644 CompareDerivedToBaseConversions(Sema &S,
03645                                 const StandardConversionSequence& SCS1,
03646                                 const StandardConversionSequence& SCS2) {
03647   QualType FromType1 = SCS1.getFromType();
03648   QualType ToType1 = SCS1.getToType(1);
03649   QualType FromType2 = SCS2.getFromType();
03650   QualType ToType2 = SCS2.getToType(1);
03651 
03652   // Adjust the types we're converting from via the array-to-pointer
03653   // conversion, if we need to.
03654   if (SCS1.First == ICK_Array_To_Pointer)
03655     FromType1 = S.Context.getArrayDecayedType(FromType1);
03656   if (SCS2.First == ICK_Array_To_Pointer)
03657     FromType2 = S.Context.getArrayDecayedType(FromType2);
03658 
03659   // Canonicalize all of the types.
03660   FromType1 = S.Context.getCanonicalType(FromType1);
03661   ToType1 = S.Context.getCanonicalType(ToType1);
03662   FromType2 = S.Context.getCanonicalType(FromType2);
03663   ToType2 = S.Context.getCanonicalType(ToType2);
03664 
03665   // C++ [over.ics.rank]p4b3:
03666   //
03667   //   If class B is derived directly or indirectly from class A and
03668   //   class C is derived directly or indirectly from B,
03669   //
03670   // Compare based on pointer conversions.
03671   if (SCS1.Second == ICK_Pointer_Conversion &&
03672       SCS2.Second == ICK_Pointer_Conversion &&
03673       /*FIXME: Remove if Objective-C id conversions get their own rank*/
03674       FromType1->isPointerType() && FromType2->isPointerType() &&
03675       ToType1->isPointerType() && ToType2->isPointerType()) {
03676     QualType FromPointee1
03677       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
03678     QualType ToPointee1
03679       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
03680     QualType FromPointee2
03681       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
03682     QualType ToPointee2
03683       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
03684 
03685     //   -- conversion of C* to B* is better than conversion of C* to A*,
03686     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
03687       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
03688         return ImplicitConversionSequence::Better;
03689       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
03690         return ImplicitConversionSequence::Worse;
03691     }
03692 
03693     //   -- conversion of B* to A* is better than conversion of C* to A*,
03694     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
03695       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
03696         return ImplicitConversionSequence::Better;
03697       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
03698         return ImplicitConversionSequence::Worse;
03699     }
03700   } else if (SCS1.Second == ICK_Pointer_Conversion &&
03701              SCS2.Second == ICK_Pointer_Conversion) {
03702     const ObjCObjectPointerType *FromPtr1
03703       = FromType1->getAs<ObjCObjectPointerType>();
03704     const ObjCObjectPointerType *FromPtr2
03705       = FromType2->getAs<ObjCObjectPointerType>();
03706     const ObjCObjectPointerType *ToPtr1
03707       = ToType1->getAs<ObjCObjectPointerType>();
03708     const ObjCObjectPointerType *ToPtr2
03709       = ToType2->getAs<ObjCObjectPointerType>();
03710     
03711     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
03712       // Apply the same conversion ranking rules for Objective-C pointer types
03713       // that we do for C++ pointers to class types. However, we employ the
03714       // Objective-C pseudo-subtyping relationship used for assignment of
03715       // Objective-C pointer types.
03716       bool FromAssignLeft
03717         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
03718       bool FromAssignRight
03719         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
03720       bool ToAssignLeft
03721         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
03722       bool ToAssignRight
03723         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
03724       
03725       // A conversion to an a non-id object pointer type or qualified 'id' 
03726       // type is better than a conversion to 'id'.
03727       if (ToPtr1->isObjCIdType() &&
03728           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
03729         return ImplicitConversionSequence::Worse;
03730       if (ToPtr2->isObjCIdType() &&
03731           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
03732         return ImplicitConversionSequence::Better;
03733       
03734       // A conversion to a non-id object pointer type is better than a 
03735       // conversion to a qualified 'id' type 
03736       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
03737         return ImplicitConversionSequence::Worse;
03738       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
03739         return ImplicitConversionSequence::Better;
03740   
03741       // A conversion to an a non-Class object pointer type or qualified 'Class' 
03742       // type is better than a conversion to 'Class'.
03743       if (ToPtr1->isObjCClassType() &&
03744           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
03745         return ImplicitConversionSequence::Worse;
03746       if (ToPtr2->isObjCClassType() &&
03747           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
03748         return ImplicitConversionSequence::Better;
03749       
03750       // A conversion to a non-Class object pointer type is better than a 
03751       // conversion to a qualified 'Class' type.
03752       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
03753         return ImplicitConversionSequence::Worse;
03754       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
03755         return ImplicitConversionSequence::Better;
03756 
03757       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
03758       if (S.Context.hasSameType(FromType1, FromType2) && 
03759           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
03760           (ToAssignLeft != ToAssignRight))
03761         return ToAssignLeft? ImplicitConversionSequence::Worse
03762                            : ImplicitConversionSequence::Better;
03763 
03764       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
03765       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
03766           (FromAssignLeft != FromAssignRight))
03767         return FromAssignLeft? ImplicitConversionSequence::Better
03768         : ImplicitConversionSequence::Worse;
03769     }
03770   }
03771   
03772   // Ranking of member-pointer types.
03773   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
03774       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
03775       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
03776     const MemberPointerType * FromMemPointer1 =
03777                                         FromType1->getAs<MemberPointerType>();
03778     const MemberPointerType * ToMemPointer1 =
03779                                           ToType1->getAs<MemberPointerType>();
03780     const MemberPointerType * FromMemPointer2 =
03781                                           FromType2->getAs<MemberPointerType>();
03782     const MemberPointerType * ToMemPointer2 =
03783                                           ToType2->getAs<MemberPointerType>();
03784     const Type *FromPointeeType1 = FromMemPointer1->getClass();
03785     const Type *ToPointeeType1 = ToMemPointer1->getClass();
03786     const Type *FromPointeeType2 = FromMemPointer2->getClass();
03787     const Type *ToPointeeType2 = ToMemPointer2->getClass();
03788     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
03789     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
03790     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
03791     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
03792     // conversion of A::* to B::* is better than conversion of A::* to C::*,
03793     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
03794       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
03795         return ImplicitConversionSequence::Worse;
03796       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
03797         return ImplicitConversionSequence::Better;
03798     }
03799     // conversion of B::* to C::* is better than conversion of A::* to C::*
03800     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
03801       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
03802         return ImplicitConversionSequence::Better;
03803       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
03804         return ImplicitConversionSequence::Worse;
03805     }
03806   }
03807 
03808   if (SCS1.Second == ICK_Derived_To_Base) {
03809     //   -- conversion of C to B is better than conversion of C to A,
03810     //   -- binding of an expression of type C to a reference of type
03811     //      B& is better than binding an expression of type C to a
03812     //      reference of type A&,
03813     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
03814         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
03815       if (S.IsDerivedFrom(ToType1, ToType2))
03816         return ImplicitConversionSequence::Better;
03817       else if (S.IsDerivedFrom(ToType2, ToType1))
03818         return ImplicitConversionSequence::Worse;
03819     }
03820 
03821     //   -- conversion of B to A is better than conversion of C to A.
03822     //   -- binding of an expression of type B to a reference of type
03823     //      A& is better than binding an expression of type C to a
03824     //      reference of type A&,
03825     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
03826         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
03827       if (S.IsDerivedFrom(FromType2, FromType1))
03828         return ImplicitConversionSequence::Better;
03829       else if (S.IsDerivedFrom(FromType1, FromType2))
03830         return ImplicitConversionSequence::Worse;
03831     }
03832   }
03833 
03834   return ImplicitConversionSequence::Indistinguishable;
03835 }
03836 
03837 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
03838 /// determine whether they are reference-related,
03839 /// reference-compatible, reference-compatible with added
03840 /// qualification, or incompatible, for use in C++ initialization by
03841 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
03842 /// type, and the first type (T1) is the pointee type of the reference
03843 /// type being initialized.
03844 Sema::ReferenceCompareResult
03845 Sema::CompareReferenceRelationship(SourceLocation Loc,
03846                                    QualType OrigT1, QualType OrigT2,
03847                                    bool &DerivedToBase,
03848                                    bool &ObjCConversion,
03849                                    bool &ObjCLifetimeConversion) {
03850   assert(!OrigT1->isReferenceType() &&
03851     "T1 must be the pointee type of the reference type");
03852   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
03853 
03854   QualType T1 = Context.getCanonicalType(OrigT1);
03855   QualType T2 = Context.getCanonicalType(OrigT2);
03856   Qualifiers T1Quals, T2Quals;
03857   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
03858   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
03859 
03860   // C++ [dcl.init.ref]p4:
03861   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
03862   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
03863   //   T1 is a base class of T2.
03864   DerivedToBase = false;
03865   ObjCConversion = false;
03866   ObjCLifetimeConversion = false;
03867   if (UnqualT1 == UnqualT2) {
03868     // Nothing to do.
03869   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
03870            IsDerivedFrom(UnqualT2, UnqualT1))
03871     DerivedToBase = true;
03872   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
03873            UnqualT2->isObjCObjectOrInterfaceType() &&
03874            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
03875     ObjCConversion = true;
03876   else
03877     return Ref_Incompatible;
03878 
03879   // At this point, we know that T1 and T2 are reference-related (at
03880   // least).
03881 
03882   // If the type is an array type, promote the element qualifiers to the type
03883   // for comparison.
03884   if (isa<ArrayType>(T1) && T1Quals)
03885     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
03886   if (isa<ArrayType>(T2) && T2Quals)
03887     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
03888 
03889   // C++ [dcl.init.ref]p4:
03890   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
03891   //   reference-related to T2 and cv1 is the same cv-qualification
03892   //   as, or greater cv-qualification than, cv2. For purposes of
03893   //   overload resolution, cases for which cv1 is greater
03894   //   cv-qualification than cv2 are identified as
03895   //   reference-compatible with added qualification (see 13.3.3.2).
03896   //
03897   // Note that we also require equivalence of Objective-C GC and address-space
03898   // qualifiers when performing these computations, so that e.g., an int in
03899   // address space 1 is not reference-compatible with an int in address
03900   // space 2.
03901   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
03902       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
03903     T1Quals.removeObjCLifetime();
03904     T2Quals.removeObjCLifetime();    
03905     ObjCLifetimeConversion = true;
03906   }
03907     
03908   if (T1Quals == T2Quals)
03909     return Ref_Compatible;
03910   else if (T1Quals.compatiblyIncludes(T2Quals))
03911     return Ref_Compatible_With_Added_Qualification;
03912   else
03913     return Ref_Related;
03914 }
03915 
03916 /// \brief Look for a user-defined conversion to an value reference-compatible
03917 ///        with DeclType. Return true if something definite is found.
03918 static bool
03919 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
03920                          QualType DeclType, SourceLocation DeclLoc,
03921                          Expr *Init, QualType T2, bool AllowRvalues,
03922                          bool AllowExplicit) {
03923   assert(T2->isRecordType() && "Can only find conversions of record types.");
03924   CXXRecordDecl *T2RecordDecl
03925     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
03926 
03927   OverloadCandidateSet CandidateSet(DeclLoc);
03928   const UnresolvedSetImpl *Conversions
03929     = T2RecordDecl->getVisibleConversionFunctions();
03930   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
03931          E = Conversions->end(); I != E; ++I) {
03932     NamedDecl *D = *I;
03933     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
03934     if (isa<UsingShadowDecl>(D))
03935       D = cast<UsingShadowDecl>(D)->getTargetDecl();
03936 
03937     FunctionTemplateDecl *ConvTemplate
03938       = dyn_cast<FunctionTemplateDecl>(D);
03939     CXXConversionDecl *Conv;
03940     if (ConvTemplate)
03941       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
03942     else
03943       Conv = cast<CXXConversionDecl>(D);
03944 
03945     // If this is an explicit conversion, and we're not allowed to consider
03946     // explicit conversions, skip it.
03947     if (!AllowExplicit && Conv->isExplicit())
03948       continue;
03949 
03950     if (AllowRvalues) {
03951       bool DerivedToBase = false;
03952       bool ObjCConversion = false;
03953       bool ObjCLifetimeConversion = false;
03954       
03955       // If we are initializing an rvalue reference, don't permit conversion
03956       // functions that return lvalues.
03957       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
03958         const ReferenceType *RefType
03959           = Conv->getConversionType()->getAs<LValueReferenceType>();
03960         if (RefType && !RefType->getPointeeType()->isFunctionType())
03961           continue;
03962       }
03963       
03964       if (!ConvTemplate &&
03965           S.CompareReferenceRelationship(
03966             DeclLoc,
03967             Conv->getConversionType().getNonReferenceType()
03968               .getUnqualifiedType(),
03969             DeclType.getNonReferenceType().getUnqualifiedType(),
03970             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
03971           Sema::Ref_Incompatible)
03972         continue;
03973     } else {
03974       // If the conversion function doesn't return a reference type,
03975       // it can't be considered for this conversion. An rvalue reference
03976       // is only acceptable if its referencee is a function type.
03977 
03978       const ReferenceType *RefType =
03979         Conv->getConversionType()->getAs<ReferenceType>();
03980       if (!RefType ||
03981           (!RefType->isLValueReferenceType() &&
03982            !RefType->getPointeeType()->isFunctionType()))
03983         continue;
03984     }
03985 
03986     if (ConvTemplate)
03987       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
03988                                        Init, DeclType, CandidateSet);
03989     else
03990       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
03991                                DeclType, CandidateSet);
03992   }
03993 
03994   bool HadMultipleCandidates = (CandidateSet.size() > 1);
03995 
03996   OverloadCandidateSet::iterator Best;
03997   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
03998   case OR_Success:
03999     // C++ [over.ics.ref]p1:
04000     //
04001     //   [...] If the parameter binds directly to the result of
04002     //   applying a conversion function to the argument
04003     //   expression, the implicit conversion sequence is a
04004     //   user-defined conversion sequence (13.3.3.1.2), with the
04005     //   second standard conversion sequence either an identity
04006     //   conversion or, if the conversion function returns an
04007     //   entity of a type that is a derived class of the parameter
04008     //   type, a derived-to-base Conversion.
04009     if (!Best->FinalConversion.DirectBinding)
04010       return false;
04011 
04012     if (Best->Function)
04013       S.MarkFunctionReferenced(DeclLoc, Best->Function);
04014     ICS.setUserDefined();
04015     ICS.UserDefined.Before = Best->Conversions[0].Standard;
04016     ICS.UserDefined.After = Best->FinalConversion;
04017     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
04018     ICS.UserDefined.ConversionFunction = Best->Function;
04019     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
04020     ICS.UserDefined.EllipsisConversion = false;
04021     assert(ICS.UserDefined.After.ReferenceBinding &&
04022            ICS.UserDefined.After.DirectBinding &&
04023            "Expected a direct reference binding!");
04024     return true;
04025 
04026   case OR_Ambiguous:
04027     ICS.setAmbiguous();
04028     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
04029          Cand != CandidateSet.end(); ++Cand)
04030       if (Cand->Viable)
04031         ICS.Ambiguous.addConversion(Cand->Function);
04032     return true;
04033 
04034   case OR_No_Viable_Function:
04035   case OR_Deleted:
04036     // There was no suitable conversion, or we found a deleted
04037     // conversion; continue with other checks.
04038     return false;
04039   }
04040 
04041   llvm_unreachable("Invalid OverloadResult!");
04042 }
04043 
04044 /// \brief Compute an implicit conversion sequence for reference
04045 /// initialization.
04046 static ImplicitConversionSequence
04047 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
04048                  SourceLocation DeclLoc,
04049                  bool SuppressUserConversions,
04050                  bool AllowExplicit) {
04051   assert(DeclType->isReferenceType() && "Reference init needs a reference");
04052 
04053   // Most paths end in a failed conversion.
04054   ImplicitConversionSequence ICS;
04055   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
04056 
04057   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
04058   QualType T2 = Init->getType();
04059 
04060   // If the initializer is the address of an overloaded function, try
04061   // to resolve the overloaded function. If all goes well, T2 is the
04062   // type of the resulting function.
04063   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
04064     DeclAccessPair Found;
04065     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
04066                                                                 false, Found))
04067       T2 = Fn->getType();
04068   }
04069 
04070   // Compute some basic properties of the types and the initializer.
04071   bool isRValRef = DeclType->isRValueReferenceType();
04072   bool DerivedToBase = false;
04073   bool ObjCConversion = false;
04074   bool ObjCLifetimeConversion = false;
04075   Expr::Classification InitCategory = Init->Classify(S.Context);
04076   Sema::ReferenceCompareResult RefRelationship
04077     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
04078                                      ObjCConversion, ObjCLifetimeConversion);
04079 
04080 
04081   // C++0x [dcl.init.ref]p5:
04082   //   A reference to type "cv1 T1" is initialized by an expression
04083   //   of type "cv2 T2" as follows:
04084 
04085   //     -- If reference is an lvalue reference and the initializer expression
04086   if (!isRValRef) {
04087     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
04088     //        reference-compatible with "cv2 T2," or
04089     //
04090     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
04091     if (InitCategory.isLValue() &&
04092         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
04093       // C++ [over.ics.ref]p1:
04094       //   When a parameter of reference type binds directly (8.5.3)
04095       //   to an argument expression, the implicit conversion sequence
04096       //   is the identity conversion, unless the argument expression
04097       //   has a type that is a derived class of the parameter type,
04098       //   in which case the implicit conversion sequence is a
04099       //   derived-to-base Conversion (13.3.3.1).
04100       ICS.setStandard();
04101       ICS.Standard.First = ICK_Identity;
04102       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
04103                          : ObjCConversion? ICK_Compatible_Conversion
04104                          : ICK_Identity;
04105       ICS.Standard.Third = ICK_Identity;
04106       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
04107       ICS.Standard.setToType(0, T2);
04108       ICS.Standard.setToType(1, T1);
04109       ICS.Standard.setToType(2, T1);
04110       ICS.Standard.ReferenceBinding = true;
04111       ICS.Standard.DirectBinding = true;
04112       ICS.Standard.IsLvalueReference = !isRValRef;
04113       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
04114       ICS.Standard.BindsToRvalue = false;
04115       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
04116       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
04117       ICS.Standard.CopyConstructor = 0;
04118 
04119       // Nothing more to do: the inaccessibility/ambiguity check for
04120       // derived-to-base conversions is suppressed when we're
04121       // computing the implicit conversion sequence (C++
04122       // [over.best.ics]p2).
04123       return ICS;
04124     }
04125 
04126     //       -- has a class type (i.e., T2 is a class type), where T1 is
04127     //          not reference-related to T2, and can be implicitly
04128     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
04129     //          is reference-compatible with "cv3 T3" 92) (this
04130     //          conversion is selected by enumerating the applicable
04131     //          conversion functions (13.3.1.6) and choosing the best
04132     //          one through overload resolution (13.3)),
04133     if (!SuppressUserConversions && T2->isRecordType() &&
04134         !S.RequireCompleteType(DeclLoc, T2, 0) &&
04135         RefRelationship == Sema::Ref_Incompatible) {
04136       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
04137                                    Init, T2, /*AllowRvalues=*/false,
04138                                    AllowExplicit))
04139         return ICS;
04140     }
04141   }
04142 
04143   //     -- Otherwise, the reference shall be an lvalue reference to a
04144   //        non-volatile const type (i.e., cv1 shall be const), or the reference
04145   //        shall be an rvalue reference.
04146   //
04147   // We actually handle one oddity of C++ [over.ics.ref] at this
04148   // point, which is that, due to p2 (which short-circuits reference
04149   // binding by only attempting a simple conversion for non-direct
04150   // bindings) and p3's strange wording, we allow a const volatile
04151   // reference to bind to an rvalue. Hence the check for the presence
04152   // of "const" rather than checking for "const" being the only
04153   // qualifier.
04154   // This is also the point where rvalue references and lvalue inits no longer
04155   // go together.
04156   if (!isRValRef && !T1.isConstQualified())
04157     return ICS;
04158 
04159   //       -- If the initializer expression
04160   //
04161   //            -- is an xvalue, class prvalue, array prvalue or function
04162   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
04163   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
04164       (InitCategory.isXValue() ||
04165       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
04166       (InitCategory.isLValue() && T2->isFunctionType()))) {
04167     ICS.setStandard();
04168     ICS.Standard.First = ICK_Identity;
04169     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
04170                       : ObjCConversion? ICK_Compatible_Conversion
04171                       : ICK_Identity;
04172     ICS.Standard.Third = ICK_Identity;
04173     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
04174     ICS.Standard.setToType(0, T2);
04175     ICS.Standard.setToType(1, T1);
04176     ICS.Standard.setToType(2, T1);
04177     ICS.Standard.ReferenceBinding = true;
04178     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
04179     // binding unless we're binding to a class prvalue.
04180     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
04181     // allow the use of rvalue references in C++98/03 for the benefit of
04182     // standard library implementors; therefore, we need the xvalue check here.
04183     ICS.Standard.DirectBinding =
04184       S.getLangOpts().CPlusPlus0x ||
04185       (InitCategory.isPRValue() && !T2->isRecordType());
04186     ICS.Standard.IsLvalueReference = !isRValRef;
04187     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
04188     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
04189     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
04190     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
04191     ICS.Standard.CopyConstructor = 0;
04192     return ICS;
04193   }
04194 
04195   //            -- has a class type (i.e., T2 is a class type), where T1 is not
04196   //               reference-related to T2, and can be implicitly converted to
04197   //               an xvalue, class prvalue, or function lvalue of type
04198   //               "cv3 T3", where "cv1 T1" is reference-compatible with
04199   //               "cv3 T3",
04200   //
04201   //          then the reference is bound to the value of the initializer
04202   //          expression in the first case and to the result of the conversion
04203   //          in the second case (or, in either case, to an appropriate base
04204   //          class subobject).
04205   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
04206       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
04207       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
04208                                Init, T2, /*AllowRvalues=*/true,
04209                                AllowExplicit)) {
04210     // In the second case, if the reference is an rvalue reference
04211     // and the second standard conversion sequence of the
04212     // user-defined conversion sequence includes an lvalue-to-rvalue
04213     // conversion, the program is ill-formed.
04214     if (ICS.isUserDefined() && isRValRef &&
04215         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
04216       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
04217 
04218     return ICS;
04219   }
04220 
04221   //       -- Otherwise, a temporary of type "cv1 T1" is created and
04222   //          initialized from the initializer expression using the
04223   //          rules for a non-reference copy initialization (8.5). The
04224   //          reference is then bound to the temporary. If T1 is
04225   //          reference-related to T2, cv1 must be the same
04226   //          cv-qualification as, or greater cv-qualification than,
04227   //          cv2; otherwise, the program is ill-formed.
04228   if (RefRelationship == Sema::Ref_Related) {
04229     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
04230     // we would be reference-compatible or reference-compatible with
04231     // added qualification. But that wasn't the case, so the reference
04232     // initialization fails.
04233     //
04234     // Note that we only want to check address spaces and cvr-qualifiers here.
04235     // ObjC GC and lifetime qualifiers aren't important.
04236     Qualifiers T1Quals = T1.getQualifiers();
04237     Qualifiers T2Quals = T2.getQualifiers();
04238     T1Quals.removeObjCGCAttr();
04239     T1Quals.removeObjCLifetime();
04240     T2Quals.removeObjCGCAttr();
04241     T2Quals.removeObjCLifetime();
04242     if (!T1Quals.compatiblyIncludes(T2Quals))
04243       return ICS;
04244   }
04245 
04246   // If at least one of the types is a class type, the types are not
04247   // related, and we aren't allowed any user conversions, the
04248   // reference binding fails. This case is important for breaking
04249   // recursion, since TryImplicitConversion below will attempt to
04250   // create a temporary through the use of a copy constructor.
04251   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
04252       (T1->isRecordType() || T2->isRecordType()))
04253     return ICS;
04254 
04255   // If T1 is reference-related to T2 and the reference is an rvalue
04256   // reference, the initializer expression shall not be an lvalue.
04257   if (RefRelationship >= Sema::Ref_Related &&
04258       isRValRef && Init->Classify(S.Context).isLValue())
04259     return ICS;
04260 
04261   // C++ [over.ics.ref]p2:
04262   //   When a parameter of reference type is not bound directly to
04263   //   an argument expression, the conversion sequence is the one
04264   //   required to convert the argument expression to the
04265   //   underlying type of the reference according to
04266   //   13.3.3.1. Conceptually, this conversion sequence corresponds
04267   //   to copy-initializing a temporary of the underlying type with
04268   //   the argument expression. Any difference in top-level
04269   //   cv-qualification is subsumed by the initialization itself
04270   //   and does not constitute a conversion.
04271   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
04272                               /*AllowExplicit=*/false,
04273                               /*InOverloadResolution=*/false,
04274                               /*CStyle=*/false,
04275                               /*AllowObjCWritebackConversion=*/false);
04276 
04277   // Of course, that's still a reference binding.
04278   if (ICS.isStandard()) {
04279     ICS.Standard.ReferenceBinding = true;
04280     ICS.Standard.IsLvalueReference = !isRValRef;
04281     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
04282     ICS.Standard.BindsToRvalue = true;
04283     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
04284     ICS.Standard.ObjCLifetimeConversionBinding = false;
04285   } else if (ICS.isUserDefined()) {
04286     // Don't allow rvalue references to bind to lvalues.
04287     if (DeclType->isRValueReferenceType()) {
04288       if (const ReferenceType *RefType
04289             = ICS.UserDefined.ConversionFunction->getResultType()
04290                 ->getAs<LValueReferenceType>()) {
04291         if (!RefType->getPointeeType()->isFunctionType()) {
04292           ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 
04293                      DeclType);
04294           return ICS;
04295         }
04296       }
04297     }
04298     
04299     ICS.UserDefined.After.ReferenceBinding = true;
04300     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
04301     ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
04302     ICS.UserDefined.After.BindsToRvalue = true;
04303     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
04304     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
04305   }
04306 
04307   return ICS;
04308 }
04309 
04310 static ImplicitConversionSequence
04311 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
04312                       bool SuppressUserConversions,
04313                       bool InOverloadResolution,
04314                       bool AllowObjCWritebackConversion,
04315                       bool AllowExplicit = false);
04316 
04317 /// TryListConversion - Try to copy-initialize a value of type ToType from the
04318 /// initializer list From.
04319 static ImplicitConversionSequence
04320 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
04321                   bool SuppressUserConversions,
04322                   bool InOverloadResolution,
04323                   bool AllowObjCWritebackConversion) {
04324   // C++11 [over.ics.list]p1:
04325   //   When an argument is an initializer list, it is not an expression and
04326   //   special rules apply for converting it to a parameter type.
04327 
04328   ImplicitConversionSequence Result;
04329   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
04330   Result.setListInitializationSequence();
04331 
04332   // We need a complete type for what follows. Incomplete types can never be
04333   // initialized from init lists.
04334   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
04335     return Result;
04336 
04337   // C++11 [over.ics.list]p2:
04338   //   If the parameter type is std::initializer_list<X> or "array of X" and
04339   //   all the elements can be implicitly converted to X, the implicit
04340   //   conversion sequence is the worst conversion necessary to convert an
04341   //   element of the list to X.
04342   bool toStdInitializerList = false;
04343   QualType X;
04344   if (ToType->isArrayType())
04345     X = S.Context.getBaseElementType(ToType);
04346   else
04347     toStdInitializerList = S.isStdInitializerList(ToType, &X);
04348   if (!X.isNull()) {
04349     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
04350       Expr *Init = From->getInit(i);
04351       ImplicitConversionSequence ICS =
04352           TryCopyInitialization(S, Init, X, SuppressUserConversions,
04353                                 InOverloadResolution,
04354                                 AllowObjCWritebackConversion);
04355       // If a single element isn't convertible, fail.
04356       if (ICS.isBad()) {
04357         Result = ICS;
04358         break;
04359       }
04360       // Otherwise, look for the worst conversion.
04361       if (Result.isBad() ||
04362           CompareImplicitConversionSequences(S, ICS, Result) ==
04363               ImplicitConversionSequence::Worse)
04364         Result = ICS;
04365     }
04366 
04367     // For an empty list, we won't have computed any conversion sequence.
04368     // Introduce the identity conversion sequence.
04369     if (From->getNumInits() == 0) {
04370       Result.setStandard();
04371       Result.Standard.setAsIdentityConversion();
04372       Result.Standard.setFromType(ToType);
04373       Result.Standard.setAllToTypes(ToType);
04374     }
04375 
04376     Result.setListInitializationSequence();
04377     Result.setStdInitializerListElement(toStdInitializerList);
04378     return Result;
04379   }
04380 
04381   // C++11 [over.ics.list]p3:
04382   //   Otherwise, if the parameter is a non-aggregate class X and overload
04383   //   resolution chooses a single best constructor [...] the implicit
04384   //   conversion sequence is a user-defined conversion sequence. If multiple
04385   //   constructors are viable but none is better than the others, the
04386   //   implicit conversion sequence is a user-defined conversion sequence.
04387   if (ToType->isRecordType() && !ToType->isAggregateType()) {
04388     // This function can deal with initializer lists.
04389     Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
04390                                       /*AllowExplicit=*/false,
04391                                       InOverloadResolution, /*CStyle=*/false,
04392                                       AllowObjCWritebackConversion);
04393     Result.setListInitializationSequence();
04394     return Result;
04395   }
04396 
04397   // C++11 [over.ics.list]p4:
04398   //   Otherwise, if the parameter has an aggregate type which can be
04399   //   initialized from the initializer list [...] the implicit conversion
04400   //   sequence is a user-defined conversion sequence.
04401   if (ToType->isAggregateType()) {
04402     // Type is an aggregate, argument is an init list. At this point it comes
04403     // down to checking whether the initialization works.
04404     // FIXME: Find out whether this parameter is consumed or not.
04405     InitializedEntity Entity =
04406         InitializedEntity::InitializeParameter(S.Context, ToType,
04407                                                /*Consumed=*/false);
04408     if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
04409       Result.setUserDefined();
04410       Result.UserDefined.Before.setAsIdentityConversion();
04411       // Initializer lists don't have a type.
04412       Result.UserDefined.Before.setFromType(QualType());
04413       Result.UserDefined.Before.setAllToTypes(QualType());
04414 
04415       Result.UserDefined.After.setAsIdentityConversion();
04416       Result.UserDefined.After.setFromType(ToType);
04417       Result.UserDefined.After.setAllToTypes(ToType);
04418       Result.UserDefined.ConversionFunction = 0;
04419     }
04420     return Result;
04421   }
04422 
04423   // C++11 [over.ics.list]p5:
04424   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
04425   if (ToType->isReferenceType()) {
04426     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
04427     // mention initializer lists in any way. So we go by what list-
04428     // initialization would do and try to extrapolate from that.
04429 
04430     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
04431 
04432     // If the initializer list has a single element that is reference-related
04433     // to the parameter type, we initialize the reference from that.
04434     if (From->getNumInits() == 1) {
04435       Expr *Init = From->getInit(0);
04436 
04437       QualType T2 = Init->getType();
04438 
04439       // If the initializer is the address of an overloaded function, try
04440       // to resolve the overloaded function. If all goes well, T2 is the
04441       // type of the resulting function.
04442       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
04443         DeclAccessPair Found;
04444         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
04445                                    Init, ToType, false, Found))
04446           T2 = Fn->getType();
04447       }
04448 
04449       // Compute some basic properties of the types and the initializer.
04450       bool dummy1 = false;
04451       bool dummy2 = false;
04452       bool dummy3 = false;
04453       Sema::ReferenceCompareResult RefRelationship
04454         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
04455                                          dummy2, dummy3);
04456 
04457       if (RefRelationship >= Sema::Ref_Related)
04458         return TryReferenceInit(S, Init, ToType,
04459                                 /*FIXME:*/From->getLocStart(),
04460                                 SuppressUserConversions,
04461                                 /*AllowExplicit=*/false);
04462     }
04463 
04464     // Otherwise, we bind the reference to a temporary created from the
04465     // initializer list.
04466     Result = TryListConversion(S, From, T1, SuppressUserConversions,
04467                                InOverloadResolution,
04468                                AllowObjCWritebackConversion);
04469     if (Result.isFailure())
04470       return Result;
04471     assert(!Result.isEllipsis() &&
04472            "Sub-initialization cannot result in ellipsis conversion.");
04473 
04474     // Can we even bind to a temporary?
04475     if (ToType->isRValueReferenceType() ||
04476         (T1.isConstQualified() && !T1.isVolatileQualified())) {
04477       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
04478                                             Result.UserDefined.After;
04479       SCS.ReferenceBinding = true;
04480       SCS.IsLvalueReference = ToType->isLValueReferenceType();
04481       SCS.BindsToRvalue = true;
04482       SCS.BindsToFunctionLvalue = false;
04483       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
04484       SCS.ObjCLifetimeConversionBinding = false;
04485     } else
04486       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
04487                     From, ToType);
04488     return Result;
04489   }
04490 
04491   // C++11 [over.ics.list]p6:
04492   //   Otherwise, if the parameter type is not a class:
04493   if (!ToType->isRecordType()) {
04494     //    - if the initializer list has one element, the implicit conversion
04495     //      sequence is the one required to convert the element to the
04496     //      parameter type.
04497     unsigned NumInits = From->getNumInits();
04498     if (NumInits == 1)
04499       Result = TryCopyInitialization(S, From->getInit(0), ToType,
04500                                      SuppressUserConversions,
04501                                      InOverloadResolution,
04502                                      AllowObjCWritebackConversion);
04503     //    - if the initializer list has no elements, the implicit conversion
04504     //      sequence is the identity conversion.
04505     else if (NumInits == 0) {
04506       Result.setStandard();
04507       Result.Standard.setAsIdentityConversion();
04508       Result.Standard.setFromType(ToType);
04509       Result.Standard.setAllToTypes(ToType);
04510     }
04511     Result.setListInitializationSequence();
04512     return Result;
04513   }
04514 
04515   // C++11 [over.ics.list]p7:
04516   //   In all cases other than those enumerated above, no conversion is possible
04517   return Result;
04518 }
04519 
04520 /// TryCopyInitialization - Try to copy-initialize a value of type
04521 /// ToType from the expression From. Return the implicit conversion
04522 /// sequence required to pass this argument, which may be a bad
04523 /// conversion sequence (meaning that the argument cannot be passed to
04524 /// a parameter of this type). If @p SuppressUserConversions, then we
04525 /// do not permit any user-defined conversion sequences.
04526 static ImplicitConversionSequence
04527 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
04528                       bool SuppressUserConversions,
04529                       bool InOverloadResolution,
04530                       bool AllowObjCWritebackConversion,
04531                       bool AllowExplicit) {
04532   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
04533     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
04534                              InOverloadResolution,AllowObjCWritebackConversion);
04535 
04536   if (ToType->isReferenceType())
04537     return TryReferenceInit(S, From, ToType,
04538                             /*FIXME:*/From->getLocStart(),
04539                             SuppressUserConversions,
04540                             AllowExplicit);
04541 
04542   return TryImplicitConversion(S, From, ToType,
04543                                SuppressUserConversions,
04544                                /*AllowExplicit=*/false,
04545                                InOverloadResolution,
04546                                /*CStyle=*/false,
04547                                AllowObjCWritebackConversion);
04548 }
04549 
04550 static bool TryCopyInitialization(const CanQualType FromQTy,
04551                                   const CanQualType ToQTy,
04552                                   Sema &S,
04553                                   SourceLocation Loc,
04554                                   ExprValueKind FromVK) {
04555   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
04556   ImplicitConversionSequence ICS =
04557     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
04558 
04559   return !ICS.isBad();
04560 }
04561 
04562 /// TryObjectArgumentInitialization - Try to initialize the object
04563 /// parameter of the given member function (@c Method) from the
04564 /// expression @p From.
04565 static ImplicitConversionSequence
04566 TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
04567                                 Expr::Classification FromClassification,
04568                                 CXXMethodDecl *Method,
04569                                 CXXRecordDecl *ActingContext) {
04570   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
04571   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
04572   //                 const volatile object.
04573   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
04574     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
04575   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
04576 
04577   // Set up the conversion sequence as a "bad" conversion, to allow us
04578   // to exit early.
04579   ImplicitConversionSequence ICS;
04580 
04581   // We need to have an object of class type.
04582   QualType FromType = OrigFromType;
04583   if (const PointerType *PT = FromType->getAs<PointerType>()) {
04584     FromType = PT->getPointeeType();
04585 
04586     // When we had a pointer, it's implicitly dereferenced, so we
04587     // better have an lvalue.
04588     assert(FromClassification.isLValue());
04589   }
04590 
04591   assert(FromType->isRecordType());
04592 
04593   // C++0x [over.match.funcs]p4:
04594   //   For non-static member functions, the type of the implicit object
04595   //   parameter is
04596   //
04597   //     - "lvalue reference to cv X" for functions declared without a
04598   //        ref-qualifier or with the & ref-qualifier
04599   //     - "rvalue reference to cv X" for functions declared with the &&
04600   //        ref-qualifier
04601   //
04602   // where X is the class of which the function is a member and cv is the
04603   // cv-qualification on the member function declaration.
04604   //
04605   // However, when finding an implicit conversion sequence for the argument, we
04606   // are not allowed to create temporaries or perform user-defined conversions
04607   // (C++ [over.match.funcs]p5). We perform a simplified version of
04608   // reference binding here, that allows class rvalues to bind to
04609   // non-constant references.
04610 
04611   // First check the qualifiers.
04612   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
04613   if (ImplicitParamType.getCVRQualifiers()
04614                                     != FromTypeCanon.getLocalCVRQualifiers() &&
04615       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
04616     ICS.setBad(BadConversionSequence::bad_qualifiers,
04617                OrigFromType, ImplicitParamType);
04618     return ICS;
04619   }
04620 
04621   // Check that we have either the same type or a derived type. It
04622   // affects the conversion rank.
04623   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
04624   ImplicitConversionKind SecondKind;
04625   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
04626     SecondKind = ICK_Identity;
04627   } else if (S.IsDerivedFrom(FromType, ClassType))
04628     SecondKind = ICK_Derived_To_Base;
04629   else {
04630     ICS.setBad(BadConversionSequence::unrelated_class,
04631                FromType, ImplicitParamType);
04632     return ICS;
04633   }
04634 
04635   // Check the ref-qualifier.
04636   switch (Method->getRefQualifier()) {
04637   case RQ_None:
04638     // Do nothing; we don't care about lvalueness or rvalueness.
04639     break;
04640 
04641   case RQ_LValue:
04642     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
04643       // non-const lvalue reference cannot bind to an rvalue
04644       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
04645                  ImplicitParamType);
04646       return ICS;
04647     }
04648     break;
04649 
04650   case RQ_RValue:
04651     if (!FromClassification.isRValue()) {
04652       // rvalue reference cannot bind to an lvalue
04653       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
04654                  ImplicitParamType);
04655       return ICS;
04656     }
04657     break;
04658   }
04659 
04660   // Success. Mark this as a reference binding.
04661   ICS.setStandard();
04662   ICS.Standard.setAsIdentityConversion();
04663   ICS.Standard.Second = SecondKind;
04664   ICS.Standard.setFromType(FromType);
04665   ICS.Standard.setAllToTypes(ImplicitParamType);
04666   ICS.Standard.ReferenceBinding = true;
04667   ICS.Standard.DirectBinding = true;
04668   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
04669   ICS.Standard.BindsToFunctionLvalue = false;
04670   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
04671   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
04672     = (Method->getRefQualifier() == RQ_None);
04673   return ICS;
04674 }
04675 
04676 /// PerformObjectArgumentInitialization - Perform initialization of
04677 /// the implicit object parameter for the given Method with the given
04678 /// expression.
04679 ExprResult
04680 Sema::PerformObjectArgumentInitialization(Expr *From,
04681                                           NestedNameSpecifier *Qualifier,
04682                                           NamedDecl *FoundDecl,
04683                                           CXXMethodDecl *Method) {
04684   QualType FromRecordType, DestType;
04685   QualType ImplicitParamRecordType  =
04686     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
04687 
04688   Expr::Classification FromClassification;
04689   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
04690     FromRecordType = PT->getPointeeType();
04691     DestType = Method->getThisType(Context);
04692     FromClassification = Expr::Classification::makeSimpleLValue();
04693   } else {
04694     FromRecordType = From->getType();
04695     DestType = ImplicitParamRecordType;
04696     FromClassification = From->Classify(Context);
04697   }
04698 
04699   // Note that we always use the true parent context when performing
04700   // the actual argument initialization.
04701   ImplicitConversionSequence ICS
04702     = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
04703                                       Method, Method->getParent());
04704   if (ICS.isBad()) {
04705     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
04706       Qualifiers FromQs = FromRecordType.getQualifiers();
04707       Qualifiers ToQs = DestType.getQualifiers();
04708       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
04709       if (CVR) {
04710         Diag(From->getLocStart(),
04711              diag::err_member_function_call_bad_cvr)
04712           << Method->getDeclName() << FromRecordType << (CVR - 1)
04713           << From->getSourceRange();
04714         Diag(Method->getLocation(), diag::note_previous_decl)
04715           << Method->getDeclName();
04716         return ExprError();
04717       }
04718     }
04719 
04720     return Diag(From->getLocStart(),
04721                 diag::err_implicit_object_parameter_init)
04722        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
04723   }
04724 
04725   if (ICS.Standard.Second == ICK_Derived_To_Base) {
04726     ExprResult FromRes =
04727       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
04728     if (FromRes.isInvalid())
04729       return ExprError();
04730     From = FromRes.take();
04731   }
04732 
04733   if (!Context.hasSameType(From->getType(), DestType))
04734     From = ImpCastExprToType(From, DestType, CK_NoOp,
04735                              From->getValueKind()).take();
04736   return Owned(From);
04737 }
04738 
04739 /// TryContextuallyConvertToBool - Attempt to contextually convert the
04740 /// expression From to bool (C++0x [conv]p3).
04741 static ImplicitConversionSequence
04742 TryContextuallyConvertToBool(Sema &S, Expr *From) {
04743   // FIXME: This is pretty broken.
04744   return TryImplicitConversion(S, From, S.Context.BoolTy,
04745                                // FIXME: Are these flags correct?
04746                                /*SuppressUserConversions=*/false,
04747                                /*AllowExplicit=*/true,
04748                                /*InOverloadResolution=*/false,
04749                                /*CStyle=*/false,
04750                                /*AllowObjCWritebackConversion=*/false);
04751 }
04752 
04753 /// PerformContextuallyConvertToBool - Perform a contextual conversion
04754 /// of the expression From to bool (C++0x [conv]p3).
04755 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
04756   if (checkPlaceholderForOverload(*this, From))
04757     return ExprError();
04758 
04759   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
04760   if (!ICS.isBad())
04761     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
04762 
04763   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
04764     return Diag(From->getLocStart(),
04765                 diag::err_typecheck_bool_condition)
04766                   << From->getType() << From->getSourceRange();
04767   return ExprError();
04768 }
04769 
04770 /// Check that the specified conversion is permitted in a converted constant
04771 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
04772 /// is acceptable.
04773 static bool CheckConvertedConstantConversions(Sema &S,
04774                                               StandardConversionSequence &SCS) {
04775   // Since we know that the target type is an integral or unscoped enumeration
04776   // type, most conversion kinds are impossible. All possible First and Third
04777   // conversions are fine.
04778   switch (SCS.Second) {
04779   case ICK_Identity:
04780   case ICK_Integral_Promotion:
04781   case ICK_Integral_Conversion:
04782     return true;
04783 
04784   case ICK_Boolean_Conversion:
04785     // Conversion from an integral or unscoped enumeration type to bool is
04786     // classified as ICK_Boolean_Conversion, but it's also an integral
04787     // conversion, so it's permitted in a converted constant expression.
04788     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
04789            SCS.getToType(2)->isBooleanType();
04790 
04791   case ICK_Floating_Integral:
04792   case ICK_Complex_Real:
04793     return false;
04794 
04795   case ICK_Lvalue_To_Rvalue:
04796   case ICK_Array_To_Pointer:
04797   case ICK_Function_To_Pointer:
04798   case ICK_NoReturn_Adjustment:
04799   case ICK_Qualification:
04800   case ICK_Compatible_Conversion:
04801   case ICK_Vector_Conversion:
04802   case ICK_Vector_Splat:
04803   case ICK_Derived_To_Base:
04804   case ICK_Pointer_Conversion:
04805   case ICK_Pointer_Member:
04806   case ICK_Block_Pointer_Conversion:
04807   case ICK_Writeback_Conversion:
04808   case ICK_Floating_Promotion:
04809   case ICK_Complex_Promotion:
04810   case ICK_Complex_Conversion:
04811   case ICK_Floating_Conversion:
04812   case ICK_TransparentUnionConversion:
04813     llvm_unreachable("unexpected second conversion kind");
04814 
04815   case ICK_Num_Conversion_Kinds:
04816     break;
04817   }
04818 
04819   llvm_unreachable("unknown conversion kind");
04820 }
04821 
04822 /// CheckConvertedConstantExpression - Check that the expression From is a
04823 /// converted constant expression of type T, perform the conversion and produce
04824 /// the converted expression, per C++11 [expr.const]p3.
04825 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
04826                                                   llvm::APSInt &Value,
04827                                                   CCEKind CCE) {
04828   assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
04829   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
04830 
04831   if (checkPlaceholderForOverload(*this, From))
04832     return ExprError();
04833 
04834   // C++11 [expr.const]p3 with proposed wording fixes:
04835   //  A converted constant expression of type T is a core constant expression,
04836   //  implicitly converted to a prvalue of type T, where the converted
04837   //  expression is a literal constant expression and the implicit conversion
04838   //  sequence contains only user-defined conversions, lvalue-to-rvalue
04839   //  conversions, integral promotions, and integral conversions other than
04840   //  narrowing conversions.
04841   ImplicitConversionSequence ICS =
04842     TryImplicitConversion(From, T,
04843                           /*SuppressUserConversions=*/false,
04844                           /*AllowExplicit=*/false,
04845                           /*InOverloadResolution=*/false,
04846                           /*CStyle=*/false,
04847                           /*AllowObjcWritebackConversion=*/false);
04848   StandardConversionSequence *SCS = 0;
04849   switch (ICS.getKind()) {
04850   case ImplicitConversionSequence::StandardConversion:
04851     if (!CheckConvertedConstantConversions(*this, ICS.Standard))
04852       return Diag(From->getLocStart(),
04853                   diag::err_typecheck_converted_constant_expression_disallowed)
04854                << From->getType() << From->getSourceRange() << T;
04855     SCS = &ICS.Standard;
04856     break;
04857   case ImplicitConversionSequence::UserDefinedConversion:
04858     // We are converting from class type to an integral or enumeration type, so
04859     // the Before sequence must be trivial.
04860     if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
04861       return Diag(From->getLocStart(),
04862                   diag::err_typecheck_converted_constant_expression_disallowed)
04863                << From->getType() << From->getSourceRange() << T;
04864     SCS = &ICS.UserDefined.After;
04865     break;
04866   case ImplicitConversionSequence::AmbiguousConversion:
04867   case ImplicitConversionSequence::BadConversion:
04868     if (!DiagnoseMultipleUserDefinedConversion(From, T))
04869       return Diag(From->getLocStart(),
04870                   diag::err_typecheck_converted_constant_expression)
04871                     << From->getType() << From->getSourceRange() << T;
04872     return ExprError();
04873 
04874   case ImplicitConversionSequence::EllipsisConversion:
04875     llvm_unreachable("ellipsis conversion in converted constant expression");
04876   }
04877 
04878   ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
04879   if (Result.isInvalid())
04880     return Result;
04881 
04882   // Check for a narrowing implicit conversion.
04883   APValue PreNarrowingValue;
04884   QualType PreNarrowingType;
04885   switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
04886                                 PreNarrowingType)) {
04887   case NK_Variable_Narrowing:
04888     // Implicit conversion to a narrower type, and the value is not a constant
04889     // expression. We'll diagnose this in a moment.
04890   case NK_Not_Narrowing:
04891     break;
04892 
04893   case NK_Constant_Narrowing:
04894     Diag(From->getLocStart(),
04895          isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
04896                              diag::err_cce_narrowing)
04897       << CCE << /*Constant*/1
04898       << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
04899     break;
04900 
04901   case NK_Type_Narrowing:
04902     Diag(From->getLocStart(),
04903          isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
04904                              diag::err_cce_narrowing)
04905       << CCE << /*Constant*/0 << From->getType() << T;
04906     break;
04907   }
04908 
04909   // Check the expression is a constant expression.
04910   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
04911   Expr::EvalResult Eval;
04912   Eval.Diag = &Notes;
04913 
04914   if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
04915     // The expression can't be folded, so we can't keep it at this position in
04916     // the AST.
04917     Result = ExprError();
04918   } else {
04919     Value = Eval.Val.getInt();
04920 
04921     if (Notes.empty()) {
04922       // It's a constant expression.
04923       return Result;
04924     }
04925   }
04926 
04927   // It's not a constant expression. Produce an appropriate diagnostic.
04928   if (Notes.size() == 1 &&
04929       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
04930     Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
04931   else {
04932     Diag(From->getLocStart(), diag::err_expr_not_cce)
04933       << CCE << From->getSourceRange();
04934     for (unsigned I = 0; I < Notes.size(); ++I)
04935       Diag(Notes[I].first, Notes[I].second);
04936   }
04937   return Result;
04938 }
04939 
04940 /// dropPointerConversions - If the given standard conversion sequence
04941 /// involves any pointer conversions, remove them.  This may change
04942 /// the result type of the conversion sequence.
04943 static void dropPointerConversion(StandardConversionSequence &SCS) {
04944   if (SCS.Second == ICK_Pointer_Conversion) {
04945     SCS.Second = ICK_Identity;
04946     SCS.Third = ICK_Identity;
04947     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
04948   }
04949 }
04950 
04951 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
04952 /// convert the expression From to an Objective-C pointer type.
04953 static ImplicitConversionSequence
04954 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
04955   // Do an implicit conversion to 'id'.
04956   QualType Ty = S.Context.getObjCIdType();
04957   ImplicitConversionSequence ICS
04958     = TryImplicitConversion(S, From, Ty,
04959                             // FIXME: Are these flags correct?
04960                             /*SuppressUserConversions=*/false,
04961                             /*AllowExplicit=*/true,
04962                             /*InOverloadResolution=*/false,
04963                             /*CStyle=*/false,
04964                             /*AllowObjCWritebackConversion=*/false);
04965 
04966   // Strip off any final conversions to 'id'.
04967   switch (ICS.getKind()) {
04968   case ImplicitConversionSequence::BadConversion:
04969   case ImplicitConversionSequence::AmbiguousConversion:
04970   case ImplicitConversionSequence::EllipsisConversion:
04971     break;
04972 
04973   case ImplicitConversionSequence::UserDefinedConversion:
04974     dropPointerConversion(ICS.UserDefined.After);
04975     break;
04976 
04977   case ImplicitConversionSequence::StandardConversion:
04978     dropPointerConversion(ICS.Standard);
04979     break;
04980   }
04981 
04982   return ICS;
04983 }
04984 
04985 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
04986 /// conversion of the expression From to an Objective-C pointer type.
04987 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
04988   if (checkPlaceholderForOverload(*this, From))
04989     return ExprError();
04990 
04991   QualType Ty = Context.getObjCIdType();
04992   ImplicitConversionSequence ICS =
04993     TryContextuallyConvertToObjCPointer(*this, From);
04994   if (!ICS.isBad())
04995     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
04996   return ExprError();
04997 }
04998 
04999 /// Determine whether the provided type is an integral type, or an enumeration
05000 /// type of a permitted flavor.
05001 static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
05002   return AllowScopedEnum ? T->isIntegralOrEnumerationType()
05003                          : T->isIntegralOrUnscopedEnumerationType();
05004 }
05005 
05006 /// \brief Attempt to convert the given expression to an integral or
05007 /// enumeration type.
05008 ///
05009 /// This routine will attempt to convert an expression of class type to an
05010 /// integral or enumeration type, if that class type only has a single
05011 /// conversion to an integral or enumeration type.
05012 ///
05013 /// \param Loc The source location of the construct that requires the
05014 /// conversion.
05015 ///
05016 /// \param FromE The expression we're converting from.
05017 ///
05018 /// \param NotIntDiag The diagnostic to be emitted if the expression does not
05019 /// have integral or enumeration type.
05020 ///
05021 /// \param IncompleteDiag The diagnostic to be emitted if the expression has
05022 /// incomplete class type.
05023 ///
05024 /// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
05025 /// explicit conversion function (because no implicit conversion functions
05026 /// were available). This is a recovery mode.
05027 ///
05028 /// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
05029 /// showing which conversion was picked.
05030 ///
05031 /// \param AmbigDiag The diagnostic to be emitted if there is more than one
05032 /// conversion function that could convert to integral or enumeration type.
05033 ///
05034 /// \param AmbigNote The note to be emitted with \p AmbigDiag for each
05035 /// usable conversion function.
05036 ///
05037 /// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
05038 /// function, which may be an extension in this case.
05039 ///
05040 /// \param AllowScopedEnumerations Specifies whether conversions to scoped
05041 /// enumerations should be considered.
05042 ///
05043 /// \returns The expression, converted to an integral or enumeration type if
05044 /// successful.
05045 ExprResult
05046 Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
05047                                          ICEConvertDiagnoser &Diagnoser,
05048                                          bool AllowScopedEnumerations) {
05049   // We can't perform any more checking for type-dependent expressions.
05050   if (From->isTypeDependent())
05051     return Owned(From);
05052 
05053   // Process placeholders immediately.
05054   if (From->hasPlaceholderType()) {
05055     ExprResult result = CheckPlaceholderExpr(From);
05056     if (result.isInvalid()) return result;
05057     From = result.take();
05058   }
05059 
05060   // If the expression already has integral or enumeration type, we're golden.
05061   QualType T = From->getType();
05062   if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
05063     return DefaultLvalueConversion(From);
05064 
05065   // FIXME: Check for missing '()' if T is a function type?
05066 
05067   // If we don't have a class type in C++, there's no way we can get an
05068   // expression of integral or enumeration type.
05069   const RecordType *RecordTy = T->getAs<RecordType>();
05070   if (!RecordTy || !getLangOpts().CPlusPlus) {
05071     if (!Diagnoser.Suppress)
05072       Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
05073     return Owned(From);
05074   }
05075 
05076   // We must have a complete class type.
05077   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
05078     ICEConvertDiagnoser &Diagnoser;
05079     Expr *From;
05080     
05081     TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
05082       : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
05083     
05084     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
05085       Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
05086     }
05087   } IncompleteDiagnoser(Diagnoser, From);
05088 
05089   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
05090     return Owned(From);
05091 
05092   // Look for a conversion to an integral or enumeration type.
05093   UnresolvedSet<4> ViableConversions;
05094   UnresolvedSet<4> ExplicitConversions;
05095   const UnresolvedSetImpl *Conversions
05096     = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
05097 
05098   bool HadMultipleCandidates = (Conversions->size() > 1);
05099 
05100   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
05101                                    E = Conversions->end();
05102        I != E;
05103        ++I) {
05104     if (CXXConversionDecl *Conversion
05105           = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
05106       if (isIntegralOrEnumerationType(
05107             Conversion->getConversionType().getNonReferenceType(),
05108             AllowScopedEnumerations)) {
05109         if (Conversion->isExplicit())
05110           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
05111         else
05112           ViableConversions.addDecl(I.getDecl(), I.getAccess());
05113       }
05114     }
05115   }
05116 
05117   switch (ViableConversions.size()) {
05118   case 0:
05119     if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
05120       DeclAccessPair Found = ExplicitConversions[0];
05121       CXXConversionDecl *Conversion
05122         = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
05123 
05124       // The user probably meant to invoke the given explicit
05125       // conversion; use it.
05126       QualType ConvTy
05127         = Conversion->getConversionType().getNonReferenceType();
05128       std::string TypeStr;
05129       ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
05130 
05131       Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
05132         << FixItHint::CreateInsertion(From->getLocStart(),
05133                                       "static_cast<" + TypeStr + ">(")
05134         << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
05135                                       ")");
05136       Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
05137 
05138       // If we aren't in a SFINAE context, build a call to the
05139       // explicit conversion function.
05140       if (isSFINAEContext())
05141         return ExprError();
05142 
05143       CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
05144       ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
05145                                                  HadMultipleCandidates);
05146       if (Result.isInvalid())
05147         return ExprError();
05148       // Record usage of conversion in an implicit cast.
05149       From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
05150                                       CK_UserDefinedConversion,
05151                                       Result.get(), 0,
05152                                       Result.get()->getValueKind());
05153     }
05154 
05155     // We'll complain below about a non-integral condition type.
05156     break;
05157 
05158   case 1: {
05159     // Apply this conversion.
05160     DeclAccessPair Found = ViableConversions[0];
05161     CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
05162 
05163     CXXConversionDecl *Conversion
05164       = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
05165     QualType ConvTy
05166       = Conversion->getConversionType().getNonReferenceType();
05167     if (!Diagnoser.SuppressConversion) {
05168       if (isSFINAEContext())
05169         return ExprError();
05170 
05171       Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
05172         << From->getSourceRange();
05173     }
05174 
05175     ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
05176                                                HadMultipleCandidates);
05177     if (Result.isInvalid())
05178       return ExprError();
05179     // Record usage of conversion in an implicit cast.
05180     From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
05181                                     CK_UserDefinedConversion,
05182                                     Result.get(), 0,
05183                                     Result.get()->getValueKind());
05184     break;
05185   }
05186 
05187   default:
05188     if (Diagnoser.Suppress)
05189       return ExprError();
05190 
05191     Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
05192     for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
05193       CXXConversionDecl *Conv
05194         = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
05195       QualType ConvTy = Conv->getConversionType().getNonReferenceType();
05196       Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
05197     }
05198     return Owned(From);
05199   }
05200 
05201   if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
05202       !Diagnoser.Suppress) {
05203     Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
05204       << From->getSourceRange();
05205   }
05206 
05207   return DefaultLvalueConversion(From);
05208 }
05209 
05210 /// AddOverloadCandidate - Adds the given function to the set of
05211 /// candidate functions, using the given function call arguments.  If
05212 /// @p SuppressUserConversions, then don't allow user-defined
05213 /// conversions via constructors or conversion operators.
05214 ///
05215 /// \para PartialOverloading true if we are performing "partial" overloading
05216 /// based on an incomplete set of function arguments. This feature is used by
05217 /// code completion.
05218 void
05219 Sema::AddOverloadCandidate(FunctionDecl *Function,
05220                            DeclAccessPair FoundDecl,
05221                            llvm::ArrayRef<Expr *> Args,
05222                            OverloadCandidateSet& CandidateSet,
05223                            bool SuppressUserConversions,
05224                            bool PartialOverloading,
05225                            bool AllowExplicit) {
05226   const FunctionProtoType* Proto
05227     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
05228   assert(Proto && "Functions without a prototype cannot be overloaded");
05229   assert(!Function->getDescribedFunctionTemplate() &&
05230          "Use AddTemplateOverloadCandidate for function templates");
05231 
05232   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
05233     if (!isa<CXXConstructorDecl>(Method)) {
05234       // If we get here, it's because we're calling a member function
05235       // that is named without a member access expression (e.g.,
05236       // "this->f") that was either written explicitly or created
05237       // implicitly. This can happen with a qualified call to a member
05238       // function, e.g., X::f(). We use an empty type for the implied
05239       // object argument (C++ [over.call.func]p3), and the acting context
05240       // is irrelevant.
05241       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
05242                          QualType(), Expr::Classification::makeSimpleLValue(),
05243                          Args, CandidateSet, SuppressUserConversions);
05244       return;
05245     }
05246     // We treat a constructor like a non-member function, since its object
05247     // argument doesn't participate in overload resolution.
05248   }
05249 
05250   if (!CandidateSet.isNewCandidate(Function))
05251     return;
05252 
05253   // Overload resolution is always an unevaluated context.
05254   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
05255 
05256   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
05257     // C++ [class.copy]p3:
05258     //   A member function template is never instantiated to perform the copy
05259     //   of a class object to an object of its class type.
05260     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
05261     if (Args.size() == 1 &&
05262         Constructor->isSpecializationCopyingObject() &&
05263         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
05264          IsDerivedFrom(Args[0]->getType(), ClassType)))
05265       return;
05266   }
05267 
05268   // Add this candidate
05269   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
05270   Candidate.FoundDecl = FoundDecl;
05271   Candidate.Function = Function;
05272   Candidate.Viable = true;
05273   Candidate.IsSurrogate = false;
05274   Candidate.IgnoreObjectArgument = false;
05275   Candidate.ExplicitCallArguments = Args.size();
05276 
05277   unsigned NumArgsInProto = Proto->getNumArgs();
05278 
05279   // (C++ 13.3.2p2): A candidate function having fewer than m
05280   // parameters is viable only if it has an ellipsis in its parameter
05281   // list (8.3.5).
05282   if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
05283       !Proto->isVariadic()) {
05284     Candidate.Viable = false;
05285     Candidate.FailureKind = ovl_fail_too_many_arguments;
05286     return;
05287   }
05288 
05289   // (C++ 13.3.2p2): A candidate function having more than m parameters
05290   // is viable only if the (m+1)st parameter has a default argument
05291   // (8.3.6). For the purposes of overload resolution, the
05292   // parameter list is truncated on the right, so that there are
05293   // exactly m parameters.
05294   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
05295   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
05296     // Not enough arguments.
05297     Candidate.Viable = false;
05298     Candidate.FailureKind = ovl_fail_too_few_arguments;
05299     return;
05300   }
05301 
05302   // (CUDA B.1): Check for invalid calls between targets.
05303   if (getLangOpts().CUDA)
05304     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
05305       if (CheckCUDATarget(Caller, Function)) {
05306         Candidate.Viable = false;
05307         Candidate.FailureKind = ovl_fail_bad_target;
05308         return;
05309       }
05310 
05311   // Determine the implicit conversion sequences for each of the
05312   // arguments.
05313   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
05314     if (ArgIdx < NumArgsInProto) {
05315       // (C++ 13.3.2p3): for F to be a viable function, there shall
05316       // exist for each argument an implicit conversion sequence
05317       // (13.3.3.1) that converts that argument to the corresponding
05318       // parameter of F.
05319       QualType ParamType = Proto->getArgType(ArgIdx);
05320       Candidate.Conversions[ArgIdx]
05321         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
05322                                 SuppressUserConversions,
05323                                 /*InOverloadResolution=*/true,
05324                                 /*AllowObjCWritebackConversion=*/
05325                                   getLangOpts().ObjCAutoRefCount,
05326                                 AllowExplicit);
05327       if (Candidate.Conversions[ArgIdx].isBad()) {
05328         Candidate.Viable = false;
05329         Candidate.FailureKind = ovl_fail_bad_conversion;
05330         break;
05331       }
05332     } else {
05333       // (C++ 13.3.2p2): For the purposes of overload resolution, any
05334       // argument for which there is no corresponding parameter is
05335       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
05336       Candidate.Conversions[ArgIdx].setEllipsis();
05337     }
05338   }
05339 }
05340 
05341 /// \brief Add all of the function declarations in the given function set to
05342 /// the overload canddiate set.
05343 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
05344                                  llvm::ArrayRef<Expr *> Args,
05345                                  OverloadCandidateSet& CandidateSet,
05346                                  bool SuppressUserConversions,
05347                                TemplateArgumentListInfo *ExplicitTemplateArgs) {
05348   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
05349     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
05350     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
05351       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
05352         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
05353                            cast<CXXMethodDecl>(FD)->getParent(),
05354                            Args[0]->getType(), Args[0]->Classify(Context),
05355                            Args.slice(1), CandidateSet,
05356                            SuppressUserConversions);
05357       else
05358         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
05359                              SuppressUserConversions);
05360     } else {
05361       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
05362       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
05363           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
05364         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
05365                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
05366                                    ExplicitTemplateArgs,
05367                                    Args[0]->getType(),
05368                                    Args[0]->Classify(Context), Args.slice(1),
05369                                    CandidateSet, SuppressUserConversions);
05370       else
05371         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
05372                                      ExplicitTemplateArgs, Args,
05373                                      CandidateSet, SuppressUserConversions);
05374     }
05375   }
05376 }
05377 
05378 /// AddMethodCandidate - Adds a named decl (which is some kind of
05379 /// method) as a method candidate to the given overload set.
05380 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
05381                               QualType ObjectType,
05382                               Expr::Classification ObjectClassification,
05383                               Expr **Args, unsigned NumArgs,
05384                               OverloadCandidateSet& CandidateSet,
05385                               bool SuppressUserConversions) {
05386   NamedDecl *Decl = FoundDecl.getDecl();
05387   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
05388 
05389   if (isa<UsingShadowDecl>(Decl))
05390     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
05391 
05392   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
05393     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
05394            "Expected a member function template");
05395     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
05396                                /*ExplicitArgs*/ 0,
05397                                ObjectType, ObjectClassification,
05398                                llvm::makeArrayRef(Args, NumArgs), CandidateSet,
05399                                SuppressUserConversions);
05400   } else {
05401     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
05402                        ObjectType, ObjectClassification,
05403                        llvm::makeArrayRef(Args, NumArgs),
05404                        CandidateSet, SuppressUserConversions);
05405   }
05406 }
05407 
05408 /// AddMethodCandidate - Adds the given C++ member function to the set
05409 /// of candidate functions, using the given function call arguments
05410 /// and the object argument (@c Object). For example, in a call
05411 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
05412 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
05413 /// allow user-defined conversions via constructors or conversion
05414 /// operators.
05415 void
05416 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
05417                          CXXRecordDecl *ActingContext, QualType ObjectType,
05418                          Expr::Classification ObjectClassification,
05419                          llvm::ArrayRef<Expr *> Args,
05420                          OverloadCandidateSet& CandidateSet,
05421                          bool SuppressUserConversions) {
05422   const FunctionProtoType* Proto
05423     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
05424   assert(Proto && "Methods without a prototype cannot be overloaded");
05425   assert(!isa<CXXConstructorDecl>(Method) &&
05426          "Use AddOverloadCandidate for constructors");
05427 
05428   if (!CandidateSet.isNewCandidate(Method))
05429     return;
05430 
05431   // Overload resolution is always an unevaluated context.
05432   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
05433 
05434   // Add this candidate
05435   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
05436   Candidate.FoundDecl = FoundDecl;
05437   Candidate.Function = Method;
05438   Candidate.IsSurrogate = false;
05439   Candidate.IgnoreObjectArgument = false;
05440   Candidate.ExplicitCallArguments = Args.size();
05441 
05442   unsigned NumArgsInProto = Proto->getNumArgs();
05443 
05444   // (C++ 13.3.2p2): A candidate function having fewer than m
05445   // parameters is viable only if it has an ellipsis in its parameter
05446   // list (8.3.5).
05447   if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
05448     Candidate.Viable = false;
05449     Candidate.FailureKind = ovl_fail_too_many_arguments;
05450     return;
05451   }
05452 
05453   // (C++ 13.3.2p2): A candidate function having more than m parameters
05454   // is viable only if the (m+1)st parameter has a default argument
05455   // (8.3.6). For the purposes of overload resolution, the
05456   // parameter list is truncated on the right, so that there are
05457   // exactly m parameters.
05458   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
05459   if (Args.size() < MinRequiredArgs) {
05460     // Not enough arguments.
05461     Candidate.Viable = false;
05462     Candidate.FailureKind = ovl_fail_too_few_arguments;
05463     return;
05464   }
05465 
05466   Candidate.Viable = true;
05467 
05468   if (Method->isStatic() || ObjectType.isNull())
05469     // The implicit object argument is ignored.
05470     Candidate.IgnoreObjectArgument = true;
05471   else {
05472     // Determine the implicit conversion sequence for the object
05473     // parameter.
05474     Candidate.Conversions[0]
05475       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
05476                                         Method, ActingContext);
05477     if (Candidate.Conversions[0].isBad()) {
05478       Candidate.Viable = false;
05479       Candidate.FailureKind = ovl_fail_bad_conversion;
05480       return;
05481     }
05482   }
05483 
05484   // Determine the implicit conversion sequences for each of the
05485   // arguments.
05486   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
05487     if (ArgIdx < NumArgsInProto) {
05488       // (C++ 13.3.2p3): for F to be a viable function, there shall
05489       // exist for each argument an implicit conversion sequence
05490       // (13.3.3.1) that converts that argument to the corresponding
05491       // parameter of F.
05492       QualType ParamType = Proto->getArgType(ArgIdx);
05493       Candidate.Conversions[ArgIdx + 1]
05494         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
05495                                 SuppressUserConversions,
05496                                 /*InOverloadResolution=*/true,
05497                                 /*AllowObjCWritebackConversion=*/
05498                                   getLangOpts().ObjCAutoRefCount);
05499       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
05500         Candidate.Viable = false;
05501         Candidate.FailureKind = ovl_fail_bad_conversion;
05502         break;
05503       }
05504     } else {
05505       // (C++ 13.3.2p2): For the purposes of overload resolution, any
05506       // argument for which there is no corresponding parameter is
05507       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
05508       Candidate.Conversions[ArgIdx + 1].setEllipsis();
05509     }
05510   }
05511 }
05512 
05513 /// \brief Add a C++ member function template as a candidate to the candidate
05514 /// set, using template argument deduction to produce an appropriate member
05515 /// function template specialization.
05516 void
05517 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
05518                                  DeclAccessPair FoundDecl,
05519                                  CXXRecordDecl *ActingContext,
05520                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
05521                                  QualType ObjectType,
05522                                  Expr::Classification ObjectClassification,
05523                                  llvm::ArrayRef<Expr *> Args,
05524                                  OverloadCandidateSet& CandidateSet,
05525                                  bool SuppressUserConversions) {
05526   if (!CandidateSet.isNewCandidate(MethodTmpl))
05527     return;
05528 
05529   // C++ [over.match.funcs]p7:
05530   //   In each case where a candidate is a function template, candidate
05531   //   function template specializations are generated using template argument
05532   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
05533   //   candidate functions in the usual way.113) A given name can refer to one
05534   //   or more function templates and also to a set of overloaded non-template
05535   //   functions. In such a case, the candidate functions generated from each
05536   //   function template are combined with the set of non-template candidate
05537   //   functions.
05538   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
05539   FunctionDecl *Specialization = 0;
05540   if (TemplateDeductionResult Result
05541       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
05542                                 Specialization, Info)) {
05543     OverloadCandidate &Candidate = CandidateSet.addCandidate();
05544     Candidate.FoundDecl = FoundDecl;
05545     Candidate.Function = MethodTmpl->getTemplatedDecl();
05546     Candidate.Viable = false;
05547     Candidate.FailureKind = ovl_fail_bad_deduction;
05548     Candidate.IsSurrogate = false;
05549     Candidate.IgnoreObjectArgument = false;
05550     Candidate.ExplicitCallArguments = Args.size();
05551     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
05552                                                           Info);
05553     return;
05554   }
05555 
05556   // Add the function template specialization produced by template argument
05557   // deduction as a candidate.
05558   assert(Specialization && "Missing member function template specialization?");
05559   assert(isa<CXXMethodDecl>(Specialization) &&
05560          "Specialization is not a member function?");
05561   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
05562                      ActingContext, ObjectType, ObjectClassification, Args,
05563                      CandidateSet, SuppressUserConversions);
05564 }
05565 
05566 /// \brief Add a C++ function template specialization as a candidate
05567 /// in the candidate set, using template argument deduction to produce
05568 /// an appropriate function template specialization.
05569 void
05570 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
05571                                    DeclAccessPair FoundDecl,
05572                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
05573                                    llvm::ArrayRef<Expr *> Args,
05574                                    OverloadCandidateSet& CandidateSet,
05575                                    bool SuppressUserConversions) {
05576   if (!CandidateSet.isNewCandidate(FunctionTemplate))
05577     return;
05578 
05579   // C++ [over.match.funcs]p7:
05580   //   In each case where a candidate is a function template, candidate
05581   //   function template specializations are generated using template argument
05582   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
05583   //   candidate functions in the usual way.113) A given name can refer to one
05584   //   or more function templates and also to a set of overloaded non-template
05585   //   functions. In such a case, the candidate functions generated from each
05586   //   function template are combined with the set of non-template candidate
05587   //   functions.
05588   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
05589   FunctionDecl *Specialization = 0;
05590   if (TemplateDeductionResult Result
05591         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
05592                                   Specialization, Info)) {
05593     OverloadCandidate &Candidate = CandidateSet.addCandidate();
05594     Candidate.FoundDecl = FoundDecl;
05595     Candidate.Function = FunctionTemplate->getTemplatedDecl();
05596     Candidate.Viable = false;
05597     Candidate.FailureKind = ovl_fail_bad_deduction;
05598     Candidate.IsSurrogate = false;
05599     Candidate.IgnoreObjectArgument = false;
05600     Candidate.ExplicitCallArguments = Args.size();
05601     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
05602                                                           Info);
05603     return;
05604   }
05605 
05606   // Add the function template specialization produced by template argument
05607   // deduction as a candidate.
05608   assert(Specialization && "Missing function template specialization?");
05609   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
05610                        SuppressUserConversions);
05611 }
05612 
05613 /// AddConversionCandidate - Add a C++ conversion function as a
05614 /// candidate in the candidate set (C++ [over.match.conv],
05615 /// C++ [over.match.copy]). From is the expression we're converting from,
05616 /// and ToType is the type that we're eventually trying to convert to
05617 /// (which may or may not be the same type as the type that the
05618 /// conversion function produces).
05619 void
05620 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
05621                              DeclAccessPair FoundDecl,
05622                              CXXRecordDecl *ActingContext,
05623                              Expr *From, QualType ToType,
05624                              OverloadCandidateSet& CandidateSet) {
05625   assert(!Conversion->getDescribedFunctionTemplate() &&
05626          "Conversion function templates use AddTemplateConversionCandidate");
05627   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
05628   if (!CandidateSet.isNewCandidate(Conversion))
05629     return;
05630 
05631   // Overload resolution is always an unevaluated context.
05632   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
05633 
05634   // Add this candidate
05635   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
05636   Candidate.FoundDecl = FoundDecl;
05637   Candidate.Function = Conversion;
05638   Candidate.IsSurrogate = false;
05639   Candidate.IgnoreObjectArgument = false;
05640   Candidate.FinalConversion.setAsIdentityConversion();
05641   Candidate.FinalConversion.setFromType(ConvType);
05642   Candidate.FinalConversion.setAllToTypes(ToType);
05643   Candidate.Viable = true;
05644   Candidate.ExplicitCallArguments = 1;
05645 
05646   // C++ [over.match.funcs]p4:
05647   //   For conversion functions, the function is considered to be a member of
05648   //   the class of the implicit implied object argument for the purpose of
05649   //   defining the type of the implicit object parameter.
05650   //
05651   // Determine the implicit conversion sequence for the implicit
05652   // object parameter.
05653   QualType ImplicitParamType = From->getType();
05654   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
05655     ImplicitParamType = FromPtrType->getPointeeType();
05656   CXXRecordDecl *ConversionContext
05657     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
05658 
05659   Candidate.Conversions[0]
05660     = TryObjectArgumentInitialization(*this, From->getType(),
05661                                       From->Classify(Context),
05662                                       Conversion, ConversionContext);
05663 
05664   if (Candidate.Conversions[0].isBad()) {
05665     Candidate.Viable = false;
05666     Candidate.FailureKind = ovl_fail_bad_conversion;
05667     return;
05668   }
05669 
05670   // We won't go through a user-define type conversion function to convert a
05671   // derived to base as such conversions are given Conversion Rank. They only
05672   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
05673   QualType FromCanon
05674     = Context.getCanonicalType(From->getType().getUnqualifiedType());
05675   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
05676   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
05677     Candidate.Viable = false;
05678     Candidate.FailureKind = ovl_fail_trivial_conversion;
05679     return;
05680   }
05681 
05682   // To determine what the conversion from the result of calling the
05683   // conversion function to the type we're eventually trying to
05684   // convert to (ToType), we need to synthesize a call to the
05685   // conversion function and attempt copy initialization from it. This
05686   // makes sure that we get the right semantics with respect to
05687   // lvalues/rvalues and the type. Fortunately, we can allocate this
05688   // call on the stack and we don't need its arguments to be
05689   // well-formed.
05690   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
05691                             VK_LValue, From->getLocStart());
05692   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
05693                                 Context.getPointerType(Conversion->getType()),
05694                                 CK_FunctionToPointerDecay,
05695                                 &ConversionRef, VK_RValue);
05696 
05697   QualType ConversionType = Conversion->getConversionType();
05698   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
05699     Candidate.Viable = false;
05700     Candidate.FailureKind = ovl_fail_bad_final_conversion;
05701     return;
05702   }
05703 
05704   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
05705 
05706   // Note that it is safe to allocate CallExpr on the stack here because
05707   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
05708   // allocator).
05709   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
05710   CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
05711                 From->getLocStart());
05712   ImplicitConversionSequence ICS =
05713     TryCopyInitialization(*this, &Call, ToType,
05714                           /*SuppressUserConversions=*/true,
05715                           /*InOverloadResolution=*/false,
05716                           /*AllowObjCWritebackConversion=*/false);
05717 
05718   switch (ICS.getKind()) {
05719   case ImplicitConversionSequence::StandardConversion:
05720     Candidate.FinalConversion = ICS.Standard;
05721 
05722     // C++ [over.ics.user]p3:
05723     //   If the user-defined conversion is specified by a specialization of a
05724     //   conversion function template, the second standard conversion sequence
05725     //   shall have exact match rank.
05726     if (Conversion->getPrimaryTemplate() &&
05727         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
05728       Candidate.Viable = false;
05729       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
05730     }
05731 
05732     // C++0x [dcl.init.ref]p5:
05733     //    In the second case, if the reference is an rvalue reference and
05734     //    the second standard conversion sequence of the user-defined
05735     //    conversion sequence includes an lvalue-to-rvalue conversion, the
05736     //    program is ill-formed.
05737     if (ToType->isRValueReferenceType() &&
05738         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
05739       Candidate.Viable = false;
05740       Candidate.FailureKind = ovl_fail_bad_final_conversion;
05741     }
05742     break;
05743 
05744   case ImplicitConversionSequence::BadConversion:
05745     Candidate.Viable = false;
05746     Candidate.FailureKind = ovl_fail_bad_final_conversion;
05747     break;
05748 
05749   default:
05750     llvm_unreachable(
05751            "Can only end up with a standard conversion sequence or failure");
05752   }
05753 }
05754 
05755 /// \brief Adds a conversion function template specialization
05756 /// candidate to the overload set, using template argument deduction
05757 /// to deduce the template arguments of the conversion function
05758 /// template from the type that we are converting to (C++
05759 /// [temp.deduct.conv]).
05760 void
05761 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
05762                                      DeclAccessPair FoundDecl,
05763                                      CXXRecordDecl *ActingDC,
05764                                      Expr *From, QualType ToType,
05765                                      OverloadCandidateSet &CandidateSet) {
05766   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
05767          "Only conversion function templates permitted here");
05768 
05769   if (!CandidateSet.isNewCandidate(FunctionTemplate))
05770     return;
05771 
05772   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
05773   CXXConversionDecl *Specialization = 0;
05774   if (TemplateDeductionResult Result
05775         = DeduceTemplateArguments(FunctionTemplate, ToType,
05776                                   Specialization, Info)) {
05777     OverloadCandidate &Candidate = CandidateSet.addCandidate();
05778     Candidate.FoundDecl = FoundDecl;
05779     Candidate.Function = FunctionTemplate->getTemplatedDecl();
05780     Candidate.Viable = false;
05781     Candidate.FailureKind = ovl_fail_bad_deduction;
05782     Candidate.IsSurrogate = false;
05783     Candidate.IgnoreObjectArgument = false;
05784     Candidate.ExplicitCallArguments = 1;
05785     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
05786                                                           Info);
05787     return;
05788   }
05789 
05790   // Add the conversion function template specialization produced by
05791   // template argument deduction as a candidate.
05792   assert(Specialization && "Missing function template specialization?");
05793   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
05794                          CandidateSet);
05795 }
05796 
05797 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
05798 /// converts the given @c Object to a function pointer via the
05799 /// conversion function @c Conversion, and then attempts to call it
05800 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
05801 /// the type of function that we'll eventually be calling.
05802 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
05803                                  DeclAccessPair FoundDecl,
05804                                  CXXRecordDecl *ActingContext,
05805                                  const FunctionProtoType *Proto,
05806                                  Expr *Object,
05807                                  llvm::ArrayRef<Expr *> Args,
05808                                  OverloadCandidateSet& CandidateSet) {
05809   if (!CandidateSet.isNewCandidate(Conversion))
05810     return;
05811 
05812   // Overload resolution is always an unevaluated context.
05813   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
05814 
05815   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
05816   Candidate.FoundDecl = FoundDecl;
05817   Candidate.Function = 0;
05818   Candidate.Surrogate = Conversion;
05819   Candidate.Viable = true;
05820   Candidate.IsSurrogate = true;
05821   Candidate.IgnoreObjectArgument = false;
05822   Candidate.ExplicitCallArguments = Args.size();
05823 
05824   // Determine the implicit conversion sequence for the implicit
05825   // object parameter.
05826   ImplicitConversionSequence ObjectInit
05827     = TryObjectArgumentInitialization(*this, Object->getType(),
05828                                       Object->Classify(Context),
05829                                       Conversion, ActingContext);
05830   if (ObjectInit.isBad()) {
05831     Candidate.Viable = false;
05832     Candidate.FailureKind = ovl_fail_bad_conversion;
05833     Candidate.Conversions[0] = ObjectInit;
05834     return;
05835   }
05836 
05837   // The first conversion is actually a user-defined conversion whose
05838   // first conversion is ObjectInit's standard conversion (which is
05839   // effectively a reference binding). Record it as such.
05840   Candidate.Conversions[0].setUserDefined();
05841   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
05842   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
05843   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
05844   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
05845   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
05846   Candidate.Conversions[0].UserDefined.After
05847     = Candidate.Conversions[0].UserDefined.Before;
05848   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
05849 
05850   // Find the
05851   unsigned NumArgsInProto = Proto->getNumArgs();
05852 
05853   // (C++ 13.3.2p2): A candidate function having fewer than m
05854   // parameters is viable only if it has an ellipsis in its parameter
05855   // list (8.3.5).
05856   if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
05857     Candidate.Viable = false;
05858     Candidate.FailureKind = ovl_fail_too_many_arguments;
05859     return;
05860   }
05861 
05862   // Function types don't have any default arguments, so just check if
05863   // we have enough arguments.
05864   if (Args.size() < NumArgsInProto) {
05865     // Not enough arguments.
05866     Candidate.Viable = false;
05867     Candidate.FailureKind = ovl_fail_too_few_arguments;
05868     return;
05869   }
05870 
05871   // Determine the implicit conversion sequences for each of the
05872   // arguments.
05873   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
05874     if (ArgIdx < NumArgsInProto) {
05875       // (C++ 13.3.2p3): for F to be a viable function, there shall
05876       // exist for each argument an implicit conversion sequence
05877       // (13.3.3.1) that converts that argument to the corresponding
05878       // parameter of F.
05879       QualType ParamType = Proto->getArgType(ArgIdx);
05880       Candidate.Conversions[ArgIdx + 1]
05881         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
05882                                 /*SuppressUserConversions=*/false,
05883                                 /*InOverloadResolution=*/false,
05884                                 /*AllowObjCWritebackConversion=*/
05885                                   getLangOpts().ObjCAutoRefCount);
05886       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
05887         Candidate.Viable = false;
05888         Candidate.FailureKind = ovl_fail_bad_conversion;
05889         break;
05890       }
05891     } else {
05892       // (C++ 13.3.2p2): For the purposes of overload resolution, any
05893       // argument for which there is no corresponding parameter is
05894       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
05895       Candidate.Conversions[ArgIdx + 1].setEllipsis();
05896     }
05897   }
05898 }
05899 
05900 /// \brief Add overload candidates for overloaded operators that are
05901 /// member functions.
05902 ///
05903 /// Add the overloaded operator candidates that are member functions
05904 /// for the operator Op that was used in an operator expression such
05905 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
05906 /// CandidateSet will store the added overload candidates. (C++
05907 /// [over.match.oper]).
05908 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
05909                                        SourceLocation OpLoc,
05910                                        Expr **Args, unsigned NumArgs,
05911                                        OverloadCandidateSet& CandidateSet,
05912                                        SourceRange OpRange) {
05913   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
05914 
05915   // C++ [over.match.oper]p3:
05916   //   For a unary operator @ with an operand of a type whose
05917   //   cv-unqualified version is T1, and for a binary operator @ with
05918   //   a left operand of a type whose cv-unqualified version is T1 and
05919   //   a right operand of a type whose cv-unqualified version is T2,
05920   //   three sets of candidate functions, designated member
05921   //   candidates, non-member candidates and built-in candidates, are
05922   //   constructed as follows:
05923   QualType T1 = Args[0]->getType();
05924 
05925   //     -- If T1 is a class type, the set of member candidates is the
05926   //        result of the qualified lookup of T1::operator@
05927   //        (13.3.1.1.1); otherwise, the set of member candidates is
05928   //        empty.
05929   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
05930     // Complete the type if it can be completed. Otherwise, we're done.
05931     if (RequireCompleteType(OpLoc, T1, 0))
05932       return;
05933 
05934     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
05935     LookupQualifiedName(Operators, T1Rec->getDecl());
05936     Operators.suppressDiagnostics();
05937 
05938     for (LookupResult::iterator Oper = Operators.begin(),
05939                              OperEnd = Operators.end();
05940          Oper != OperEnd;
05941          ++Oper)
05942       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
05943                          Args[0]->Classify(Context), Args + 1, NumArgs - 1,
05944                          CandidateSet,
05945                          /* SuppressUserConversions = */ false);
05946   }
05947 }
05948 
05949 /// AddBuiltinCandidate - Add a candidate for a built-in
05950 /// operator. ResultTy and ParamTys are the result and parameter types
05951 /// of the built-in candidate, respectively. Args and NumArgs are the
05952 /// arguments being passed to the candidate. IsAssignmentOperator
05953 /// should be true when this built-in candidate is an assignment
05954 /// operator. NumContextualBoolArguments is the number of arguments
05955 /// (at the beginning of the argument list) that will be contextually
05956 /// converted to bool.
05957 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
05958                                Expr **Args, unsigned NumArgs,
05959                                OverloadCandidateSet& CandidateSet,
05960                                bool IsAssignmentOperator,
05961                                unsigned NumContextualBoolArguments) {
05962   // Overload resolution is always an unevaluated context.
05963   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
05964 
05965   // Add this candidate
05966   OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
05967   Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
05968   Candidate.Function = 0;
05969   Candidate.IsSurrogate = false;
05970   Candidate.IgnoreObjectArgument = false;
05971   Candidate.BuiltinTypes.ResultTy = ResultTy;
05972   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
05973     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
05974 
05975   // Determine the implicit conversion sequences for each of the
05976   // arguments.
05977   Candidate.Viable = true;
05978   Candidate.ExplicitCallArguments = NumArgs;
05979   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
05980     // C++ [over.match.oper]p4:
05981     //   For the built-in assignment operators, conversions of the
05982     //   left operand are restricted as follows:
05983     //     -- no temporaries are introduced to hold the left operand, and
05984     //     -- no user-defined conversions are applied to the left
05985     //        operand to achieve a type match with the left-most
05986     //        parameter of a built-in candidate.
05987     //
05988     // We block these conversions by turning off user-defined
05989     // conversions, since that is the only way that initialization of
05990     // a reference to a non-class type can occur from something that
05991     // is not of the same type.
05992     if (ArgIdx < NumContextualBoolArguments) {
05993       assert(ParamTys[ArgIdx] == Context.BoolTy &&
05994              "Contextual conversion to bool requires bool type");
05995       Candidate.Conversions[ArgIdx]
05996         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
05997     } else {
05998       Candidate.Conversions[ArgIdx]
05999         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
06000                                 ArgIdx == 0 && IsAssignmentOperator,
06001                                 /*InOverloadResolution=*/false,
06002                                 /*AllowObjCWritebackConversion=*/
06003                                   getLangOpts().ObjCAutoRefCount);
06004     }
06005     if (Candidate.Conversions[ArgIdx].isBad()) {
06006       Candidate.Viable = false;
06007       Candidate.FailureKind = ovl_fail_bad_conversion;
06008       break;
06009     }
06010   }
06011 }
06012 
06013 /// BuiltinCandidateTypeSet - A set of types that will be used for the
06014 /// candidate operator functions for built-in operators (C++
06015 /// [over.built]). The types are separated into pointer types and
06016 /// enumeration types.
06017 class BuiltinCandidateTypeSet  {
06018   /// TypeSet - A set of types.
06019   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
06020 
06021   /// PointerTypes - The set of pointer types that will be used in the
06022   /// built-in candidates.
06023   TypeSet PointerTypes;
06024 
06025   /// MemberPointerTypes - The set of member pointer types that will be
06026   /// used in the built-in candidates.
06027   TypeSet MemberPointerTypes;
06028 
06029   /// EnumerationTypes - The set of enumeration types that will be
06030   /// used in the built-in candidates.
06031   TypeSet EnumerationTypes;
06032 
06033   /// \brief The set of vector types that will be used in the built-in
06034   /// candidates.
06035   TypeSet VectorTypes;
06036 
06037   /// \brief A flag indicating non-record types are viable candidates
06038   bool HasNonRecordTypes;
06039 
06040   /// \brief A flag indicating whether either arithmetic or enumeration types
06041   /// were present in the candidate set.
06042   bool HasArithmeticOrEnumeralTypes;
06043 
06044   /// \brief A flag indicating whether the nullptr type was present in the
06045   /// candidate set.
06046   bool HasNullPtrType;
06047   
06048   /// Sema - The semantic analysis instance where we are building the
06049   /// candidate type set.
06050   Sema &SemaRef;
06051 
06052   /// Context - The AST context in which we will build the type sets.
06053   ASTContext &Context;
06054 
06055   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
06056                                                const Qualifiers &VisibleQuals);
06057   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
06058 
06059 public:
06060   /// iterator - Iterates through the types that are part of the set.
06061   typedef TypeSet::iterator iterator;
06062 
06063   BuiltinCandidateTypeSet(Sema &SemaRef)
06064     : HasNonRecordTypes(false),
06065       HasArithmeticOrEnumeralTypes(false),
06066       HasNullPtrType(false),
06067       SemaRef(SemaRef),
06068       Context(SemaRef.Context) { }
06069 
06070   void AddTypesConvertedFrom(QualType Ty,
06071                              SourceLocation Loc,
06072                              bool AllowUserConversions,
06073                              bool AllowExplicitConversions,
06074                              const Qualifiers &VisibleTypeConversionsQuals);
06075 
06076   /// pointer_begin - First pointer type found;
06077   iterator pointer_begin() { return PointerTypes.begin(); }
06078 
06079   /// pointer_end - Past the last pointer type found;
06080   iterator pointer_end() { return PointerTypes.end(); }
06081 
06082   /// member_pointer_begin - First member pointer type found;
06083   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
06084 
06085   /// member_pointer_end - Past the last member pointer type found;
06086   iterator member_pointer_end() { return MemberPointerTypes.end(); }
06087 
06088   /// enumeration_begin - First enumeration type found;
06089   iterator enumeration_begin() { return EnumerationTypes.begin(); }
06090 
06091   /// enumeration_end - Past the last enumeration type found;
06092   iterator enumeration_end() { return EnumerationTypes.end(); }
06093 
06094   iterator vector_begin() { return VectorTypes.begin(); }
06095   iterator vector_end() { return VectorTypes.end(); }
06096 
06097   bool hasNonRecordTypes() { return HasNonRecordTypes; }
06098   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
06099   bool hasNullPtrType() const { return HasNullPtrType; }
06100 };
06101 
06102 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
06103 /// the set of pointer types along with any more-qualified variants of
06104 /// that type. For example, if @p Ty is "int const *", this routine
06105 /// will add "int const *", "int const volatile *", "int const
06106 /// restrict *", and "int const volatile restrict *" to the set of
06107 /// pointer types. Returns true if the add of @p Ty itself succeeded,
06108 /// false otherwise.
06109 ///
06110 /// FIXME: what to do about extended qualifiers?
06111 bool
06112 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
06113                                              const Qualifiers &VisibleQuals) {
06114 
06115   // Insert this type.
06116   if (!PointerTypes.insert(Ty))
06117     return false;
06118 
06119   QualType PointeeTy;
06120   const PointerType *PointerTy = Ty->getAs<PointerType>();
06121   bool buildObjCPtr = false;
06122   if (!PointerTy) {
06123     if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
06124       PointeeTy = PTy->getPointeeType();
06125       buildObjCPtr = true;
06126     }
06127     else
06128       llvm_unreachable("type was not a pointer type!");
06129   }
06130   else
06131     PointeeTy = PointerTy->getPointeeType();
06132 
06133   // Don't add qualified variants of arrays. For one, they're not allowed
06134   // (the qualifier would sink to the element type), and for another, the
06135   // only overload situation where it matters is subscript or pointer +- int,
06136   // and those shouldn't have qualifier variants anyway.
06137   if (PointeeTy->isArrayType())
06138     return true;
06139   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
06140   if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
06141     BaseCVR = Array->getElementType().getCVRQualifiers();
06142   bool hasVolatile = VisibleQuals.hasVolatile();
06143   bool hasRestrict = VisibleQuals.hasRestrict();
06144 
06145   // Iterate through all strict supersets of BaseCVR.
06146   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
06147     if ((CVR | BaseCVR) != CVR) continue;
06148     // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
06149     // in the types.
06150     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
06151     if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
06152     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
06153     if (!buildObjCPtr)
06154       PointerTypes.insert(Context.getPointerType(QPointeeTy));
06155     else
06156       PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
06157   }
06158 
06159   return true;
06160 }
06161 
06162 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
06163 /// to the set of pointer types along with any more-qualified variants of
06164 /// that type. For example, if @p Ty is "int const *", this routine
06165 /// will add "int const *", "int const volatile *", "int const
06166 /// restrict *", and "int const volatile restrict *" to the set of
06167 /// pointer types. Returns true if the add of @p Ty itself succeeded,
06168 /// false otherwise.
06169 ///
06170 /// FIXME: what to do about extended qualifiers?
06171 bool
06172 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
06173     QualType Ty) {
06174   // Insert this type.
06175   if (!MemberPointerTypes.insert(Ty))
06176     return false;
06177 
06178   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
06179   assert(PointerTy && "type was not a member pointer type!");
06180 
06181   QualType PointeeTy = PointerTy->getPointeeType();
06182   // Don't add qualified variants of arrays. For one, they're not allowed
06183   // (the qualifier would sink to the element type), and for another, the
06184   // only overload situation where it matters is subscript or pointer +- int,
06185   // and those shouldn't have qualifier variants anyway.
06186   if (PointeeTy->isArrayType())
06187     return true;
06188   const Type *ClassTy = PointerTy->getClass();
06189 
06190   // Iterate through all strict supersets of the pointee type's CVR
06191   // qualifiers.
06192   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
06193   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
06194     if ((CVR | BaseCVR) != CVR) continue;
06195 
06196     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
06197     MemberPointerTypes.insert(
06198       Context.getMemberPointerType(QPointeeTy, ClassTy));
06199   }
06200 
06201   return true;
06202 }
06203 
06204 /// AddTypesConvertedFrom - Add each of the types to which the type @p
06205 /// Ty can be implicit converted to the given set of @p Types. We're
06206 /// primarily interested in pointer types and enumeration types. We also
06207 /// take member pointer types, for the conditional operator.
06208 /// AllowUserConversions is true if we should look at the conversion
06209 /// functions of a class type, and AllowExplicitConversions if we
06210 /// should also include the explicit conversion functions of a class
06211 /// type.
06212 void
06213 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
06214                                                SourceLocation Loc,
06215                                                bool AllowUserConversions,
06216                                                bool AllowExplicitConversions,
06217                                                const Qualifiers &VisibleQuals) {
06218   // Only deal with canonical types.
06219   Ty = Context.getCanonicalType(Ty);
06220 
06221   // Look through reference types; they aren't part of the type of an
06222   // expression for the purposes of conversions.
06223   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
06224     Ty = RefTy->getPointeeType();
06225 
06226   // If we're dealing with an array type, decay to the pointer.
06227   if (Ty->isArrayType())
06228     Ty = SemaRef.Context.getArrayDecayedType(Ty);
06229 
06230   // Otherwise, we don't care about qualifiers on the type.
06231   Ty = Ty.getLocalUnqualifiedType();
06232 
06233   // Flag if we ever add a non-record type.
06234   const RecordType *TyRec = Ty->getAs<RecordType>();
06235   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
06236 
06237   // Flag if we encounter an arithmetic type.
06238   HasArithmeticOrEnumeralTypes =
06239     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
06240 
06241   if (Ty->isObjCIdType() || Ty->isObjCClassType())
06242     PointerTypes.insert(Ty);
06243   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
06244     // Insert our type, and its more-qualified variants, into the set
06245     // of types.
06246     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
06247       return;
06248   } else if (Ty->isMemberPointerType()) {
06249     // Member pointers are far easier, since the pointee can't be converted.
06250     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
06251       return;
06252   } else if (Ty->isEnumeralType()) {
06253     HasArithmeticOrEnumeralTypes = true;
06254     EnumerationTypes.insert(Ty);
06255   } else if (Ty->isVectorType()) {
06256     // We treat vector types as arithmetic types in many contexts as an
06257     // extension.
06258     HasArithmeticOrEnumeralTypes = true;
06259     VectorTypes.insert(Ty);
06260   } else if (Ty->isNullPtrType()) {
06261     HasNullPtrType = true;
06262   } else if (AllowUserConversions && TyRec) {
06263     // No conversion functions in incomplete types.
06264     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
06265       return;
06266 
06267     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
06268     const UnresolvedSetImpl *Conversions
06269       = ClassDecl->getVisibleConversionFunctions();
06270     for (UnresolvedSetImpl::iterator I = Conversions->begin(),
06271            E = Conversions->end(); I != E; ++I) {
06272       NamedDecl *D = I.getDecl();
06273       if (isa<UsingShadowDecl>(D))
06274         D = cast<UsingShadowDecl>(D)->getTargetDecl();
06275 
06276       // Skip conversion function templates; they don't tell us anything
06277       // about which builtin types we can convert to.
06278       if (isa<FunctionTemplateDecl>(D))
06279         continue;
06280 
06281       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
06282       if (AllowExplicitConversions || !Conv->isExplicit()) {
06283         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
06284                               VisibleQuals);
06285       }
06286     }
06287   }
06288 }
06289 
06290 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
06291 /// the volatile- and non-volatile-qualified assignment operators for the
06292 /// given type to the candidate set.
06293 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
06294                                                    QualType T,
06295                                                    Expr **Args,
06296                                                    unsigned NumArgs,
06297                                     OverloadCandidateSet &CandidateSet) {
06298   QualType ParamTypes[2];
06299 
06300   // T& operator=(T&, T)
06301   ParamTypes[0] = S.Context.getLValueReferenceType(T);
06302   ParamTypes[1] = T;
06303   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
06304                         /*IsAssignmentOperator=*/true);
06305 
06306   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
06307     // volatile T& operator=(volatile T&, T)
06308     ParamTypes[0]
06309       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
06310     ParamTypes[1] = T;
06311     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
06312                           /*IsAssignmentOperator=*/true);
06313   }
06314 }
06315 
06316 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
06317 /// if any, found in visible type conversion functions found in ArgExpr's type.
06318 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
06319     Qualifiers VRQuals;
06320     const RecordType *TyRec;
06321     if (const MemberPointerType *RHSMPType =
06322         ArgExpr->getType()->getAs<MemberPointerType>())
06323       TyRec = RHSMPType->getClass()->getAs<RecordType>();
06324     else
06325       TyRec = ArgExpr->getType()->getAs<RecordType>();
06326     if (!TyRec) {
06327       // Just to be safe, assume the worst case.
06328       VRQuals.addVolatile();
06329       VRQuals.addRestrict();
06330       return VRQuals;
06331     }
06332 
06333     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
06334     if (!ClassDecl->hasDefinition())
06335       return VRQuals;
06336 
06337     const UnresolvedSetImpl *Conversions =
06338       ClassDecl->getVisibleConversionFunctions();
06339 
06340     for (UnresolvedSetImpl::iterator I = Conversions->begin(),
06341            E = Conversions->end(); I != E; ++I) {
06342       NamedDecl *D = I.getDecl();
06343       if (isa<UsingShadowDecl>(D))
06344         D = cast<UsingShadowDecl>(D)->getTargetDecl();
06345       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
06346         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
06347         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
06348           CanTy = ResTypeRef->getPointeeType();
06349         // Need to go down the pointer/mempointer chain and add qualifiers
06350         // as see them.
06351         bool done = false;
06352         while (!done) {
06353           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
06354             CanTy = ResTypePtr->getPointeeType();
06355           else if (const MemberPointerType *ResTypeMPtr =
06356                 CanTy->getAs<MemberPointerType>())
06357             CanTy = ResTypeMPtr->getPointeeType();
06358           else
06359             done = true;
06360           if (CanTy.isVolatileQualified())
06361             VRQuals.addVolatile();
06362           if (CanTy.isRestrictQualified())
06363             VRQuals.addRestrict();
06364           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
06365             return VRQuals;
06366         }
06367       }
06368     }
06369     return VRQuals;
06370 }
06371 
06372 namespace {
06373 
06374 /// \brief Helper class to manage the addition of builtin operator overload
06375 /// candidates. It provides shared state and utility methods used throughout
06376 /// the process, as well as a helper method to add each group of builtin
06377 /// operator overloads from the standard to a candidate set.
06378 class BuiltinOperatorOverloadBuilder {
06379   // Common instance state available to all overload candidate addition methods.
06380   Sema &S;
06381   Expr **Args;
06382   unsigned NumArgs;
06383   Qualifiers VisibleTypeConversionsQuals;
06384   bool HasArithmeticOrEnumeralCandidateType;
06385   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
06386   OverloadCandidateSet &CandidateSet;
06387 
06388   // Define some constants used to index and iterate over the arithemetic types
06389   // provided via the getArithmeticType() method below.
06390   // The "promoted arithmetic types" are the arithmetic
06391   // types are that preserved by promotion (C++ [over.built]p2).
06392   static const unsigned FirstIntegralType = 3;
06393   static const unsigned LastIntegralType = 18;
06394   static const unsigned FirstPromotedIntegralType = 3,
06395                         LastPromotedIntegralType = 9;
06396   static const unsigned FirstPromotedArithmeticType = 0,
06397                         LastPromotedArithmeticType = 9;
06398   static const unsigned NumArithmeticTypes = 18;
06399 
06400   /// \brief Get the canonical type for a given arithmetic type index.
06401   CanQualType getArithmeticType(unsigned index) {
06402     assert(index < NumArithmeticTypes);
06403     static CanQualType ASTContext::* const
06404       ArithmeticTypes[NumArithmeticTypes] = {
06405       // Start of promoted types.
06406       &ASTContext::FloatTy,
06407       &ASTContext::DoubleTy,
06408       &ASTContext::LongDoubleTy,
06409 
06410       // Start of integral types.
06411       &ASTContext::IntTy,
06412       &ASTContext::LongTy,
06413       &ASTContext::LongLongTy,
06414       &ASTContext::UnsignedIntTy,
06415       &ASTContext::UnsignedLongTy,
06416       &ASTContext::UnsignedLongLongTy,
06417       // End of promoted types.
06418 
06419       &ASTContext::BoolTy,
06420       &ASTContext::CharTy,
06421       &ASTContext::WCharTy,
06422       &ASTContext::Char16Ty,
06423       &ASTContext::Char32Ty,
06424       &ASTContext::SignedCharTy,
06425       &ASTContext::ShortTy,
06426       &ASTContext::UnsignedCharTy,
06427       &ASTContext::UnsignedShortTy,
06428       // End of integral types.
06429       // FIXME: What about complex?
06430     };
06431     return S.Context.*ArithmeticTypes[index];
06432   }
06433 
06434   /// \brief Gets the canonical type resulting from the usual arithemetic
06435   /// converions for the given arithmetic types.
06436   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
06437     // Accelerator table for performing the usual arithmetic conversions.
06438     // The rules are basically:
06439     //   - if either is floating-point, use the wider floating-point
06440     //   - if same signedness, use the higher rank
06441     //   - if same size, use unsigned of the higher rank
06442     //   - use the larger type
06443     // These rules, together with the axiom that higher ranks are
06444     // never smaller, are sufficient to precompute all of these results
06445     // *except* when dealing with signed types of higher rank.
06446     // (we could precompute SLL x UI for all known platforms, but it's
06447     // better not to make any assumptions).
06448     enum PromotedType {
06449                   Flt,  Dbl, LDbl,   SI,   SL,  SLL,   UI,   UL,  ULL, Dep=-1
06450     };
06451     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
06452                                         [LastPromotedArithmeticType] = {
06453       /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
06454       /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
06455       /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
06456       /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL,   UI,   UL,  ULL },
06457       /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL,  Dep,   UL,  ULL },
06458       /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL,  Dep,  Dep,  ULL },
06459       /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep,   UI,   UL,  ULL },
06460       /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep,   UL,   UL,  ULL },
06461       /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL,  ULL,  ULL,  ULL },
06462     };
06463 
06464     assert(L < LastPromotedArithmeticType);
06465     assert(R < LastPromotedArithmeticType);
06466     int Idx = ConversionsTable[L][R];
06467 
06468     // Fast path: the table gives us a concrete answer.
06469     if (Idx != Dep) return getArithmeticType(Idx);
06470 
06471     // Slow path: we need to compare widths.
06472     // An invariant is that the signed type has higher rank.
06473     CanQualType LT = getArithmeticType(L),
06474                 RT = getArithmeticType(R);
06475     unsigned LW = S.Context.getIntWidth(LT),
06476              RW = S.Context.getIntWidth(RT);
06477 
06478     // If they're different widths, use the signed type.
06479     if (LW > RW) return LT;
06480     else if (LW < RW) return RT;
06481 
06482     // Otherwise, use the unsigned type of the signed type's rank.
06483     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
06484     assert(L == SLL || R == SLL);
06485     return S.Context.UnsignedLongLongTy;
06486   }
06487 
06488   /// \brief Helper method to factor out the common pattern of adding overloads
06489   /// for '++' and '--' builtin operators.
06490   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
06491                                            bool HasVolatile) {
06492     QualType ParamTypes[2] = {
06493       S.Context.getLValueReferenceType(CandidateTy),
06494       S.Context.IntTy
06495     };
06496 
06497     // Non-volatile version.
06498     if (NumArgs == 1)
06499       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
06500     else
06501       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
06502 
06503     // Use a heuristic to reduce number of builtin candidates in the set:
06504     // add volatile version only if there are conversions to a volatile type.
06505     if (HasVolatile) {
06506       ParamTypes[0] =
06507         S.Context.getLValueReferenceType(
06508           S.Context.getVolatileType(CandidateTy));
06509       if (NumArgs == 1)
06510         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
06511       else
06512         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
06513     }
06514   }
06515 
06516 public:
06517   BuiltinOperatorOverloadBuilder(
06518     Sema &S, Expr **Args, unsigned NumArgs,
06519     Qualifiers VisibleTypeConversionsQuals,
06520     bool HasArithmeticOrEnumeralCandidateType,
06521     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
06522     OverloadCandidateSet &CandidateSet)
06523     : S(S), Args(Args), NumArgs(NumArgs),
06524       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
06525       HasArithmeticOrEnumeralCandidateType(
06526         HasArithmeticOrEnumeralCandidateType),
06527       CandidateTypes(CandidateTypes),
06528       CandidateSet(CandidateSet) {
06529     // Validate some of our static helper constants in debug builds.
06530     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
06531            "Invalid first promoted integral type");
06532     assert(getArithmeticType(LastPromotedIntegralType - 1)
06533              == S.Context.UnsignedLongLongTy &&
06534            "Invalid last promoted integral type");
06535     assert(getArithmeticType(FirstPromotedArithmeticType)
06536              == S.Context.FloatTy &&
06537            "Invalid first promoted arithmetic type");
06538     assert(getArithmeticType(LastPromotedArithmeticType - 1)
06539              == S.Context.UnsignedLongLongTy &&
06540            "Invalid last promoted arithmetic type");
06541   }
06542 
06543   // C++ [over.built]p3:
06544   //
06545   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
06546   //   is either volatile or empty, there exist candidate operator
06547   //   functions of the form
06548   //
06549   //       VQ T&      operator++(VQ T&);
06550   //       T          operator++(VQ T&, int);
06551   //
06552   // C++ [over.built]p4:
06553   //
06554   //   For every pair (T, VQ), where T is an arithmetic type other
06555   //   than bool, and VQ is either volatile or empty, there exist
06556   //   candidate operator functions of the form
06557   //
06558   //       VQ T&      operator--(VQ T&);
06559   //       T          operator--(VQ T&, int);
06560   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
06561     if (!HasArithmeticOrEnumeralCandidateType)
06562       return;
06563 
06564     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
06565          Arith < NumArithmeticTypes; ++Arith) {
06566       addPlusPlusMinusMinusStyleOverloads(
06567         getArithmeticType(Arith),
06568         VisibleTypeConversionsQuals.hasVolatile());
06569     }
06570   }
06571 
06572   // C++ [over.built]p5:
06573   //
06574   //   For every pair (T, VQ), where T is a cv-qualified or
06575   //   cv-unqualified object type, and VQ is either volatile or
06576   //   empty, there exist candidate operator functions of the form
06577   //
06578   //       T*VQ&      operator++(T*VQ&);
06579   //       T*VQ&      operator--(T*VQ&);
06580   //       T*         operator++(T*VQ&, int);
06581   //       T*         operator--(T*VQ&, int);
06582   void addPlusPlusMinusMinusPointerOverloads() {
06583     for (BuiltinCandidateTypeSet::iterator
06584               Ptr = CandidateTypes[0].pointer_begin(),
06585            PtrEnd = CandidateTypes[0].pointer_end();
06586          Ptr != PtrEnd; ++Ptr) {
06587       // Skip pointer types that aren't pointers to object types.
06588       if (!(*Ptr)->getPointeeType()->isObjectType())
06589         continue;
06590 
06591       addPlusPlusMinusMinusStyleOverloads(*Ptr,
06592         (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
06593          VisibleTypeConversionsQuals.hasVolatile()));
06594     }
06595   }
06596 
06597   // C++ [over.built]p6:
06598   //   For every cv-qualified or cv-unqualified object type T, there
06599   //   exist candidate operator functions of the form
06600   //
06601   //       T&         operator*(T*);
06602   //
06603   // C++ [over.built]p7:
06604   //   For every function type T that does not have cv-qualifiers or a
06605   //   ref-qualifier, there exist candidate operator functions of the form
06606   //       T&         operator*(T*);
06607   void addUnaryStarPointerOverloads() {
06608     for (BuiltinCandidateTypeSet::iterator
06609               Ptr = CandidateTypes[0].pointer_begin(),
06610            PtrEnd = CandidateTypes[0].pointer_end();
06611          Ptr != PtrEnd; ++Ptr) {
06612       QualType ParamTy = *Ptr;
06613       QualType PointeeTy = ParamTy->getPointeeType();
06614       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
06615         continue;
06616 
06617       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
06618         if (Proto->getTypeQuals() || Proto->getRefQualifier())
06619           continue;
06620 
06621       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
06622                             &ParamTy, Args, 1, CandidateSet);
06623     }
06624   }
06625 
06626   // C++ [over.built]p9:
06627   //  For every promoted arithmetic type T, there exist candidate
06628   //  operator functions of the form
06629   //
06630   //       T         operator+(T);
06631   //       T         operator-(T);
06632   void addUnaryPlusOrMinusArithmeticOverloads() {
06633     if (!HasArithmeticOrEnumeralCandidateType)
06634       return;
06635 
06636     for (unsigned Arith = FirstPromotedArithmeticType;
06637          Arith < LastPromotedArithmeticType; ++Arith) {
06638       QualType ArithTy = getArithmeticType(Arith);
06639       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
06640     }
06641 
06642     // Extension: We also add these operators for vector types.
06643     for (BuiltinCandidateTypeSet::iterator
06644               Vec = CandidateTypes[0].vector_begin(),
06645            VecEnd = CandidateTypes[0].vector_end();
06646          Vec != VecEnd; ++Vec) {
06647       QualType VecTy = *Vec;
06648       S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
06649     }
06650   }
06651 
06652   // C++ [over.built]p8:
06653   //   For every type T, there exist candidate operator functions of
06654   //   the form
06655   //
06656   //       T*         operator+(T*);
06657   void addUnaryPlusPointerOverloads() {
06658     for (BuiltinCandidateTypeSet::iterator
06659               Ptr = CandidateTypes[0].pointer_begin(),
06660            PtrEnd = CandidateTypes[0].pointer_end();
06661          Ptr != PtrEnd; ++Ptr) {
06662       QualType ParamTy = *Ptr;
06663       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
06664     }
06665   }
06666 
06667   // C++ [over.built]p10:
06668   //   For every promoted integral type T, there exist candidate
06669   //   operator functions of the form
06670   //
06671   //        T         operator~(T);
06672   void addUnaryTildePromotedIntegralOverloads() {
06673     if (!HasArithmeticOrEnumeralCandidateType)
06674       return;
06675 
06676     for (unsigned Int = FirstPromotedIntegralType;
06677          Int < LastPromotedIntegralType; ++Int) {
06678       QualType IntTy = getArithmeticType(Int);
06679       S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
06680     }
06681 
06682     // Extension: We also add this operator for vector types.
06683     for (BuiltinCandidateTypeSet::iterator
06684               Vec = CandidateTypes[0].vector_begin(),
06685            VecEnd = CandidateTypes[0].vector_end();
06686          Vec != VecEnd; ++Vec) {
06687       QualType VecTy = *Vec;
06688       S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
06689     }
06690   }
06691 
06692   // C++ [over.match.oper]p16:
06693   //   For every pointer to member type T, there exist candidate operator
06694   //   functions of the form
06695   //
06696   //        bool operator==(T,T);
06697   //        bool operator!=(T,T);
06698   void addEqualEqualOrNotEqualMemberPointerOverloads() {
06699     /// Set of (canonical) types that we've already handled.
06700     llvm::SmallPtrSet<QualType, 8> AddedTypes;
06701 
06702     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
06703       for (BuiltinCandidateTypeSet::iterator
06704                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
06705              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
06706            MemPtr != MemPtrEnd;
06707            ++MemPtr) {
06708         // Don't add the same builtin candidate twice.
06709         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
06710           continue;
06711 
06712         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
06713         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
06714                               CandidateSet);
06715       }
06716     }
06717   }
06718 
06719   // C++ [over.built]p15:
06720   //
06721   //   For every T, where T is an enumeration type, a pointer type, or 
06722   //   std::nullptr_t, there exist candidate operator functions of the form
06723   //
06724   //        bool       operator<(T, T);
06725   //        bool       operator>(T, T);
06726   //        bool       operator<=(T, T);
06727   //        bool       operator>=(T, T);
06728   //        bool       operator==(T, T);
06729   //        bool       operator!=(T, T);
06730   void addRelationalPointerOrEnumeralOverloads() {
06731     // C++ [over.built]p1:
06732     //   If there is a user-written candidate with the same name and parameter
06733     //   types as a built-in candidate operator function, the built-in operator
06734     //   function is hidden and is not included in the set of candidate
06735     //   functions.
06736     //
06737     // The text is actually in a note, but if we don't implement it then we end
06738     // up with ambiguities when the user provides an overloaded operator for
06739     // an enumeration type. Note that only enumeration types have this problem,
06740     // so we track which enumeration types we've seen operators for. Also, the
06741     // only other overloaded operator with enumeration argumenst, operator=,
06742     // cannot be overloaded for enumeration types, so this is the only place
06743     // where we must suppress candidates like this.
06744     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
06745       UserDefinedBinaryOperators;
06746 
06747     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
06748       if (CandidateTypes[ArgIdx].enumeration_begin() !=
06749           CandidateTypes[ArgIdx].enumeration_end()) {
06750         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
06751                                          CEnd = CandidateSet.end();
06752              C != CEnd; ++C) {
06753           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
06754             continue;
06755 
06756           QualType FirstParamType =
06757             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
06758           QualType SecondParamType =
06759             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
06760 
06761           // Skip if either parameter isn't of enumeral type.
06762           if (!FirstParamType->isEnumeralType() ||
06763               !SecondParamType->isEnumeralType())
06764             continue;
06765 
06766           // Add this operator to the set of known user-defined operators.
06767           UserDefinedBinaryOperators.insert(
06768             std::make_pair(S.Context.getCanonicalType(FirstParamType),
06769                            S.Context.getCanonicalType(SecondParamType)));
06770         }
06771       }
06772     }
06773 
06774     /// Set of (canonical) types that we've already handled.
06775     llvm::SmallPtrSet<QualType, 8> AddedTypes;
06776 
06777     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
06778       for (BuiltinCandidateTypeSet::iterator
06779                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
06780              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
06781            Ptr != PtrEnd; ++Ptr) {
06782         // Don't add the same builtin candidate twice.
06783         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
06784           continue;
06785 
06786         QualType ParamTypes[2] = { *Ptr, *Ptr };
06787         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
06788                               CandidateSet);
06789       }
06790       for (BuiltinCandidateTypeSet::iterator
06791                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
06792              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
06793            Enum != EnumEnd; ++Enum) {
06794         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
06795 
06796         // Don't add the same builtin candidate twice, or if a user defined
06797         // candidate exists.
06798         if (!AddedTypes.insert(CanonType) ||
06799             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
06800                                                             CanonType)))
06801           continue;
06802 
06803         QualType ParamTypes[2] = { *Enum, *Enum };
06804         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
06805                               CandidateSet);
06806       }
06807       
06808       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
06809         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
06810         if (AddedTypes.insert(NullPtrTy) &&
06811             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 
06812                                                              NullPtrTy))) {
06813           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
06814           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 
06815                                 CandidateSet);
06816         }
06817       }
06818     }
06819   }
06820 
06821   // C++ [over.built]p13:
06822   //
06823   //   For every cv-qualified or cv-unqualified object type T
06824   //   there exist candidate operator functions of the form
06825   //
06826   //      T*         operator+(T*, ptrdiff_t);
06827   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
06828   //      T*         operator-(T*, ptrdiff_t);
06829   //      T*         operator+(ptrdiff_t, T*);
06830   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
06831   //
06832   // C++ [over.built]p14:
06833   //
06834   //   For every T, where T is a pointer to object type, there
06835   //   exist candidate operator functions of the form
06836   //
06837   //      ptrdiff_t  operator-(T, T);
06838   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
06839     /// Set of (canonical) types that we've already handled.
06840     llvm::SmallPtrSet<QualType, 8> AddedTypes;
06841 
06842     for (int Arg = 0; Arg < 2; ++Arg) {
06843       QualType AsymetricParamTypes[2] = {
06844         S.Context.getPointerDiffType(),
06845         S.Context.getPointerDiffType(),
06846       };
06847       for (BuiltinCandidateTypeSet::iterator
06848                 Ptr = CandidateTypes[Arg].pointer_begin(),
06849              PtrEnd = CandidateTypes[Arg].pointer_end();
06850            Ptr != PtrEnd; ++Ptr) {
06851         QualType PointeeTy = (*Ptr)->getPointeeType();
06852         if (!PointeeTy->isObjectType())
06853           continue;
06854 
06855         AsymetricParamTypes[Arg] = *Ptr;
06856         if (Arg == 0 || Op == OO_Plus) {
06857           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
06858           // T* operator+(ptrdiff_t, T*);
06859           S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
06860                                 CandidateSet);
06861         }
06862         if (Op == OO_Minus) {
06863           // ptrdiff_t operator-(T, T);
06864           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
06865             continue;
06866 
06867           QualType ParamTypes[2] = { *Ptr, *Ptr };
06868           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
06869                                 Args, 2, CandidateSet);
06870         }
06871       }
06872     }
06873   }
06874 
06875   // C++ [over.built]p12:
06876   //
06877   //   For every pair of promoted arithmetic types L and R, there
06878   //   exist candidate operator functions of the form
06879   //
06880   //        LR         operator*(L, R);
06881   //        LR         operator/(L, R);
06882   //        LR         operator+(L, R);
06883   //        LR         operator-(L, R);
06884   //        bool       operator<(L, R);
06885   //        bool       operator>(L, R);
06886   //        bool       operator<=(L, R);
06887   //        bool       operator>=(L, R);
06888   //        bool       operator==(L, R);
06889   //        bool       operator!=(L, R);
06890   //
06891   //   where LR is the result of the usual arithmetic conversions
06892   //   between types L and R.
06893   //
06894   // C++ [over.built]p24:
06895   //
06896   //   For every pair of promoted arithmetic types L and R, there exist
06897   //   candidate operator functions of the form
06898   //
06899   //        LR       operator?(bool, L, R);
06900   //
06901   //   where LR is the result of the usual arithmetic conversions
06902   //   between types L and R.
06903   // Our candidates ignore the first parameter.
06904   void addGenericBinaryArithmeticOverloads(bool isComparison) {
06905     if (!HasArithmeticOrEnumeralCandidateType)
06906       return;
06907 
06908     for (unsigned Left = FirstPromotedArithmeticType;
06909          Left < LastPromotedArithmeticType; ++Left) {
06910       for (unsigned Right = FirstPromotedArithmeticType;
06911            Right < LastPromotedArithmeticType; ++Right) {
06912         QualType LandR[2] = { getArithmeticType(Left),
06913                               getArithmeticType(Right) };
06914         QualType Result =
06915           isComparison ? S.Context.BoolTy
06916                        : getUsualArithmeticConversions(Left, Right);
06917         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
06918       }
06919     }
06920 
06921     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
06922     // conditional operator for vector types.
06923     for (BuiltinCandidateTypeSet::iterator
06924               Vec1 = CandidateTypes[0].vector_begin(),
06925            Vec1End = CandidateTypes[0].vector_end();
06926          Vec1 != Vec1End; ++Vec1) {
06927       for (BuiltinCandidateTypeSet::iterator
06928                 Vec2 = CandidateTypes[1].vector_begin(),
06929              Vec2End = CandidateTypes[1].vector_end();
06930            Vec2 != Vec2End; ++Vec2) {
06931         QualType LandR[2] = { *Vec1, *Vec2 };
06932         QualType Result = S.Context.BoolTy;
06933         if (!isComparison) {
06934           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
06935             Result = *Vec1;
06936           else
06937             Result = *Vec2;
06938         }
06939 
06940         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
06941       }
06942     }
06943   }
06944 
06945   // C++ [over.built]p17:
06946   //
06947   //   For every pair of promoted integral types L and R, there
06948   //   exist candidate operator functions of the form
06949   //
06950   //      LR         operator%(L, R);
06951   //      LR         operator&(L, R);
06952   //      LR         operator^(L, R);
06953   //      LR         operator|(L, R);
06954   //      L          operator<<(L, R);
06955   //      L          operator>>(L, R);
06956   //
06957   //   where LR is the result of the usual arithmetic conversions
06958   //   between types L and R.
06959   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
06960     if (!HasArithmeticOrEnumeralCandidateType)
06961       return;
06962 
06963     for (unsigned Left = FirstPromotedIntegralType;
06964          Left < LastPromotedIntegralType; ++Left) {
06965       for (unsigned Right = FirstPromotedIntegralType;
06966            Right < LastPromotedIntegralType; ++Right) {
06967         QualType LandR[2] = { getArithmeticType(Left),
06968                               getArithmeticType(Right) };
06969         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
06970             ? LandR[0]
06971             : getUsualArithmeticConversions(Left, Right);
06972         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
06973       }
06974     }
06975   }
06976 
06977   // C++ [over.built]p20:
06978   //
06979   //   For every pair (T, VQ), where T is an enumeration or
06980   //   pointer to member type and VQ is either volatile or
06981   //   empty, there exist candidate operator functions of the form
06982   //
06983   //        VQ T&      operator=(VQ T&, T);
06984   void addAssignmentMemberPointerOrEnumeralOverloads() {
06985     /// Set of (canonical) types that we've already handled.
06986     llvm::SmallPtrSet<QualType, 8> AddedTypes;
06987 
06988     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
06989       for (BuiltinCandidateTypeSet::iterator
06990                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
06991              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
06992            Enum != EnumEnd; ++Enum) {
06993         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
06994           continue;
06995 
06996         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
06997                                                CandidateSet);
06998       }
06999 
07000       for (BuiltinCandidateTypeSet::iterator
07001                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
07002              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
07003            MemPtr != MemPtrEnd; ++MemPtr) {
07004         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
07005           continue;
07006 
07007         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
07008                                                CandidateSet);
07009       }
07010     }
07011   }
07012 
07013   // C++ [over.built]p19:
07014   //
07015   //   For every pair (T, VQ), where T is any type and VQ is either
07016   //   volatile or empty, there exist candidate operator functions
07017   //   of the form
07018   //
07019   //        T*VQ&      operator=(T*VQ&, T*);
07020   //
07021   // C++ [over.built]p21:
07022   //
07023   //   For every pair (T, VQ), where T is a cv-qualified or
07024   //   cv-unqualified object type and VQ is either volatile or
07025   //   empty, there exist candidate operator functions of the form
07026   //
07027   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
07028   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
07029   void addAssignmentPointerOverloads(bool isEqualOp) {
07030     /// Set of (canonical) types that we've already handled.
07031     llvm::SmallPtrSet<QualType, 8> AddedTypes;
07032 
07033     for (BuiltinCandidateTypeSet::iterator
07034               Ptr = CandidateTypes[0].pointer_begin(),
07035            PtrEnd = CandidateTypes[0].pointer_end();
07036          Ptr != PtrEnd; ++Ptr) {
07037       // If this is operator=, keep track of the builtin candidates we added.
07038       if (isEqualOp)
07039         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
07040       else if (!(*Ptr)->getPointeeType()->isObjectType())
07041         continue;
07042 
07043       // non-volatile version
07044       QualType ParamTypes[2] = {
07045         S.Context.getLValueReferenceType(*Ptr),
07046         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
07047       };
07048       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
07049                             /*IsAssigmentOperator=*/ isEqualOp);
07050 
07051       if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
07052           VisibleTypeConversionsQuals.hasVolatile()) {
07053         // volatile version
07054         ParamTypes[0] =
07055           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
07056         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
07057                               /*IsAssigmentOperator=*/isEqualOp);
07058       }
07059     }
07060 
07061     if (isEqualOp) {
07062       for (BuiltinCandidateTypeSet::iterator
07063                 Ptr = CandidateTypes[1].pointer_begin(),
07064              PtrEnd = CandidateTypes[1].pointer_end();
07065            Ptr != PtrEnd; ++Ptr) {
07066         // Make sure we don't add the same candidate twice.
07067         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
07068           continue;
07069 
07070         QualType ParamTypes[2] = {
07071           S.Context.getLValueReferenceType(*Ptr),
07072           *Ptr,
07073         };
07074 
07075         // non-volatile version
07076         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
07077                               /*IsAssigmentOperator=*/true);
07078 
07079         if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
07080             VisibleTypeConversionsQuals.hasVolatile()) {
07081           // volatile version
07082           ParamTypes[0] =
07083             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
07084           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
07085                                 CandidateSet, /*IsAssigmentOperator=*/true);
07086         }
07087       }
07088     }
07089   }
07090 
07091   // C++ [over.built]p18:
07092   //
07093   //   For every triple (L, VQ, R), where L is an arithmetic type,
07094   //   VQ is either volatile or empty, and R is a promoted
07095   //   arithmetic type, there exist candidate operator functions of
07096   //   the form
07097   //
07098   //        VQ L&      operator=(VQ L&, R);
07099   //        VQ L&      operator*=(VQ L&, R);
07100   //        VQ L&      operator/=(VQ L&, R);
07101   //        VQ L&      operator+=(VQ L&, R);
07102   //        VQ L&      operator-=(VQ L&, R);
07103   void addAssignmentArithmeticOverloads(bool isEqualOp) {
07104     if (!HasArithmeticOrEnumeralCandidateType)
07105       return;
07106 
07107     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
07108       for (unsigned Right = FirstPromotedArithmeticType;
07109            Right < LastPromotedArithmeticType; ++Right) {
07110         QualType ParamTypes[2];
07111         ParamTypes[1] = getArithmeticType(Right);
07112 
07113         // Add this built-in operator as a candidate (VQ is empty).
07114         ParamTypes[0] =
07115           S.Context.getLValueReferenceType(getArithmeticType(Left));
07116         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
07117                               /*IsAssigmentOperator=*/isEqualOp);
07118 
07119         // Add this built-in operator as a candidate (VQ is 'volatile').
07120         if (VisibleTypeConversionsQuals.hasVolatile()) {
07121           ParamTypes[0] =
07122             S.Context.getVolatileType(getArithmeticType(Left));
07123           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
07124           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
07125                                 CandidateSet,
07126                                 /*IsAssigmentOperator=*/isEqualOp);
07127         }
07128       }
07129     }
07130 
07131     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
07132     for (BuiltinCandidateTypeSet::iterator
07133               Vec1 = CandidateTypes[0].vector_begin(),
07134            Vec1End = CandidateTypes[0].vector_end();
07135          Vec1 != Vec1End; ++Vec1) {
07136       for (BuiltinCandidateTypeSet::iterator
07137                 Vec2 = CandidateTypes[1].vector_begin(),
07138              Vec2End = CandidateTypes[1].vector_end();
07139            Vec2 != Vec2End; ++Vec2) {
07140         QualType ParamTypes[2];
07141         ParamTypes[1] = *Vec2;
07142         // Add this built-in operator as a candidate (VQ is empty).
07143         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
07144         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
07145                               /*IsAssigmentOperator=*/isEqualOp);
07146 
07147         // Add this built-in operator as a candidate (VQ is 'volatile').
07148         if (VisibleTypeConversionsQuals.hasVolatile()) {
07149           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
07150           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
07151           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
07152                                 CandidateSet,
07153                                 /*IsAssigmentOperator=*/isEqualOp);
07154         }
07155       }
07156     }
07157   }
07158 
07159   // C++ [over.built]p22:
07160   //
07161   //   For every triple (L, VQ, R), where L is an integral type, VQ
07162   //   is either volatile or empty, and R is a promoted integral
07163   //   type, there exist candidate operator functions of the form
07164   //
07165   //        VQ L&       operator%=(VQ L&, R);
07166   //        VQ L&       operator<<=(VQ L&, R);
07167   //        VQ L&       operator>>=(VQ L&, R);
07168   //        VQ L&       operator&=(VQ L&, R);
07169   //        VQ L&       operator^=(VQ L&, R);
07170   //        VQ L&       operator|=(VQ L&, R);
07171   void addAssignmentIntegralOverloads() {
07172     if (!HasArithmeticOrEnumeralCandidateType)
07173       return;
07174 
07175     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
07176       for (unsigned Right = FirstPromotedIntegralType;
07177            Right < LastPromotedIntegralType; ++Right) {
07178         QualType ParamTypes[2];
07179         ParamTypes[1] = getArithmeticType(Right);
07180 
07181         // Add this built-in operator as a candidate (VQ is empty).
07182         ParamTypes[0] =
07183           S.Context.getLValueReferenceType(getArithmeticType(Left));
07184         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
07185         if (VisibleTypeConversionsQuals.hasVolatile()) {
07186           // Add this built-in operator as a candidate (VQ is 'volatile').
07187           ParamTypes[0] = getArithmeticType(Left);
07188           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
07189           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
07190           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
07191                                 CandidateSet);
07192         }
07193       }
07194     }
07195   }
07196 
07197   // C++ [over.operator]p23:
07198   //
07199   //   There also exist candidate operator functions of the form
07200   //
07201   //        bool        operator!(bool);
07202   //        bool        operator&&(bool, bool);
07203   //        bool        operator||(bool, bool);
07204   void addExclaimOverload() {
07205     QualType ParamTy = S.Context.BoolTy;
07206     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
07207                           /*IsAssignmentOperator=*/false,
07208                           /*NumContextualBoolArguments=*/1);
07209   }
07210   void addAmpAmpOrPipePipeOverload() {
07211     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
07212     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
07213                           /*IsAssignmentOperator=*/false,
07214                           /*NumContextualBoolArguments=*/2);
07215   }
07216 
07217   // C++ [over.built]p13:
07218   //
07219   //   For every cv-qualified or cv-unqualified object type T there
07220   //   exist candidate operator functions of the form
07221   //
07222   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
07223   //        T&         operator[](T*, ptrdiff_t);
07224   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
07225   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
07226   //        T&         operator[](ptrdiff_t, T*);
07227   void addSubscriptOverloads() {
07228     for (BuiltinCandidateTypeSet::iterator
07229               Ptr = CandidateTypes[0].pointer_begin(),
07230            PtrEnd = CandidateTypes[0].pointer_end();
07231          Ptr != PtrEnd; ++Ptr) {
07232       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
07233       QualType PointeeType = (*Ptr)->getPointeeType();
07234       if (!PointeeType->isObjectType())
07235         continue;
07236 
07237       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
07238 
07239       // T& operator[](T*, ptrdiff_t)
07240       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
07241     }
07242 
07243     for (BuiltinCandidateTypeSet::iterator
07244               Ptr = CandidateTypes[1].pointer_begin(),
07245            PtrEnd = CandidateTypes[1].pointer_end();
07246          Ptr != PtrEnd; ++Ptr) {
07247       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
07248       QualType PointeeType = (*Ptr)->getPointeeType();
07249       if (!PointeeType->isObjectType())
07250         continue;
07251 
07252       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
07253 
07254       // T& operator[](ptrdiff_t, T*)
07255       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
07256     }
07257   }
07258 
07259   // C++ [over.built]p11:
07260   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
07261   //    C1 is the same type as C2 or is a derived class of C2, T is an object
07262   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
07263   //    there exist candidate operator functions of the form
07264   //
07265   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
07266   //
07267   //    where CV12 is the union of CV1 and CV2.
07268   void addArrowStarOverloads() {
07269     for (BuiltinCandidateTypeSet::iterator
07270              Ptr = CandidateTypes[0].pointer_begin(),
07271            PtrEnd = CandidateTypes[0].pointer_end();
07272          Ptr != PtrEnd; ++Ptr) {
07273       QualType C1Ty = (*Ptr);
07274       QualType C1;
07275       QualifierCollector Q1;
07276       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
07277       if (!isa<RecordType>(C1))
07278         continue;
07279       // heuristic to reduce number of builtin candidates in the set.
07280       // Add volatile/restrict version only if there are conversions to a
07281       // volatile/restrict type.
07282       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
07283         continue;
07284       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
07285         continue;
07286       for (BuiltinCandidateTypeSet::iterator
07287                 MemPtr = CandidateTypes[1].member_pointer_begin(),
07288              MemPtrEnd = CandidateTypes[1].member_pointer_end();
07289            MemPtr != MemPtrEnd; ++MemPtr) {
07290         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
07291         QualType C2 = QualType(mptr->getClass(), 0);
07292         C2 = C2.getUnqualifiedType();
07293         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
07294           break;
07295         QualType ParamTypes[2] = { *Ptr, *MemPtr };
07296         // build CV12 T&
07297         QualType T = mptr->getPointeeType();
07298         if (!VisibleTypeConversionsQuals.hasVolatile() &&
07299             T.isVolatileQualified())
07300           continue;
07301         if (!VisibleTypeConversionsQuals.hasRestrict() &&
07302             T.isRestrictQualified())
07303           continue;
07304         T = Q1.apply(S.Context, T);
07305         QualType ResultTy = S.Context.getLValueReferenceType(T);
07306         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
07307       }
07308     }
07309   }
07310 
07311   // Note that we don't consider the first argument, since it has been
07312   // contextually converted to bool long ago. The candidates below are
07313   // therefore added as binary.
07314   //
07315   // C++ [over.built]p25:
07316   //   For every type T, where T is a pointer, pointer-to-member, or scoped
07317   //   enumeration type, there exist candidate operator functions of the form
07318   //
07319   //        T        operator?(bool, T, T);
07320   //
07321   void addConditionalOperatorOverloads() {
07322     /// Set of (canonical) types that we've already handled.
07323     llvm::SmallPtrSet<QualType, 8> AddedTypes;
07324 
07325     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
07326       for (BuiltinCandidateTypeSet::iterator
07327                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
07328              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
07329            Ptr != PtrEnd; ++Ptr) {
07330         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
07331           continue;
07332 
07333         QualType ParamTypes[2] = { *Ptr, *Ptr };
07334         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
07335       }
07336 
07337       for (BuiltinCandidateTypeSet::iterator
07338                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
07339              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
07340            MemPtr != MemPtrEnd; ++MemPtr) {
07341         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
07342           continue;
07343 
07344         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
07345         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
07346       }
07347 
07348       if (S.getLangOpts().CPlusPlus0x) {
07349         for (BuiltinCandidateTypeSet::iterator
07350                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
07351                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
07352              Enum != EnumEnd; ++Enum) {
07353           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
07354             continue;
07355 
07356           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
07357             continue;
07358 
07359           QualType ParamTypes[2] = { *Enum, *Enum };
07360           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
07361         }
07362       }
07363     }
07364   }
07365 };
07366 
07367 } // end anonymous namespace
07368 
07369 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
07370 /// operator overloads to the candidate set (C++ [over.built]), based
07371 /// on the operator @p Op and the arguments given. For example, if the
07372 /// operator is a binary '+', this routine might add "int
07373 /// operator+(int, int)" to cover integer addition.
07374 void
07375 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
07376                                    SourceLocation OpLoc,
07377                                    Expr **Args, unsigned NumArgs,
07378                                    OverloadCandidateSet& CandidateSet) {
07379   // Find all of the types that the arguments can convert to, but only
07380   // if the operator we're looking at has built-in operator candidates
07381   // that make use of these types. Also record whether we encounter non-record
07382   // candidate types or either arithmetic or enumeral candidate types.
07383   Qualifiers VisibleTypeConversionsQuals;
07384   VisibleTypeConversionsQuals.addConst();
07385   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
07386     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
07387 
07388   bool HasNonRecordCandidateType = false;
07389   bool HasArithmeticOrEnumeralCandidateType = false;
07390   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
07391   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
07392     CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
07393     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
07394                                                  OpLoc,
07395                                                  true,
07396                                                  (Op == OO_Exclaim ||
07397                                                   Op == OO_AmpAmp ||
07398                                                   Op == OO_PipePipe),
07399                                                  VisibleTypeConversionsQuals);
07400     HasNonRecordCandidateType = HasNonRecordCandidateType ||
07401         CandidateTypes[ArgIdx].hasNonRecordTypes();
07402     HasArithmeticOrEnumeralCandidateType =
07403         HasArithmeticOrEnumeralCandidateType ||
07404         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
07405   }
07406 
07407   // Exit early when no non-record types have been added to the candidate set
07408   // for any of the arguments to the operator.
07409   //
07410   // We can't exit early for !, ||, or &&, since there we have always have
07411   // 'bool' overloads.
07412   if (!HasNonRecordCandidateType && 
07413       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
07414     return;
07415 
07416   // Setup an object to manage the common state for building overloads.
07417   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
07418                                            VisibleTypeConversionsQuals,
07419                                            HasArithmeticOrEnumeralCandidateType,
07420                                            CandidateTypes, CandidateSet);
07421 
07422   // Dispatch over the operation to add in only those overloads which apply.
07423   switch (Op) {
07424   case OO_None:
07425   case NUM_OVERLOADED_OPERATORS:
07426     llvm_unreachable("Expected an overloaded operator");
07427 
07428   case OO_New:
07429   case OO_Delete:
07430   case OO_Array_New:
07431   case OO_Array_Delete:
07432   case OO_Call:
07433     llvm_unreachable(
07434                     "Special operators don't use AddBuiltinOperatorCandidates");
07435 
07436   case OO_Comma:
07437   case OO_Arrow:
07438     // C++ [over.match.oper]p3:
07439     //   -- For the operator ',', the unary operator '&', or the
07440     //      operator '->', the built-in candidates set is empty.
07441     break;
07442 
07443   case OO_Plus: // '+' is either unary or binary
07444     if (NumArgs == 1)
07445       OpBuilder.addUnaryPlusPointerOverloads();
07446     // Fall through.
07447 
07448   case OO_Minus: // '-' is either unary or binary
07449     if (NumArgs == 1) {
07450       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
07451     } else {
07452       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
07453       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
07454     }
07455     break;
07456 
07457   case OO_Star: // '*' is either unary or binary
07458     if (NumArgs == 1)
07459       OpBuilder.addUnaryStarPointerOverloads();
07460     else
07461       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
07462     break;
07463 
07464   case OO_Slash:
07465     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
07466     break;
07467 
07468   case OO_PlusPlus:
07469   case OO_MinusMinus:
07470     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
07471     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
07472     break;
07473 
07474   case OO_EqualEqual:
07475   case OO_ExclaimEqual:
07476     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
07477     // Fall through.
07478 
07479   case OO_Less:
07480   case OO_Greater:
07481   case OO_LessEqual:
07482   case OO_GreaterEqual:
07483     OpBuilder.addRelationalPointerOrEnumeralOverloads();
07484     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
07485     break;
07486 
07487   case OO_Percent:
07488   case OO_Caret:
07489   case OO_Pipe:
07490   case OO_LessLess:
07491   case OO_GreaterGreater:
07492     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
07493     break;
07494 
07495   case OO_Amp: // '&' is either unary or binary
07496     if (NumArgs == 1)
07497       // C++ [over.match.oper]p3:
07498       //   -- For the operator ',', the unary operator '&', or the
07499       //      operator '->', the built-in candidates set is empty.
07500       break;
07501 
07502     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
07503     break;
07504 
07505   case OO_Tilde:
07506     OpBuilder.addUnaryTildePromotedIntegralOverloads();
07507     break;
07508 
07509   case OO_Equal:
07510     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
07511     // Fall through.
07512 
07513   case OO_PlusEqual:
07514   case OO_MinusEqual:
07515     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
07516     // Fall through.
07517 
07518   case OO_StarEqual:
07519   case OO_SlashEqual:
07520     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
07521     break;
07522 
07523   case OO_PercentEqual:
07524   case OO_LessLessEqual:
07525   case OO_GreaterGreaterEqual:
07526   case OO_AmpEqual:
07527   case OO_CaretEqual:
07528   case OO_PipeEqual:
07529     OpBuilder.addAssignmentIntegralOverloads();
07530     break;
07531 
07532   case OO_Exclaim:
07533     OpBuilder.addExclaimOverload();
07534     break;
07535 
07536   case OO_AmpAmp:
07537   case OO_PipePipe:
07538     OpBuilder.addAmpAmpOrPipePipeOverload();
07539     break;
07540 
07541   case OO_Subscript:
07542     OpBuilder.addSubscriptOverloads();
07543     break;
07544 
07545   case OO_ArrowStar:
07546     OpBuilder.addArrowStarOverloads();
07547     break;
07548 
07549   case OO_Conditional:
07550     OpBuilder.addConditionalOperatorOverloads();
07551     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
07552     break;
07553   }
07554 }
07555 
07556 /// \brief Add function candidates found via argument-dependent lookup
07557 /// to the set of overloading candidates.
07558 ///
07559 /// This routine performs argument-dependent name lookup based on the
07560 /// given function name (which may also be an operator name) and adds
07561 /// all of the overload candidates found by ADL to the overload
07562 /// candidate set (C++ [basic.lookup.argdep]).
07563 void
07564 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
07565                                            bool Operator, SourceLocation Loc,
07566                                            llvm::ArrayRef<Expr *> Args,
07567                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
07568                                            OverloadCandidateSet& CandidateSet,
07569                                            bool PartialOverloading,
07570                                            bool StdNamespaceIsAssociated) {
07571   ADLResult Fns;
07572 
07573   // FIXME: This approach for uniquing ADL results (and removing
07574   // redundant candidates from the set) relies on pointer-equality,
07575   // which means we need to key off the canonical decl.  However,
07576   // always going back to the canonical decl might not get us the
07577   // right set of default arguments.  What default arguments are
07578   // we supposed to consider on ADL candidates, anyway?
07579 
07580   // FIXME: Pass in the explicit template arguments?
07581   ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
07582                           StdNamespaceIsAssociated);
07583 
07584   // Erase all of the candidates we already knew about.
07585   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
07586                                    CandEnd = CandidateSet.end();
07587        Cand != CandEnd; ++Cand)
07588     if (Cand->Function) {
07589       Fns.erase(Cand->Function);
07590       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
07591         Fns.erase(FunTmpl);
07592     }
07593 
07594   // For each of the ADL candidates we found, add it to the overload
07595   // set.
07596   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
07597     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
07598     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
07599       if (ExplicitTemplateArgs)
07600         continue;
07601 
07602       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
07603                            PartialOverloading);
07604     } else
07605       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
07606                                    FoundDecl, ExplicitTemplateArgs,
07607                                    Args, CandidateSet);
07608   }
07609 }
07610 
07611 /// isBetterOverloadCandidate - Determines whether the first overload
07612 /// candidate is a better candidate than the second (C++ 13.3.3p1).
07613 bool
07614 isBetterOverloadCandidate(Sema &S,
07615                           const OverloadCandidate &Cand1,
07616                           const OverloadCandidate &Cand2,
07617                           SourceLocation Loc,
07618                           bool UserDefinedConversion) {
07619   // Define viable functions to be better candidates than non-viable
07620   // functions.
07621   if (!Cand2.Viable)
07622     return Cand1.Viable;
07623   else if (!Cand1.Viable)
07624     return false;
07625 
07626   // C++ [over.match.best]p1:
07627   //
07628   //   -- if F is a static member function, ICS1(F) is defined such
07629   //      that ICS1(F) is neither better nor worse than ICS1(G) for
07630   //      any function G, and, symmetrically, ICS1(G) is neither
07631   //      better nor worse than ICS1(F).
07632   unsigned StartArg = 0;
07633   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
07634     StartArg = 1;
07635 
07636   // C++ [over.match.best]p1:
07637   //   A viable function F1 is defined to be a better function than another
07638   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
07639   //   conversion sequence than ICSi(F2), and then...
07640   unsigned NumArgs = Cand1.NumConversions;
07641   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
07642   bool HasBetterConversion = false;
07643   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
07644     switch (CompareImplicitConversionSequences(S,
07645                                                Cand1.Conversions[ArgIdx],
07646                                                Cand2.Conversions[ArgIdx])) {
07647     case ImplicitConversionSequence::Better:
07648       // Cand1 has a better conversion sequence.
07649       HasBetterConversion = true;
07650       break;
07651 
07652     case ImplicitConversionSequence::Worse:
07653       // Cand1 can't be better than Cand2.
07654       return false;
07655 
07656     case ImplicitConversionSequence::Indistinguishable:
07657       // Do nothing.
07658       break;
07659     }
07660   }
07661 
07662   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
07663   //       ICSj(F2), or, if not that,
07664   if (HasBetterConversion)
07665     return true;
07666 
07667   //     - F1 is a non-template function and F2 is a function template
07668   //       specialization, or, if not that,
07669   if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
07670       Cand2.Function && Cand2.Function->getPrimaryTemplate())
07671     return true;
07672 
07673   //   -- F1 and F2 are function template specializations, and the function
07674   //      template for F1 is more specialized than the template for F2
07675   //      according to the partial ordering rules described in 14.5.5.2, or,
07676   //      if not that,
07677   if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
07678       Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
07679     if (FunctionTemplateDecl *BetterTemplate
07680           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
07681                                          Cand2.Function->getPrimaryTemplate(),
07682                                          Loc,
07683                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
07684                                                              : TPOC_Call,
07685                                          Cand1.ExplicitCallArguments))
07686       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
07687   }
07688 
07689   //   -- the context is an initialization by user-defined conversion
07690   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
07691   //      from the return type of F1 to the destination type (i.e.,
07692   //      the type of the entity being initialized) is a better
07693   //      conversion sequence than the standard conversion sequence
07694   //      from the return type of F2 to the destination type.
07695   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
07696       isa<CXXConversionDecl>(Cand1.Function) &&
07697       isa<CXXConversionDecl>(Cand2.Function)) {
07698     // First check whether we prefer one of the conversion functions over the
07699     // other. This only distinguishes the results in non-standard, extension
07700     // cases such as the conversion from a lambda closure type to a function
07701     // pointer or block.
07702     ImplicitConversionSequence::CompareKind FuncResult
07703       = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
07704     if (FuncResult != ImplicitConversionSequence::Indistinguishable)
07705       return FuncResult;
07706           
07707     switch (CompareStandardConversionSequences(S,
07708                                                Cand1.FinalConversion,
07709                                                Cand2.FinalConversion)) {
07710     case ImplicitConversionSequence::Better:
07711       // Cand1 has a better conversion sequence.
07712       return true;
07713 
07714     case ImplicitConversionSequence::Worse:
07715       // Cand1 can't be better than Cand2.
07716       return false;
07717 
07718     case ImplicitConversionSequence::Indistinguishable:
07719       // Do nothing
07720       break;
07721     }
07722   }
07723 
07724   return false;
07725 }
07726 
07727 /// \brief Computes the best viable function (C++ 13.3.3)
07728 /// within an overload candidate set.
07729 ///
07730 /// \param CandidateSet the set of candidate functions.
07731 ///
07732 /// \param Loc the location of the function name (or operator symbol) for
07733 /// which overload resolution occurs.
07734 ///
07735 /// \param Best f overload resolution was successful or found a deleted
07736 /// function, Best points to the candidate function found.
07737 ///
07738 /// \returns The result of overload resolution.
07739 OverloadingResult
07740 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
07741                                          iterator &Best,
07742                                          bool UserDefinedConversion) {
07743   // Find the best viable function.
07744   Best = end();
07745   for (iterator Cand = begin(); Cand != end(); ++Cand) {
07746     if (Cand->Viable)
07747       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
07748                                                      UserDefinedConversion))
07749         Best = Cand;
07750   }
07751 
07752   // If we didn't find any viable functions, abort.
07753   if (Best == end())
07754     return OR_No_Viable_Function;
07755 
07756   // Make sure that this function is better than every other viable
07757   // function. If not, we have an ambiguity.
07758   for (iterator Cand = begin(); Cand != end(); ++Cand) {
07759     if (Cand->Viable &&
07760         Cand != Best &&
07761         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
07762                                    UserDefinedConversion)) {
07763       Best = end();
07764       return OR_Ambiguous;
07765     }
07766   }
07767 
07768   // Best is the best viable function.
07769   if (Best->Function &&
07770       (Best->Function->isDeleted() ||
07771        S.isFunctionConsideredUnavailable(Best->Function)))
07772     return OR_Deleted;
07773 
07774   return OR_Success;
07775 }
07776 
07777 namespace {
07778 
07779 enum OverloadCandidateKind {
07780   oc_function,
07781   oc_method,
07782   oc_constructor,
07783   oc_function_template,
07784   oc_method_template,
07785   oc_constructor_template,
07786   oc_implicit_default_constructor,
07787   oc_implicit_copy_constructor,
07788   oc_implicit_move_constructor,
07789   oc_implicit_copy_assignment,
07790   oc_implicit_move_assignment,
07791   oc_implicit_inherited_constructor
07792 };
07793 
07794 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
07795                                                 FunctionDecl *Fn,
07796                                                 std::string &Description) {
07797   bool isTemplate = false;
07798 
07799   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
07800     isTemplate = true;
07801     Description = S.getTemplateArgumentBindingsText(
07802       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
07803   }
07804 
07805   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
07806     if (!Ctor->isImplicit())
07807       return isTemplate ? oc_constructor_template : oc_constructor;
07808 
07809     if (Ctor->getInheritedConstructor())
07810       return oc_implicit_inherited_constructor;
07811 
07812     if (Ctor->isDefaultConstructor())
07813       return oc_implicit_default_constructor;
07814 
07815     if (Ctor->isMoveConstructor())
07816       return oc_implicit_move_constructor;
07817 
07818     assert(Ctor->isCopyConstructor() &&
07819            "unexpected sort of implicit constructor");
07820     return oc_implicit_copy_constructor;
07821   }
07822 
07823   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
07824     // This actually gets spelled 'candidate function' for now, but
07825     // it doesn't hurt to split it out.
07826     if (!Meth->isImplicit())
07827       return isTemplate ? oc_method_template : oc_method;
07828 
07829     if (Meth->isMoveAssignmentOperator())
07830       return oc_implicit_move_assignment;
07831 
07832     if (Meth->isCopyAssignmentOperator())
07833       return oc_implicit_copy_assignment;
07834 
07835     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
07836     return oc_method;
07837   }
07838 
07839   return isTemplate ? oc_function_template : oc_function;
07840 }
07841 
07842 void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
07843   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
07844   if (!Ctor) return;
07845 
07846   Ctor = Ctor->getInheritedConstructor();
07847   if (!Ctor) return;
07848 
07849   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
07850 }
07851 
07852 } // end anonymous namespace
07853 
07854 // Notes the location of an overload candidate.
07855 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
07856   std::string FnDesc;
07857   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
07858   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
07859                              << (unsigned) K << FnDesc;
07860   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
07861   Diag(Fn->getLocation(), PD);
07862   MaybeEmitInheritedConstructorNote(*this, Fn);
07863 }
07864 
07865 //Notes the location of all overload candidates designated through 
07866 // OverloadedExpr
07867 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
07868   assert(OverloadedExpr->getType() == Context.OverloadTy);
07869 
07870   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
07871   OverloadExpr *OvlExpr = Ovl.Expression;
07872 
07873   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
07874                             IEnd = OvlExpr->decls_end(); 
07875        I != IEnd; ++I) {
07876     if (FunctionTemplateDecl *FunTmpl = 
07877                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
07878       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
07879     } else if (FunctionDecl *Fun 
07880                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
07881       NoteOverloadCandidate(Fun, DestType);
07882     }
07883   }
07884 }
07885 
07886 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
07887 /// "lead" diagnostic; it will be given two arguments, the source and
07888 /// target types of the conversion.
07889 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
07890                                  Sema &S,
07891                                  SourceLocation CaretLoc,
07892                                  const PartialDiagnostic &PDiag) const {
07893   S.Diag(CaretLoc, PDiag)
07894     << Ambiguous.getFromType() << Ambiguous.getToType();
07895   for (AmbiguousConversionSequence::const_iterator
07896          I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
07897     S.NoteOverloadCandidate(*I);
07898   }
07899 }
07900 
07901 namespace {
07902 
07903 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
07904   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
07905   assert(Conv.isBad());
07906   assert(Cand->Function && "for now, candidate must be a function");
07907   FunctionDecl *Fn = Cand->Function;
07908 
07909   // There's a conversion slot for the object argument if this is a
07910   // non-constructor method.  Note that 'I' corresponds the
07911   // conversion-slot index.
07912   bool isObjectArgument = false;
07913   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
07914     if (I == 0)
07915       isObjectArgument = true;
07916     else
07917       I--;
07918   }
07919 
07920   std::string FnDesc;
07921   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
07922 
07923   Expr *FromExpr = Conv.Bad.FromExpr;
07924   QualType FromTy = Conv.Bad.getFromType();
07925   QualType ToTy = Conv.Bad.getToType();
07926 
07927   if (FromTy == S.Context.OverloadTy) {
07928     assert(FromExpr && "overload set argument came from implicit argument?");
07929     Expr *E = FromExpr->IgnoreParens();
07930     if (isa<UnaryOperator>(E))
07931       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
07932     DeclarationName Name = cast<OverloadExpr>(E)->getName();
07933 
07934     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
07935       << (unsigned) FnKind << FnDesc
07936       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
07937       << ToTy << Name << I+1;
07938     MaybeEmitInheritedConstructorNote(S, Fn);
07939     return;
07940   }
07941 
07942   // Do some hand-waving analysis to see if the non-viability is due
07943   // to a qualifier mismatch.
07944   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
07945   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
07946   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
07947     CToTy = RT->getPointeeType();
07948   else {
07949     // TODO: detect and diagnose the full richness of const mismatches.
07950     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
07951       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
07952         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
07953   }
07954 
07955   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
07956       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
07957     Qualifiers FromQs = CFromTy.getQualifiers();
07958     Qualifiers ToQs = CToTy.getQualifiers();
07959 
07960     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
07961       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
07962         << (unsigned) FnKind << FnDesc
07963         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
07964         << FromTy
07965         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
07966         << (unsigned) isObjectArgument << I+1;
07967       MaybeEmitInheritedConstructorNote(S, Fn);
07968       return;
07969     }
07970 
07971     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
07972       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
07973         << (unsigned) FnKind << FnDesc
07974         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
07975         << FromTy
07976         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
07977         << (unsigned) isObjectArgument << I+1;
07978       MaybeEmitInheritedConstructorNote(S, Fn);
07979       return;
07980     }
07981 
07982     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
07983       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
07984       << (unsigned) FnKind << FnDesc
07985       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
07986       << FromTy
07987       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
07988       << (unsigned) isObjectArgument << I+1;
07989       MaybeEmitInheritedConstructorNote(S, Fn);
07990       return;
07991     }
07992 
07993     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
07994     assert(CVR && "unexpected qualifiers mismatch");
07995 
07996     if (isObjectArgument) {
07997       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
07998         << (unsigned) FnKind << FnDesc
07999         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08000         << FromTy << (CVR - 1);
08001     } else {
08002       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
08003         << (unsigned) FnKind << FnDesc
08004         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08005         << FromTy << (CVR - 1) << I+1;
08006     }
08007     MaybeEmitInheritedConstructorNote(S, Fn);
08008     return;
08009   }
08010 
08011   // Special diagnostic for failure to convert an initializer list, since
08012   // telling the user that it has type void is not useful.
08013   if (FromExpr && isa<InitListExpr>(FromExpr)) {
08014     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
08015       << (unsigned) FnKind << FnDesc
08016       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08017       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
08018     MaybeEmitInheritedConstructorNote(S, Fn);
08019     return;
08020   }
08021 
08022   // Diagnose references or pointers to incomplete types differently,
08023   // since it's far from impossible that the incompleteness triggered
08024   // the failure.
08025   QualType TempFromTy = FromTy.getNonReferenceType();
08026   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
08027     TempFromTy = PTy->getPointeeType();
08028   if (TempFromTy->isIncompleteType()) {
08029     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
08030       << (unsigned) FnKind << FnDesc
08031       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08032       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
08033     MaybeEmitInheritedConstructorNote(S, Fn);
08034     return;
08035   }
08036 
08037   // Diagnose base -> derived pointer conversions.
08038   unsigned BaseToDerivedConversion = 0;
08039   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
08040     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
08041       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
08042                                                FromPtrTy->getPointeeType()) &&
08043           !FromPtrTy->getPointeeType()->isIncompleteType() &&
08044           !ToPtrTy->getPointeeType()->isIncompleteType() &&
08045           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
08046                           FromPtrTy->getPointeeType()))
08047         BaseToDerivedConversion = 1;
08048     }
08049   } else if (const ObjCObjectPointerType *FromPtrTy
08050                                     = FromTy->getAs<ObjCObjectPointerType>()) {
08051     if (const ObjCObjectPointerType *ToPtrTy
08052                                         = ToTy->getAs<ObjCObjectPointerType>())
08053       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
08054         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
08055           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
08056                                                 FromPtrTy->getPointeeType()) &&
08057               FromIface->isSuperClassOf(ToIface))
08058             BaseToDerivedConversion = 2;
08059   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
08060       if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
08061           !FromTy->isIncompleteType() &&
08062           !ToRefTy->getPointeeType()->isIncompleteType() &&
08063           S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
08064         BaseToDerivedConversion = 3;
08065     }
08066 
08067   if (BaseToDerivedConversion) {
08068     S.Diag(Fn->getLocation(),
08069            diag::note_ovl_candidate_bad_base_to_derived_conv)
08070       << (unsigned) FnKind << FnDesc
08071       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08072       << (BaseToDerivedConversion - 1)
08073       << FromTy << ToTy << I+1;
08074     MaybeEmitInheritedConstructorNote(S, Fn);
08075     return;
08076   }
08077 
08078   if (isa<ObjCObjectPointerType>(CFromTy) &&
08079       isa<PointerType>(CToTy)) {
08080       Qualifiers FromQs = CFromTy.getQualifiers();
08081       Qualifiers ToQs = CToTy.getQualifiers();
08082       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
08083         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
08084         << (unsigned) FnKind << FnDesc
08085         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08086         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
08087         MaybeEmitInheritedConstructorNote(S, Fn);
08088         return;
08089       }
08090   }
08091   
08092   // Emit the generic diagnostic and, optionally, add the hints to it.
08093   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
08094   FDiag << (unsigned) FnKind << FnDesc
08095     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
08096     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
08097     << (unsigned) (Cand->Fix.Kind);
08098 
08099   // If we can fix the conversion, suggest the FixIts.
08100   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
08101        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
08102     FDiag << *HI;
08103   S.Diag(Fn->getLocation(), FDiag);
08104 
08105   MaybeEmitInheritedConstructorNote(S, Fn);
08106 }
08107 
08108 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
08109                            unsigned NumFormalArgs) {
08110   // TODO: treat calls to a missing default constructor as a special case
08111 
08112   FunctionDecl *Fn = Cand->Function;
08113   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
08114 
08115   unsigned MinParams = Fn->getMinRequiredArguments();
08116 
08117   // With invalid overloaded operators, it's possible that we think we
08118   // have an arity mismatch when it fact it looks like we have the
08119   // right number of arguments, because only overloaded operators have
08120   // the weird behavior of overloading member and non-member functions.
08121   // Just don't report anything.
08122   if (Fn->isInvalidDecl() && 
08123       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
08124     return;
08125 
08126   // at least / at most / exactly
08127   unsigned mode, modeCount;
08128   if (NumFormalArgs < MinParams) {
08129     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
08130            (Cand->FailureKind == ovl_fail_bad_deduction &&
08131             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
08132     if (MinParams != FnTy->getNumArgs() ||
08133         FnTy->isVariadic() || FnTy->isTemplateVariadic())
08134       mode = 0; // "at least"
08135     else
08136       mode = 2; // "exactly"
08137     modeCount = MinParams;
08138   } else {
08139     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
08140            (Cand->FailureKind == ovl_fail_bad_deduction &&
08141             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
08142     if (MinParams != FnTy->getNumArgs())
08143       mode = 1; // "at most"
08144     else
08145       mode = 2; // "exactly"
08146     modeCount = FnTy->getNumArgs();
08147   }
08148 
08149   std::string Description;
08150   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
08151 
08152   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
08153     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
08154       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
08155       << Fn->getParamDecl(0) << NumFormalArgs;
08156   else
08157     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
08158       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
08159       << modeCount << NumFormalArgs;
08160   MaybeEmitInheritedConstructorNote(S, Fn);
08161 }
08162 
08163 /// Diagnose a failed template-argument deduction.
08164 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
08165                           unsigned NumArgs) {
08166   FunctionDecl *Fn = Cand->Function; // pattern
08167 
08168   TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
08169   NamedDecl *ParamD;
08170   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
08171   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
08172   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
08173   switch (Cand->DeductionFailure.Result) {
08174   case Sema::TDK_Success:
08175     llvm_unreachable("TDK_success while diagnosing bad deduction");
08176 
08177   case Sema::TDK_Incomplete: {
08178     assert(ParamD && "no parameter found for incomplete deduction result");
08179     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
08180       << ParamD->getDeclName();
08181     MaybeEmitInheritedConstructorNote(S, Fn);
08182     return;
08183   }
08184 
08185   case Sema::TDK_Underqualified: {
08186     assert(ParamD && "no parameter found for bad qualifiers deduction result");
08187     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
08188 
08189     QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
08190 
08191     // Param will have been canonicalized, but it should just be a
08192     // qualified version of ParamD, so move the qualifiers to that.
08193     QualifierCollector Qs;
08194     Qs.strip(Param);
08195     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
08196     assert(S.Context.hasSameType(Param, NonCanonParam));
08197 
08198     // Arg has also been canonicalized, but there's nothing we can do
08199     // about that.  It also doesn't matter as much, because it won't
08200     // have any template parameters in it (because deduction isn't
08201     // done on dependent types).
08202     QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
08203 
08204     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
08205       << ParamD->getDeclName() << Arg << NonCanonParam;
08206     MaybeEmitInheritedConstructorNote(S, Fn);
08207     return;
08208   }
08209 
08210   case Sema::TDK_Inconsistent: {
08211     assert(ParamD && "no parameter found for inconsistent deduction result");
08212     int which = 0;
08213     if (isa<TemplateTypeParmDecl>(ParamD))
08214       which = 0;
08215     else if (isa<NonTypeTemplateParmDecl>(ParamD))
08216       which = 1;
08217     else {
08218       which = 2;
08219     }
08220 
08221     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
08222       << which << ParamD->getDeclName()
08223       << *Cand->DeductionFailure.getFirstArg()
08224       << *Cand->DeductionFailure.getSecondArg();
08225     MaybeEmitInheritedConstructorNote(S, Fn);
08226     return;
08227   }
08228 
08229   case Sema::TDK_InvalidExplicitArguments:
08230     assert(ParamD && "no parameter found for invalid explicit arguments");
08231     if (ParamD->getDeclName())
08232       S.Diag(Fn->getLocation(),
08233              diag::note_ovl_candidate_explicit_arg_mismatch_named)
08234         << ParamD->getDeclName();
08235     else {
08236       int index = 0;
08237       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
08238         index = TTP->getIndex();
08239       else if (NonTypeTemplateParmDecl *NTTP
08240                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
08241         index = NTTP->getIndex();
08242       else
08243         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
08244       S.Diag(Fn->getLocation(),
08245              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
08246         << (index + 1);
08247     }
08248     MaybeEmitInheritedConstructorNote(S, Fn);
08249     return;
08250 
08251   case Sema::TDK_TooManyArguments:
08252   case Sema::TDK_TooFewArguments:
08253     DiagnoseArityMismatch(S, Cand, NumArgs);
08254     return;
08255 
08256   case Sema::TDK_InstantiationDepth:
08257     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
08258     MaybeEmitInheritedConstructorNote(S, Fn);
08259     return;
08260 
08261   case Sema::TDK_SubstitutionFailure: {
08262     // Format the template argument list into the argument string.
08263     llvm::SmallString<128> TemplateArgString;
08264     if (TemplateArgumentList *Args =
08265           Cand->DeductionFailure.getTemplateArgumentList()) {
08266       TemplateArgString = " ";
08267       TemplateArgString += S.getTemplateArgumentBindingsText(
08268           Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
08269     }
08270 
08271     // If this candidate was disabled by enable_if, say so.
08272     PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
08273     if (PDiag && PDiag->second.getDiagID() ==
08274           diag::err_typename_nested_not_found_enable_if) {
08275       // FIXME: Use the source range of the condition, and the fully-qualified
08276       //        name of the enable_if template. These are both present in PDiag.
08277       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
08278         << "'enable_if'" << TemplateArgString;
08279       return;
08280     }
08281 
08282     // Format the SFINAE diagnostic into the argument string.
08283     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
08284     //        formatted message in another diagnostic.
08285     llvm::SmallString<128> SFINAEArgString;
08286     SourceRange R;
08287     if (PDiag) {
08288       SFINAEArgString = ": ";
08289       R = SourceRange(PDiag->first, PDiag->first);
08290       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
08291     }
08292 
08293     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
08294       << TemplateArgString << SFINAEArgString << R;
08295     MaybeEmitInheritedConstructorNote(S, Fn);
08296     return;
08297   }
08298 
08299   // TODO: diagnose these individually, then kill off
08300   // note_ovl_candidate_bad_deduction, which is uselessly vague.
08301   case Sema::TDK_NonDeducedMismatch:
08302   case Sema::TDK_FailedOverloadResolution:
08303     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
08304     MaybeEmitInheritedConstructorNote(S, Fn);
08305     return;
08306   }
08307 }
08308 
08309 /// CUDA: diagnose an invalid call across targets.
08310 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
08311   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
08312   FunctionDecl *Callee = Cand->Function;
08313 
08314   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
08315                            CalleeTarget = S.IdentifyCUDATarget(Callee);
08316 
08317   std::string FnDesc;
08318   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
08319 
08320   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
08321       << (unsigned) FnKind << CalleeTarget << CallerTarget;
08322 }
08323 
08324 /// Generates a 'note' diagnostic for an overload candidate.  We've
08325 /// already generated a primary error at the call site.
08326 ///
08327 /// It really does need to be a single diagnostic with its caret
08328 /// pointed at the candidate declaration.  Yes, this creates some
08329 /// major challenges of technical writing.  Yes, this makes pointing
08330 /// out problems with specific arguments quite awkward.  It's still
08331 /// better than generating twenty screens of text for every failed
08332 /// overload.
08333 ///
08334 /// It would be great to be able to express per-candidate problems
08335 /// more richly for those diagnostic clients that cared, but we'd
08336 /// still have to be just as careful with the default diagnostics.
08337 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
08338                            unsigned NumArgs) {
08339   FunctionDecl *Fn = Cand->Function;
08340 
08341   // Note deleted candidates, but only if they're viable.
08342   if (Cand->Viable && (Fn->isDeleted() ||
08343       S.isFunctionConsideredUnavailable(Fn))) {
08344     std::string FnDesc;
08345     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
08346 
08347     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
08348       << FnKind << FnDesc
08349       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
08350     MaybeEmitInheritedConstructorNote(S, Fn);
08351     return;
08352   }
08353 
08354   // We don't really have anything else to say about viable candidates.
08355   if (Cand->Viable) {
08356     S.NoteOverloadCandidate(Fn);
08357     return;
08358   }
08359 
08360   switch (Cand->FailureKind) {
08361   case ovl_fail_too_many_arguments:
08362   case ovl_fail_too_few_arguments:
08363     return DiagnoseArityMismatch(S, Cand, NumArgs);
08364 
08365   case ovl_fail_bad_deduction:
08366     return DiagnoseBadDeduction(S, Cand, NumArgs);
08367 
08368   case ovl_fail_trivial_conversion:
08369   case ovl_fail_bad_final_conversion:
08370   case ovl_fail_final_conversion_not_exact:
08371     return S.NoteOverloadCandidate(Fn);
08372 
08373   case ovl_fail_bad_conversion: {
08374     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
08375     for (unsigned N = Cand->NumConversions; I != N; ++I)
08376       if (Cand->Conversions[I].isBad())
08377         return DiagnoseBadConversion(S, Cand, I);
08378 
08379     // FIXME: this currently happens when we're called from SemaInit
08380     // when user-conversion overload fails.  Figure out how to handle
08381     // those conditions and diagnose them well.
08382     return S.NoteOverloadCandidate(Fn);
08383   }
08384 
08385   case ovl_fail_bad_target:
08386     return DiagnoseBadTarget(S, Cand);
08387   }
08388 }
08389 
08390 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
08391   // Desugar the type of the surrogate down to a function type,
08392   // retaining as many typedefs as possible while still showing
08393   // the function type (and, therefore, its parameter types).
08394   QualType FnType = Cand->Surrogate->getConversionType();
08395   bool isLValueReference = false;
08396   bool isRValueReference = false;
08397   bool isPointer = false;
08398   if (const LValueReferenceType *FnTypeRef =
08399         FnType->getAs<LValueReferenceType>()) {
08400     FnType = FnTypeRef->getPointeeType();
08401     isLValueReference = true;
08402   } else if (const RValueReferenceType *FnTypeRef =
08403                FnType->getAs<RValueReferenceType>()) {
08404     FnType = FnTypeRef->getPointeeType();
08405     isRValueReference = true;
08406   }
08407   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
08408     FnType = FnTypePtr->getPointeeType();
08409     isPointer = true;
08410   }
08411   // Desugar down to a function type.
08412   FnType = QualType(FnType->getAs<FunctionType>(), 0);
08413   // Reconstruct the pointer/reference as appropriate.
08414   if (isPointer) FnType = S.Context.getPointerType(FnType);
08415   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
08416   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
08417 
08418   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
08419     << FnType;
08420   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
08421 }
08422 
08423 void NoteBuiltinOperatorCandidate(Sema &S,
08424                                   const char *Opc,
08425                                   SourceLocation OpLoc,
08426                                   OverloadCandidate *Cand) {
08427   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
08428   std::string TypeStr("operator");
08429   TypeStr += Opc;
08430   TypeStr += "(";
08431   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
08432   if (Cand->NumConversions == 1) {
08433     TypeStr += ")";
08434     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
08435   } else {
08436     TypeStr += ", ";
08437     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
08438     TypeStr += ")";
08439     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
08440   }
08441 }
08442 
08443 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
08444                                   OverloadCandidate *Cand) {
08445   unsigned NoOperands = Cand->NumConversions;
08446   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
08447     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
08448     if (ICS.isBad()) break; // all meaningless after first invalid
08449     if (!ICS.isAmbiguous()) continue;
08450 
08451     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
08452                               S.PDiag(diag::note_ambiguous_type_conversion));
08453   }
08454 }
08455 
08456 SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
08457   if (Cand->Function)
08458     return Cand->Function->getLocation();
08459   if (Cand->IsSurrogate)
08460     return Cand->Surrogate->getLocation();
08461   return SourceLocation();
08462 }
08463 
08464 static unsigned
08465 RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
08466   switch ((Sema::TemplateDeductionResult)DFI.Result) {
08467   case Sema::TDK_Success:
08468     llvm_unreachable("TDK_success while diagnosing bad deduction");
08469 
08470   case Sema::TDK_Incomplete:
08471     return 1;
08472 
08473   case Sema::TDK_Underqualified:
08474   case Sema::TDK_Inconsistent:
08475     return 2;
08476 
08477   case Sema::TDK_SubstitutionFailure:
08478   case Sema::TDK_NonDeducedMismatch:
08479     return 3;
08480 
08481   case Sema::TDK_InstantiationDepth:
08482   case Sema::TDK_FailedOverloadResolution:
08483     return 4;
08484 
08485   case Sema::TDK_InvalidExplicitArguments:
08486     return 5;
08487 
08488   case Sema::TDK_TooManyArguments:
08489   case Sema::TDK_TooFewArguments:
08490     return 6;
08491   }
08492   llvm_unreachable("Unhandled deduction result");
08493 }
08494 
08495 struct CompareOverloadCandidatesForDisplay {
08496   Sema &S;
08497   CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
08498 
08499   bool operator()(const OverloadCandidate *L,
08500                   const OverloadCandidate *R) {
08501     // Fast-path this check.
08502     if (L == R) return false;
08503 
08504     // Order first by viability.
08505     if (L->Viable) {
08506       if (!R->Viable) return true;
08507 
08508       // TODO: introduce a tri-valued comparison for overload
08509       // candidates.  Would be more worthwhile if we had a sort
08510       // that could exploit it.
08511       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
08512       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
08513     } else if (R->Viable)
08514       return false;
08515 
08516     assert(L->Viable == R->Viable);
08517 
08518     // Criteria by which we can sort non-viable candidates:
08519     if (!L->Viable) {
08520       // 1. Arity mismatches come after other candidates.
08521       if (L->FailureKind == ovl_fail_too_many_arguments ||
08522           L->FailureKind == ovl_fail_too_few_arguments)
08523         return false;
08524       if (R->FailureKind == ovl_fail_too_many_arguments ||
08525           R->FailureKind == ovl_fail_too_few_arguments)
08526         return true;
08527 
08528       // 2. Bad conversions come first and are ordered by the number
08529       // of bad conversions and quality of good conversions.
08530       if (L->FailureKind == ovl_fail_bad_conversion) {
08531         if (R->FailureKind != ovl_fail_bad_conversion)
08532           return true;
08533 
08534         // The conversion that can be fixed with a smaller number of changes,
08535         // comes first.
08536         unsigned numLFixes = L->Fix.NumConversionsFixed;
08537         unsigned numRFixes = R->Fix.NumConversionsFixed;
08538         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
08539         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
08540         if (numLFixes != numRFixes) {
08541           if (numLFixes < numRFixes)
08542             return true;
08543           else
08544             return false;
08545         }
08546 
08547         // If there's any ordering between the defined conversions...
08548         // FIXME: this might not be transitive.
08549         assert(L->NumConversions == R->NumConversions);
08550 
08551         int leftBetter = 0;
08552         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
08553         for (unsigned E = L->NumConversions; I != E; ++I) {
08554           switch (CompareImplicitConversionSequences(S,
08555                                                      L->Conversions[I],
08556                                                      R->Conversions[I])) {
08557           case ImplicitConversionSequence::Better:
08558             leftBetter++;
08559             break;
08560 
08561           case ImplicitConversionSequence::Worse:
08562             leftBetter--;
08563             break;
08564 
08565           case ImplicitConversionSequence::Indistinguishable:
08566             break;
08567           }
08568         }
08569         if (leftBetter > 0) return true;
08570         if (leftBetter < 0) return false;
08571 
08572       } else if (R->FailureKind == ovl_fail_bad_conversion)
08573         return false;
08574 
08575       if (L->FailureKind == ovl_fail_bad_deduction) {
08576         if (R->FailureKind != ovl_fail_bad_deduction)
08577           return true;
08578 
08579         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
08580           return RankDeductionFailure(L->DeductionFailure)
08581                < RankDeductionFailure(R->DeductionFailure);
08582       } else if (R->FailureKind == ovl_fail_bad_deduction)
08583         return false;
08584 
08585       // TODO: others?
08586     }
08587 
08588     // Sort everything else by location.
08589     SourceLocation LLoc = GetLocationForCandidate(L);
08590     SourceLocation RLoc = GetLocationForCandidate(R);
08591 
08592     // Put candidates without locations (e.g. builtins) at the end.
08593     if (LLoc.isInvalid()) return false;
08594     if (RLoc.isInvalid()) return true;
08595 
08596     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
08597   }
08598 };
08599 
08600 /// CompleteNonViableCandidate - Normally, overload resolution only
08601 /// computes up to the first. Produces the FixIt set if possible.
08602 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
08603                                 llvm::ArrayRef<Expr *> Args) {
08604   assert(!Cand->Viable);
08605 
08606   // Don't do anything on failures other than bad conversion.
08607   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
08608 
08609   // We only want the FixIts if all the arguments can be corrected.
08610   bool Unfixable = false;
08611   // Use a implicit copy initialization to check conversion fixes.
08612   Cand->Fix.setConversionChecker(TryCopyInitialization);
08613 
08614   // Skip forward to the first bad conversion.
08615   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
08616   unsigned ConvCount = Cand->NumConversions;
08617   while (true) {
08618     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
08619     ConvIdx++;
08620     if (Cand->Conversions[ConvIdx - 1].isBad()) {
08621       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
08622       break;
08623     }
08624   }
08625 
08626   if (ConvIdx == ConvCount)
08627     return;
08628 
08629   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
08630          "remaining conversion is initialized?");
08631 
08632   // FIXME: this should probably be preserved from the overload
08633   // operation somehow.
08634   bool SuppressUserConversions = false;
08635 
08636   const FunctionProtoType* Proto;
08637   unsigned ArgIdx = ConvIdx;
08638 
08639   if (Cand->IsSurrogate) {
08640     QualType ConvType
08641       = Cand->Surrogate->getConversionType().getNonReferenceType();
08642     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
08643       ConvType = ConvPtrType->getPointeeType();
08644     Proto = ConvType->getAs<FunctionProtoType>();
08645     ArgIdx--;
08646   } else if (Cand->Function) {
08647     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
08648     if (isa<CXXMethodDecl>(Cand->Function) &&
08649         !isa<CXXConstructorDecl>(Cand->Function))
08650       ArgIdx--;
08651   } else {
08652     // Builtin binary operator with a bad first conversion.
08653     assert(ConvCount <= 3);
08654     for (; ConvIdx != ConvCount; ++ConvIdx)
08655       Cand->Conversions[ConvIdx]
08656         = TryCopyInitialization(S, Args[ConvIdx],
08657                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
08658                                 SuppressUserConversions,
08659                                 /*InOverloadResolution*/ true,
08660                                 /*AllowObjCWritebackConversion=*/
08661                                   S.getLangOpts().ObjCAutoRefCount);
08662     return;
08663   }
08664 
08665   // Fill in the rest of the conversions.
08666   unsigned NumArgsInProto = Proto->getNumArgs();
08667   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
08668     if (ArgIdx < NumArgsInProto) {
08669       Cand->Conversions[ConvIdx]
08670         = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
08671                                 SuppressUserConversions,
08672                                 /*InOverloadResolution=*/true,
08673                                 /*AllowObjCWritebackConversion=*/
08674                                   S.getLangOpts().ObjCAutoRefCount);
08675       // Store the FixIt in the candidate if it exists.
08676       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
08677         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
08678     }
08679     else
08680       Cand->Conversions[ConvIdx].setEllipsis();
08681   }
08682 }
08683 
08684 } // end anonymous namespace
08685 
08686 /// PrintOverloadCandidates - When overload resolution fails, prints
08687 /// diagnostic messages containing the candidates in the candidate
08688 /// set.
08689 void OverloadCandidateSet::NoteCandidates(Sema &S,
08690                                           OverloadCandidateDisplayKind OCD,
08691                                           llvm::ArrayRef<Expr *> Args,
08692                                           const char *Opc,
08693                                           SourceLocation OpLoc) {
08694   // Sort the candidates by viability and position.  Sorting directly would
08695   // be prohibitive, so we make a set of pointers and sort those.
08696   SmallVector<OverloadCandidate*, 32> Cands;
08697   if (OCD == OCD_AllCandidates) Cands.reserve(size());
08698   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
08699     if (Cand->Viable)
08700       Cands.push_back(Cand);
08701     else if (OCD == OCD_AllCandidates) {
08702       CompleteNonViableCandidate(S, Cand, Args);
08703       if (Cand->Function || Cand->IsSurrogate)
08704         Cands.push_back(Cand);
08705       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
08706       // want to list every possible builtin candidate.
08707     }
08708   }
08709 
08710   std::sort(Cands.begin(), Cands.end(),
08711             CompareOverloadCandidatesForDisplay(S));
08712 
08713   bool ReportedAmbiguousConversions = false;
08714 
08715   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
08716   const DiagnosticsEngine::OverloadsShown ShowOverloads = 
08717       S.Diags.getShowOverloads();
08718   unsigned CandsShown = 0;
08719   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
08720     OverloadCandidate *Cand = *I;
08721 
08722     // Set an arbitrary limit on the number of candidate functions we'll spam
08723     // the user with.  FIXME: This limit should depend on details of the
08724     // candidate list.
08725     if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
08726       break;
08727     }
08728     ++CandsShown;
08729 
08730     if (Cand->Function)
08731       NoteFunctionCandidate(S, Cand, Args.size());
08732     else if (Cand->IsSurrogate)
08733       NoteSurrogateCandidate(S, Cand);
08734     else {
08735       assert(Cand->Viable &&
08736              "Non-viable built-in candidates are not added to Cands.");
08737       // Generally we only see ambiguities including viable builtin
08738       // operators if overload resolution got screwed up by an
08739       // ambiguous user-defined conversion.
08740       //
08741       // FIXME: It's quite possible for different conversions to see
08742       // different ambiguities, though.
08743       if (!ReportedAmbiguousConversions) {
08744         NoteAmbiguousUserConversions(S, OpLoc, Cand);
08745         ReportedAmbiguousConversions = true;
08746       }
08747 
08748       // If this is a viable builtin, print it.
08749       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
08750     }
08751   }
08752 
08753   if (I != E)
08754     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
08755 }
08756 
08757 // [PossiblyAFunctionType]  -->   [Return]
08758 // NonFunctionType --> NonFunctionType
08759 // R (A) --> R(A)
08760 // R (*)(A) --> R (A)
08761 // R (&)(A) --> R (A)
08762 // R (S::*)(A) --> R (A)
08763 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
08764   QualType Ret = PossiblyAFunctionType;
08765   if (const PointerType *ToTypePtr = 
08766     PossiblyAFunctionType->getAs<PointerType>())
08767     Ret = ToTypePtr->getPointeeType();
08768   else if (const ReferenceType *ToTypeRef = 
08769     PossiblyAFunctionType->getAs<ReferenceType>())
08770     Ret = ToTypeRef->getPointeeType();
08771   else if (const MemberPointerType *MemTypePtr =
08772     PossiblyAFunctionType->getAs<MemberPointerType>()) 
08773     Ret = MemTypePtr->getPointeeType();   
08774   Ret = 
08775     Context.getCanonicalType(Ret).getUnqualifiedType();
08776   return Ret;
08777 }
08778 
08779 // A helper class to help with address of function resolution
08780 // - allows us to avoid passing around all those ugly parameters
08781 class AddressOfFunctionResolver 
08782 {
08783   Sema& S;
08784   Expr* SourceExpr;
08785   const QualType& TargetType; 
08786   QualType TargetFunctionType; // Extracted function type from target type 
08787    
08788   bool Complain;
08789   //DeclAccessPair& ResultFunctionAccessPair;
08790   ASTContext& Context;
08791 
08792   bool TargetTypeIsNonStaticMemberFunction;
08793   bool FoundNonTemplateFunction;
08794 
08795   OverloadExpr::FindResult OvlExprInfo; 
08796   OverloadExpr *OvlExpr;
08797   TemplateArgumentListInfo OvlExplicitTemplateArgs;
08798   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
08799 
08800 public:
08801   AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 
08802                             const QualType& TargetType, bool Complain)
08803     : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 
08804       Complain(Complain), Context(S.getASTContext()), 
08805       TargetTypeIsNonStaticMemberFunction(
08806                                     !!TargetType->getAs<MemberPointerType>()),
08807       FoundNonTemplateFunction(false),
08808       OvlExprInfo(OverloadExpr::find(SourceExpr)),
08809       OvlExpr(OvlExprInfo.Expression)
08810   {
08811     ExtractUnqualifiedFunctionTypeFromTargetType();
08812     
08813     if (!TargetFunctionType->isFunctionType()) {        
08814       if (OvlExpr->hasExplicitTemplateArgs()) {
08815         DeclAccessPair dap;
08816         if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
08817                                             OvlExpr, false, &dap) ) {
08818 
08819           if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
08820             if (!Method->isStatic()) {
08821               // If the target type is a non-function type and the function
08822               // found is a non-static member function, pretend as if that was
08823               // the target, it's the only possible type to end up with.
08824               TargetTypeIsNonStaticMemberFunction = true;
08825 
08826               // And skip adding the function if its not in the proper form.
08827               // We'll diagnose this due to an empty set of functions.
08828               if (!OvlExprInfo.HasFormOfMemberPointer)
08829                 return;
08830             }
08831           }
08832 
08833           Matches.push_back(std::make_pair(dap,Fn));
08834         }
08835       }
08836       return;
08837     }
08838     
08839     if (OvlExpr->hasExplicitTemplateArgs())
08840       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
08841 
08842     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
08843       // C++ [over.over]p4:
08844       //   If more than one function is selected, [...]
08845       if (Matches.size() > 1) {
08846         if (FoundNonTemplateFunction)
08847           EliminateAllTemplateMatches();
08848         else
08849           EliminateAllExceptMostSpecializedTemplate();
08850       }
08851     }
08852   }
08853   
08854 private:
08855   bool isTargetTypeAFunction() const {
08856     return TargetFunctionType->isFunctionType();
08857   }
08858 
08859   // [ToType]     [Return]
08860 
08861   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
08862   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
08863   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
08864   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
08865     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
08866   }
08867 
08868   // return true if any matching specializations were found
08869   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 
08870                                    const DeclAccessPair& CurAccessFunPair) {
08871     if (CXXMethodDecl *Method
08872               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
08873       // Skip non-static function templates when converting to pointer, and
08874       // static when converting to member pointer.
08875       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
08876         return false;
08877     } 
08878     else if (TargetTypeIsNonStaticMemberFunction)
08879       return false;
08880 
08881     // C++ [over.over]p2:
08882     //   If the name is a function template, template argument deduction is
08883     //   done (14.8.2.2), and if the argument deduction succeeds, the
08884     //   resulting template argument list is used to generate a single
08885     //   function template specialization, which is added to the set of
08886     //   overloaded functions considered.
08887     FunctionDecl *Specialization = 0;
08888     TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
08889     if (Sema::TemplateDeductionResult Result
08890           = S.DeduceTemplateArguments(FunctionTemplate, 
08891                                       &OvlExplicitTemplateArgs,
08892                                       TargetFunctionType, Specialization, 
08893                                       Info)) {
08894       // FIXME: make a note of the failed deduction for diagnostics.
08895       (void)Result;
08896       return false;
08897     } 
08898     
08899     // Template argument deduction ensures that we have an exact match.
08900     // This function template specicalization works.
08901     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
08902     assert(TargetFunctionType
08903                       == Context.getCanonicalType(Specialization->getType()));
08904     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
08905     return true;
08906   }
08907   
08908   bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 
08909                                       const DeclAccessPair& CurAccessFunPair) {
08910     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
08911       // Skip non-static functions when converting to pointer, and static
08912       // when converting to member pointer.
08913       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
08914         return false;
08915     } 
08916     else if (TargetTypeIsNonStaticMemberFunction)
08917       return false;
08918 
08919     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
08920       if (S.getLangOpts().CUDA)
08921         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
08922           if (S.CheckCUDATarget(Caller, FunDecl))
08923             return false;
08924 
08925       QualType ResultTy;
08926       if (Context.hasSameUnqualifiedType(TargetFunctionType, 
08927                                          FunDecl->getType()) ||
08928           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
08929                                  ResultTy)) {
08930         Matches.push_back(std::make_pair(CurAccessFunPair,
08931           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
08932         FoundNonTemplateFunction = true;
08933         return true;
08934       }
08935     }
08936     
08937     return false;
08938   }
08939   
08940   bool FindAllFunctionsThatMatchTargetTypeExactly() {
08941     bool Ret = false;
08942     
08943     // If the overload expression doesn't have the form of a pointer to
08944     // member, don't try to convert it to a pointer-to-member type.
08945     if (IsInvalidFormOfPointerToMemberFunction())
08946       return false;
08947 
08948     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
08949                                E = OvlExpr->decls_end(); 
08950          I != E; ++I) {
08951       // Look through any using declarations to find the underlying function.
08952       NamedDecl *Fn = (*I)->getUnderlyingDecl();
08953 
08954       // C++ [over.over]p3:
08955       //   Non-member functions and static member functions match
08956       //   targets of type "pointer-to-function" or "reference-to-function."
08957       //   Nonstatic member functions match targets of
08958       //   type "pointer-to-member-function."
08959       // Note that according to DR 247, the containing class does not matter.
08960       if (FunctionTemplateDecl *FunctionTemplate
08961                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
08962         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
08963           Ret = true;
08964       }
08965       // If we have explicit template arguments supplied, skip non-templates.
08966       else if (!OvlExpr->hasExplicitTemplateArgs() &&
08967                AddMatchingNonTemplateFunction(Fn, I.getPair()))
08968         Ret = true;
08969     }
08970     assert(Ret || Matches.empty());
08971     return Ret;
08972   }
08973 
08974   void EliminateAllExceptMostSpecializedTemplate() {
08975     //   [...] and any given function template specialization F1 is
08976     //   eliminated if the set contains a second function template
08977     //   specialization whose function template is more specialized
08978     //   than the function template of F1 according to the partial
08979     //   ordering rules of 14.5.5.2.
08980 
08981     // The algorithm specified above is quadratic. We instead use a
08982     // two-pass algorithm (similar to the one used to identify the
08983     // best viable function in an overload set) that identifies the
08984     // best function template (if it exists).
08985 
08986     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
08987     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
08988       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
08989 
08990     UnresolvedSetIterator Result =
08991       S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
08992                            TPOC_Other, 0, SourceExpr->getLocStart(),
08993                            S.PDiag(),
08994                            S.PDiag(diag::err_addr_ovl_ambiguous)
08995                              << Matches[0].second->getDeclName(),
08996                            S.PDiag(diag::note_ovl_candidate)
08997                              << (unsigned) oc_function_template,
08998                            Complain, TargetFunctionType);
08999 
09000     if (Result != MatchesCopy.end()) {
09001       // Make it the first and only element
09002       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
09003       Matches[0].second = cast<FunctionDecl>(*Result);
09004       Matches.resize(1);
09005     }
09006   }
09007 
09008   void EliminateAllTemplateMatches() {
09009     //   [...] any function template specializations in the set are
09010     //   eliminated if the set also contains a non-template function, [...]
09011     for (unsigned I = 0, N = Matches.size(); I != N; ) {
09012       if (Matches[I].second->getPrimaryTemplate() == 0)
09013         ++I;
09014       else {
09015         Matches[I] = Matches[--N];
09016         Matches.set_size(N);
09017       }
09018     }
09019   }
09020 
09021 public:
09022   void ComplainNoMatchesFound() const {
09023     assert(Matches.empty());
09024     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
09025         << OvlExpr->getName() << TargetFunctionType
09026         << OvlExpr->getSourceRange();
09027     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
09028   } 
09029   
09030   bool IsInvalidFormOfPointerToMemberFunction() const {
09031     return TargetTypeIsNonStaticMemberFunction &&
09032       !OvlExprInfo.HasFormOfMemberPointer;
09033   }
09034   
09035   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
09036       // TODO: Should we condition this on whether any functions might
09037       // have matched, or is it more appropriate to do that in callers?
09038       // TODO: a fixit wouldn't hurt.
09039       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
09040         << TargetType << OvlExpr->getSourceRange();
09041   }
09042   
09043   void ComplainOfInvalidConversion() const {
09044     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
09045       << OvlExpr->getName() << TargetType;
09046   }
09047 
09048   void ComplainMultipleMatchesFound() const {
09049     assert(Matches.size() > 1);
09050     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
09051       << OvlExpr->getName()
09052       << OvlExpr->getSourceRange();
09053     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
09054   }
09055 
09056   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
09057 
09058   int getNumMatches() const { return Matches.size(); }
09059   
09060   FunctionDecl* getMatchingFunctionDecl() const {
09061     if (Matches.size() != 1) return 0;
09062     return Matches[0].second;
09063   }
09064   
09065   const DeclAccessPair* getMatchingFunctionAccessPair() const {
09066     if (Matches.size() != 1) return 0;
09067     return &Matches[0].first;
09068   }
09069 };
09070   
09071 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
09072 /// an overloaded function (C++ [over.over]), where @p From is an
09073 /// expression with overloaded function type and @p ToType is the type
09074 /// we're trying to resolve to. For example:
09075 ///
09076 /// @code
09077 /// int f(double);
09078 /// int f(int);
09079 ///
09080 /// int (*pfd)(double) = f; // selects f(double)
09081 /// @endcode
09082 ///
09083 /// This routine returns the resulting FunctionDecl if it could be
09084 /// resolved, and NULL otherwise. When @p Complain is true, this
09085 /// routine will emit diagnostics if there is an error.
09086 FunctionDecl *
09087 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
09088                                          QualType TargetType,
09089                                          bool Complain,
09090                                          DeclAccessPair &FoundResult,
09091                                          bool *pHadMultipleCandidates) {
09092   assert(AddressOfExpr->getType() == Context.OverloadTy);
09093 
09094   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
09095                                      Complain);
09096   int NumMatches = Resolver.getNumMatches();
09097   FunctionDecl* Fn = 0;
09098   if (NumMatches == 0 && Complain) {
09099     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
09100       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
09101     else
09102       Resolver.ComplainNoMatchesFound();
09103   }
09104   else if (NumMatches > 1 && Complain)
09105     Resolver.ComplainMultipleMatchesFound();
09106   else if (NumMatches == 1) {
09107     Fn = Resolver.getMatchingFunctionDecl();
09108     assert(Fn);
09109     FoundResult = *Resolver.getMatchingFunctionAccessPair();
09110     MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
09111     if (Complain)
09112       CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
09113   }
09114 
09115   if (pHadMultipleCandidates)
09116     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
09117   return Fn;
09118 }
09119 
09120 /// \brief Given an expression that refers to an overloaded function, try to
09121 /// resolve that overloaded function expression down to a single function.
09122 ///
09123 /// This routine can only resolve template-ids that refer to a single function
09124 /// template, where that template-id refers to a single template whose template
09125 /// arguments are either provided by the template-id or have defaults,
09126 /// as described in C++0x [temp.arg.explicit]p3.
09127 FunctionDecl *
09128 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 
09129                                                   bool Complain,
09130                                                   DeclAccessPair *FoundResult) {
09131   // C++ [over.over]p1:
09132   //   [...] [Note: any redundant set of parentheses surrounding the
09133   //   overloaded function name is ignored (5.1). ]
09134   // C++ [over.over]p1:
09135   //   [...] The overloaded function name can be preceded by the &
09136   //   operator.
09137 
09138   // If we didn't actually find any template-ids, we're done.
09139   if (!ovl->hasExplicitTemplateArgs())
09140     return 0;
09141 
09142   TemplateArgumentListInfo ExplicitTemplateArgs;
09143   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
09144 
09145   // Look through all of the overloaded functions, searching for one
09146   // whose type matches exactly.
09147   FunctionDecl *Matched = 0;
09148   for (UnresolvedSetIterator I = ovl->decls_begin(),
09149          E = ovl->decls_end(); I != E; ++I) {
09150     // C++0x [temp.arg.explicit]p3:
09151     //   [...] In contexts where deduction is done and fails, or in contexts
09152     //   where deduction is not done, if a template argument list is
09153     //   specified and it, along with any default template arguments,
09154     //   identifies a single function template specialization, then the
09155     //   template-id is an lvalue for the function template specialization.
09156     FunctionTemplateDecl *FunctionTemplate
09157       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
09158 
09159     // C++ [over.over]p2:
09160     //   If the name is a function template, template argument deduction is
09161     //   done (14.8.2.2), and if the argument deduction succeeds, the
09162     //   resulting template argument list is used to generate a single
09163     //   function template specialization, which is added to the set of
09164     //   overloaded functions considered.
09165     FunctionDecl *Specialization = 0;
09166     TemplateDeductionInfo Info(Context, ovl->getNameLoc());
09167     if (TemplateDeductionResult Result
09168           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
09169                                     Specialization, Info)) {
09170       // FIXME: make a note of the failed deduction for diagnostics.
09171       (void)Result;
09172       continue;
09173     }
09174 
09175     assert(Specialization && "no specialization and no error?");
09176 
09177     // Multiple matches; we can't resolve to a single declaration.
09178     if (Matched) {
09179       if (Complain) {
09180         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
09181           << ovl->getName();
09182         NoteAllOverloadCandidates(ovl);
09183       }
09184       return 0;
09185     }
09186     
09187     Matched = Specialization;
09188     if (FoundResult) *FoundResult = I.getPair();    
09189   }
09190 
09191   return Matched;
09192 }
09193 
09194 
09195 
09196 
09197 // Resolve and fix an overloaded expression that can be resolved
09198 // because it identifies a single function template specialization.
09199 //
09200 // Last three arguments should only be supplied if Complain = true
09201 //
09202 // Return true if it was logically possible to so resolve the
09203 // expression, regardless of whether or not it succeeded.  Always
09204 // returns true if 'complain' is set.
09205 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
09206                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
09207                    bool complain, const SourceRange& OpRangeForComplaining, 
09208                                            QualType DestTypeForComplaining, 
09209                                             unsigned DiagIDForComplaining) {
09210   assert(SrcExpr.get()->getType() == Context.OverloadTy);
09211 
09212   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
09213 
09214   DeclAccessPair found;
09215   ExprResult SingleFunctionExpression;
09216   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
09217                            ovl.Expression, /*complain*/ false, &found)) {
09218     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
09219       SrcExpr = ExprError();
09220       return true;
09221     }
09222 
09223     // It is only correct to resolve to an instance method if we're
09224     // resolving a form that's permitted to be a pointer to member.
09225     // Otherwise we'll end up making a bound member expression, which
09226     // is illegal in all the contexts we resolve like this.
09227     if (!ovl.HasFormOfMemberPointer &&
09228         isa<CXXMethodDecl>(fn) &&
09229         cast<CXXMethodDecl>(fn)->isInstance()) {
09230       if (!complain) return false;
09231 
09232       Diag(ovl.Expression->getExprLoc(),
09233            diag::err_bound_member_function)
09234         << 0 << ovl.Expression->getSourceRange();
09235 
09236       // TODO: I believe we only end up here if there's a mix of
09237       // static and non-static candidates (otherwise the expression
09238       // would have 'bound member' type, not 'overload' type).
09239       // Ideally we would note which candidate was chosen and why
09240       // the static candidates were rejected.
09241       SrcExpr = ExprError();
09242       return true;
09243     }
09244 
09245     // Fix the expresion to refer to 'fn'.
09246     SingleFunctionExpression =
09247       Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
09248 
09249     // If desired, do function-to-pointer decay.
09250     if (doFunctionPointerConverion) {
09251       SingleFunctionExpression =
09252         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
09253       if (SingleFunctionExpression.isInvalid()) {
09254         SrcExpr = ExprError();
09255         return true;
09256       }
09257     }
09258   }
09259 
09260   if (!SingleFunctionExpression.isUsable()) {
09261     if (complain) {
09262       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
09263         << ovl.Expression->getName()
09264         << DestTypeForComplaining
09265         << OpRangeForComplaining 
09266         << ovl.Expression->getQualifierLoc().getSourceRange();
09267       NoteAllOverloadCandidates(SrcExpr.get());
09268 
09269       SrcExpr = ExprError();
09270       return true;
09271     }
09272 
09273     return false;
09274   }
09275 
09276   SrcExpr = SingleFunctionExpression;
09277   return true;
09278 }
09279 
09280 /// \brief Add a single candidate to the overload set.
09281 static void AddOverloadedCallCandidate(Sema &S,
09282                                        DeclAccessPair FoundDecl,
09283                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
09284                                        llvm::ArrayRef<Expr *> Args,
09285                                        OverloadCandidateSet &CandidateSet,
09286                                        bool PartialOverloading,
09287                                        bool KnownValid) {
09288   NamedDecl *Callee = FoundDecl.getDecl();
09289   if (isa<UsingShadowDecl>(Callee))
09290     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
09291 
09292   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
09293     if (ExplicitTemplateArgs) {
09294       assert(!KnownValid && "Explicit template arguments?");
09295       return;
09296     }
09297     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
09298                            PartialOverloading);
09299     return;
09300   }
09301 
09302   if (FunctionTemplateDecl *FuncTemplate
09303       = dyn_cast<FunctionTemplateDecl>(Callee)) {
09304     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
09305                                    ExplicitTemplateArgs, Args, CandidateSet);
09306     return;
09307   }
09308 
09309   assert(!KnownValid && "unhandled case in overloaded call candidate");
09310 }
09311 
09312 /// \brief Add the overload candidates named by callee and/or found by argument
09313 /// dependent lookup to the given overload set.
09314 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
09315                                        llvm::ArrayRef<Expr *> Args,
09316                                        OverloadCandidateSet &CandidateSet,
09317                                        bool PartialOverloading) {
09318 
09319 #ifndef NDEBUG
09320   // Verify that ArgumentDependentLookup is consistent with the rules
09321   // in C++0x [basic.lookup.argdep]p3:
09322   //
09323   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
09324   //   and let Y be the lookup set produced by argument dependent
09325   //   lookup (defined as follows). If X contains
09326   //
09327   //     -- a declaration of a class member, or
09328   //
09329   //     -- a block-scope function declaration that is not a
09330   //        using-declaration, or
09331   //
09332   //     -- a declaration that is neither a function or a function
09333   //        template
09334   //
09335   //   then Y is empty.
09336 
09337   if (ULE->requiresADL()) {
09338     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
09339            E = ULE->decls_end(); I != E; ++I) {
09340       assert(!(*I)->getDeclContext()->isRecord());
09341       assert(isa<UsingShadowDecl>(*I) ||
09342              !(*I)->getDeclContext()->isFunctionOrMethod());
09343       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
09344     }
09345   }
09346 #endif
09347 
09348   // It would be nice to avoid this copy.
09349   TemplateArgumentListInfo TABuffer;
09350   TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
09351   if (ULE->hasExplicitTemplateArgs()) {
09352     ULE->copyTemplateArgumentsInto(TABuffer);
09353     ExplicitTemplateArgs = &TABuffer;
09354   }
09355 
09356   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
09357          E = ULE->decls_end(); I != E; ++I)
09358     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
09359                                CandidateSet, PartialOverloading,
09360                                /*KnownValid*/ true);
09361 
09362   if (ULE->requiresADL())
09363     AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
09364                                          ULE->getExprLoc(),
09365                                          Args, ExplicitTemplateArgs,
09366                                          CandidateSet, PartialOverloading,
09367                                          ULE->isStdAssociatedNamespace());
09368 }
09369 
09370 /// Attempt to recover from an ill-formed use of a non-dependent name in a
09371 /// template, where the non-dependent name was declared after the template
09372 /// was defined. This is common in code written for a compilers which do not
09373 /// correctly implement two-stage name lookup.
09374 ///
09375 /// Returns true if a viable candidate was found and a diagnostic was issued.
09376 static bool
09377 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
09378                        const CXXScopeSpec &SS, LookupResult &R,
09379                        TemplateArgumentListInfo *ExplicitTemplateArgs,
09380                        llvm::ArrayRef<Expr *> Args) {
09381   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
09382     return false;
09383 
09384   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
09385     if (DC->isTransparentContext())
09386       continue;
09387 
09388     SemaRef.LookupQualifiedName(R, DC);
09389 
09390     if (!R.empty()) {
09391       R.suppressDiagnostics();
09392 
09393       if (isa<CXXRecordDecl>(DC)) {
09394         // Don't diagnose names we find in classes; we get much better
09395         // diagnostics for these from DiagnoseEmptyLookup.
09396         R.clear();
09397         return false;
09398       }
09399 
09400       OverloadCandidateSet Candidates(FnLoc);
09401       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
09402         AddOverloadedCallCandidate(SemaRef, I.getPair(),
09403                                    ExplicitTemplateArgs, Args,
09404                                    Candidates, false, /*KnownValid*/ false);
09405 
09406       OverloadCandidateSet::iterator Best;
09407       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
09408         // No viable functions. Don't bother the user with notes for functions
09409         // which don't work and shouldn't be found anyway.
09410         R.clear();
09411         return false;
09412       }
09413 
09414       // Find the namespaces where ADL would have looked, and suggest
09415       // declaring the function there instead.
09416       Sema::AssociatedNamespaceSet AssociatedNamespaces;
09417       Sema::AssociatedClassSet AssociatedClasses;
09418       SemaRef.FindAssociatedClassesAndNamespaces(Args,
09419                                                  AssociatedNamespaces,
09420                                                  AssociatedClasses);
09421       // Never suggest declaring a function within namespace 'std'. 
09422       Sema::AssociatedNamespaceSet SuggestedNamespaces;
09423       if (DeclContext *Std = SemaRef.getStdNamespace()) {
09424         for (Sema::AssociatedNamespaceSet::iterator
09425                it = AssociatedNamespaces.begin(),
09426                end = AssociatedNamespaces.end(); it != end; ++it) {
09427           if (!Std->Encloses(*it))
09428             SuggestedNamespaces.insert(*it);
09429         }
09430       } else {
09431         // Lacking the 'std::' namespace, use all of the associated namespaces.
09432         SuggestedNamespaces = AssociatedNamespaces;
09433       }
09434 
09435       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
09436         << R.getLookupName();
09437       if (SuggestedNamespaces.empty()) {
09438         SemaRef.Diag(Best->Function->getLocation(),
09439                      diag::note_not_found_by_two_phase_lookup)
09440           << R.getLookupName() << 0;
09441       } else if (SuggestedNamespaces.size() == 1) {
09442         SemaRef.Diag(Best->Function->getLocation(),
09443                      diag::note_not_found_by_two_phase_lookup)
09444           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
09445       } else {
09446         // FIXME: It would be useful to list the associated namespaces here,
09447         // but the diagnostics infrastructure doesn't provide a way to produce
09448         // a localized representation of a list of items.
09449         SemaRef.Diag(Best->Function->getLocation(),
09450                      diag::note_not_found_by_two_phase_lookup)
09451           << R.getLookupName() << 2;
09452       }
09453 
09454       // Try to recover by calling this function.
09455       return true;
09456     }
09457 
09458     R.clear();
09459   }
09460 
09461   return false;
09462 }
09463 
09464 /// Attempt to recover from ill-formed use of a non-dependent operator in a
09465 /// template, where the non-dependent operator was declared after the template
09466 /// was defined.
09467 ///
09468 /// Returns true if a viable candidate was found and a diagnostic was issued.
09469 static bool
09470 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
09471                                SourceLocation OpLoc,
09472                                llvm::ArrayRef<Expr *> Args) {
09473   DeclarationName OpName =
09474     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
09475   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
09476   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
09477                                 /*ExplicitTemplateArgs=*/0, Args);
09478 }
09479 
09480 namespace {
09481 // Callback to limit the allowed keywords and to only accept typo corrections
09482 // that are keywords or whose decls refer to functions (or template functions)
09483 // that accept the given number of arguments.
09484 class RecoveryCallCCC : public CorrectionCandidateCallback {
09485  public:
09486   RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
09487       : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
09488     WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
09489     WantRemainingKeywords = false;
09490   }
09491 
09492   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
09493     if (!candidate.getCorrectionDecl())
09494       return candidate.isKeyword();
09495 
09496     for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
09497            DIEnd = candidate.end(); DI != DIEnd; ++DI) {
09498       FunctionDecl *FD = 0;
09499       NamedDecl *ND = (*DI)->getUnderlyingDecl();
09500       if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
09501         FD = FTD->getTemplatedDecl();
09502       if (!HasExplicitTemplateArgs && !FD) {
09503         if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
09504           // If the Decl is neither a function nor a template function,
09505           // determine if it is a pointer or reference to a function. If so,
09506           // check against the number of arguments expected for the pointee.
09507           QualType ValType = cast<ValueDecl>(ND)->getType();
09508           if (ValType->isAnyPointerType() || ValType->isReferenceType())
09509             ValType = ValType->getPointeeType();
09510           if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
09511             if (FPT->getNumArgs() == NumArgs)
09512               return true;
09513         }
09514       }
09515       if (FD && FD->getNumParams() >= NumArgs &&
09516           FD->getMinRequiredArguments() <= NumArgs)
09517         return true;
09518     }
09519     return false;
09520   }
09521 
09522  private:
09523   unsigned NumArgs;
09524   bool HasExplicitTemplateArgs;
09525 };
09526 
09527 // Callback that effectively disabled typo correction
09528 class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
09529  public:
09530   NoTypoCorrectionCCC() {
09531     WantTypeSpecifiers = false;
09532     WantExpressionKeywords = false;
09533     WantCXXNamedCasts = false;
09534     WantRemainingKeywords = false;
09535   }
09536 
09537   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
09538     return false;
09539   }
09540 };
09541 }
09542 
09543 /// Attempts to recover from a call where no functions were found.
09544 ///
09545 /// Returns true if new candidates were found.
09546 static ExprResult
09547 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
09548                       UnresolvedLookupExpr *ULE,
09549                       SourceLocation LParenLoc,
09550                       llvm::MutableArrayRef<Expr *> Args,
09551                       SourceLocation RParenLoc,
09552                       bool EmptyLookup, bool AllowTypoCorrection) {
09553 
09554   CXXScopeSpec SS;
09555   SS.Adopt(ULE->getQualifierLoc());
09556   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
09557 
09558   TemplateArgumentListInfo TABuffer;
09559   TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
09560   if (ULE->hasExplicitTemplateArgs()) {
09561     ULE->copyTemplateArgumentsInto(TABuffer);
09562     ExplicitTemplateArgs = &TABuffer;
09563   }
09564 
09565   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
09566                  Sema::LookupOrdinaryName);
09567   RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
09568   NoTypoCorrectionCCC RejectAll;
09569   CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
09570       (CorrectionCandidateCallback*)&Validator :
09571       (CorrectionCandidateCallback*)&RejectAll;
09572   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
09573                               ExplicitTemplateArgs, Args) &&
09574       (!EmptyLookup ||
09575        SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
09576                                    ExplicitTemplateArgs, Args)))
09577     return ExprError();
09578 
09579   assert(!R.empty() && "lookup results empty despite recovery");
09580 
09581   // Build an implicit member call if appropriate.  Just drop the
09582   // casts and such from the call, we don't really care.
09583   ExprResult NewFn = ExprError();
09584   if ((*R.begin())->isCXXClassMember())
09585     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
09586                                                     R, ExplicitTemplateArgs);
09587   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
09588     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
09589                                         ExplicitTemplateArgs);
09590   else
09591     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
09592 
09593   if (NewFn.isInvalid())
09594     return ExprError();
09595 
09596   // This shouldn't cause an infinite loop because we're giving it
09597   // an expression with viable lookup results, which should never
09598   // end up here.
09599   return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
09600                                MultiExprArg(Args.data(), Args.size()),
09601                                RParenLoc);
09602 }
09603 
09604 /// ResolveOverloadedCallFn - Given the call expression that calls Fn
09605 /// (which eventually refers to the declaration Func) and the call
09606 /// arguments Args/NumArgs, attempt to resolve the function call down
09607 /// to a specific function. If overload resolution succeeds, returns
09608 /// the function declaration produced by overload
09609 /// resolution. Otherwise, emits diagnostics, deletes all of the
09610 /// arguments and Fn, and returns NULL.
09611 ExprResult
09612 Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
09613                               SourceLocation LParenLoc,
09614                               Expr **Args, unsigned NumArgs,
09615                               SourceLocation RParenLoc,
09616                               Expr *ExecConfig,
09617                               bool AllowTypoCorrection) {
09618 #ifndef NDEBUG
09619   if (ULE->requiresADL()) {
09620     // To do ADL, we must have found an unqualified name.
09621     assert(!ULE->getQualifier() && "qualified name with ADL");
09622 
09623     // We don't perform ADL for implicit declarations of builtins.
09624     // Verify that this was correctly set up.
09625     FunctionDecl *F;
09626     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
09627         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
09628         F->getBuiltinID() && F->isImplicit())
09629       llvm_unreachable("performing ADL for builtin");
09630 
09631     // We don't perform ADL in C.
09632     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
09633   } else
09634     assert(!ULE->isStdAssociatedNamespace() &&
09635            "std is associated namespace but not doing ADL");
09636 #endif
09637 
09638   UnbridgedCastsSet UnbridgedCasts;
09639   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
09640     return ExprError();
09641 
09642   OverloadCandidateSet CandidateSet(Fn->getExprLoc());
09643 
09644   // Add the functions denoted by the callee to the set of candidate
09645   // functions, including those from argument-dependent lookup.
09646   AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
09647                               CandidateSet);
09648 
09649   // If we found nothing, try to recover.
09650   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
09651   // out if it fails.
09652   if (CandidateSet.empty()) {
09653     // In Microsoft mode, if we are inside a template class member function then
09654     // create a type dependent CallExpr. The goal is to postpone name lookup
09655     // to instantiation time to be able to search into type dependent base
09656     // classes.
09657     if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 
09658         (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
09659       CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
09660                                           Context.DependentTy, VK_RValue,
09661                                           RParenLoc);
09662       CE->setTypeDependent(true);
09663       return Owned(CE);
09664     }
09665     return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
09666                                  llvm::MutableArrayRef<Expr *>(Args, NumArgs),
09667                                  RParenLoc, /*EmptyLookup=*/true,
09668                                  AllowTypoCorrection);
09669   }
09670 
09671   UnbridgedCasts.restore();
09672 
09673   OverloadCandidateSet::iterator Best;
09674   switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
09675   case OR_Success: {
09676     FunctionDecl *FDecl = Best->Function;
09677     MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
09678     CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
09679     DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
09680     Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
09681     return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
09682                                  ExecConfig);
09683   }
09684 
09685   case OR_No_Viable_Function: {
09686     // Try to recover by looking for viable functions which the user might
09687     // have meant to call.
09688     ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
09689                                   llvm::MutableArrayRef<Expr *>(Args, NumArgs),
09690                                                 RParenLoc,
09691                                                 /*EmptyLookup=*/false,
09692                                                 AllowTypoCorrection);
09693     if (!Recovery.isInvalid())
09694       return Recovery;
09695 
09696     Diag(Fn->getLocStart(),
09697          diag::err_ovl_no_viable_function_in_call)
09698       << ULE->getName() << Fn->getSourceRange();
09699     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
09700                                 llvm::makeArrayRef(Args, NumArgs));
09701     break;
09702   }
09703 
09704   case OR_Ambiguous:
09705     Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
09706       << ULE->getName() << Fn->getSourceRange();
09707     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
09708                                 llvm::makeArrayRef(Args, NumArgs));
09709     break;
09710 
09711   case OR_Deleted:
09712     {
09713       Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
09714         << Best->Function->isDeleted()
09715         << ULE->getName()
09716         << getDeletedOrUnavailableSuffix(Best->Function)
09717         << Fn->getSourceRange();
09718       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
09719                                   llvm::makeArrayRef(Args, NumArgs));
09720 
09721       // We emitted an error for the unvailable/deleted function call but keep
09722       // the call in the AST.
09723       FunctionDecl *FDecl = Best->Function;
09724       Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
09725       return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
09726                                    RParenLoc, ExecConfig);
09727     }
09728   }
09729 
09730   // Overload resolution failed.
09731   return ExprError();
09732 }
09733 
09734 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
09735   return Functions.size() > 1 ||
09736     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
09737 }
09738 
09739 /// \brief Create a unary operation that may resolve to an overloaded
09740 /// operator.
09741 ///
09742 /// \param OpLoc The location of the operator itself (e.g., '*').
09743 ///
09744 /// \param OpcIn The UnaryOperator::Opcode that describes this
09745 /// operator.
09746 ///
09747 /// \param Functions The set of non-member functions that will be
09748 /// considered by overload resolution. The caller needs to build this
09749 /// set based on the context using, e.g.,
09750 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
09751 /// set should not contain any member functions; those will be added
09752 /// by CreateOverloadedUnaryOp().
09753 ///
09754 /// \param input The input argument.
09755 ExprResult
09756 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
09757                               const UnresolvedSetImpl &Fns,
09758                               Expr *Input) {
09759   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
09760 
09761   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
09762   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
09763   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
09764   // TODO: provide better source location info.
09765   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
09766 
09767   if (checkPlaceholderForOverload(*this, Input))
09768     return ExprError();
09769 
09770   Expr *Args[2] = { Input, 0 };
09771   unsigned NumArgs = 1;
09772 
09773   // For post-increment and post-decrement, add the implicit '0' as
09774   // the second argument, so that we know this is a post-increment or
09775   // post-decrement.
09776   if (Opc == UO_PostInc || Opc == UO_PostDec) {
09777     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
09778     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
09779                                      SourceLocation());
09780     NumArgs = 2;
09781   }
09782 
09783   if (Input->isTypeDependent()) {
09784     if (Fns.empty())
09785       return Owned(new (Context) UnaryOperator(Input,
09786                                                Opc,
09787                                                Context.DependentTy,
09788                                                VK_RValue, OK_Ordinary,
09789                                                OpLoc));
09790 
09791     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
09792     UnresolvedLookupExpr *Fn
09793       = UnresolvedLookupExpr::Create(Context, NamingClass,
09794                                      NestedNameSpecifierLoc(), OpNameInfo,
09795                                      /*ADL*/ true, IsOverloaded(Fns),
09796                                      Fns.begin(), Fns.end());
09797     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
09798                                                   &Args[0], NumArgs,
09799                                                    Context.DependentTy,
09800                                                    VK_RValue,
09801                                                    OpLoc));
09802   }
09803 
09804   // Build an empty overload set.
09805   OverloadCandidateSet CandidateSet(OpLoc);
09806 
09807   // Add the candidates from the given function set.
09808   AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
09809                         false);
09810 
09811   // Add operator candidates that are member functions.
09812   AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
09813 
09814   // Add candidates from ADL.
09815   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
09816                                        OpLoc, llvm::makeArrayRef(Args, NumArgs),
09817                                        /*ExplicitTemplateArgs*/ 0,
09818                                        CandidateSet);
09819 
09820   // Add builtin operator candidates.
09821   AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
09822 
09823   bool HadMultipleCandidates = (CandidateSet.size() > 1);
09824 
09825   // Perform overload resolution.
09826   OverloadCandidateSet::iterator Best;
09827   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
09828   case OR_Success: {
09829     // We found a built-in operator or an overloaded operator.
09830     FunctionDecl *FnDecl = Best->Function;
09831 
09832     if (FnDecl) {
09833       // We matched an overloaded operator. Build a call to that
09834       // operator.
09835 
09836       MarkFunctionReferenced(OpLoc, FnDecl);
09837 
09838       // Convert the arguments.
09839       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
09840         CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
09841 
09842         ExprResult InputRes =
09843           PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
09844                                               Best->FoundDecl, Method);
09845         if (InputRes.isInvalid())
09846           return ExprError();
09847         Input = InputRes.take();
09848       } else {
09849         // Convert the arguments.
09850         ExprResult InputInit
09851           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
09852                                                       Context,
09853                                                       FnDecl->getParamDecl(0)),
09854                                       SourceLocation(),
09855                                       Input);
09856         if (InputInit.isInvalid())
09857           return ExprError();
09858         Input = InputInit.take();
09859       }
09860 
09861       DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
09862 
09863       // Determine the result type.
09864       QualType ResultTy = FnDecl->getResultType();
09865       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
09866       ResultTy = ResultTy.getNonLValueExprType(Context);
09867 
09868       // Build the actual expression node.
09869       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
09870                                                 HadMultipleCandidates, OpLoc);
09871       if (FnExpr.isInvalid())
09872         return ExprError();
09873 
09874       Args[0] = Input;
09875       CallExpr *TheCall =
09876         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
09877                                           Args, NumArgs, ResultTy, VK, OpLoc);
09878 
09879       if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
09880                               FnDecl))
09881         return ExprError();
09882 
09883       return MaybeBindToTemporary(TheCall);
09884     } else {
09885       // We matched a built-in operator. Convert the arguments, then
09886       // break out so that we will build the appropriate built-in
09887       // operator node.
09888       ExprResult InputRes =
09889         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
09890                                   Best->Conversions[0], AA_Passing);
09891       if (InputRes.isInvalid())
09892         return ExprError();
09893       Input = InputRes.take();
09894       break;
09895     }
09896   }
09897 
09898   case OR_No_Viable_Function:
09899     // This is an erroneous use of an operator which can be overloaded by
09900     // a non-member function. Check for non-member operators which were
09901     // defined too late to be candidates.
09902     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
09903                                        llvm::makeArrayRef(Args, NumArgs)))
09904       // FIXME: Recover by calling the found function.
09905       return ExprError();
09906 
09907     // No viable function; fall through to handling this as a
09908     // built-in operator, which will produce an error message for us.
09909     break;
09910 
09911   case OR_Ambiguous:
09912     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
09913         << UnaryOperator::getOpcodeStr(Opc)
09914         << Input->getType()
09915         << Input->getSourceRange();
09916     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
09917                                 llvm::makeArrayRef(Args, NumArgs),
09918                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
09919     return ExprError();
09920 
09921   case OR_Deleted:
09922     Diag(OpLoc, diag::err_ovl_deleted_oper)
09923       << Best->Function->isDeleted()
09924       << UnaryOperator::getOpcodeStr(Opc)
09925       << getDeletedOrUnavailableSuffix(Best->Function)
09926       << Input->getSourceRange();
09927     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
09928                                 llvm::makeArrayRef(Args, NumArgs),
09929                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
09930     return ExprError();
09931   }
09932 
09933   // Either we found no viable overloaded operator or we matched a
09934   // built-in operator. In either case, fall through to trying to
09935   // build a built-in operation.
09936   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
09937 }
09938 
09939 /// \brief Create a binary operation that may resolve to an overloaded
09940 /// operator.
09941 ///
09942 /// \param OpLoc The location of the operator itself (e.g., '+').
09943 ///
09944 /// \param OpcIn The BinaryOperator::Opcode that describes this
09945 /// operator.
09946 ///
09947 /// \param Functions The set of non-member functions that will be
09948 /// considered by overload resolution. The caller needs to build this
09949 /// set based on the context using, e.g.,
09950 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
09951 /// set should not contain any member functions; those will be added
09952 /// by CreateOverloadedBinOp().
09953 ///
09954 /// \param LHS Left-hand argument.
09955 /// \param RHS Right-hand argument.
09956 ExprResult
09957 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
09958                             unsigned OpcIn,
09959                             const UnresolvedSetImpl &Fns,
09960                             Expr *LHS, Expr *RHS) {
09961   Expr *Args[2] = { LHS, RHS };
09962   LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
09963 
09964   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
09965   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
09966   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
09967 
09968   // If either side is type-dependent, create an appropriate dependent
09969   // expression.
09970   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
09971     if (Fns.empty()) {
09972       // If there are no functions to store, just build a dependent
09973       // BinaryOperator or CompoundAssignment.
09974       if (Opc <= BO_Assign || Opc > BO_OrAssign)
09975         return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
09976                                                   Context.DependentTy,
09977                                                   VK_RValue, OK_Ordinary,
09978                                                   OpLoc));
09979 
09980       return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
09981                                                         Context.DependentTy,
09982                                                         VK_LValue,
09983                                                         OK_Ordinary,
09984                                                         Context.DependentTy,
09985                                                         Context.DependentTy,
09986                                                         OpLoc));
09987     }
09988 
09989     // FIXME: save results of ADL from here?
09990     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
09991     // TODO: provide better source location info in DNLoc component.
09992     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
09993     UnresolvedLookupExpr *Fn
09994       = UnresolvedLookupExpr::Create(Context, NamingClass, 
09995                                      NestedNameSpecifierLoc(), OpNameInfo, 
09996                                      /*ADL*/ true, IsOverloaded(Fns),
09997                                      Fns.begin(), Fns.end());
09998     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
09999                                                    Args, 2,
10000                                                    Context.DependentTy,
10001                                                    VK_RValue,
10002                                                    OpLoc));
10003   }
10004 
10005   // Always do placeholder-like conversions on the RHS.
10006   if (checkPlaceholderForOverload(*this, Args[1]))
10007     return ExprError();
10008 
10009   // Do placeholder-like conversion on the LHS; note that we should
10010   // not get here with a PseudoObject LHS.
10011   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10012   if (checkPlaceholderForOverload(*this, Args[0]))
10013     return ExprError();
10014 
10015   // If this is the assignment operator, we only perform overload resolution
10016   // if the left-hand side is a class or enumeration type. This is actually
10017   // a hack. The standard requires that we do overload resolution between the
10018   // various built-in candidates, but as DR507 points out, this can lead to
10019   // problems. So we do it this way, which pretty much follows what GCC does.
10020   // Note that we go the traditional code path for compound assignment forms.
10021   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10022     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10023 
10024   // If this is the .* operator, which is not overloadable, just
10025   // create a built-in binary operator.
10026   if (Opc == BO_PtrMemD)
10027     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10028 
10029   // Build an empty overload set.
10030   OverloadCandidateSet CandidateSet(OpLoc);
10031 
10032   // Add the candidates from the given function set.
10033   AddFunctionCandidates(Fns, Args, CandidateSet, false);
10034 
10035   // Add operator candidates that are member functions.
10036   AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10037 
10038   // Add candidates from ADL.
10039   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10040                                        OpLoc, Args,
10041                                        /*ExplicitTemplateArgs*/ 0,
10042                                        CandidateSet);
10043 
10044   // Add builtin operator candidates.
10045   AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10046 
10047   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10048 
10049   // Perform overload resolution.
10050   OverloadCandidateSet::iterator Best;
10051   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10052     case OR_Success: {
10053       // We found a built-in operator or an overloaded operator.
10054       FunctionDecl *FnDecl = Best->Function;
10055 
10056       if (FnDecl) {
10057         // We matched an overloaded operator. Build a call to that
10058         // operator.
10059 
10060         MarkFunctionReferenced(OpLoc, FnDecl);
10061 
10062         // Convert the arguments.
10063         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10064           // Best->Access is only meaningful for class members.
10065           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10066 
10067           ExprResult Arg1 =
10068             PerformCopyInitialization(
10069               InitializedEntity::InitializeParameter(Context,
10070                                                      FnDecl->getParamDecl(0)),
10071               SourceLocation(), Owned(Args[1]));
10072           if (Arg1.isInvalid())
10073             return ExprError();
10074 
10075           ExprResult Arg0 =
10076             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10077                                                 Best->FoundDecl, Method);
10078           if (Arg0.isInvalid())
10079             return ExprError();
10080           Args[0] = Arg0.takeAs<Expr>();
10081           Args[1] = RHS = Arg1.takeAs<Expr>();
10082         } else {
10083           // Convert the arguments.
10084           ExprResult Arg0 = PerformCopyInitialization(
10085             InitializedEntity::InitializeParameter(Context,
10086                                                    FnDecl->getParamDecl(0)),
10087             SourceLocation(), Owned(Args[0]));
10088           if (Arg0.isInvalid())
10089             return ExprError();
10090 
10091           ExprResult Arg1 =
10092             PerformCopyInitialization(
10093               InitializedEntity::InitializeParameter(Context,
10094                                                      FnDecl->getParamDecl(1)),
10095               SourceLocation(), Owned(Args[1]));
10096           if (Arg1.isInvalid())
10097             return ExprError();
10098           Args[0] = LHS = Arg0.takeAs<Expr>();
10099           Args[1] = RHS = Arg1.takeAs<Expr>();
10100         }
10101 
10102         DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10103 
10104         // Determine the result type.
10105         QualType ResultTy = FnDecl->getResultType();
10106         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10107         ResultTy = ResultTy.getNonLValueExprType(Context);
10108 
10109         // Build the actual expression node.
10110         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10111                                                   HadMultipleCandidates, OpLoc);
10112         if (FnExpr.isInvalid())
10113           return ExprError();
10114 
10115         CXXOperatorCallExpr *TheCall =
10116           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10117                                             Args, 2, ResultTy, VK, OpLoc);
10118 
10119         if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10120                                 FnDecl))
10121           return ExprError();
10122 
10123         return MaybeBindToTemporary(TheCall);
10124       } else {
10125         // We matched a built-in operator. Convert the arguments, then
10126         // break out so that we will build the appropriate built-in
10127         // operator node.
10128         ExprResult ArgsRes0 =
10129           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10130                                     Best->Conversions[0], AA_Passing);
10131         if (ArgsRes0.isInvalid())
10132           return ExprError();
10133         Args[0] = ArgsRes0.take();
10134 
10135         ExprResult ArgsRes1 =
10136           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10137                                     Best->Conversions[1], AA_Passing);
10138         if (ArgsRes1.isInvalid())
10139           return ExprError();
10140         Args[1] = ArgsRes1.take();
10141         break;
10142       }
10143     }
10144 
10145     case OR_No_Viable_Function: {
10146       // C++ [over.match.oper]p9:
10147       //   If the operator is the operator , [...] and there are no
10148       //   viable functions, then the operator is assumed to be the
10149       //   built-in operator and interpreted according to clause 5.
10150       if (Opc == BO_Comma)
10151         break;
10152 
10153       // For class as left operand for assignment or compound assigment
10154       // operator do not fall through to handling in built-in, but report that
10155       // no overloaded assignment operator found
10156       ExprResult Result = ExprError();
10157       if (Args[0]->getType()->isRecordType() &&
10158           Opc >= BO_Assign && Opc <= BO_OrAssign) {
10159         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10160              << BinaryOperator::getOpcodeStr(Opc)
10161              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10162       } else {
10163         // This is an erroneous use of an operator which can be overloaded by
10164         // a non-member function. Check for non-member operators which were
10165         // defined too late to be candidates.
10166         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10167           // FIXME: Recover by calling the found function.
10168           return ExprError();
10169 
10170         // No viable function; try to create a built-in operation, which will
10171         // produce an error. Then, show the non-viable candidates.
10172         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10173       }
10174       assert(Result.isInvalid() &&
10175              "C++ binary operator overloading is missing candidates!");
10176       if (Result.isInvalid())
10177         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10178                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
10179       return move(Result);
10180     }
10181 
10182     case OR_Ambiguous:
10183       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10184           << BinaryOperator::getOpcodeStr(Opc)
10185           << Args[0]->getType() << Args[1]->getType()
10186           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10187       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10188                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
10189       return ExprError();
10190 
10191     case OR_Deleted:
10192       if (isImplicitlyDeleted(Best->Function)) {
10193         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10194         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10195           << getSpecialMember(Method)
10196           << BinaryOperator::getOpcodeStr(Opc)
10197           << getDeletedOrUnavailableSuffix(Best->Function);
10198 
10199         if (getSpecialMember(Method) != CXXInvalid) {
10200           // The user probably meant to call this special member. Just
10201           // explain why it's deleted.
10202           NoteDeletedFunction(Method);
10203           return ExprError();
10204         }
10205       } else {
10206         Diag(OpLoc, diag::err_ovl_deleted_oper)
10207           << Best->Function->isDeleted()
10208           << BinaryOperator::getOpcodeStr(Opc)
10209           << getDeletedOrUnavailableSuffix(Best->Function)
10210           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10211       }
10212       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10213                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
10214       return ExprError();
10215   }
10216 
10217   // We matched a built-in operator; build it.
10218   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10219 }
10220 
10221 ExprResult
10222 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10223                                          SourceLocation RLoc,
10224                                          Expr *Base, Expr *Idx) {
10225   Expr *Args[2] = { Base, Idx };
10226   DeclarationName OpName =
10227       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10228 
10229   // If either side is type-dependent, create an appropriate dependent
10230   // expression.
10231   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10232 
10233     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10234     // CHECKME: no 'operator' keyword?
10235     DeclarationNameInfo OpNameInfo(OpName, LLoc);
10236     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10237     UnresolvedLookupExpr *Fn
10238       = UnresolvedLookupExpr::Create(Context, NamingClass,
10239                                      NestedNameSpecifierLoc(), OpNameInfo,
10240                                      /*ADL*/ true, /*Overloaded*/ false,
10241                                      UnresolvedSetIterator(),
10242                                      UnresolvedSetIterator());
10243     // Can't add any actual overloads yet
10244 
10245     return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10246                                                    Args, 2,
10247                                                    Context.DependentTy,
10248                                                    VK_RValue,
10249                                                    RLoc));
10250   }
10251 
10252   // Handle placeholders on both operands.
10253   if (checkPlaceholderForOverload(*this, Args[0]))
10254     return ExprError();
10255   if (checkPlaceholderForOverload(*this, Args[1]))
10256     return ExprError();
10257 
10258   // Build an empty overload set.
10259   OverloadCandidateSet CandidateSet(LLoc);
10260 
10261   // Subscript can only be overloaded as a member function.
10262 
10263   // Add operator candidates that are member functions.
10264   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10265 
10266   // Add builtin operator candidates.
10267   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10268 
10269   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10270 
10271   // Perform overload resolution.
10272   OverloadCandidateSet::iterator Best;
10273   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10274     case OR_Success: {
10275       // We found a built-in operator or an overloaded operator.
10276       FunctionDecl *FnDecl = Best->Function;
10277 
10278       if (FnDecl) {
10279         // We matched an overloaded operator. Build a call to that
10280         // operator.
10281 
10282         MarkFunctionReferenced(LLoc, FnDecl);
10283 
10284         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10285         DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
10286 
10287         // Convert the arguments.
10288         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10289         ExprResult Arg0 =
10290           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10291                                               Best->FoundDecl, Method);
10292         if (Arg0.isInvalid())
10293           return ExprError();
10294         Args[0] = Arg0.take();
10295 
10296         // Convert the arguments.
10297         ExprResult InputInit
10298           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10299                                                       Context,
10300                                                       FnDecl->getParamDecl(0)),
10301                                       SourceLocation(),
10302                                       Owned(Args[1]));
10303         if (InputInit.isInvalid())
10304           return ExprError();
10305 
10306         Args[1] = InputInit.takeAs<Expr>();
10307 
10308         // Determine the result type
10309         QualType ResultTy = FnDecl->getResultType();
10310         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10311         ResultTy = ResultTy.getNonLValueExprType(Context);
10312 
10313         // Build the actual expression node.
10314         DeclarationNameInfo OpLocInfo(OpName, LLoc);
10315         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10316         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10317                                                   HadMultipleCandidates,
10318                                                   OpLocInfo.getLoc(),
10319                                                   OpLocInfo.getInfo());
10320         if (FnExpr.isInvalid())
10321           return ExprError();
10322 
10323         CXXOperatorCallExpr *TheCall =
10324           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10325                                             FnExpr.take(), Args, 2,
10326                                             ResultTy, VK, RLoc);
10327 
10328         if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10329                                 FnDecl))
10330           return ExprError();
10331 
10332         return MaybeBindToTemporary(TheCall);
10333       } else {
10334         // We matched a built-in operator. Convert the arguments, then
10335         // break out so that we will build the appropriate built-in
10336         // operator node.
10337         ExprResult ArgsRes0 =
10338           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10339                                     Best->Conversions[0], AA_Passing);
10340         if (ArgsRes0.isInvalid())
10341           return ExprError();
10342         Args[0] = ArgsRes0.take();
10343 
10344         ExprResult ArgsRes1 =
10345           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10346                                     Best->Conversions[1], AA_Passing);
10347         if (ArgsRes1.isInvalid())
10348           return ExprError();
10349         Args[1] = ArgsRes1.take();
10350 
10351         break;
10352       }
10353     }
10354 
10355     case OR_No_Viable_Function: {
10356       if (CandidateSet.empty())
10357         Diag(LLoc, diag::err_ovl_no_oper)
10358           << Args[0]->getType() << /*subscript*/ 0
10359           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10360       else
10361         Diag(LLoc, diag::err_ovl_no_viable_subscript)
10362           << Args[0]->getType()
10363           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10364       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10365                                   "[]", LLoc);
10366       return ExprError();
10367     }
10368 
10369     case OR_Ambiguous:
10370       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10371           << "[]"
10372           << Args[0]->getType() << Args[1]->getType()
10373           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10374       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10375                                   "[]", LLoc);
10376       return ExprError();
10377 
10378     case OR_Deleted:
10379       Diag(LLoc, diag::err_ovl_deleted_oper)
10380         << Best->Function->isDeleted() << "[]"
10381         << getDeletedOrUnavailableSuffix(Best->Function)
10382         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10383       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10384                                   "[]", LLoc);
10385       return ExprError();
10386     }
10387 
10388   // We matched a built-in operator; build it.
10389   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10390 }
10391 
10392 /// BuildCallToMemberFunction - Build a call to a member
10393 /// function. MemExpr is the expression that refers to the member
10394 /// function (and includes the object parameter), Args/NumArgs are the
10395 /// arguments to the function call (not including the object
10396 /// parameter). The caller needs to validate that the member
10397 /// expression refers to a non-static member function or an overloaded
10398 /// member function.
10399 ExprResult
10400 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10401                                 SourceLocation LParenLoc, Expr **Args,
10402                                 unsigned NumArgs, SourceLocation RParenLoc) {
10403   assert(MemExprE->getType() == Context.BoundMemberTy ||
10404          MemExprE->getType() == Context.OverloadTy);
10405 
10406   // Dig out the member expression. This holds both the object
10407   // argument and the member function we're referring to.
10408   Expr *NakedMemExpr = MemExprE->IgnoreParens();
10409 
10410   // Determine whether this is a call to a pointer-to-member function.
10411   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10412     assert(op->getType() == Context.BoundMemberTy);
10413     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10414 
10415     QualType fnType =
10416       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10417 
10418     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10419     QualType resultType = proto->getCallResultType(Context);
10420     ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10421 
10422     // Check that the object type isn't more qualified than the
10423     // member function we're calling.
10424     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10425 
10426     QualType objectType = op->getLHS()->getType();
10427     if (op->getOpcode() == BO_PtrMemI)
10428       objectType = objectType->castAs<PointerType>()->getPointeeType();
10429     Qualifiers objectQuals = objectType.getQualifiers();
10430 
10431     Qualifiers difference = objectQuals - funcQuals;
10432     difference.removeObjCGCAttr();
10433     difference.removeAddressSpace();
10434     if (difference) {
10435       std::string qualsString = difference.getAsString();
10436       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10437         << fnType.getUnqualifiedType()
10438         << qualsString
10439         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10440     }
10441               
10442     CXXMemberCallExpr *call
10443       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10444                                         resultType, valueKind, RParenLoc);
10445 
10446     if (CheckCallReturnType(proto->getResultType(),
10447                             op->getRHS()->getLocStart(),
10448                             call, 0))
10449       return ExprError();
10450 
10451     if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10452       return ExprError();
10453 
10454     return MaybeBindToTemporary(call);
10455   }
10456 
10457   UnbridgedCastsSet UnbridgedCasts;
10458   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10459     return ExprError();
10460 
10461   MemberExpr *MemExpr;
10462   CXXMethodDecl *Method = 0;
10463   DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
10464   NestedNameSpecifier *Qualifier = 0;
10465   if (isa<MemberExpr>(NakedMemExpr)) {
10466     MemExpr = cast<MemberExpr>(NakedMemExpr);
10467     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
10468     FoundDecl = MemExpr->getFoundDecl();
10469     Qualifier = MemExpr->getQualifier();
10470     UnbridgedCasts.restore();
10471   } else {
10472     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
10473     Qualifier = UnresExpr->getQualifier();
10474 
10475     QualType ObjectType = UnresExpr->getBaseType();
10476     Expr::Classification ObjectClassification
10477       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10478                             : UnresExpr->getBase()->Classify(Context);
10479 
10480     // Add overload candidates
10481     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
10482 
10483     // FIXME: avoid copy.
10484     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10485     if (UnresExpr->hasExplicitTemplateArgs()) {
10486       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10487       TemplateArgs = &TemplateArgsBuffer;
10488     }
10489 
10490     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10491            E = UnresExpr->decls_end(); I != E; ++I) {
10492 
10493       NamedDecl *Func = *I;
10494       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10495       if (isa<UsingShadowDecl>(Func))
10496         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10497 
10498 
10499       // Microsoft supports direct constructor calls.
10500       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
10501         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10502                              llvm::makeArrayRef(Args, NumArgs), CandidateSet);
10503       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
10504         // If explicit template arguments were provided, we can't call a
10505         // non-template member function.
10506         if (TemplateArgs)
10507           continue;
10508 
10509         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
10510                            ObjectClassification,
10511                            llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10512                            /*SuppressUserConversions=*/false);
10513       } else {
10514         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
10515                                    I.getPair(), ActingDC, TemplateArgs,
10516                                    ObjectType,  ObjectClassification,
10517                                    llvm::makeArrayRef(Args, NumArgs),
10518                                    CandidateSet,
10519                                    /*SuppressUsedConversions=*/false);
10520       }
10521     }
10522 
10523     DeclarationName DeclName = UnresExpr->getMemberName();
10524 
10525     UnbridgedCasts.restore();
10526 
10527     OverloadCandidateSet::iterator Best;
10528     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
10529                                             Best)) {
10530     case OR_Success:
10531       Method = cast<CXXMethodDecl>(Best->Function);
10532       MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
10533       FoundDecl = Best->FoundDecl;
10534       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
10535       DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
10536       break;
10537 
10538     case OR_No_Viable_Function:
10539       Diag(UnresExpr->getMemberLoc(),
10540            diag::err_ovl_no_viable_member_function_in_call)
10541         << DeclName << MemExprE->getSourceRange();
10542       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10543                                   llvm::makeArrayRef(Args, NumArgs));
10544       // FIXME: Leaking incoming expressions!
10545       return ExprError();
10546 
10547     case OR_Ambiguous:
10548       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
10549         << DeclName << MemExprE->getSourceRange();
10550       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10551                                   llvm::makeArrayRef(Args, NumArgs));
10552       // FIXME: Leaking incoming expressions!
10553       return ExprError();
10554 
10555     case OR_Deleted:
10556       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
10557         << Best->Function->isDeleted()
10558         << DeclName 
10559         << getDeletedOrUnavailableSuffix(Best->Function)
10560         << MemExprE->getSourceRange();
10561       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10562                                   llvm::makeArrayRef(Args, NumArgs));
10563       // FIXME: Leaking incoming expressions!
10564       return ExprError();
10565     }
10566 
10567     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
10568 
10569     // If overload resolution picked a static member, build a
10570     // non-member call based on that function.
10571     if (Method->isStatic()) {
10572       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10573                                    Args, NumArgs, RParenLoc);
10574     }
10575 
10576     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
10577   }
10578 
10579   QualType ResultType = Method->getResultType();
10580   ExprValueKind VK = Expr::getValueKindForType(ResultType);
10581   ResultType = ResultType.getNonLValueExprType(Context);
10582 
10583   assert(Method && "Member call to something that isn't a method?");
10584   CXXMemberCallExpr *TheCall =
10585     new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10586                                     ResultType, VK, RParenLoc);
10587 
10588   // Check for a valid return type.
10589   if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
10590                           TheCall, Method))
10591     return ExprError();
10592 
10593   // Convert the object argument (for a non-static member function call).
10594   // We only need to do this if there was actually an overload; otherwise
10595   // it was done at lookup.
10596   if (!Method->isStatic()) {
10597     ExprResult ObjectArg =
10598       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10599                                           FoundDecl, Method);
10600     if (ObjectArg.isInvalid())
10601       return ExprError();
10602     MemExpr->setBase(ObjectArg.take());
10603   }
10604 
10605   // Convert the rest of the arguments
10606   const FunctionProtoType *Proto =
10607     Method->getType()->getAs<FunctionProtoType>();
10608   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
10609                               RParenLoc))
10610     return ExprError();
10611 
10612   DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10613 
10614   if (CheckFunctionCall(Method, TheCall))
10615     return ExprError();
10616 
10617   if ((isa<CXXConstructorDecl>(CurContext) || 
10618        isa<CXXDestructorDecl>(CurContext)) && 
10619       TheCall->getMethodDecl()->isPure()) {
10620     const CXXMethodDecl *MD = TheCall->getMethodDecl();
10621 
10622     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
10623       Diag(MemExpr->getLocStart(), 
10624            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10625         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10626         << MD->getParent()->getDeclName();
10627 
10628       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
10629     }
10630   }
10631   return MaybeBindToTemporary(TheCall);
10632 }
10633 
10634 /// BuildCallToObjectOfClassType - Build a call to an object of class
10635 /// type (C++ [over.call.object]), which can end up invoking an
10636 /// overloaded function call operator (@c operator()) or performing a
10637 /// user-defined conversion on the object argument.
10638 ExprResult
10639 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
10640                                    SourceLocation LParenLoc,
10641                                    Expr **Args, unsigned NumArgs,
10642                                    SourceLocation RParenLoc) {
10643   if (checkPlaceholderForOverload(*this, Obj))
10644     return ExprError();
10645   ExprResult Object = Owned(Obj);
10646 
10647   UnbridgedCastsSet UnbridgedCasts;
10648   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10649     return ExprError();
10650 
10651   assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10652   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
10653 
10654   // C++ [over.call.object]p1:
10655   //  If the primary-expression E in the function call syntax
10656   //  evaluates to a class object of type "cv T", then the set of
10657   //  candidate functions includes at least the function call
10658   //  operators of T. The function call operators of T are obtained by
10659   //  ordinary lookup of the name operator() in the context of
10660   //  (E).operator().
10661   OverloadCandidateSet CandidateSet(LParenLoc);
10662   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
10663 
10664   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
10665                           diag::err_incomplete_object_call, Object.get()))
10666     return true;
10667 
10668   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10669   LookupQualifiedName(R, Record->getDecl());
10670   R.suppressDiagnostics();
10671 
10672   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10673        Oper != OperEnd; ++Oper) {
10674     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10675                        Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
10676                        /*SuppressUserConversions=*/ false);
10677   }
10678 
10679   // C++ [over.call.object]p2:
10680   //   In addition, for each (non-explicit in C++0x) conversion function 
10681   //   declared in T of the form
10682   //
10683   //        operator conversion-type-id () cv-qualifier;
10684   //
10685   //   where cv-qualifier is the same cv-qualification as, or a
10686   //   greater cv-qualification than, cv, and where conversion-type-id
10687   //   denotes the type "pointer to function of (P1,...,Pn) returning
10688   //   R", or the type "reference to pointer to function of
10689   //   (P1,...,Pn) returning R", or the type "reference to function
10690   //   of (P1,...,Pn) returning R", a surrogate call function [...]
10691   //   is also considered as a candidate function. Similarly,
10692   //   surrogate call functions are added to the set of candidate
10693   //   functions for each conversion function declared in an
10694   //   accessible base class provided the function is not hidden
10695   //   within T by another intervening declaration.
10696   const UnresolvedSetImpl *Conversions
10697     = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
10698   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
10699          E = Conversions->end(); I != E; ++I) {
10700     NamedDecl *D = *I;
10701     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10702     if (isa<UsingShadowDecl>(D))
10703       D = cast<UsingShadowDecl>(D)->getTargetDecl();
10704 
10705     // Skip over templated conversion functions; they aren't
10706     // surrogates.
10707     if (isa<FunctionTemplateDecl>(D))
10708       continue;
10709 
10710     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
10711     if (!Conv->isExplicit()) {
10712       // Strip the reference type (if any) and then the pointer type (if
10713       // any) to get down to what might be a function type.
10714       QualType ConvType = Conv->getConversionType().getNonReferenceType();
10715       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10716         ConvType = ConvPtrType->getPointeeType();
10717 
10718       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10719       {
10720         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10721                               Object.get(), llvm::makeArrayRef(Args, NumArgs),
10722                               CandidateSet);
10723       }
10724     }
10725   }
10726 
10727   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10728 
10729   // Perform overload resolution.
10730   OverloadCandidateSet::iterator Best;
10731   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
10732                              Best)) {
10733   case OR_Success:
10734     // Overload resolution succeeded; we'll build the appropriate call
10735     // below.
10736     break;
10737 
10738   case OR_No_Viable_Function:
10739     if (CandidateSet.empty())
10740       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
10741         << Object.get()->getType() << /*call*/ 1
10742         << Object.get()->getSourceRange();
10743     else
10744       Diag(Object.get()->getLocStart(),
10745            diag::err_ovl_no_viable_object_call)
10746         << Object.get()->getType() << Object.get()->getSourceRange();
10747     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10748                                 llvm::makeArrayRef(Args, NumArgs));
10749     break;
10750 
10751   case OR_Ambiguous:
10752     Diag(Object.get()->getLocStart(),
10753          diag::err_ovl_ambiguous_object_call)
10754       << Object.get()->getType() << Object.get()->getSourceRange();
10755     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10756                                 llvm::makeArrayRef(Args, NumArgs));
10757     break;
10758 
10759   case OR_Deleted:
10760     Diag(Object.get()->getLocStart(),
10761          diag::err_ovl_deleted_object_call)
10762       << Best->Function->isDeleted()
10763       << Object.get()->getType() 
10764       << getDeletedOrUnavailableSuffix(Best->Function)
10765       << Object.get()->getSourceRange();
10766     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10767                                 llvm::makeArrayRef(Args, NumArgs));
10768     break;
10769   }
10770 
10771   if (Best == CandidateSet.end())
10772     return true;
10773 
10774   UnbridgedCasts.restore();
10775 
10776   if (Best->Function == 0) {
10777     // Since there is no function declaration, this is one of the
10778     // surrogate candidates. Dig out the conversion function.
10779     CXXConversionDecl *Conv
10780       = cast<CXXConversionDecl>(
10781                          Best->Conversions[0].UserDefined.ConversionFunction);
10782 
10783     CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
10784     DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
10785 
10786     // We selected one of the surrogate functions that converts the
10787     // object parameter to a function pointer. Perform the conversion
10788     // on the object argument, then let ActOnCallExpr finish the job.
10789 
10790     // Create an implicit member expr to refer to the conversion operator.
10791     // and then call it.
10792     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10793                                              Conv, HadMultipleCandidates);
10794     if (Call.isInvalid())
10795       return ExprError();
10796     // Record usage of conversion in an implicit cast.
10797     Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10798                                           CK_UserDefinedConversion,
10799                                           Call.get(), 0, VK_RValue));
10800 
10801     return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
10802                          RParenLoc);
10803   }
10804 
10805   MarkFunctionReferenced(LParenLoc, Best->Function);
10806   CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
10807   DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
10808 
10809   // We found an overloaded operator(). Build a CXXOperatorCallExpr
10810   // that calls this method, using Object for the implicit object
10811   // parameter and passing along the remaining arguments.
10812   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10813   const FunctionProtoType *Proto =
10814     Method->getType()->getAs<FunctionProtoType>();
10815 
10816   unsigned NumArgsInProto = Proto->getNumArgs();
10817   unsigned NumArgsToCheck = NumArgs;
10818 
10819   // Build the full argument list for the method call (the
10820   // implicit object parameter is placed at the beginning of the
10821   // list).
10822   Expr **MethodArgs;
10823   if (NumArgs < NumArgsInProto) {
10824     NumArgsToCheck = NumArgsInProto;
10825     MethodArgs = new Expr*[NumArgsInProto + 1];
10826   } else {
10827     MethodArgs = new Expr*[NumArgs + 1];
10828   }
10829   MethodArgs[0] = Object.get();
10830   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10831     MethodArgs[ArgIdx + 1] = Args[ArgIdx];
10832 
10833   DeclarationNameInfo OpLocInfo(
10834                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10835   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
10836   ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10837                                            HadMultipleCandidates,
10838                                            OpLocInfo.getLoc(),
10839                                            OpLocInfo.getInfo());
10840   if (NewFn.isInvalid())
10841     return true;
10842 
10843   // Once we've built TheCall, all of the expressions are properly
10844   // owned.
10845   QualType ResultTy = Method->getResultType();
10846   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10847   ResultTy = ResultTy.getNonLValueExprType(Context);
10848 
10849   CXXOperatorCallExpr *TheCall =
10850     new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
10851                                       MethodArgs, NumArgs + 1,
10852                                       ResultTy, VK, RParenLoc);
10853   delete [] MethodArgs;
10854 
10855   if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
10856                           Method))
10857     return true;
10858 
10859   // We may have default arguments. If so, we need to allocate more
10860   // slots in the call for them.
10861   if (NumArgs < NumArgsInProto)
10862     TheCall->setNumArgs(Context, NumArgsInProto + 1);
10863   else if (NumArgs > NumArgsInProto)
10864     NumArgsToCheck = NumArgsInProto;
10865 
10866   bool IsError = false;
10867 
10868   // Initialize the implicit object parameter.
10869   ExprResult ObjRes =
10870     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10871                                         Best->FoundDecl, Method);
10872   if (ObjRes.isInvalid())
10873     IsError = true;
10874   else
10875     Object = move(ObjRes);
10876   TheCall->setArg(0, Object.take());
10877 
10878   // Check the argument types.
10879   for (unsigned i = 0; i != NumArgsToCheck; i++) {
10880     Expr *Arg;
10881     if (i < NumArgs) {
10882       Arg = Args[i];
10883 
10884       // Pass the argument.
10885 
10886       ExprResult InputInit
10887         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10888                                                     Context,
10889                                                     Method->getParamDecl(i)),
10890                                     SourceLocation(), Arg);
10891 
10892       IsError |= InputInit.isInvalid();
10893       Arg = InputInit.takeAs<Expr>();
10894     } else {
10895       ExprResult DefArg
10896         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10897       if (DefArg.isInvalid()) {
10898         IsError = true;
10899         break;
10900       }
10901 
10902       Arg = DefArg.takeAs<Expr>();
10903     }
10904 
10905     TheCall->setArg(i + 1, Arg);
10906   }
10907 
10908   // If this is a variadic call, handle args passed through "...".
10909   if (Proto->isVariadic()) {
10910     // Promote the arguments (C99 6.5.2.2p7).
10911     for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
10912       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10913       IsError |= Arg.isInvalid();
10914       TheCall->setArg(i + 1, Arg.take());
10915     }
10916   }
10917 
10918   if (IsError) return true;
10919 
10920   DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10921 
10922   if (CheckFunctionCall(Method, TheCall))
10923     return true;
10924 
10925   return MaybeBindToTemporary(TheCall);
10926 }
10927 
10928 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
10929 ///  (if one exists), where @c Base is an expression of class type and
10930 /// @c Member is the name of the member we're trying to find.
10931 ExprResult
10932 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
10933   assert(Base->getType()->isRecordType() &&
10934          "left-hand side must have class type");
10935 
10936   if (checkPlaceholderForOverload(*this, Base))
10937     return ExprError();
10938 
10939   SourceLocation Loc = Base->getExprLoc();
10940 
10941   // C++ [over.ref]p1:
10942   //
10943   //   [...] An expression x->m is interpreted as (x.operator->())->m
10944   //   for a class object x of type T if T::operator->() exists and if
10945   //   the operator is selected as the best match function by the
10946   //   overload resolution mechanism (13.3).
10947   DeclarationName OpName =
10948     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
10949   OverloadCandidateSet CandidateSet(Loc);
10950   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
10951 
10952   if (RequireCompleteType(Loc, Base->getType(),
10953                           diag::err_typecheck_incomplete_tag, Base))
10954     return ExprError();
10955 
10956   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10957   LookupQualifiedName(R, BaseRecord->getDecl());
10958   R.suppressDiagnostics();
10959 
10960   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10961        Oper != OperEnd; ++Oper) {
10962     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10963                        0, 0, CandidateSet, /*SuppressUserConversions=*/false);
10964   }
10965 
10966   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10967 
10968   // Perform overload resolution.
10969   OverloadCandidateSet::iterator Best;
10970   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10971   case OR_Success:
10972     // Overload resolution succeeded; we'll build the call below.
10973     break;
10974 
10975   case OR_No_Viable_Function:
10976     if (CandidateSet.empty())
10977       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
10978         << Base->getType() << Base->getSourceRange();
10979     else
10980       Diag(OpLoc, diag::err_ovl_no_viable_oper)
10981         << "operator->" << Base->getSourceRange();
10982     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
10983     return ExprError();
10984 
10985   case OR_Ambiguous:
10986     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10987       << "->" << Base->getType() << Base->getSourceRange();
10988     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
10989     return ExprError();
10990 
10991   case OR_Deleted:
10992     Diag(OpLoc,  diag::err_ovl_deleted_oper)
10993       << Best->Function->isDeleted()
10994       << "->" 
10995       << getDeletedOrUnavailableSuffix(Best->Function)
10996       << Base->getSourceRange();
10997     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
10998     return ExprError();
10999   }
11000 
11001   MarkFunctionReferenced(OpLoc, Best->Function);
11002   CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11003   DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
11004 
11005   // Convert the object parameter.
11006   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11007   ExprResult BaseResult =
11008     PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11009                                         Best->FoundDecl, Method);
11010   if (BaseResult.isInvalid())
11011     return ExprError();
11012   Base = BaseResult.take();
11013 
11014   // Build the operator call.
11015   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
11016                                             HadMultipleCandidates, OpLoc);
11017   if (FnExpr.isInvalid())
11018     return ExprError();
11019 
11020   QualType ResultTy = Method->getResultType();
11021   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11022   ResultTy = ResultTy.getNonLValueExprType(Context);
11023   CXXOperatorCallExpr *TheCall =
11024     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11025                                       &Base, 1, ResultTy, VK, OpLoc);
11026 
11027   if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11028                           Method))
11029           return ExprError();
11030 
11031   return MaybeBindToTemporary(TheCall);
11032 }
11033 
11034 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11035 /// a literal operator described by the provided lookup results.
11036 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11037                                           DeclarationNameInfo &SuffixInfo,
11038                                           ArrayRef<Expr*> Args,
11039                                           SourceLocation LitEndLoc,
11040                                        TemplateArgumentListInfo *TemplateArgs) {
11041   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11042 
11043   OverloadCandidateSet CandidateSet(UDSuffixLoc);
11044   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11045                         TemplateArgs);
11046 
11047   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11048 
11049   // Perform overload resolution. This will usually be trivial, but might need
11050   // to perform substitutions for a literal operator template.
11051   OverloadCandidateSet::iterator Best;
11052   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11053   case OR_Success:
11054   case OR_Deleted:
11055     break;
11056 
11057   case OR_No_Viable_Function:
11058     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11059       << R.getLookupName();
11060     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11061     return ExprError();
11062 
11063   case OR_Ambiguous:
11064     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11065     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11066     return ExprError();
11067   }
11068 
11069   FunctionDecl *FD = Best->Function;
11070   MarkFunctionReferenced(UDSuffixLoc, FD);
11071   DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
11072 
11073   ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11074                                         SuffixInfo.getLoc(),
11075                                         SuffixInfo.getInfo());
11076   if (Fn.isInvalid())
11077     return true;
11078 
11079   // Check the argument types. This should almost always be a no-op, except
11080   // that array-to-pointer decay is applied to string literals.
11081   Expr *ConvArgs[2];
11082   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11083     ExprResult InputInit = PerformCopyInitialization(
11084       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11085       SourceLocation(), Args[ArgIdx]);
11086     if (InputInit.isInvalid())
11087       return true;
11088     ConvArgs[ArgIdx] = InputInit.take();
11089   }
11090 
11091   QualType ResultTy = FD->getResultType();
11092   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11093   ResultTy = ResultTy.getNonLValueExprType(Context);
11094 
11095   UserDefinedLiteral *UDL =
11096     new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11097                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
11098 
11099   if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11100     return ExprError();
11101 
11102   if (CheckFunctionCall(FD, UDL))
11103     return ExprError();
11104 
11105   return MaybeBindToTemporary(UDL);
11106 }
11107 
11108 /// FixOverloadedFunctionReference - E is an expression that refers to
11109 /// a C++ overloaded function (possibly with some parentheses and
11110 /// perhaps a '&' around it). We have resolved the overloaded function
11111 /// to the function declaration Fn, so patch up the expression E to
11112 /// refer (possibly indirectly) to Fn. Returns the new expr.
11113 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11114                                            FunctionDecl *Fn) {
11115   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11116     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11117                                                    Found, Fn);
11118     if (SubExpr == PE->getSubExpr())
11119       return PE;
11120 
11121     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11122   }
11123 
11124   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11125     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11126                                                    Found, Fn);
11127     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11128                                SubExpr->getType()) &&
11129            "Implicit cast type cannot be determined from overload");
11130     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11131     if (SubExpr == ICE->getSubExpr())
11132       return ICE;
11133 
11134     return ImplicitCastExpr::Create(Context, ICE->getType(),
11135                                     ICE->getCastKind(),
11136                                     SubExpr, 0,
11137                                     ICE->getValueKind());
11138   }
11139 
11140   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11141     assert(UnOp->getOpcode() == UO_AddrOf &&
11142            "Can only take the address of an overloaded function");
11143     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11144       if (Method->isStatic()) {
11145         // Do nothing: static member functions aren't any different
11146         // from non-member functions.
11147       } else {
11148         // Fix the sub expression, which really has to be an
11149         // UnresolvedLookupExpr holding an overloaded member function
11150         // or template.
11151         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11152                                                        Found, Fn);
11153         if (SubExpr == UnOp->getSubExpr())
11154           return UnOp;
11155 
11156         assert(isa<DeclRefExpr>(SubExpr)
11157                && "fixed to something other than a decl ref");
11158         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11159                && "fixed to a member ref with no nested name qualifier");
11160 
11161         // We have taken the address of a pointer to member
11162         // function. Perform the computation here so that we get the
11163         // appropriate pointer to member type.
11164         QualType ClassType
11165           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11166         QualType MemPtrType
11167           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11168 
11169         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11170                                            VK_RValue, OK_Ordinary,
11171                                            UnOp->getOperatorLoc());
11172       }
11173     }
11174     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11175                                                    Found, Fn);
11176     if (SubExpr == UnOp->getSubExpr())
11177       return UnOp;
11178 
11179     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11180                                      Context.getPointerType(SubExpr->getType()),
11181                                        VK_RValue, OK_Ordinary,
11182                                        UnOp->getOperatorLoc());
11183   }
11184 
11185   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11186     // FIXME: avoid copy.
11187     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11188     if (ULE->hasExplicitTemplateArgs()) {
11189       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11190       TemplateArgs = &TemplateArgsBuffer;
11191     }
11192 
11193     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11194                                            ULE->getQualifierLoc(),
11195                                            ULE->getTemplateKeywordLoc(),
11196                                            Fn,
11197                                            /*enclosing*/ false, // FIXME?
11198                                            ULE->getNameLoc(),
11199                                            Fn->getType(),
11200                                            VK_LValue,
11201                                            Found.getDecl(),
11202                                            TemplateArgs);
11203     MarkDeclRefReferenced(DRE);
11204     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11205     return DRE;
11206   }
11207 
11208   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11209     // FIXME: avoid copy.
11210     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11211     if (MemExpr->hasExplicitTemplateArgs()) {
11212       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11213       TemplateArgs = &TemplateArgsBuffer;
11214     }
11215 
11216     Expr *Base;
11217 
11218     // If we're filling in a static method where we used to have an
11219     // implicit member access, rewrite to a simple decl ref.
11220     if (MemExpr->isImplicitAccess()) {
11221       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11222         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11223                                                MemExpr->getQualifierLoc(),
11224                                                MemExpr->getTemplateKeywordLoc(),
11225                                                Fn,
11226                                                /*enclosing*/ false,
11227                                                MemExpr->getMemberLoc(),
11228                                                Fn->getType(),
11229                                                VK_LValue,
11230                                                Found.getDecl(),
11231                                                TemplateArgs);
11232         MarkDeclRefReferenced(DRE);
11233         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11234         return DRE;
11235       } else {
11236         SourceLocation Loc = MemExpr->getMemberLoc();
11237         if (MemExpr->getQualifier())
11238           Loc = MemExpr->getQualifierLoc().getBeginLoc();
11239         CheckCXXThisCapture(Loc);
11240         Base = new (Context) CXXThisExpr(Loc,
11241                                          MemExpr->getBaseType(),
11242                                          /*isImplicit=*/true);
11243       }
11244     } else
11245       Base = MemExpr->getBase();
11246 
11247     ExprValueKind valueKind;
11248     QualType type;
11249     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11250       valueKind = VK_LValue;
11251       type = Fn->getType();
11252     } else {
11253       valueKind = VK_RValue;
11254       type = Context.BoundMemberTy;
11255     }
11256 
11257     MemberExpr *ME = MemberExpr::Create(Context, Base,
11258                                         MemExpr->isArrow(),
11259                                         MemExpr->getQualifierLoc(),
11260                                         MemExpr->getTemplateKeywordLoc(),
11261                                         Fn,
11262                                         Found,
11263                                         MemExpr->getMemberNameInfo(),
11264                                         TemplateArgs,
11265                                         type, valueKind, OK_Ordinary);
11266     ME->setHadMultipleCandidates(true);
11267     return ME;
11268   }
11269 
11270   llvm_unreachable("Invalid reference to overloaded function");
11271 }
11272 
11273 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11274                                                 DeclAccessPair Found,
11275                                                 FunctionDecl *Fn) {
11276   return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11277 }
11278 
11279 } // end namespace clang