SemaOverload.cpp revision 66118c215183dec714cbbdec8060497675cebcac
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/Overload.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/AST/TypeOrdering.h"
22#include "clang/Basic/Diagnostic.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
30#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallString.h"
34#include <algorithm>
35
36namespace clang {
37using namespace sema;
38
39/// A convenience routine for creating a decayed reference to a function.
40static ExprResult
41CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
42                      bool HadMultipleCandidates,
43                      SourceLocation Loc = SourceLocation(),
44                      const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
45  if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
46    return ExprError();
47  // If FoundDecl is different from Fn (such as if one is a template
48  // and the other a specialization), make sure DiagnoseUseOfDecl is
49  // called on both.
50  // FIXME: This would be more comprehensively addressed by modifying
51  // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
52  // being used.
53  if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
54    return ExprError();
55  DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
56                                                 VK_LValue, Loc, LocInfo);
57  if (HadMultipleCandidates)
58    DRE->setHadMultipleCandidates(true);
59
60  S.MarkDeclRefReferenced(DRE);
61
62  ExprResult E = S.Owned(DRE);
63  E = S.DefaultFunctionArrayConversion(E.take());
64  if (E.isInvalid())
65    return ExprError();
66  return E;
67}
68
69static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
70                                 bool InOverloadResolution,
71                                 StandardConversionSequence &SCS,
72                                 bool CStyle,
73                                 bool AllowObjCWritebackConversion);
74
75static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
76                                                 QualType &ToType,
77                                                 bool InOverloadResolution,
78                                                 StandardConversionSequence &SCS,
79                                                 bool CStyle);
80static OverloadingResult
81IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
82                        UserDefinedConversionSequence& User,
83                        OverloadCandidateSet& Conversions,
84                        bool AllowExplicit);
85
86
87static ImplicitConversionSequence::CompareKind
88CompareStandardConversionSequences(Sema &S,
89                                   const StandardConversionSequence& SCS1,
90                                   const StandardConversionSequence& SCS2);
91
92static ImplicitConversionSequence::CompareKind
93CompareQualificationConversions(Sema &S,
94                                const StandardConversionSequence& SCS1,
95                                const StandardConversionSequence& SCS2);
96
97static ImplicitConversionSequence::CompareKind
98CompareDerivedToBaseConversions(Sema &S,
99                                const StandardConversionSequence& SCS1,
100                                const StandardConversionSequence& SCS2);
101
102
103
104/// GetConversionCategory - Retrieve the implicit conversion
105/// category corresponding to the given implicit conversion kind.
106ImplicitConversionCategory
107GetConversionCategory(ImplicitConversionKind Kind) {
108  static const ImplicitConversionCategory
109    Category[(int)ICK_Num_Conversion_Kinds] = {
110    ICC_Identity,
111    ICC_Lvalue_Transformation,
112    ICC_Lvalue_Transformation,
113    ICC_Lvalue_Transformation,
114    ICC_Identity,
115    ICC_Qualification_Adjustment,
116    ICC_Promotion,
117    ICC_Promotion,
118    ICC_Promotion,
119    ICC_Conversion,
120    ICC_Conversion,
121    ICC_Conversion,
122    ICC_Conversion,
123    ICC_Conversion,
124    ICC_Conversion,
125    ICC_Conversion,
126    ICC_Conversion,
127    ICC_Conversion,
128    ICC_Conversion,
129    ICC_Conversion,
130    ICC_Conversion,
131    ICC_Conversion
132  };
133  return Category[(int)Kind];
134}
135
136/// GetConversionRank - Retrieve the implicit conversion rank
137/// corresponding to the given implicit conversion kind.
138ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
139  static const ImplicitConversionRank
140    Rank[(int)ICK_Num_Conversion_Kinds] = {
141    ICR_Exact_Match,
142    ICR_Exact_Match,
143    ICR_Exact_Match,
144    ICR_Exact_Match,
145    ICR_Exact_Match,
146    ICR_Exact_Match,
147    ICR_Promotion,
148    ICR_Promotion,
149    ICR_Promotion,
150    ICR_Conversion,
151    ICR_Conversion,
152    ICR_Conversion,
153    ICR_Conversion,
154    ICR_Conversion,
155    ICR_Conversion,
156    ICR_Conversion,
157    ICR_Conversion,
158    ICR_Conversion,
159    ICR_Conversion,
160    ICR_Conversion,
161    ICR_Complex_Real_Conversion,
162    ICR_Conversion,
163    ICR_Conversion,
164    ICR_Writeback_Conversion
165  };
166  return Rank[(int)Kind];
167}
168
169/// GetImplicitConversionName - Return the name of this kind of
170/// implicit conversion.
171const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
172  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
173    "No conversion",
174    "Lvalue-to-rvalue",
175    "Array-to-pointer",
176    "Function-to-pointer",
177    "Noreturn adjustment",
178    "Qualification",
179    "Integral promotion",
180    "Floating point promotion",
181    "Complex promotion",
182    "Integral conversion",
183    "Floating conversion",
184    "Complex conversion",
185    "Floating-integral conversion",
186    "Pointer conversion",
187    "Pointer-to-member conversion",
188    "Boolean conversion",
189    "Compatible-types conversion",
190    "Derived-to-base conversion",
191    "Vector conversion",
192    "Vector splat",
193    "Complex-real conversion",
194    "Block Pointer conversion",
195    "Transparent Union Conversion"
196    "Writeback conversion"
197  };
198  return Name[Kind];
199}
200
201/// StandardConversionSequence - Set the standard conversion
202/// sequence to the identity conversion.
203void StandardConversionSequence::setAsIdentityConversion() {
204  First = ICK_Identity;
205  Second = ICK_Identity;
206  Third = ICK_Identity;
207  DeprecatedStringLiteralToCharPtr = false;
208  QualificationIncludesObjCLifetime = false;
209  ReferenceBinding = false;
210  DirectBinding = false;
211  IsLvalueReference = true;
212  BindsToFunctionLvalue = false;
213  BindsToRvalue = false;
214  BindsImplicitObjectArgumentWithoutRefQualifier = false;
215  ObjCLifetimeConversionBinding = false;
216  CopyConstructor = 0;
217}
218
219/// getRank - Retrieve the rank of this standard conversion sequence
220/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
221/// implicit conversions.
222ImplicitConversionRank StandardConversionSequence::getRank() const {
223  ImplicitConversionRank Rank = ICR_Exact_Match;
224  if  (GetConversionRank(First) > Rank)
225    Rank = GetConversionRank(First);
226  if  (GetConversionRank(Second) > Rank)
227    Rank = GetConversionRank(Second);
228  if  (GetConversionRank(Third) > Rank)
229    Rank = GetConversionRank(Third);
230  return Rank;
231}
232
233/// isPointerConversionToBool - Determines whether this conversion is
234/// a conversion of a pointer or pointer-to-member to bool. This is
235/// used as part of the ranking of standard conversion sequences
236/// (C++ 13.3.3.2p4).
237bool StandardConversionSequence::isPointerConversionToBool() const {
238  // Note that FromType has not necessarily been transformed by the
239  // array-to-pointer or function-to-pointer implicit conversions, so
240  // check for their presence as well as checking whether FromType is
241  // a pointer.
242  if (getToType(1)->isBooleanType() &&
243      (getFromType()->isPointerType() ||
244       getFromType()->isObjCObjectPointerType() ||
245       getFromType()->isBlockPointerType() ||
246       getFromType()->isNullPtrType() ||
247       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
248    return true;
249
250  return false;
251}
252
253/// isPointerConversionToVoidPointer - Determines whether this
254/// conversion is a conversion of a pointer to a void pointer. This is
255/// used as part of the ranking of standard conversion sequences (C++
256/// 13.3.3.2p4).
257bool
258StandardConversionSequence::
259isPointerConversionToVoidPointer(ASTContext& Context) const {
260  QualType FromType = getFromType();
261  QualType ToType = getToType(1);
262
263  // Note that FromType has not necessarily been transformed by the
264  // array-to-pointer implicit conversion, so check for its presence
265  // and redo the conversion to get a pointer.
266  if (First == ICK_Array_To_Pointer)
267    FromType = Context.getArrayDecayedType(FromType);
268
269  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
270    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
271      return ToPtrType->getPointeeType()->isVoidType();
272
273  return false;
274}
275
276/// Skip any implicit casts which could be either part of a narrowing conversion
277/// or after one in an implicit conversion.
278static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
279  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
280    switch (ICE->getCastKind()) {
281    case CK_NoOp:
282    case CK_IntegralCast:
283    case CK_IntegralToBoolean:
284    case CK_IntegralToFloating:
285    case CK_FloatingToIntegral:
286    case CK_FloatingToBoolean:
287    case CK_FloatingCast:
288      Converted = ICE->getSubExpr();
289      continue;
290
291    default:
292      return Converted;
293    }
294  }
295
296  return Converted;
297}
298
299/// Check if this standard conversion sequence represents a narrowing
300/// conversion, according to C++11 [dcl.init.list]p7.
301///
302/// \param Ctx  The AST context.
303/// \param Converted  The result of applying this standard conversion sequence.
304/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
305///        value of the expression prior to the narrowing conversion.
306/// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
307///        type of the expression prior to the narrowing conversion.
308NarrowingKind
309StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
310                                             const Expr *Converted,
311                                             APValue &ConstantValue,
312                                             QualType &ConstantType) const {
313  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
314
315  // C++11 [dcl.init.list]p7:
316  //   A narrowing conversion is an implicit conversion ...
317  QualType FromType = getToType(0);
318  QualType ToType = getToType(1);
319  switch (Second) {
320  // -- from a floating-point type to an integer type, or
321  //
322  // -- from an integer type or unscoped enumeration type to a floating-point
323  //    type, except where the source is a constant expression and the actual
324  //    value after conversion will fit into the target type and will produce
325  //    the original value when converted back to the original type, or
326  case ICK_Floating_Integral:
327    if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
328      return NK_Type_Narrowing;
329    } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
330      llvm::APSInt IntConstantValue;
331      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
332      if (Initializer &&
333          Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
334        // Convert the integer to the floating type.
335        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
336        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
337                                llvm::APFloat::rmNearestTiesToEven);
338        // And back.
339        llvm::APSInt ConvertedValue = IntConstantValue;
340        bool ignored;
341        Result.convertToInteger(ConvertedValue,
342                                llvm::APFloat::rmTowardZero, &ignored);
343        // If the resulting value is different, this was a narrowing conversion.
344        if (IntConstantValue != ConvertedValue) {
345          ConstantValue = APValue(IntConstantValue);
346          ConstantType = Initializer->getType();
347          return NK_Constant_Narrowing;
348        }
349      } else {
350        // Variables are always narrowings.
351        return NK_Variable_Narrowing;
352      }
353    }
354    return NK_Not_Narrowing;
355
356  // -- from long double to double or float, or from double to float, except
357  //    where the source is a constant expression and the actual value after
358  //    conversion is within the range of values that can be represented (even
359  //    if it cannot be represented exactly), or
360  case ICK_Floating_Conversion:
361    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
362        Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
363      // FromType is larger than ToType.
364      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
365      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
366        // Constant!
367        assert(ConstantValue.isFloat());
368        llvm::APFloat FloatVal = ConstantValue.getFloat();
369        // Convert the source value into the target type.
370        bool ignored;
371        llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
372          Ctx.getFloatTypeSemantics(ToType),
373          llvm::APFloat::rmNearestTiesToEven, &ignored);
374        // If there was no overflow, the source value is within the range of
375        // values that can be represented.
376        if (ConvertStatus & llvm::APFloat::opOverflow) {
377          ConstantType = Initializer->getType();
378          return NK_Constant_Narrowing;
379        }
380      } else {
381        return NK_Variable_Narrowing;
382      }
383    }
384    return NK_Not_Narrowing;
385
386  // -- from an integer type or unscoped enumeration type to an integer type
387  //    that cannot represent all the values of the original type, except where
388  //    the source is a constant expression and the actual value after
389  //    conversion will fit into the target type and will produce the original
390  //    value when converted back to the original type.
391  case ICK_Boolean_Conversion:  // Bools are integers too.
392    if (!FromType->isIntegralOrUnscopedEnumerationType()) {
393      // Boolean conversions can be from pointers and pointers to members
394      // [conv.bool], and those aren't considered narrowing conversions.
395      return NK_Not_Narrowing;
396    }  // Otherwise, fall through to the integral case.
397  case ICK_Integral_Conversion: {
398    assert(FromType->isIntegralOrUnscopedEnumerationType());
399    assert(ToType->isIntegralOrUnscopedEnumerationType());
400    const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
401    const unsigned FromWidth = Ctx.getIntWidth(FromType);
402    const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
403    const unsigned ToWidth = Ctx.getIntWidth(ToType);
404
405    if (FromWidth > ToWidth ||
406        (FromWidth == ToWidth && FromSigned != ToSigned) ||
407        (FromSigned && !ToSigned)) {
408      // Not all values of FromType can be represented in ToType.
409      llvm::APSInt InitializerValue;
410      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
411      if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
412        // Such conversions on variables are always narrowing.
413        return NK_Variable_Narrowing;
414      }
415      bool Narrowing = false;
416      if (FromWidth < ToWidth) {
417        // Negative -> unsigned is narrowing. Otherwise, more bits is never
418        // narrowing.
419        if (InitializerValue.isSigned() && InitializerValue.isNegative())
420          Narrowing = true;
421      } else {
422        // Add a bit to the InitializerValue so we don't have to worry about
423        // signed vs. unsigned comparisons.
424        InitializerValue = InitializerValue.extend(
425          InitializerValue.getBitWidth() + 1);
426        // Convert the initializer to and from the target width and signed-ness.
427        llvm::APSInt ConvertedValue = InitializerValue;
428        ConvertedValue = ConvertedValue.trunc(ToWidth);
429        ConvertedValue.setIsSigned(ToSigned);
430        ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
431        ConvertedValue.setIsSigned(InitializerValue.isSigned());
432        // If the result is different, this was a narrowing conversion.
433        if (ConvertedValue != InitializerValue)
434          Narrowing = true;
435      }
436      if (Narrowing) {
437        ConstantType = Initializer->getType();
438        ConstantValue = APValue(InitializerValue);
439        return NK_Constant_Narrowing;
440      }
441    }
442    return NK_Not_Narrowing;
443  }
444
445  default:
446    // Other kinds of conversions are not narrowings.
447    return NK_Not_Narrowing;
448  }
449}
450
451/// DebugPrint - Print this standard conversion sequence to standard
452/// error. Useful for debugging overloading issues.
453void StandardConversionSequence::DebugPrint() const {
454  raw_ostream &OS = llvm::errs();
455  bool PrintedSomething = false;
456  if (First != ICK_Identity) {
457    OS << GetImplicitConversionName(First);
458    PrintedSomething = true;
459  }
460
461  if (Second != ICK_Identity) {
462    if (PrintedSomething) {
463      OS << " -> ";
464    }
465    OS << GetImplicitConversionName(Second);
466
467    if (CopyConstructor) {
468      OS << " (by copy constructor)";
469    } else if (DirectBinding) {
470      OS << " (direct reference binding)";
471    } else if (ReferenceBinding) {
472      OS << " (reference binding)";
473    }
474    PrintedSomething = true;
475  }
476
477  if (Third != ICK_Identity) {
478    if (PrintedSomething) {
479      OS << " -> ";
480    }
481    OS << GetImplicitConversionName(Third);
482    PrintedSomething = true;
483  }
484
485  if (!PrintedSomething) {
486    OS << "No conversions required";
487  }
488}
489
490/// DebugPrint - Print this user-defined conversion sequence to standard
491/// error. Useful for debugging overloading issues.
492void UserDefinedConversionSequence::DebugPrint() const {
493  raw_ostream &OS = llvm::errs();
494  if (Before.First || Before.Second || Before.Third) {
495    Before.DebugPrint();
496    OS << " -> ";
497  }
498  if (ConversionFunction)
499    OS << '\'' << *ConversionFunction << '\'';
500  else
501    OS << "aggregate initialization";
502  if (After.First || After.Second || After.Third) {
503    OS << " -> ";
504    After.DebugPrint();
505  }
506}
507
508/// DebugPrint - Print this implicit conversion sequence to standard
509/// error. Useful for debugging overloading issues.
510void ImplicitConversionSequence::DebugPrint() const {
511  raw_ostream &OS = llvm::errs();
512  if (isStdInitializerListElement())
513    OS << "Worst std::initializer_list element conversion: ";
514  switch (ConversionKind) {
515  case StandardConversion:
516    OS << "Standard conversion: ";
517    Standard.DebugPrint();
518    break;
519  case UserDefinedConversion:
520    OS << "User-defined conversion: ";
521    UserDefined.DebugPrint();
522    break;
523  case EllipsisConversion:
524    OS << "Ellipsis conversion";
525    break;
526  case AmbiguousConversion:
527    OS << "Ambiguous conversion";
528    break;
529  case BadConversion:
530    OS << "Bad conversion";
531    break;
532  }
533
534  OS << "\n";
535}
536
537void AmbiguousConversionSequence::construct() {
538  new (&conversions()) ConversionSet();
539}
540
541void AmbiguousConversionSequence::destruct() {
542  conversions().~ConversionSet();
543}
544
545void
546AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
547  FromTypePtr = O.FromTypePtr;
548  ToTypePtr = O.ToTypePtr;
549  new (&conversions()) ConversionSet(O.conversions());
550}
551
552namespace {
553  // Structure used by DeductionFailureInfo to store
554  // template argument information.
555  struct DFIArguments {
556    TemplateArgument FirstArg;
557    TemplateArgument SecondArg;
558  };
559  // Structure used by DeductionFailureInfo to store
560  // template parameter and template argument information.
561  struct DFIParamWithArguments : DFIArguments {
562    TemplateParameter Param;
563  };
564}
565
566/// \brief Convert from Sema's representation of template deduction information
567/// to the form used in overload-candidate information.
568DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
569                                              Sema::TemplateDeductionResult TDK,
570                                              TemplateDeductionInfo &Info) {
571  DeductionFailureInfo Result;
572  Result.Result = static_cast<unsigned>(TDK);
573  Result.HasDiagnostic = false;
574  Result.Data = 0;
575  switch (TDK) {
576  case Sema::TDK_Success:
577  case Sema::TDK_Invalid:
578  case Sema::TDK_InstantiationDepth:
579  case Sema::TDK_TooManyArguments:
580  case Sema::TDK_TooFewArguments:
581    break;
582
583  case Sema::TDK_Incomplete:
584  case Sema::TDK_InvalidExplicitArguments:
585    Result.Data = Info.Param.getOpaqueValue();
586    break;
587
588  case Sema::TDK_NonDeducedMismatch: {
589    // FIXME: Should allocate from normal heap so that we can free this later.
590    DFIArguments *Saved = new (Context) DFIArguments;
591    Saved->FirstArg = Info.FirstArg;
592    Saved->SecondArg = Info.SecondArg;
593    Result.Data = Saved;
594    break;
595  }
596
597  case Sema::TDK_Inconsistent:
598  case Sema::TDK_Underqualified: {
599    // FIXME: Should allocate from normal heap so that we can free this later.
600    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
601    Saved->Param = Info.Param;
602    Saved->FirstArg = Info.FirstArg;
603    Saved->SecondArg = Info.SecondArg;
604    Result.Data = Saved;
605    break;
606  }
607
608  case Sema::TDK_SubstitutionFailure:
609    Result.Data = Info.take();
610    if (Info.hasSFINAEDiagnostic()) {
611      PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
612          SourceLocation(), PartialDiagnostic::NullDiagnostic());
613      Info.takeSFINAEDiagnostic(*Diag);
614      Result.HasDiagnostic = true;
615    }
616    break;
617
618  case Sema::TDK_FailedOverloadResolution:
619    Result.Data = Info.Expression;
620    break;
621
622  case Sema::TDK_MiscellaneousDeductionFailure:
623    break;
624  }
625
626  return Result;
627}
628
629void DeductionFailureInfo::Destroy() {
630  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
631  case Sema::TDK_Success:
632  case Sema::TDK_Invalid:
633  case Sema::TDK_InstantiationDepth:
634  case Sema::TDK_Incomplete:
635  case Sema::TDK_TooManyArguments:
636  case Sema::TDK_TooFewArguments:
637  case Sema::TDK_InvalidExplicitArguments:
638  case Sema::TDK_FailedOverloadResolution:
639    break;
640
641  case Sema::TDK_Inconsistent:
642  case Sema::TDK_Underqualified:
643  case Sema::TDK_NonDeducedMismatch:
644    // FIXME: Destroy the data?
645    Data = 0;
646    break;
647
648  case Sema::TDK_SubstitutionFailure:
649    // FIXME: Destroy the template argument list?
650    Data = 0;
651    if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
652      Diag->~PartialDiagnosticAt();
653      HasDiagnostic = false;
654    }
655    break;
656
657  // Unhandled
658  case Sema::TDK_MiscellaneousDeductionFailure:
659    break;
660  }
661}
662
663PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
664  if (HasDiagnostic)
665    return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
666  return 0;
667}
668
669TemplateParameter DeductionFailureInfo::getTemplateParameter() {
670  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
671  case Sema::TDK_Success:
672  case Sema::TDK_Invalid:
673  case Sema::TDK_InstantiationDepth:
674  case Sema::TDK_TooManyArguments:
675  case Sema::TDK_TooFewArguments:
676  case Sema::TDK_SubstitutionFailure:
677  case Sema::TDK_NonDeducedMismatch:
678  case Sema::TDK_FailedOverloadResolution:
679    return TemplateParameter();
680
681  case Sema::TDK_Incomplete:
682  case Sema::TDK_InvalidExplicitArguments:
683    return TemplateParameter::getFromOpaqueValue(Data);
684
685  case Sema::TDK_Inconsistent:
686  case Sema::TDK_Underqualified:
687    return static_cast<DFIParamWithArguments*>(Data)->Param;
688
689  // Unhandled
690  case Sema::TDK_MiscellaneousDeductionFailure:
691    break;
692  }
693
694  return TemplateParameter();
695}
696
697TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
698  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
699  case Sema::TDK_Success:
700  case Sema::TDK_Invalid:
701  case Sema::TDK_InstantiationDepth:
702  case Sema::TDK_TooManyArguments:
703  case Sema::TDK_TooFewArguments:
704  case Sema::TDK_Incomplete:
705  case Sema::TDK_InvalidExplicitArguments:
706  case Sema::TDK_Inconsistent:
707  case Sema::TDK_Underqualified:
708  case Sema::TDK_NonDeducedMismatch:
709  case Sema::TDK_FailedOverloadResolution:
710    return 0;
711
712  case Sema::TDK_SubstitutionFailure:
713    return static_cast<TemplateArgumentList*>(Data);
714
715  // Unhandled
716  case Sema::TDK_MiscellaneousDeductionFailure:
717    break;
718  }
719
720  return 0;
721}
722
723const TemplateArgument *DeductionFailureInfo::getFirstArg() {
724  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
725  case Sema::TDK_Success:
726  case Sema::TDK_Invalid:
727  case Sema::TDK_InstantiationDepth:
728  case Sema::TDK_Incomplete:
729  case Sema::TDK_TooManyArguments:
730  case Sema::TDK_TooFewArguments:
731  case Sema::TDK_InvalidExplicitArguments:
732  case Sema::TDK_SubstitutionFailure:
733  case Sema::TDK_FailedOverloadResolution:
734    return 0;
735
736  case Sema::TDK_Inconsistent:
737  case Sema::TDK_Underqualified:
738  case Sema::TDK_NonDeducedMismatch:
739    return &static_cast<DFIArguments*>(Data)->FirstArg;
740
741  // Unhandled
742  case Sema::TDK_MiscellaneousDeductionFailure:
743    break;
744  }
745
746  return 0;
747}
748
749const TemplateArgument *DeductionFailureInfo::getSecondArg() {
750  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
751  case Sema::TDK_Success:
752  case Sema::TDK_Invalid:
753  case Sema::TDK_InstantiationDepth:
754  case Sema::TDK_Incomplete:
755  case Sema::TDK_TooManyArguments:
756  case Sema::TDK_TooFewArguments:
757  case Sema::TDK_InvalidExplicitArguments:
758  case Sema::TDK_SubstitutionFailure:
759  case Sema::TDK_FailedOverloadResolution:
760    return 0;
761
762  case Sema::TDK_Inconsistent:
763  case Sema::TDK_Underqualified:
764  case Sema::TDK_NonDeducedMismatch:
765    return &static_cast<DFIArguments*>(Data)->SecondArg;
766
767  // Unhandled
768  case Sema::TDK_MiscellaneousDeductionFailure:
769    break;
770  }
771
772  return 0;
773}
774
775Expr *DeductionFailureInfo::getExpr() {
776  if (static_cast<Sema::TemplateDeductionResult>(Result) ==
777        Sema::TDK_FailedOverloadResolution)
778    return static_cast<Expr*>(Data);
779
780  return 0;
781}
782
783void OverloadCandidateSet::destroyCandidates() {
784  for (iterator i = begin(), e = end(); i != e; ++i) {
785    for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
786      i->Conversions[ii].~ImplicitConversionSequence();
787    if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
788      i->DeductionFailure.Destroy();
789  }
790}
791
792void OverloadCandidateSet::clear() {
793  destroyCandidates();
794  NumInlineSequences = 0;
795  Candidates.clear();
796  Functions.clear();
797}
798
799namespace {
800  class UnbridgedCastsSet {
801    struct Entry {
802      Expr **Addr;
803      Expr *Saved;
804    };
805    SmallVector<Entry, 2> Entries;
806
807  public:
808    void save(Sema &S, Expr *&E) {
809      assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
810      Entry entry = { &E, E };
811      Entries.push_back(entry);
812      E = S.stripARCUnbridgedCast(E);
813    }
814
815    void restore() {
816      for (SmallVectorImpl<Entry>::iterator
817             i = Entries.begin(), e = Entries.end(); i != e; ++i)
818        *i->Addr = i->Saved;
819    }
820  };
821}
822
823/// checkPlaceholderForOverload - Do any interesting placeholder-like
824/// preprocessing on the given expression.
825///
826/// \param unbridgedCasts a collection to which to add unbridged casts;
827///   without this, they will be immediately diagnosed as errors
828///
829/// Return true on unrecoverable error.
830static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
831                                        UnbridgedCastsSet *unbridgedCasts = 0) {
832  if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
833    // We can't handle overloaded expressions here because overload
834    // resolution might reasonably tweak them.
835    if (placeholder->getKind() == BuiltinType::Overload) return false;
836
837    // If the context potentially accepts unbridged ARC casts, strip
838    // the unbridged cast and add it to the collection for later restoration.
839    if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
840        unbridgedCasts) {
841      unbridgedCasts->save(S, E);
842      return false;
843    }
844
845    // Go ahead and check everything else.
846    ExprResult result = S.CheckPlaceholderExpr(E);
847    if (result.isInvalid())
848      return true;
849
850    E = result.take();
851    return false;
852  }
853
854  // Nothing to do.
855  return false;
856}
857
858/// checkArgPlaceholdersForOverload - Check a set of call operands for
859/// placeholders.
860static bool checkArgPlaceholdersForOverload(Sema &S,
861                                            MultiExprArg Args,
862                                            UnbridgedCastsSet &unbridged) {
863  for (unsigned i = 0, e = Args.size(); i != e; ++i)
864    if (checkPlaceholderForOverload(S, Args[i], &unbridged))
865      return true;
866
867  return false;
868}
869
870// IsOverload - Determine whether the given New declaration is an
871// overload of the declarations in Old. This routine returns false if
872// New and Old cannot be overloaded, e.g., if New has the same
873// signature as some function in Old (C++ 1.3.10) or if the Old
874// declarations aren't functions (or function templates) at all. When
875// it does return false, MatchedDecl will point to the decl that New
876// cannot be overloaded with.  This decl may be a UsingShadowDecl on
877// top of the underlying declaration.
878//
879// Example: Given the following input:
880//
881//   void f(int, float); // #1
882//   void f(int, int); // #2
883//   int f(int, int); // #3
884//
885// When we process #1, there is no previous declaration of "f",
886// so IsOverload will not be used.
887//
888// When we process #2, Old contains only the FunctionDecl for #1.  By
889// comparing the parameter types, we see that #1 and #2 are overloaded
890// (since they have different signatures), so this routine returns
891// false; MatchedDecl is unchanged.
892//
893// When we process #3, Old is an overload set containing #1 and #2. We
894// compare the signatures of #3 to #1 (they're overloaded, so we do
895// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
896// identical (return types of functions are not part of the
897// signature), IsOverload returns false and MatchedDecl will be set to
898// point to the FunctionDecl for #2.
899//
900// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
901// into a class by a using declaration.  The rules for whether to hide
902// shadow declarations ignore some properties which otherwise figure
903// into a function template's signature.
904Sema::OverloadKind
905Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
906                    NamedDecl *&Match, bool NewIsUsingDecl) {
907  for (LookupResult::iterator I = Old.begin(), E = Old.end();
908         I != E; ++I) {
909    NamedDecl *OldD = *I;
910
911    bool OldIsUsingDecl = false;
912    if (isa<UsingShadowDecl>(OldD)) {
913      OldIsUsingDecl = true;
914
915      // We can always introduce two using declarations into the same
916      // context, even if they have identical signatures.
917      if (NewIsUsingDecl) continue;
918
919      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
920    }
921
922    // If either declaration was introduced by a using declaration,
923    // we'll need to use slightly different rules for matching.
924    // Essentially, these rules are the normal rules, except that
925    // function templates hide function templates with different
926    // return types or template parameter lists.
927    bool UseMemberUsingDeclRules =
928      (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
929      !New->getFriendObjectKind();
930
931    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
932      if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
933        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
934          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
935          continue;
936        }
937
938        Match = *I;
939        return Ovl_Match;
940      }
941    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
942      if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
943        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
944          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
945          continue;
946        }
947
948        if (!shouldLinkPossiblyHiddenDecl(*I, New))
949          continue;
950
951        Match = *I;
952        return Ovl_Match;
953      }
954    } else if (isa<UsingDecl>(OldD)) {
955      // We can overload with these, which can show up when doing
956      // redeclaration checks for UsingDecls.
957      assert(Old.getLookupKind() == LookupUsingDeclName);
958    } else if (isa<TagDecl>(OldD)) {
959      // We can always overload with tags by hiding them.
960    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
961      // Optimistically assume that an unresolved using decl will
962      // overload; if it doesn't, we'll have to diagnose during
963      // template instantiation.
964    } else {
965      // (C++ 13p1):
966      //   Only function declarations can be overloaded; object and type
967      //   declarations cannot be overloaded.
968      Match = *I;
969      return Ovl_NonFunction;
970    }
971  }
972
973  return Ovl_Overload;
974}
975
976bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
977                      bool UseUsingDeclRules) {
978  // C++ [basic.start.main]p2: This function shall not be overloaded.
979  if (New->isMain())
980    return false;
981
982  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
983  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
984
985  // C++ [temp.fct]p2:
986  //   A function template can be overloaded with other function templates
987  //   and with normal (non-template) functions.
988  if ((OldTemplate == 0) != (NewTemplate == 0))
989    return true;
990
991  // Is the function New an overload of the function Old?
992  QualType OldQType = Context.getCanonicalType(Old->getType());
993  QualType NewQType = Context.getCanonicalType(New->getType());
994
995  // Compare the signatures (C++ 1.3.10) of the two functions to
996  // determine whether they are overloads. If we find any mismatch
997  // in the signature, they are overloads.
998
999  // If either of these functions is a K&R-style function (no
1000  // prototype), then we consider them to have matching signatures.
1001  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1002      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1003    return false;
1004
1005  const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1006  const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
1007
1008  // The signature of a function includes the types of its
1009  // parameters (C++ 1.3.10), which includes the presence or absence
1010  // of the ellipsis; see C++ DR 357).
1011  if (OldQType != NewQType &&
1012      (OldType->getNumArgs() != NewType->getNumArgs() ||
1013       OldType->isVariadic() != NewType->isVariadic() ||
1014       !FunctionArgTypesAreEqual(OldType, NewType)))
1015    return true;
1016
1017  // C++ [temp.over.link]p4:
1018  //   The signature of a function template consists of its function
1019  //   signature, its return type and its template parameter list. The names
1020  //   of the template parameters are significant only for establishing the
1021  //   relationship between the template parameters and the rest of the
1022  //   signature.
1023  //
1024  // We check the return type and template parameter lists for function
1025  // templates first; the remaining checks follow.
1026  //
1027  // However, we don't consider either of these when deciding whether
1028  // a member introduced by a shadow declaration is hidden.
1029  if (!UseUsingDeclRules && NewTemplate &&
1030      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1031                                       OldTemplate->getTemplateParameters(),
1032                                       false, TPL_TemplateMatch) ||
1033       OldType->getResultType() != NewType->getResultType()))
1034    return true;
1035
1036  // If the function is a class member, its signature includes the
1037  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1038  //
1039  // As part of this, also check whether one of the member functions
1040  // is static, in which case they are not overloads (C++
1041  // 13.1p2). While not part of the definition of the signature,
1042  // this check is important to determine whether these functions
1043  // can be overloaded.
1044  CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1045  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1046  if (OldMethod && NewMethod &&
1047      !OldMethod->isStatic() && !NewMethod->isStatic()) {
1048    if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1049      if (!UseUsingDeclRules &&
1050          (OldMethod->getRefQualifier() == RQ_None ||
1051           NewMethod->getRefQualifier() == RQ_None)) {
1052        // C++0x [over.load]p2:
1053        //   - Member function declarations with the same name and the same
1054        //     parameter-type-list as well as member function template
1055        //     declarations with the same name, the same parameter-type-list, and
1056        //     the same template parameter lists cannot be overloaded if any of
1057        //     them, but not all, have a ref-qualifier (8.3.5).
1058        Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1059          << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1060        Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1061      }
1062      return true;
1063    }
1064
1065    // We may not have applied the implicit const for a constexpr member
1066    // function yet (because we haven't yet resolved whether this is a static
1067    // or non-static member function). Add it now, on the assumption that this
1068    // is a redeclaration of OldMethod.
1069    unsigned NewQuals = NewMethod->getTypeQualifiers();
1070    if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
1071        !isa<CXXConstructorDecl>(NewMethod))
1072      NewQuals |= Qualifiers::Const;
1073    if (OldMethod->getTypeQualifiers() != NewQuals)
1074      return true;
1075  }
1076
1077  // The signatures match; this is not an overload.
1078  return false;
1079}
1080
1081/// \brief Checks availability of the function depending on the current
1082/// function context. Inside an unavailable function, unavailability is ignored.
1083///
1084/// \returns true if \arg FD is unavailable and current context is inside
1085/// an available function, false otherwise.
1086bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1087  return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1088}
1089
1090/// \brief Tries a user-defined conversion from From to ToType.
1091///
1092/// Produces an implicit conversion sequence for when a standard conversion
1093/// is not an option. See TryImplicitConversion for more information.
1094static ImplicitConversionSequence
1095TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1096                         bool SuppressUserConversions,
1097                         bool AllowExplicit,
1098                         bool InOverloadResolution,
1099                         bool CStyle,
1100                         bool AllowObjCWritebackConversion) {
1101  ImplicitConversionSequence ICS;
1102
1103  if (SuppressUserConversions) {
1104    // We're not in the case above, so there is no conversion that
1105    // we can perform.
1106    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1107    return ICS;
1108  }
1109
1110  // Attempt user-defined conversion.
1111  OverloadCandidateSet Conversions(From->getExprLoc());
1112  OverloadingResult UserDefResult
1113    = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1114                              AllowExplicit);
1115
1116  if (UserDefResult == OR_Success) {
1117    ICS.setUserDefined();
1118    // C++ [over.ics.user]p4:
1119    //   A conversion of an expression of class type to the same class
1120    //   type is given Exact Match rank, and a conversion of an
1121    //   expression of class type to a base class of that type is
1122    //   given Conversion rank, in spite of the fact that a copy
1123    //   constructor (i.e., a user-defined conversion function) is
1124    //   called for those cases.
1125    if (CXXConstructorDecl *Constructor
1126          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1127      QualType FromCanon
1128        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1129      QualType ToCanon
1130        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1131      if (Constructor->isCopyConstructor() &&
1132          (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1133        // Turn this into a "standard" conversion sequence, so that it
1134        // gets ranked with standard conversion sequences.
1135        ICS.setStandard();
1136        ICS.Standard.setAsIdentityConversion();
1137        ICS.Standard.setFromType(From->getType());
1138        ICS.Standard.setAllToTypes(ToType);
1139        ICS.Standard.CopyConstructor = Constructor;
1140        if (ToCanon != FromCanon)
1141          ICS.Standard.Second = ICK_Derived_To_Base;
1142      }
1143    }
1144
1145    // C++ [over.best.ics]p4:
1146    //   However, when considering the argument of a user-defined
1147    //   conversion function that is a candidate by 13.3.1.3 when
1148    //   invoked for the copying of the temporary in the second step
1149    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1150    //   13.3.1.6 in all cases, only standard conversion sequences and
1151    //   ellipsis conversion sequences are allowed.
1152    if (SuppressUserConversions && ICS.isUserDefined()) {
1153      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1154    }
1155  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1156    ICS.setAmbiguous();
1157    ICS.Ambiguous.setFromType(From->getType());
1158    ICS.Ambiguous.setToType(ToType);
1159    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1160         Cand != Conversions.end(); ++Cand)
1161      if (Cand->Viable)
1162        ICS.Ambiguous.addConversion(Cand->Function);
1163  } else {
1164    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1165  }
1166
1167  return ICS;
1168}
1169
1170/// TryImplicitConversion - Attempt to perform an implicit conversion
1171/// from the given expression (Expr) to the given type (ToType). This
1172/// function returns an implicit conversion sequence that can be used
1173/// to perform the initialization. Given
1174///
1175///   void f(float f);
1176///   void g(int i) { f(i); }
1177///
1178/// this routine would produce an implicit conversion sequence to
1179/// describe the initialization of f from i, which will be a standard
1180/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1181/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1182//
1183/// Note that this routine only determines how the conversion can be
1184/// performed; it does not actually perform the conversion. As such,
1185/// it will not produce any diagnostics if no conversion is available,
1186/// but will instead return an implicit conversion sequence of kind
1187/// "BadConversion".
1188///
1189/// If @p SuppressUserConversions, then user-defined conversions are
1190/// not permitted.
1191/// If @p AllowExplicit, then explicit user-defined conversions are
1192/// permitted.
1193///
1194/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1195/// writeback conversion, which allows __autoreleasing id* parameters to
1196/// be initialized with __strong id* or __weak id* arguments.
1197static ImplicitConversionSequence
1198TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1199                      bool SuppressUserConversions,
1200                      bool AllowExplicit,
1201                      bool InOverloadResolution,
1202                      bool CStyle,
1203                      bool AllowObjCWritebackConversion) {
1204  ImplicitConversionSequence ICS;
1205  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1206                           ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1207    ICS.setStandard();
1208    return ICS;
1209  }
1210
1211  if (!S.getLangOpts().CPlusPlus) {
1212    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1213    return ICS;
1214  }
1215
1216  // C++ [over.ics.user]p4:
1217  //   A conversion of an expression of class type to the same class
1218  //   type is given Exact Match rank, and a conversion of an
1219  //   expression of class type to a base class of that type is
1220  //   given Conversion rank, in spite of the fact that a copy/move
1221  //   constructor (i.e., a user-defined conversion function) is
1222  //   called for those cases.
1223  QualType FromType = From->getType();
1224  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1225      (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1226       S.IsDerivedFrom(FromType, ToType))) {
1227    ICS.setStandard();
1228    ICS.Standard.setAsIdentityConversion();
1229    ICS.Standard.setFromType(FromType);
1230    ICS.Standard.setAllToTypes(ToType);
1231
1232    // We don't actually check at this point whether there is a valid
1233    // copy/move constructor, since overloading just assumes that it
1234    // exists. When we actually perform initialization, we'll find the
1235    // appropriate constructor to copy the returned object, if needed.
1236    ICS.Standard.CopyConstructor = 0;
1237
1238    // Determine whether this is considered a derived-to-base conversion.
1239    if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1240      ICS.Standard.Second = ICK_Derived_To_Base;
1241
1242    return ICS;
1243  }
1244
1245  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1246                                  AllowExplicit, InOverloadResolution, CStyle,
1247                                  AllowObjCWritebackConversion);
1248}
1249
1250ImplicitConversionSequence
1251Sema::TryImplicitConversion(Expr *From, QualType ToType,
1252                            bool SuppressUserConversions,
1253                            bool AllowExplicit,
1254                            bool InOverloadResolution,
1255                            bool CStyle,
1256                            bool AllowObjCWritebackConversion) {
1257  return clang::TryImplicitConversion(*this, From, ToType,
1258                                      SuppressUserConversions, AllowExplicit,
1259                                      InOverloadResolution, CStyle,
1260                                      AllowObjCWritebackConversion);
1261}
1262
1263/// PerformImplicitConversion - Perform an implicit conversion of the
1264/// expression From to the type ToType. Returns the
1265/// converted expression. Flavor is the kind of conversion we're
1266/// performing, used in the error message. If @p AllowExplicit,
1267/// explicit user-defined conversions are permitted.
1268ExprResult
1269Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1270                                AssignmentAction Action, bool AllowExplicit) {
1271  ImplicitConversionSequence ICS;
1272  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1273}
1274
1275ExprResult
1276Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1277                                AssignmentAction Action, bool AllowExplicit,
1278                                ImplicitConversionSequence& ICS) {
1279  if (checkPlaceholderForOverload(*this, From))
1280    return ExprError();
1281
1282  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1283  bool AllowObjCWritebackConversion
1284    = getLangOpts().ObjCAutoRefCount &&
1285      (Action == AA_Passing || Action == AA_Sending);
1286
1287  ICS = clang::TryImplicitConversion(*this, From, ToType,
1288                                     /*SuppressUserConversions=*/false,
1289                                     AllowExplicit,
1290                                     /*InOverloadResolution=*/false,
1291                                     /*CStyle=*/false,
1292                                     AllowObjCWritebackConversion);
1293  return PerformImplicitConversion(From, ToType, ICS, Action);
1294}
1295
1296/// \brief Determine whether the conversion from FromType to ToType is a valid
1297/// conversion that strips "noreturn" off the nested function type.
1298bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1299                                QualType &ResultTy) {
1300  if (Context.hasSameUnqualifiedType(FromType, ToType))
1301    return false;
1302
1303  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1304  // where F adds one of the following at most once:
1305  //   - a pointer
1306  //   - a member pointer
1307  //   - a block pointer
1308  CanQualType CanTo = Context.getCanonicalType(ToType);
1309  CanQualType CanFrom = Context.getCanonicalType(FromType);
1310  Type::TypeClass TyClass = CanTo->getTypeClass();
1311  if (TyClass != CanFrom->getTypeClass()) return false;
1312  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1313    if (TyClass == Type::Pointer) {
1314      CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1315      CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1316    } else if (TyClass == Type::BlockPointer) {
1317      CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1318      CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1319    } else if (TyClass == Type::MemberPointer) {
1320      CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1321      CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1322    } else {
1323      return false;
1324    }
1325
1326    TyClass = CanTo->getTypeClass();
1327    if (TyClass != CanFrom->getTypeClass()) return false;
1328    if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1329      return false;
1330  }
1331
1332  const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1333  FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1334  if (!EInfo.getNoReturn()) return false;
1335
1336  FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1337  assert(QualType(FromFn, 0).isCanonical());
1338  if (QualType(FromFn, 0) != CanTo) return false;
1339
1340  ResultTy = ToType;
1341  return true;
1342}
1343
1344/// \brief Determine whether the conversion from FromType to ToType is a valid
1345/// vector conversion.
1346///
1347/// \param ICK Will be set to the vector conversion kind, if this is a vector
1348/// conversion.
1349static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1350                               QualType ToType, ImplicitConversionKind &ICK) {
1351  // We need at least one of these types to be a vector type to have a vector
1352  // conversion.
1353  if (!ToType->isVectorType() && !FromType->isVectorType())
1354    return false;
1355
1356  // Identical types require no conversions.
1357  if (Context.hasSameUnqualifiedType(FromType, ToType))
1358    return false;
1359
1360  // There are no conversions between extended vector types, only identity.
1361  if (ToType->isExtVectorType()) {
1362    // There are no conversions between extended vector types other than the
1363    // identity conversion.
1364    if (FromType->isExtVectorType())
1365      return false;
1366
1367    // Vector splat from any arithmetic type to a vector.
1368    if (FromType->isArithmeticType()) {
1369      ICK = ICK_Vector_Splat;
1370      return true;
1371    }
1372  }
1373
1374  // We can perform the conversion between vector types in the following cases:
1375  // 1)vector types are equivalent AltiVec and GCC vector types
1376  // 2)lax vector conversions are permitted and the vector types are of the
1377  //   same size
1378  if (ToType->isVectorType() && FromType->isVectorType()) {
1379    if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1380        (Context.getLangOpts().LaxVectorConversions &&
1381         (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1382      ICK = ICK_Vector_Conversion;
1383      return true;
1384    }
1385  }
1386
1387  return false;
1388}
1389
1390static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1391                                bool InOverloadResolution,
1392                                StandardConversionSequence &SCS,
1393                                bool CStyle);
1394
1395/// IsStandardConversion - Determines whether there is a standard
1396/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1397/// expression From to the type ToType. Standard conversion sequences
1398/// only consider non-class types; for conversions that involve class
1399/// types, use TryImplicitConversion. If a conversion exists, SCS will
1400/// contain the standard conversion sequence required to perform this
1401/// conversion and this routine will return true. Otherwise, this
1402/// routine will return false and the value of SCS is unspecified.
1403static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1404                                 bool InOverloadResolution,
1405                                 StandardConversionSequence &SCS,
1406                                 bool CStyle,
1407                                 bool AllowObjCWritebackConversion) {
1408  QualType FromType = From->getType();
1409
1410  // Standard conversions (C++ [conv])
1411  SCS.setAsIdentityConversion();
1412  SCS.DeprecatedStringLiteralToCharPtr = false;
1413  SCS.IncompatibleObjC = false;
1414  SCS.setFromType(FromType);
1415  SCS.CopyConstructor = 0;
1416
1417  // There are no standard conversions for class types in C++, so
1418  // abort early. When overloading in C, however, we do permit
1419  if (FromType->isRecordType() || ToType->isRecordType()) {
1420    if (S.getLangOpts().CPlusPlus)
1421      return false;
1422
1423    // When we're overloading in C, we allow, as standard conversions,
1424  }
1425
1426  // The first conversion can be an lvalue-to-rvalue conversion,
1427  // array-to-pointer conversion, or function-to-pointer conversion
1428  // (C++ 4p1).
1429
1430  if (FromType == S.Context.OverloadTy) {
1431    DeclAccessPair AccessPair;
1432    if (FunctionDecl *Fn
1433          = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1434                                                 AccessPair)) {
1435      // We were able to resolve the address of the overloaded function,
1436      // so we can convert to the type of that function.
1437      FromType = Fn->getType();
1438
1439      // we can sometimes resolve &foo<int> regardless of ToType, so check
1440      // if the type matches (identity) or we are converting to bool
1441      if (!S.Context.hasSameUnqualifiedType(
1442                      S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1443        QualType resultTy;
1444        // if the function type matches except for [[noreturn]], it's ok
1445        if (!S.IsNoReturnConversion(FromType,
1446              S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1447          // otherwise, only a boolean conversion is standard
1448          if (!ToType->isBooleanType())
1449            return false;
1450      }
1451
1452      // Check if the "from" expression is taking the address of an overloaded
1453      // function and recompute the FromType accordingly. Take advantage of the
1454      // fact that non-static member functions *must* have such an address-of
1455      // expression.
1456      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1457      if (Method && !Method->isStatic()) {
1458        assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1459               "Non-unary operator on non-static member address");
1460        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1461               == UO_AddrOf &&
1462               "Non-address-of operator on non-static member address");
1463        const Type *ClassType
1464          = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1465        FromType = S.Context.getMemberPointerType(FromType, ClassType);
1466      } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1467        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1468               UO_AddrOf &&
1469               "Non-address-of operator for overloaded function expression");
1470        FromType = S.Context.getPointerType(FromType);
1471      }
1472
1473      // Check that we've computed the proper type after overload resolution.
1474      assert(S.Context.hasSameType(
1475        FromType,
1476        S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1477    } else {
1478      return false;
1479    }
1480  }
1481  // Lvalue-to-rvalue conversion (C++11 4.1):
1482  //   A glvalue (3.10) of a non-function, non-array type T can
1483  //   be converted to a prvalue.
1484  bool argIsLValue = From->isGLValue();
1485  if (argIsLValue &&
1486      !FromType->isFunctionType() && !FromType->isArrayType() &&
1487      S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1488    SCS.First = ICK_Lvalue_To_Rvalue;
1489
1490    // C11 6.3.2.1p2:
1491    //   ... if the lvalue has atomic type, the value has the non-atomic version
1492    //   of the type of the lvalue ...
1493    if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1494      FromType = Atomic->getValueType();
1495
1496    // If T is a non-class type, the type of the rvalue is the
1497    // cv-unqualified version of T. Otherwise, the type of the rvalue
1498    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1499    // just strip the qualifiers because they don't matter.
1500    FromType = FromType.getUnqualifiedType();
1501  } else if (FromType->isArrayType()) {
1502    // Array-to-pointer conversion (C++ 4.2)
1503    SCS.First = ICK_Array_To_Pointer;
1504
1505    // An lvalue or rvalue of type "array of N T" or "array of unknown
1506    // bound of T" can be converted to an rvalue of type "pointer to
1507    // T" (C++ 4.2p1).
1508    FromType = S.Context.getArrayDecayedType(FromType);
1509
1510    if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1511      // This conversion is deprecated. (C++ D.4).
1512      SCS.DeprecatedStringLiteralToCharPtr = true;
1513
1514      // For the purpose of ranking in overload resolution
1515      // (13.3.3.1.1), this conversion is considered an
1516      // array-to-pointer conversion followed by a qualification
1517      // conversion (4.4). (C++ 4.2p2)
1518      SCS.Second = ICK_Identity;
1519      SCS.Third = ICK_Qualification;
1520      SCS.QualificationIncludesObjCLifetime = false;
1521      SCS.setAllToTypes(FromType);
1522      return true;
1523    }
1524  } else if (FromType->isFunctionType() && argIsLValue) {
1525    // Function-to-pointer conversion (C++ 4.3).
1526    SCS.First = ICK_Function_To_Pointer;
1527
1528    // An lvalue of function type T can be converted to an rvalue of
1529    // type "pointer to T." The result is a pointer to the
1530    // function. (C++ 4.3p1).
1531    FromType = S.Context.getPointerType(FromType);
1532  } else {
1533    // We don't require any conversions for the first step.
1534    SCS.First = ICK_Identity;
1535  }
1536  SCS.setToType(0, FromType);
1537
1538  // The second conversion can be an integral promotion, floating
1539  // point promotion, integral conversion, floating point conversion,
1540  // floating-integral conversion, pointer conversion,
1541  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1542  // For overloading in C, this can also be a "compatible-type"
1543  // conversion.
1544  bool IncompatibleObjC = false;
1545  ImplicitConversionKind SecondICK = ICK_Identity;
1546  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1547    // The unqualified versions of the types are the same: there's no
1548    // conversion to do.
1549    SCS.Second = ICK_Identity;
1550  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1551    // Integral promotion (C++ 4.5).
1552    SCS.Second = ICK_Integral_Promotion;
1553    FromType = ToType.getUnqualifiedType();
1554  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1555    // Floating point promotion (C++ 4.6).
1556    SCS.Second = ICK_Floating_Promotion;
1557    FromType = ToType.getUnqualifiedType();
1558  } else if (S.IsComplexPromotion(FromType, ToType)) {
1559    // Complex promotion (Clang extension)
1560    SCS.Second = ICK_Complex_Promotion;
1561    FromType = ToType.getUnqualifiedType();
1562  } else if (ToType->isBooleanType() &&
1563             (FromType->isArithmeticType() ||
1564              FromType->isAnyPointerType() ||
1565              FromType->isBlockPointerType() ||
1566              FromType->isMemberPointerType() ||
1567              FromType->isNullPtrType())) {
1568    // Boolean conversions (C++ 4.12).
1569    SCS.Second = ICK_Boolean_Conversion;
1570    FromType = S.Context.BoolTy;
1571  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1572             ToType->isIntegralType(S.Context)) {
1573    // Integral conversions (C++ 4.7).
1574    SCS.Second = ICK_Integral_Conversion;
1575    FromType = ToType.getUnqualifiedType();
1576  } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1577    // Complex conversions (C99 6.3.1.6)
1578    SCS.Second = ICK_Complex_Conversion;
1579    FromType = ToType.getUnqualifiedType();
1580  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1581             (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1582    // Complex-real conversions (C99 6.3.1.7)
1583    SCS.Second = ICK_Complex_Real;
1584    FromType = ToType.getUnqualifiedType();
1585  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1586    // Floating point conversions (C++ 4.8).
1587    SCS.Second = ICK_Floating_Conversion;
1588    FromType = ToType.getUnqualifiedType();
1589  } else if ((FromType->isRealFloatingType() &&
1590              ToType->isIntegralType(S.Context)) ||
1591             (FromType->isIntegralOrUnscopedEnumerationType() &&
1592              ToType->isRealFloatingType())) {
1593    // Floating-integral conversions (C++ 4.9).
1594    SCS.Second = ICK_Floating_Integral;
1595    FromType = ToType.getUnqualifiedType();
1596  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1597    SCS.Second = ICK_Block_Pointer_Conversion;
1598  } else if (AllowObjCWritebackConversion &&
1599             S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1600    SCS.Second = ICK_Writeback_Conversion;
1601  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1602                                   FromType, IncompatibleObjC)) {
1603    // Pointer conversions (C++ 4.10).
1604    SCS.Second = ICK_Pointer_Conversion;
1605    SCS.IncompatibleObjC = IncompatibleObjC;
1606    FromType = FromType.getUnqualifiedType();
1607  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1608                                         InOverloadResolution, FromType)) {
1609    // Pointer to member conversions (4.11).
1610    SCS.Second = ICK_Pointer_Member;
1611  } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1612    SCS.Second = SecondICK;
1613    FromType = ToType.getUnqualifiedType();
1614  } else if (!S.getLangOpts().CPlusPlus &&
1615             S.Context.typesAreCompatible(ToType, FromType)) {
1616    // Compatible conversions (Clang extension for C function overloading)
1617    SCS.Second = ICK_Compatible_Conversion;
1618    FromType = ToType.getUnqualifiedType();
1619  } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1620    // Treat a conversion that strips "noreturn" as an identity conversion.
1621    SCS.Second = ICK_NoReturn_Adjustment;
1622  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1623                                             InOverloadResolution,
1624                                             SCS, CStyle)) {
1625    SCS.Second = ICK_TransparentUnionConversion;
1626    FromType = ToType;
1627  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1628                                 CStyle)) {
1629    // tryAtomicConversion has updated the standard conversion sequence
1630    // appropriately.
1631    return true;
1632  } else if (ToType->isEventT() &&
1633             From->isIntegerConstantExpr(S.getASTContext()) &&
1634             (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1635    SCS.Second = ICK_Zero_Event_Conversion;
1636    FromType = ToType;
1637  } else {
1638    // No second conversion required.
1639    SCS.Second = ICK_Identity;
1640  }
1641  SCS.setToType(1, FromType);
1642
1643  QualType CanonFrom;
1644  QualType CanonTo;
1645  // The third conversion can be a qualification conversion (C++ 4p1).
1646  bool ObjCLifetimeConversion;
1647  if (S.IsQualificationConversion(FromType, ToType, CStyle,
1648                                  ObjCLifetimeConversion)) {
1649    SCS.Third = ICK_Qualification;
1650    SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1651    FromType = ToType;
1652    CanonFrom = S.Context.getCanonicalType(FromType);
1653    CanonTo = S.Context.getCanonicalType(ToType);
1654  } else {
1655    // No conversion required
1656    SCS.Third = ICK_Identity;
1657
1658    // C++ [over.best.ics]p6:
1659    //   [...] Any difference in top-level cv-qualification is
1660    //   subsumed by the initialization itself and does not constitute
1661    //   a conversion. [...]
1662    CanonFrom = S.Context.getCanonicalType(FromType);
1663    CanonTo = S.Context.getCanonicalType(ToType);
1664    if (CanonFrom.getLocalUnqualifiedType()
1665                                       == CanonTo.getLocalUnqualifiedType() &&
1666        CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1667      FromType = ToType;
1668      CanonFrom = CanonTo;
1669    }
1670  }
1671  SCS.setToType(2, FromType);
1672
1673  // If we have not converted the argument type to the parameter type,
1674  // this is a bad conversion sequence.
1675  if (CanonFrom != CanonTo)
1676    return false;
1677
1678  return true;
1679}
1680
1681static bool
1682IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1683                                     QualType &ToType,
1684                                     bool InOverloadResolution,
1685                                     StandardConversionSequence &SCS,
1686                                     bool CStyle) {
1687
1688  const RecordType *UT = ToType->getAsUnionType();
1689  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1690    return false;
1691  // The field to initialize within the transparent union.
1692  RecordDecl *UD = UT->getDecl();
1693  // It's compatible if the expression matches any of the fields.
1694  for (RecordDecl::field_iterator it = UD->field_begin(),
1695       itend = UD->field_end();
1696       it != itend; ++it) {
1697    if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1698                             CStyle, /*ObjCWritebackConversion=*/false)) {
1699      ToType = it->getType();
1700      return true;
1701    }
1702  }
1703  return false;
1704}
1705
1706/// IsIntegralPromotion - Determines whether the conversion from the
1707/// expression From (whose potentially-adjusted type is FromType) to
1708/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1709/// sets PromotedType to the promoted type.
1710bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1711  const BuiltinType *To = ToType->getAs<BuiltinType>();
1712  // All integers are built-in.
1713  if (!To) {
1714    return false;
1715  }
1716
1717  // An rvalue of type char, signed char, unsigned char, short int, or
1718  // unsigned short int can be converted to an rvalue of type int if
1719  // int can represent all the values of the source type; otherwise,
1720  // the source rvalue can be converted to an rvalue of type unsigned
1721  // int (C++ 4.5p1).
1722  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1723      !FromType->isEnumeralType()) {
1724    if (// We can promote any signed, promotable integer type to an int
1725        (FromType->isSignedIntegerType() ||
1726         // We can promote any unsigned integer type whose size is
1727         // less than int to an int.
1728         (!FromType->isSignedIntegerType() &&
1729          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1730      return To->getKind() == BuiltinType::Int;
1731    }
1732
1733    return To->getKind() == BuiltinType::UInt;
1734  }
1735
1736  // C++11 [conv.prom]p3:
1737  //   A prvalue of an unscoped enumeration type whose underlying type is not
1738  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1739  //   following types that can represent all the values of the enumeration
1740  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1741  //   unsigned int, long int, unsigned long int, long long int, or unsigned
1742  //   long long int. If none of the types in that list can represent all the
1743  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1744  //   type can be converted to an rvalue a prvalue of the extended integer type
1745  //   with lowest integer conversion rank (4.13) greater than the rank of long
1746  //   long in which all the values of the enumeration can be represented. If
1747  //   there are two such extended types, the signed one is chosen.
1748  // C++11 [conv.prom]p4:
1749  //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1750  //   can be converted to a prvalue of its underlying type. Moreover, if
1751  //   integral promotion can be applied to its underlying type, a prvalue of an
1752  //   unscoped enumeration type whose underlying type is fixed can also be
1753  //   converted to a prvalue of the promoted underlying type.
1754  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1755    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1756    // provided for a scoped enumeration.
1757    if (FromEnumType->getDecl()->isScoped())
1758      return false;
1759
1760    // We can perform an integral promotion to the underlying type of the enum,
1761    // even if that's not the promoted type.
1762    if (FromEnumType->getDecl()->isFixed()) {
1763      QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1764      return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1765             IsIntegralPromotion(From, Underlying, ToType);
1766    }
1767
1768    // We have already pre-calculated the promotion type, so this is trivial.
1769    if (ToType->isIntegerType() &&
1770        !RequireCompleteType(From->getLocStart(), FromType, 0))
1771      return Context.hasSameUnqualifiedType(ToType,
1772                                FromEnumType->getDecl()->getPromotionType());
1773  }
1774
1775  // C++0x [conv.prom]p2:
1776  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1777  //   to an rvalue a prvalue of the first of the following types that can
1778  //   represent all the values of its underlying type: int, unsigned int,
1779  //   long int, unsigned long int, long long int, or unsigned long long int.
1780  //   If none of the types in that list can represent all the values of its
1781  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1782  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1783  //   type.
1784  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1785      ToType->isIntegerType()) {
1786    // Determine whether the type we're converting from is signed or
1787    // unsigned.
1788    bool FromIsSigned = FromType->isSignedIntegerType();
1789    uint64_t FromSize = Context.getTypeSize(FromType);
1790
1791    // The types we'll try to promote to, in the appropriate
1792    // order. Try each of these types.
1793    QualType PromoteTypes[6] = {
1794      Context.IntTy, Context.UnsignedIntTy,
1795      Context.LongTy, Context.UnsignedLongTy ,
1796      Context.LongLongTy, Context.UnsignedLongLongTy
1797    };
1798    for (int Idx = 0; Idx < 6; ++Idx) {
1799      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1800      if (FromSize < ToSize ||
1801          (FromSize == ToSize &&
1802           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1803        // We found the type that we can promote to. If this is the
1804        // type we wanted, we have a promotion. Otherwise, no
1805        // promotion.
1806        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1807      }
1808    }
1809  }
1810
1811  // An rvalue for an integral bit-field (9.6) can be converted to an
1812  // rvalue of type int if int can represent all the values of the
1813  // bit-field; otherwise, it can be converted to unsigned int if
1814  // unsigned int can represent all the values of the bit-field. If
1815  // the bit-field is larger yet, no integral promotion applies to
1816  // it. If the bit-field has an enumerated type, it is treated as any
1817  // other value of that type for promotion purposes (C++ 4.5p3).
1818  // FIXME: We should delay checking of bit-fields until we actually perform the
1819  // conversion.
1820  using llvm::APSInt;
1821  if (From)
1822    if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1823      APSInt BitWidth;
1824      if (FromType->isIntegralType(Context) &&
1825          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1826        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1827        ToSize = Context.getTypeSize(ToType);
1828
1829        // Are we promoting to an int from a bitfield that fits in an int?
1830        if (BitWidth < ToSize ||
1831            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1832          return To->getKind() == BuiltinType::Int;
1833        }
1834
1835        // Are we promoting to an unsigned int from an unsigned bitfield
1836        // that fits into an unsigned int?
1837        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1838          return To->getKind() == BuiltinType::UInt;
1839        }
1840
1841        return false;
1842      }
1843    }
1844
1845  // An rvalue of type bool can be converted to an rvalue of type int,
1846  // with false becoming zero and true becoming one (C++ 4.5p4).
1847  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1848    return true;
1849  }
1850
1851  return false;
1852}
1853
1854/// IsFloatingPointPromotion - Determines whether the conversion from
1855/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1856/// returns true and sets PromotedType to the promoted type.
1857bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1858  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1859    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1860      /// An rvalue of type float can be converted to an rvalue of type
1861      /// double. (C++ 4.6p1).
1862      if (FromBuiltin->getKind() == BuiltinType::Float &&
1863          ToBuiltin->getKind() == BuiltinType::Double)
1864        return true;
1865
1866      // C99 6.3.1.5p1:
1867      //   When a float is promoted to double or long double, or a
1868      //   double is promoted to long double [...].
1869      if (!getLangOpts().CPlusPlus &&
1870          (FromBuiltin->getKind() == BuiltinType::Float ||
1871           FromBuiltin->getKind() == BuiltinType::Double) &&
1872          (ToBuiltin->getKind() == BuiltinType::LongDouble))
1873        return true;
1874
1875      // Half can be promoted to float.
1876      if (!getLangOpts().NativeHalfType &&
1877           FromBuiltin->getKind() == BuiltinType::Half &&
1878          ToBuiltin->getKind() == BuiltinType::Float)
1879        return true;
1880    }
1881
1882  return false;
1883}
1884
1885/// \brief Determine if a conversion is a complex promotion.
1886///
1887/// A complex promotion is defined as a complex -> complex conversion
1888/// where the conversion between the underlying real types is a
1889/// floating-point or integral promotion.
1890bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1891  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1892  if (!FromComplex)
1893    return false;
1894
1895  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1896  if (!ToComplex)
1897    return false;
1898
1899  return IsFloatingPointPromotion(FromComplex->getElementType(),
1900                                  ToComplex->getElementType()) ||
1901    IsIntegralPromotion(0, FromComplex->getElementType(),
1902                        ToComplex->getElementType());
1903}
1904
1905/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1906/// the pointer type FromPtr to a pointer to type ToPointee, with the
1907/// same type qualifiers as FromPtr has on its pointee type. ToType,
1908/// if non-empty, will be a pointer to ToType that may or may not have
1909/// the right set of qualifiers on its pointee.
1910///
1911static QualType
1912BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1913                                   QualType ToPointee, QualType ToType,
1914                                   ASTContext &Context,
1915                                   bool StripObjCLifetime = false) {
1916  assert((FromPtr->getTypeClass() == Type::Pointer ||
1917          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1918         "Invalid similarly-qualified pointer type");
1919
1920  /// Conversions to 'id' subsume cv-qualifier conversions.
1921  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1922    return ToType.getUnqualifiedType();
1923
1924  QualType CanonFromPointee
1925    = Context.getCanonicalType(FromPtr->getPointeeType());
1926  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1927  Qualifiers Quals = CanonFromPointee.getQualifiers();
1928
1929  if (StripObjCLifetime)
1930    Quals.removeObjCLifetime();
1931
1932  // Exact qualifier match -> return the pointer type we're converting to.
1933  if (CanonToPointee.getLocalQualifiers() == Quals) {
1934    // ToType is exactly what we need. Return it.
1935    if (!ToType.isNull())
1936      return ToType.getUnqualifiedType();
1937
1938    // Build a pointer to ToPointee. It has the right qualifiers
1939    // already.
1940    if (isa<ObjCObjectPointerType>(ToType))
1941      return Context.getObjCObjectPointerType(ToPointee);
1942    return Context.getPointerType(ToPointee);
1943  }
1944
1945  // Just build a canonical type that has the right qualifiers.
1946  QualType QualifiedCanonToPointee
1947    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1948
1949  if (isa<ObjCObjectPointerType>(ToType))
1950    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1951  return Context.getPointerType(QualifiedCanonToPointee);
1952}
1953
1954static bool isNullPointerConstantForConversion(Expr *Expr,
1955                                               bool InOverloadResolution,
1956                                               ASTContext &Context) {
1957  // Handle value-dependent integral null pointer constants correctly.
1958  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1959  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1960      Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1961    return !InOverloadResolution;
1962
1963  return Expr->isNullPointerConstant(Context,
1964                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1965                                        : Expr::NPC_ValueDependentIsNull);
1966}
1967
1968/// IsPointerConversion - Determines whether the conversion of the
1969/// expression From, which has the (possibly adjusted) type FromType,
1970/// can be converted to the type ToType via a pointer conversion (C++
1971/// 4.10). If so, returns true and places the converted type (that
1972/// might differ from ToType in its cv-qualifiers at some level) into
1973/// ConvertedType.
1974///
1975/// This routine also supports conversions to and from block pointers
1976/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1977/// pointers to interfaces. FIXME: Once we've determined the
1978/// appropriate overloading rules for Objective-C, we may want to
1979/// split the Objective-C checks into a different routine; however,
1980/// GCC seems to consider all of these conversions to be pointer
1981/// conversions, so for now they live here. IncompatibleObjC will be
1982/// set if the conversion is an allowed Objective-C conversion that
1983/// should result in a warning.
1984bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1985                               bool InOverloadResolution,
1986                               QualType& ConvertedType,
1987                               bool &IncompatibleObjC) {
1988  IncompatibleObjC = false;
1989  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1990                              IncompatibleObjC))
1991    return true;
1992
1993  // Conversion from a null pointer constant to any Objective-C pointer type.
1994  if (ToType->isObjCObjectPointerType() &&
1995      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1996    ConvertedType = ToType;
1997    return true;
1998  }
1999
2000  // Blocks: Block pointers can be converted to void*.
2001  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2002      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2003    ConvertedType = ToType;
2004    return true;
2005  }
2006  // Blocks: A null pointer constant can be converted to a block
2007  // pointer type.
2008  if (ToType->isBlockPointerType() &&
2009      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2010    ConvertedType = ToType;
2011    return true;
2012  }
2013
2014  // If the left-hand-side is nullptr_t, the right side can be a null
2015  // pointer constant.
2016  if (ToType->isNullPtrType() &&
2017      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2018    ConvertedType = ToType;
2019    return true;
2020  }
2021
2022  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2023  if (!ToTypePtr)
2024    return false;
2025
2026  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2027  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2028    ConvertedType = ToType;
2029    return true;
2030  }
2031
2032  // Beyond this point, both types need to be pointers
2033  // , including objective-c pointers.
2034  QualType ToPointeeType = ToTypePtr->getPointeeType();
2035  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2036      !getLangOpts().ObjCAutoRefCount) {
2037    ConvertedType = BuildSimilarlyQualifiedPointerType(
2038                                      FromType->getAs<ObjCObjectPointerType>(),
2039                                                       ToPointeeType,
2040                                                       ToType, Context);
2041    return true;
2042  }
2043  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2044  if (!FromTypePtr)
2045    return false;
2046
2047  QualType FromPointeeType = FromTypePtr->getPointeeType();
2048
2049  // If the unqualified pointee types are the same, this can't be a
2050  // pointer conversion, so don't do all of the work below.
2051  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2052    return false;
2053
2054  // An rvalue of type "pointer to cv T," where T is an object type,
2055  // can be converted to an rvalue of type "pointer to cv void" (C++
2056  // 4.10p2).
2057  if (FromPointeeType->isIncompleteOrObjectType() &&
2058      ToPointeeType->isVoidType()) {
2059    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2060                                                       ToPointeeType,
2061                                                       ToType, Context,
2062                                                   /*StripObjCLifetime=*/true);
2063    return true;
2064  }
2065
2066  // MSVC allows implicit function to void* type conversion.
2067  if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2068      ToPointeeType->isVoidType()) {
2069    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2070                                                       ToPointeeType,
2071                                                       ToType, Context);
2072    return true;
2073  }
2074
2075  // When we're overloading in C, we allow a special kind of pointer
2076  // conversion for compatible-but-not-identical pointee types.
2077  if (!getLangOpts().CPlusPlus &&
2078      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2079    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2080                                                       ToPointeeType,
2081                                                       ToType, Context);
2082    return true;
2083  }
2084
2085  // C++ [conv.ptr]p3:
2086  //
2087  //   An rvalue of type "pointer to cv D," where D is a class type,
2088  //   can be converted to an rvalue of type "pointer to cv B," where
2089  //   B is a base class (clause 10) of D. If B is an inaccessible
2090  //   (clause 11) or ambiguous (10.2) base class of D, a program that
2091  //   necessitates this conversion is ill-formed. The result of the
2092  //   conversion is a pointer to the base class sub-object of the
2093  //   derived class object. The null pointer value is converted to
2094  //   the null pointer value of the destination type.
2095  //
2096  // Note that we do not check for ambiguity or inaccessibility
2097  // here. That is handled by CheckPointerConversion.
2098  if (getLangOpts().CPlusPlus &&
2099      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2100      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2101      !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2102      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2103    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2104                                                       ToPointeeType,
2105                                                       ToType, Context);
2106    return true;
2107  }
2108
2109  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2110      Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2111    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2112                                                       ToPointeeType,
2113                                                       ToType, Context);
2114    return true;
2115  }
2116
2117  return false;
2118}
2119
2120/// \brief Adopt the given qualifiers for the given type.
2121static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2122  Qualifiers TQs = T.getQualifiers();
2123
2124  // Check whether qualifiers already match.
2125  if (TQs == Qs)
2126    return T;
2127
2128  if (Qs.compatiblyIncludes(TQs))
2129    return Context.getQualifiedType(T, Qs);
2130
2131  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2132}
2133
2134/// isObjCPointerConversion - Determines whether this is an
2135/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2136/// with the same arguments and return values.
2137bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2138                                   QualType& ConvertedType,
2139                                   bool &IncompatibleObjC) {
2140  if (!getLangOpts().ObjC1)
2141    return false;
2142
2143  // The set of qualifiers on the type we're converting from.
2144  Qualifiers FromQualifiers = FromType.getQualifiers();
2145
2146  // First, we handle all conversions on ObjC object pointer types.
2147  const ObjCObjectPointerType* ToObjCPtr =
2148    ToType->getAs<ObjCObjectPointerType>();
2149  const ObjCObjectPointerType *FromObjCPtr =
2150    FromType->getAs<ObjCObjectPointerType>();
2151
2152  if (ToObjCPtr && FromObjCPtr) {
2153    // If the pointee types are the same (ignoring qualifications),
2154    // then this is not a pointer conversion.
2155    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2156                                       FromObjCPtr->getPointeeType()))
2157      return false;
2158
2159    // Check for compatible
2160    // Objective C++: We're able to convert between "id" or "Class" and a
2161    // pointer to any interface (in both directions).
2162    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2163      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2164      return true;
2165    }
2166    // Conversions with Objective-C's id<...>.
2167    if ((FromObjCPtr->isObjCQualifiedIdType() ||
2168         ToObjCPtr->isObjCQualifiedIdType()) &&
2169        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2170                                                  /*compare=*/false)) {
2171      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2172      return true;
2173    }
2174    // Objective C++: We're able to convert from a pointer to an
2175    // interface to a pointer to a different interface.
2176    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2177      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2178      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2179      if (getLangOpts().CPlusPlus && LHS && RHS &&
2180          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2181                                                FromObjCPtr->getPointeeType()))
2182        return false;
2183      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2184                                                   ToObjCPtr->getPointeeType(),
2185                                                         ToType, Context);
2186      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2187      return true;
2188    }
2189
2190    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2191      // Okay: this is some kind of implicit downcast of Objective-C
2192      // interfaces, which is permitted. However, we're going to
2193      // complain about it.
2194      IncompatibleObjC = true;
2195      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2196                                                   ToObjCPtr->getPointeeType(),
2197                                                         ToType, Context);
2198      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2199      return true;
2200    }
2201  }
2202  // Beyond this point, both types need to be C pointers or block pointers.
2203  QualType ToPointeeType;
2204  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2205    ToPointeeType = ToCPtr->getPointeeType();
2206  else if (const BlockPointerType *ToBlockPtr =
2207            ToType->getAs<BlockPointerType>()) {
2208    // Objective C++: We're able to convert from a pointer to any object
2209    // to a block pointer type.
2210    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2211      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2212      return true;
2213    }
2214    ToPointeeType = ToBlockPtr->getPointeeType();
2215  }
2216  else if (FromType->getAs<BlockPointerType>() &&
2217           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2218    // Objective C++: We're able to convert from a block pointer type to a
2219    // pointer to any object.
2220    ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2221    return true;
2222  }
2223  else
2224    return false;
2225
2226  QualType FromPointeeType;
2227  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2228    FromPointeeType = FromCPtr->getPointeeType();
2229  else if (const BlockPointerType *FromBlockPtr =
2230           FromType->getAs<BlockPointerType>())
2231    FromPointeeType = FromBlockPtr->getPointeeType();
2232  else
2233    return false;
2234
2235  // If we have pointers to pointers, recursively check whether this
2236  // is an Objective-C conversion.
2237  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2238      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2239                              IncompatibleObjC)) {
2240    // We always complain about this conversion.
2241    IncompatibleObjC = true;
2242    ConvertedType = Context.getPointerType(ConvertedType);
2243    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2244    return true;
2245  }
2246  // Allow conversion of pointee being objective-c pointer to another one;
2247  // as in I* to id.
2248  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2249      ToPointeeType->getAs<ObjCObjectPointerType>() &&
2250      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2251                              IncompatibleObjC)) {
2252
2253    ConvertedType = Context.getPointerType(ConvertedType);
2254    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2255    return true;
2256  }
2257
2258  // If we have pointers to functions or blocks, check whether the only
2259  // differences in the argument and result types are in Objective-C
2260  // pointer conversions. If so, we permit the conversion (but
2261  // complain about it).
2262  const FunctionProtoType *FromFunctionType
2263    = FromPointeeType->getAs<FunctionProtoType>();
2264  const FunctionProtoType *ToFunctionType
2265    = ToPointeeType->getAs<FunctionProtoType>();
2266  if (FromFunctionType && ToFunctionType) {
2267    // If the function types are exactly the same, this isn't an
2268    // Objective-C pointer conversion.
2269    if (Context.getCanonicalType(FromPointeeType)
2270          == Context.getCanonicalType(ToPointeeType))
2271      return false;
2272
2273    // Perform the quick checks that will tell us whether these
2274    // function types are obviously different.
2275    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2276        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2277        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2278      return false;
2279
2280    bool HasObjCConversion = false;
2281    if (Context.getCanonicalType(FromFunctionType->getResultType())
2282          == Context.getCanonicalType(ToFunctionType->getResultType())) {
2283      // Okay, the types match exactly. Nothing to do.
2284    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2285                                       ToFunctionType->getResultType(),
2286                                       ConvertedType, IncompatibleObjC)) {
2287      // Okay, we have an Objective-C pointer conversion.
2288      HasObjCConversion = true;
2289    } else {
2290      // Function types are too different. Abort.
2291      return false;
2292    }
2293
2294    // Check argument types.
2295    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2296         ArgIdx != NumArgs; ++ArgIdx) {
2297      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2298      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2299      if (Context.getCanonicalType(FromArgType)
2300            == Context.getCanonicalType(ToArgType)) {
2301        // Okay, the types match exactly. Nothing to do.
2302      } else if (isObjCPointerConversion(FromArgType, ToArgType,
2303                                         ConvertedType, IncompatibleObjC)) {
2304        // Okay, we have an Objective-C pointer conversion.
2305        HasObjCConversion = true;
2306      } else {
2307        // Argument types are too different. Abort.
2308        return false;
2309      }
2310    }
2311
2312    if (HasObjCConversion) {
2313      // We had an Objective-C conversion. Allow this pointer
2314      // conversion, but complain about it.
2315      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2316      IncompatibleObjC = true;
2317      return true;
2318    }
2319  }
2320
2321  return false;
2322}
2323
2324/// \brief Determine whether this is an Objective-C writeback conversion,
2325/// used for parameter passing when performing automatic reference counting.
2326///
2327/// \param FromType The type we're converting form.
2328///
2329/// \param ToType The type we're converting to.
2330///
2331/// \param ConvertedType The type that will be produced after applying
2332/// this conversion.
2333bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2334                                     QualType &ConvertedType) {
2335  if (!getLangOpts().ObjCAutoRefCount ||
2336      Context.hasSameUnqualifiedType(FromType, ToType))
2337    return false;
2338
2339  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2340  QualType ToPointee;
2341  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2342    ToPointee = ToPointer->getPointeeType();
2343  else
2344    return false;
2345
2346  Qualifiers ToQuals = ToPointee.getQualifiers();
2347  if (!ToPointee->isObjCLifetimeType() ||
2348      ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2349      !ToQuals.withoutObjCLifetime().empty())
2350    return false;
2351
2352  // Argument must be a pointer to __strong to __weak.
2353  QualType FromPointee;
2354  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2355    FromPointee = FromPointer->getPointeeType();
2356  else
2357    return false;
2358
2359  Qualifiers FromQuals = FromPointee.getQualifiers();
2360  if (!FromPointee->isObjCLifetimeType() ||
2361      (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2362       FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2363    return false;
2364
2365  // Make sure that we have compatible qualifiers.
2366  FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2367  if (!ToQuals.compatiblyIncludes(FromQuals))
2368    return false;
2369
2370  // Remove qualifiers from the pointee type we're converting from; they
2371  // aren't used in the compatibility check belong, and we'll be adding back
2372  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2373  FromPointee = FromPointee.getUnqualifiedType();
2374
2375  // The unqualified form of the pointee types must be compatible.
2376  ToPointee = ToPointee.getUnqualifiedType();
2377  bool IncompatibleObjC;
2378  if (Context.typesAreCompatible(FromPointee, ToPointee))
2379    FromPointee = ToPointee;
2380  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2381                                    IncompatibleObjC))
2382    return false;
2383
2384  /// \brief Construct the type we're converting to, which is a pointer to
2385  /// __autoreleasing pointee.
2386  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2387  ConvertedType = Context.getPointerType(FromPointee);
2388  return true;
2389}
2390
2391bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2392                                    QualType& ConvertedType) {
2393  QualType ToPointeeType;
2394  if (const BlockPointerType *ToBlockPtr =
2395        ToType->getAs<BlockPointerType>())
2396    ToPointeeType = ToBlockPtr->getPointeeType();
2397  else
2398    return false;
2399
2400  QualType FromPointeeType;
2401  if (const BlockPointerType *FromBlockPtr =
2402      FromType->getAs<BlockPointerType>())
2403    FromPointeeType = FromBlockPtr->getPointeeType();
2404  else
2405    return false;
2406  // We have pointer to blocks, check whether the only
2407  // differences in the argument and result types are in Objective-C
2408  // pointer conversions. If so, we permit the conversion.
2409
2410  const FunctionProtoType *FromFunctionType
2411    = FromPointeeType->getAs<FunctionProtoType>();
2412  const FunctionProtoType *ToFunctionType
2413    = ToPointeeType->getAs<FunctionProtoType>();
2414
2415  if (!FromFunctionType || !ToFunctionType)
2416    return false;
2417
2418  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2419    return true;
2420
2421  // Perform the quick checks that will tell us whether these
2422  // function types are obviously different.
2423  if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2424      FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2425    return false;
2426
2427  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2428  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2429  if (FromEInfo != ToEInfo)
2430    return false;
2431
2432  bool IncompatibleObjC = false;
2433  if (Context.hasSameType(FromFunctionType->getResultType(),
2434                          ToFunctionType->getResultType())) {
2435    // Okay, the types match exactly. Nothing to do.
2436  } else {
2437    QualType RHS = FromFunctionType->getResultType();
2438    QualType LHS = ToFunctionType->getResultType();
2439    if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2440        !RHS.hasQualifiers() && LHS.hasQualifiers())
2441       LHS = LHS.getUnqualifiedType();
2442
2443     if (Context.hasSameType(RHS,LHS)) {
2444       // OK exact match.
2445     } else if (isObjCPointerConversion(RHS, LHS,
2446                                        ConvertedType, IncompatibleObjC)) {
2447     if (IncompatibleObjC)
2448       return false;
2449     // Okay, we have an Objective-C pointer conversion.
2450     }
2451     else
2452       return false;
2453   }
2454
2455   // Check argument types.
2456   for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2457        ArgIdx != NumArgs; ++ArgIdx) {
2458     IncompatibleObjC = false;
2459     QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2460     QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2461     if (Context.hasSameType(FromArgType, ToArgType)) {
2462       // Okay, the types match exactly. Nothing to do.
2463     } else if (isObjCPointerConversion(ToArgType, FromArgType,
2464                                        ConvertedType, IncompatibleObjC)) {
2465       if (IncompatibleObjC)
2466         return false;
2467       // Okay, we have an Objective-C pointer conversion.
2468     } else
2469       // Argument types are too different. Abort.
2470       return false;
2471   }
2472   if (LangOpts.ObjCAutoRefCount &&
2473       !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2474                                                    ToFunctionType))
2475     return false;
2476
2477   ConvertedType = ToType;
2478   return true;
2479}
2480
2481enum {
2482  ft_default,
2483  ft_different_class,
2484  ft_parameter_arity,
2485  ft_parameter_mismatch,
2486  ft_return_type,
2487  ft_qualifer_mismatch
2488};
2489
2490/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2491/// function types.  Catches different number of parameter, mismatch in
2492/// parameter types, and different return types.
2493void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2494                                      QualType FromType, QualType ToType) {
2495  // If either type is not valid, include no extra info.
2496  if (FromType.isNull() || ToType.isNull()) {
2497    PDiag << ft_default;
2498    return;
2499  }
2500
2501  // Get the function type from the pointers.
2502  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2503    const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2504                            *ToMember = ToType->getAs<MemberPointerType>();
2505    if (FromMember->getClass() != ToMember->getClass()) {
2506      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2507            << QualType(FromMember->getClass(), 0);
2508      return;
2509    }
2510    FromType = FromMember->getPointeeType();
2511    ToType = ToMember->getPointeeType();
2512  }
2513
2514  if (FromType->isPointerType())
2515    FromType = FromType->getPointeeType();
2516  if (ToType->isPointerType())
2517    ToType = ToType->getPointeeType();
2518
2519  // Remove references.
2520  FromType = FromType.getNonReferenceType();
2521  ToType = ToType.getNonReferenceType();
2522
2523  // Don't print extra info for non-specialized template functions.
2524  if (FromType->isInstantiationDependentType() &&
2525      !FromType->getAs<TemplateSpecializationType>()) {
2526    PDiag << ft_default;
2527    return;
2528  }
2529
2530  // No extra info for same types.
2531  if (Context.hasSameType(FromType, ToType)) {
2532    PDiag << ft_default;
2533    return;
2534  }
2535
2536  const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2537                          *ToFunction = ToType->getAs<FunctionProtoType>();
2538
2539  // Both types need to be function types.
2540  if (!FromFunction || !ToFunction) {
2541    PDiag << ft_default;
2542    return;
2543  }
2544
2545  if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2546    PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2547          << FromFunction->getNumArgs();
2548    return;
2549  }
2550
2551  // Handle different parameter types.
2552  unsigned ArgPos;
2553  if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2554    PDiag << ft_parameter_mismatch << ArgPos + 1
2555          << ToFunction->getArgType(ArgPos)
2556          << FromFunction->getArgType(ArgPos);
2557    return;
2558  }
2559
2560  // Handle different return type.
2561  if (!Context.hasSameType(FromFunction->getResultType(),
2562                           ToFunction->getResultType())) {
2563    PDiag << ft_return_type << ToFunction->getResultType()
2564          << FromFunction->getResultType();
2565    return;
2566  }
2567
2568  unsigned FromQuals = FromFunction->getTypeQuals(),
2569           ToQuals = ToFunction->getTypeQuals();
2570  if (FromQuals != ToQuals) {
2571    PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2572    return;
2573  }
2574
2575  // Unable to find a difference, so add no extra info.
2576  PDiag << ft_default;
2577}
2578
2579/// FunctionArgTypesAreEqual - This routine checks two function proto types
2580/// for equality of their argument types. Caller has already checked that
2581/// they have same number of arguments.  If the parameters are different,
2582/// ArgPos will have the parameter index of the first different parameter.
2583bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2584                                    const FunctionProtoType *NewType,
2585                                    unsigned *ArgPos) {
2586  for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2587       N = NewType->arg_type_begin(),
2588       E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2589    if (!Context.hasSameType(O->getUnqualifiedType(),
2590                             N->getUnqualifiedType())) {
2591      if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2592      return false;
2593    }
2594  }
2595  return true;
2596}
2597
2598/// CheckPointerConversion - Check the pointer conversion from the
2599/// expression From to the type ToType. This routine checks for
2600/// ambiguous or inaccessible derived-to-base pointer
2601/// conversions for which IsPointerConversion has already returned
2602/// true. It returns true and produces a diagnostic if there was an
2603/// error, or returns false otherwise.
2604bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2605                                  CastKind &Kind,
2606                                  CXXCastPath& BasePath,
2607                                  bool IgnoreBaseAccess) {
2608  QualType FromType = From->getType();
2609  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2610
2611  Kind = CK_BitCast;
2612
2613  if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2614      From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2615      Expr::NPCK_ZeroExpression) {
2616    if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2617      DiagRuntimeBehavior(From->getExprLoc(), From,
2618                          PDiag(diag::warn_impcast_bool_to_null_pointer)
2619                            << ToType << From->getSourceRange());
2620    else if (!isUnevaluatedContext())
2621      Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2622        << ToType << From->getSourceRange();
2623  }
2624  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2625    if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2626      QualType FromPointeeType = FromPtrType->getPointeeType(),
2627               ToPointeeType   = ToPtrType->getPointeeType();
2628
2629      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2630          !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2631        // We must have a derived-to-base conversion. Check an
2632        // ambiguous or inaccessible conversion.
2633        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2634                                         From->getExprLoc(),
2635                                         From->getSourceRange(), &BasePath,
2636                                         IgnoreBaseAccess))
2637          return true;
2638
2639        // The conversion was successful.
2640        Kind = CK_DerivedToBase;
2641      }
2642    }
2643  } else if (const ObjCObjectPointerType *ToPtrType =
2644               ToType->getAs<ObjCObjectPointerType>()) {
2645    if (const ObjCObjectPointerType *FromPtrType =
2646          FromType->getAs<ObjCObjectPointerType>()) {
2647      // Objective-C++ conversions are always okay.
2648      // FIXME: We should have a different class of conversions for the
2649      // Objective-C++ implicit conversions.
2650      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2651        return false;
2652    } else if (FromType->isBlockPointerType()) {
2653      Kind = CK_BlockPointerToObjCPointerCast;
2654    } else {
2655      Kind = CK_CPointerToObjCPointerCast;
2656    }
2657  } else if (ToType->isBlockPointerType()) {
2658    if (!FromType->isBlockPointerType())
2659      Kind = CK_AnyPointerToBlockPointerCast;
2660  }
2661
2662  // We shouldn't fall into this case unless it's valid for other
2663  // reasons.
2664  if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2665    Kind = CK_NullToPointer;
2666
2667  return false;
2668}
2669
2670/// IsMemberPointerConversion - Determines whether the conversion of the
2671/// expression From, which has the (possibly adjusted) type FromType, can be
2672/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2673/// If so, returns true and places the converted type (that might differ from
2674/// ToType in its cv-qualifiers at some level) into ConvertedType.
2675bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2676                                     QualType ToType,
2677                                     bool InOverloadResolution,
2678                                     QualType &ConvertedType) {
2679  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2680  if (!ToTypePtr)
2681    return false;
2682
2683  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2684  if (From->isNullPointerConstant(Context,
2685                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2686                                        : Expr::NPC_ValueDependentIsNull)) {
2687    ConvertedType = ToType;
2688    return true;
2689  }
2690
2691  // Otherwise, both types have to be member pointers.
2692  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2693  if (!FromTypePtr)
2694    return false;
2695
2696  // A pointer to member of B can be converted to a pointer to member of D,
2697  // where D is derived from B (C++ 4.11p2).
2698  QualType FromClass(FromTypePtr->getClass(), 0);
2699  QualType ToClass(ToTypePtr->getClass(), 0);
2700
2701  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2702      !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2703      IsDerivedFrom(ToClass, FromClass)) {
2704    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2705                                                 ToClass.getTypePtr());
2706    return true;
2707  }
2708
2709  return false;
2710}
2711
2712/// CheckMemberPointerConversion - Check the member pointer conversion from the
2713/// expression From to the type ToType. This routine checks for ambiguous or
2714/// virtual or inaccessible base-to-derived member pointer conversions
2715/// for which IsMemberPointerConversion has already returned true. It returns
2716/// true and produces a diagnostic if there was an error, or returns false
2717/// otherwise.
2718bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2719                                        CastKind &Kind,
2720                                        CXXCastPath &BasePath,
2721                                        bool IgnoreBaseAccess) {
2722  QualType FromType = From->getType();
2723  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2724  if (!FromPtrType) {
2725    // This must be a null pointer to member pointer conversion
2726    assert(From->isNullPointerConstant(Context,
2727                                       Expr::NPC_ValueDependentIsNull) &&
2728           "Expr must be null pointer constant!");
2729    Kind = CK_NullToMemberPointer;
2730    return false;
2731  }
2732
2733  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2734  assert(ToPtrType && "No member pointer cast has a target type "
2735                      "that is not a member pointer.");
2736
2737  QualType FromClass = QualType(FromPtrType->getClass(), 0);
2738  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2739
2740  // FIXME: What about dependent types?
2741  assert(FromClass->isRecordType() && "Pointer into non-class.");
2742  assert(ToClass->isRecordType() && "Pointer into non-class.");
2743
2744  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2745                     /*DetectVirtual=*/true);
2746  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2747  assert(DerivationOkay &&
2748         "Should not have been called if derivation isn't OK.");
2749  (void)DerivationOkay;
2750
2751  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2752                                  getUnqualifiedType())) {
2753    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2754    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2755      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2756    return true;
2757  }
2758
2759  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2760    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2761      << FromClass << ToClass << QualType(VBase, 0)
2762      << From->getSourceRange();
2763    return true;
2764  }
2765
2766  if (!IgnoreBaseAccess)
2767    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2768                         Paths.front(),
2769                         diag::err_downcast_from_inaccessible_base);
2770
2771  // Must be a base to derived member conversion.
2772  BuildBasePathArray(Paths, BasePath);
2773  Kind = CK_BaseToDerivedMemberPointer;
2774  return false;
2775}
2776
2777/// IsQualificationConversion - Determines whether the conversion from
2778/// an rvalue of type FromType to ToType is a qualification conversion
2779/// (C++ 4.4).
2780///
2781/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2782/// when the qualification conversion involves a change in the Objective-C
2783/// object lifetime.
2784bool
2785Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2786                                bool CStyle, bool &ObjCLifetimeConversion) {
2787  FromType = Context.getCanonicalType(FromType);
2788  ToType = Context.getCanonicalType(ToType);
2789  ObjCLifetimeConversion = false;
2790
2791  // If FromType and ToType are the same type, this is not a
2792  // qualification conversion.
2793  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2794    return false;
2795
2796  // (C++ 4.4p4):
2797  //   A conversion can add cv-qualifiers at levels other than the first
2798  //   in multi-level pointers, subject to the following rules: [...]
2799  bool PreviousToQualsIncludeConst = true;
2800  bool UnwrappedAnyPointer = false;
2801  while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2802    // Within each iteration of the loop, we check the qualifiers to
2803    // determine if this still looks like a qualification
2804    // conversion. Then, if all is well, we unwrap one more level of
2805    // pointers or pointers-to-members and do it all again
2806    // until there are no more pointers or pointers-to-members left to
2807    // unwrap.
2808    UnwrappedAnyPointer = true;
2809
2810    Qualifiers FromQuals = FromType.getQualifiers();
2811    Qualifiers ToQuals = ToType.getQualifiers();
2812
2813    // Objective-C ARC:
2814    //   Check Objective-C lifetime conversions.
2815    if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2816        UnwrappedAnyPointer) {
2817      if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2818        ObjCLifetimeConversion = true;
2819        FromQuals.removeObjCLifetime();
2820        ToQuals.removeObjCLifetime();
2821      } else {
2822        // Qualification conversions cannot cast between different
2823        // Objective-C lifetime qualifiers.
2824        return false;
2825      }
2826    }
2827
2828    // Allow addition/removal of GC attributes but not changing GC attributes.
2829    if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2830        (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2831      FromQuals.removeObjCGCAttr();
2832      ToQuals.removeObjCGCAttr();
2833    }
2834
2835    //   -- for every j > 0, if const is in cv 1,j then const is in cv
2836    //      2,j, and similarly for volatile.
2837    if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2838      return false;
2839
2840    //   -- if the cv 1,j and cv 2,j are different, then const is in
2841    //      every cv for 0 < k < j.
2842    if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2843        && !PreviousToQualsIncludeConst)
2844      return false;
2845
2846    // Keep track of whether all prior cv-qualifiers in the "to" type
2847    // include const.
2848    PreviousToQualsIncludeConst
2849      = PreviousToQualsIncludeConst && ToQuals.hasConst();
2850  }
2851
2852  // We are left with FromType and ToType being the pointee types
2853  // after unwrapping the original FromType and ToType the same number
2854  // of types. If we unwrapped any pointers, and if FromType and
2855  // ToType have the same unqualified type (since we checked
2856  // qualifiers above), then this is a qualification conversion.
2857  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2858}
2859
2860/// \brief - Determine whether this is a conversion from a scalar type to an
2861/// atomic type.
2862///
2863/// If successful, updates \c SCS's second and third steps in the conversion
2864/// sequence to finish the conversion.
2865static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2866                                bool InOverloadResolution,
2867                                StandardConversionSequence &SCS,
2868                                bool CStyle) {
2869  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2870  if (!ToAtomic)
2871    return false;
2872
2873  StandardConversionSequence InnerSCS;
2874  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2875                            InOverloadResolution, InnerSCS,
2876                            CStyle, /*AllowObjCWritebackConversion=*/false))
2877    return false;
2878
2879  SCS.Second = InnerSCS.Second;
2880  SCS.setToType(1, InnerSCS.getToType(1));
2881  SCS.Third = InnerSCS.Third;
2882  SCS.QualificationIncludesObjCLifetime
2883    = InnerSCS.QualificationIncludesObjCLifetime;
2884  SCS.setToType(2, InnerSCS.getToType(2));
2885  return true;
2886}
2887
2888static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2889                                              CXXConstructorDecl *Constructor,
2890                                              QualType Type) {
2891  const FunctionProtoType *CtorType =
2892      Constructor->getType()->getAs<FunctionProtoType>();
2893  if (CtorType->getNumArgs() > 0) {
2894    QualType FirstArg = CtorType->getArgType(0);
2895    if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2896      return true;
2897  }
2898  return false;
2899}
2900
2901static OverloadingResult
2902IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2903                                       CXXRecordDecl *To,
2904                                       UserDefinedConversionSequence &User,
2905                                       OverloadCandidateSet &CandidateSet,
2906                                       bool AllowExplicit) {
2907  DeclContext::lookup_result R = S.LookupConstructors(To);
2908  for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2909       Con != ConEnd; ++Con) {
2910    NamedDecl *D = *Con;
2911    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2912
2913    // Find the constructor (which may be a template).
2914    CXXConstructorDecl *Constructor = 0;
2915    FunctionTemplateDecl *ConstructorTmpl
2916      = dyn_cast<FunctionTemplateDecl>(D);
2917    if (ConstructorTmpl)
2918      Constructor
2919        = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2920    else
2921      Constructor = cast<CXXConstructorDecl>(D);
2922
2923    bool Usable = !Constructor->isInvalidDecl() &&
2924                  S.isInitListConstructor(Constructor) &&
2925                  (AllowExplicit || !Constructor->isExplicit());
2926    if (Usable) {
2927      // If the first argument is (a reference to) the target type,
2928      // suppress conversions.
2929      bool SuppressUserConversions =
2930          isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2931      if (ConstructorTmpl)
2932        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2933                                       /*ExplicitArgs*/ 0,
2934                                       From, CandidateSet,
2935                                       SuppressUserConversions);
2936      else
2937        S.AddOverloadCandidate(Constructor, FoundDecl,
2938                               From, CandidateSet,
2939                               SuppressUserConversions);
2940    }
2941  }
2942
2943  bool HadMultipleCandidates = (CandidateSet.size() > 1);
2944
2945  OverloadCandidateSet::iterator Best;
2946  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2947  case OR_Success: {
2948    // Record the standard conversion we used and the conversion function.
2949    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2950    QualType ThisType = Constructor->getThisType(S.Context);
2951    // Initializer lists don't have conversions as such.
2952    User.Before.setAsIdentityConversion();
2953    User.HadMultipleCandidates = HadMultipleCandidates;
2954    User.ConversionFunction = Constructor;
2955    User.FoundConversionFunction = Best->FoundDecl;
2956    User.After.setAsIdentityConversion();
2957    User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2958    User.After.setAllToTypes(ToType);
2959    return OR_Success;
2960  }
2961
2962  case OR_No_Viable_Function:
2963    return OR_No_Viable_Function;
2964  case OR_Deleted:
2965    return OR_Deleted;
2966  case OR_Ambiguous:
2967    return OR_Ambiguous;
2968  }
2969
2970  llvm_unreachable("Invalid OverloadResult!");
2971}
2972
2973/// Determines whether there is a user-defined conversion sequence
2974/// (C++ [over.ics.user]) that converts expression From to the type
2975/// ToType. If such a conversion exists, User will contain the
2976/// user-defined conversion sequence that performs such a conversion
2977/// and this routine will return true. Otherwise, this routine returns
2978/// false and User is unspecified.
2979///
2980/// \param AllowExplicit  true if the conversion should consider C++0x
2981/// "explicit" conversion functions as well as non-explicit conversion
2982/// functions (C++0x [class.conv.fct]p2).
2983static OverloadingResult
2984IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2985                        UserDefinedConversionSequence &User,
2986                        OverloadCandidateSet &CandidateSet,
2987                        bool AllowExplicit) {
2988  // Whether we will only visit constructors.
2989  bool ConstructorsOnly = false;
2990
2991  // If the type we are conversion to is a class type, enumerate its
2992  // constructors.
2993  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2994    // C++ [over.match.ctor]p1:
2995    //   When objects of class type are direct-initialized (8.5), or
2996    //   copy-initialized from an expression of the same or a
2997    //   derived class type (8.5), overload resolution selects the
2998    //   constructor. [...] For copy-initialization, the candidate
2999    //   functions are all the converting constructors (12.3.1) of
3000    //   that class. The argument list is the expression-list within
3001    //   the parentheses of the initializer.
3002    if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3003        (From->getType()->getAs<RecordType>() &&
3004         S.IsDerivedFrom(From->getType(), ToType)))
3005      ConstructorsOnly = true;
3006
3007    S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3008    // RequireCompleteType may have returned true due to some invalid decl
3009    // during template instantiation, but ToType may be complete enough now
3010    // to try to recover.
3011    if (ToType->isIncompleteType()) {
3012      // We're not going to find any constructors.
3013    } else if (CXXRecordDecl *ToRecordDecl
3014                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3015
3016      Expr **Args = &From;
3017      unsigned NumArgs = 1;
3018      bool ListInitializing = false;
3019      if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3020        // But first, see if there is an init-list-constructor that will work.
3021        OverloadingResult Result = IsInitializerListConstructorConversion(
3022            S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3023        if (Result != OR_No_Viable_Function)
3024          return Result;
3025        // Never mind.
3026        CandidateSet.clear();
3027
3028        // If we're list-initializing, we pass the individual elements as
3029        // arguments, not the entire list.
3030        Args = InitList->getInits();
3031        NumArgs = InitList->getNumInits();
3032        ListInitializing = true;
3033      }
3034
3035      DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3036      for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3037           Con != ConEnd; ++Con) {
3038        NamedDecl *D = *Con;
3039        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3040
3041        // Find the constructor (which may be a template).
3042        CXXConstructorDecl *Constructor = 0;
3043        FunctionTemplateDecl *ConstructorTmpl
3044          = dyn_cast<FunctionTemplateDecl>(D);
3045        if (ConstructorTmpl)
3046          Constructor
3047            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3048        else
3049          Constructor = cast<CXXConstructorDecl>(D);
3050
3051        bool Usable = !Constructor->isInvalidDecl();
3052        if (ListInitializing)
3053          Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3054        else
3055          Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3056        if (Usable) {
3057          bool SuppressUserConversions = !ConstructorsOnly;
3058          if (SuppressUserConversions && ListInitializing) {
3059            SuppressUserConversions = false;
3060            if (NumArgs == 1) {
3061              // If the first argument is (a reference to) the target type,
3062              // suppress conversions.
3063              SuppressUserConversions = isFirstArgumentCompatibleWithType(
3064                                                S.Context, Constructor, ToType);
3065            }
3066          }
3067          if (ConstructorTmpl)
3068            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3069                                           /*ExplicitArgs*/ 0,
3070                                           llvm::makeArrayRef(Args, NumArgs),
3071                                           CandidateSet, SuppressUserConversions);
3072          else
3073            // Allow one user-defined conversion when user specifies a
3074            // From->ToType conversion via an static cast (c-style, etc).
3075            S.AddOverloadCandidate(Constructor, FoundDecl,
3076                                   llvm::makeArrayRef(Args, NumArgs),
3077                                   CandidateSet, SuppressUserConversions);
3078        }
3079      }
3080    }
3081  }
3082
3083  // Enumerate conversion functions, if we're allowed to.
3084  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3085  } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3086    // No conversion functions from incomplete types.
3087  } else if (const RecordType *FromRecordType
3088                                   = From->getType()->getAs<RecordType>()) {
3089    if (CXXRecordDecl *FromRecordDecl
3090         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3091      // Add all of the conversion functions as candidates.
3092      std::pair<CXXRecordDecl::conversion_iterator,
3093                CXXRecordDecl::conversion_iterator>
3094        Conversions = FromRecordDecl->getVisibleConversionFunctions();
3095      for (CXXRecordDecl::conversion_iterator
3096             I = Conversions.first, E = Conversions.second; I != E; ++I) {
3097        DeclAccessPair FoundDecl = I.getPair();
3098        NamedDecl *D = FoundDecl.getDecl();
3099        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3100        if (isa<UsingShadowDecl>(D))
3101          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3102
3103        CXXConversionDecl *Conv;
3104        FunctionTemplateDecl *ConvTemplate;
3105        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3106          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3107        else
3108          Conv = cast<CXXConversionDecl>(D);
3109
3110        if (AllowExplicit || !Conv->isExplicit()) {
3111          if (ConvTemplate)
3112            S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3113                                             ActingContext, From, ToType,
3114                                             CandidateSet);
3115          else
3116            S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3117                                     From, ToType, CandidateSet);
3118        }
3119      }
3120    }
3121  }
3122
3123  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3124
3125  OverloadCandidateSet::iterator Best;
3126  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3127  case OR_Success:
3128    // Record the standard conversion we used and the conversion function.
3129    if (CXXConstructorDecl *Constructor
3130          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3131      // C++ [over.ics.user]p1:
3132      //   If the user-defined conversion is specified by a
3133      //   constructor (12.3.1), the initial standard conversion
3134      //   sequence converts the source type to the type required by
3135      //   the argument of the constructor.
3136      //
3137      QualType ThisType = Constructor->getThisType(S.Context);
3138      if (isa<InitListExpr>(From)) {
3139        // Initializer lists don't have conversions as such.
3140        User.Before.setAsIdentityConversion();
3141      } else {
3142        if (Best->Conversions[0].isEllipsis())
3143          User.EllipsisConversion = true;
3144        else {
3145          User.Before = Best->Conversions[0].Standard;
3146          User.EllipsisConversion = false;
3147        }
3148      }
3149      User.HadMultipleCandidates = HadMultipleCandidates;
3150      User.ConversionFunction = Constructor;
3151      User.FoundConversionFunction = Best->FoundDecl;
3152      User.After.setAsIdentityConversion();
3153      User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3154      User.After.setAllToTypes(ToType);
3155      return OR_Success;
3156    }
3157    if (CXXConversionDecl *Conversion
3158                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3159      // C++ [over.ics.user]p1:
3160      //
3161      //   [...] If the user-defined conversion is specified by a
3162      //   conversion function (12.3.2), the initial standard
3163      //   conversion sequence converts the source type to the
3164      //   implicit object parameter of the conversion function.
3165      User.Before = Best->Conversions[0].Standard;
3166      User.HadMultipleCandidates = HadMultipleCandidates;
3167      User.ConversionFunction = Conversion;
3168      User.FoundConversionFunction = Best->FoundDecl;
3169      User.EllipsisConversion = false;
3170
3171      // C++ [over.ics.user]p2:
3172      //   The second standard conversion sequence converts the
3173      //   result of the user-defined conversion to the target type
3174      //   for the sequence. Since an implicit conversion sequence
3175      //   is an initialization, the special rules for
3176      //   initialization by user-defined conversion apply when
3177      //   selecting the best user-defined conversion for a
3178      //   user-defined conversion sequence (see 13.3.3 and
3179      //   13.3.3.1).
3180      User.After = Best->FinalConversion;
3181      return OR_Success;
3182    }
3183    llvm_unreachable("Not a constructor or conversion function?");
3184
3185  case OR_No_Viable_Function:
3186    return OR_No_Viable_Function;
3187  case OR_Deleted:
3188    // No conversion here! We're done.
3189    return OR_Deleted;
3190
3191  case OR_Ambiguous:
3192    return OR_Ambiguous;
3193  }
3194
3195  llvm_unreachable("Invalid OverloadResult!");
3196}
3197
3198bool
3199Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3200  ImplicitConversionSequence ICS;
3201  OverloadCandidateSet CandidateSet(From->getExprLoc());
3202  OverloadingResult OvResult =
3203    IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3204                            CandidateSet, false);
3205  if (OvResult == OR_Ambiguous)
3206    Diag(From->getLocStart(),
3207         diag::err_typecheck_ambiguous_condition)
3208          << From->getType() << ToType << From->getSourceRange();
3209  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3210    if (!RequireCompleteType(From->getLocStart(), ToType,
3211                          diag::err_typecheck_nonviable_condition_incomplete,
3212                             From->getType(), From->getSourceRange()))
3213      Diag(From->getLocStart(),
3214           diag::err_typecheck_nonviable_condition)
3215           << From->getType() << From->getSourceRange() << ToType;
3216  }
3217  else
3218    return false;
3219  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3220  return true;
3221}
3222
3223/// \brief Compare the user-defined conversion functions or constructors
3224/// of two user-defined conversion sequences to determine whether any ordering
3225/// is possible.
3226static ImplicitConversionSequence::CompareKind
3227compareConversionFunctions(Sema &S,
3228                           FunctionDecl *Function1,
3229                           FunctionDecl *Function2) {
3230  if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3231    return ImplicitConversionSequence::Indistinguishable;
3232
3233  // Objective-C++:
3234  //   If both conversion functions are implicitly-declared conversions from
3235  //   a lambda closure type to a function pointer and a block pointer,
3236  //   respectively, always prefer the conversion to a function pointer,
3237  //   because the function pointer is more lightweight and is more likely
3238  //   to keep code working.
3239  CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3240  if (!Conv1)
3241    return ImplicitConversionSequence::Indistinguishable;
3242
3243  CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3244  if (!Conv2)
3245    return ImplicitConversionSequence::Indistinguishable;
3246
3247  if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3248    bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3249    bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3250    if (Block1 != Block2)
3251      return Block1? ImplicitConversionSequence::Worse
3252                   : ImplicitConversionSequence::Better;
3253  }
3254
3255  return ImplicitConversionSequence::Indistinguishable;
3256}
3257
3258/// CompareImplicitConversionSequences - Compare two implicit
3259/// conversion sequences to determine whether one is better than the
3260/// other or if they are indistinguishable (C++ 13.3.3.2).
3261static ImplicitConversionSequence::CompareKind
3262CompareImplicitConversionSequences(Sema &S,
3263                                   const ImplicitConversionSequence& ICS1,
3264                                   const ImplicitConversionSequence& ICS2)
3265{
3266  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3267  // conversion sequences (as defined in 13.3.3.1)
3268  //   -- a standard conversion sequence (13.3.3.1.1) is a better
3269  //      conversion sequence than a user-defined conversion sequence or
3270  //      an ellipsis conversion sequence, and
3271  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3272  //      conversion sequence than an ellipsis conversion sequence
3273  //      (13.3.3.1.3).
3274  //
3275  // C++0x [over.best.ics]p10:
3276  //   For the purpose of ranking implicit conversion sequences as
3277  //   described in 13.3.3.2, the ambiguous conversion sequence is
3278  //   treated as a user-defined sequence that is indistinguishable
3279  //   from any other user-defined conversion sequence.
3280  if (ICS1.getKindRank() < ICS2.getKindRank())
3281    return ImplicitConversionSequence::Better;
3282  if (ICS2.getKindRank() < ICS1.getKindRank())
3283    return ImplicitConversionSequence::Worse;
3284
3285  // The following checks require both conversion sequences to be of
3286  // the same kind.
3287  if (ICS1.getKind() != ICS2.getKind())
3288    return ImplicitConversionSequence::Indistinguishable;
3289
3290  ImplicitConversionSequence::CompareKind Result =
3291      ImplicitConversionSequence::Indistinguishable;
3292
3293  // Two implicit conversion sequences of the same form are
3294  // indistinguishable conversion sequences unless one of the
3295  // following rules apply: (C++ 13.3.3.2p3):
3296  if (ICS1.isStandard())
3297    Result = CompareStandardConversionSequences(S,
3298                                                ICS1.Standard, ICS2.Standard);
3299  else if (ICS1.isUserDefined()) {
3300    // User-defined conversion sequence U1 is a better conversion
3301    // sequence than another user-defined conversion sequence U2 if
3302    // they contain the same user-defined conversion function or
3303    // constructor and if the second standard conversion sequence of
3304    // U1 is better than the second standard conversion sequence of
3305    // U2 (C++ 13.3.3.2p3).
3306    if (ICS1.UserDefined.ConversionFunction ==
3307          ICS2.UserDefined.ConversionFunction)
3308      Result = CompareStandardConversionSequences(S,
3309                                                  ICS1.UserDefined.After,
3310                                                  ICS2.UserDefined.After);
3311    else
3312      Result = compareConversionFunctions(S,
3313                                          ICS1.UserDefined.ConversionFunction,
3314                                          ICS2.UserDefined.ConversionFunction);
3315  }
3316
3317  // List-initialization sequence L1 is a better conversion sequence than
3318  // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3319  // for some X and L2 does not.
3320  if (Result == ImplicitConversionSequence::Indistinguishable &&
3321      !ICS1.isBad()) {
3322    if (ICS1.isStdInitializerListElement() &&
3323        !ICS2.isStdInitializerListElement())
3324      return ImplicitConversionSequence::Better;
3325    if (!ICS1.isStdInitializerListElement() &&
3326        ICS2.isStdInitializerListElement())
3327      return ImplicitConversionSequence::Worse;
3328  }
3329
3330  return Result;
3331}
3332
3333static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3334  while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3335    Qualifiers Quals;
3336    T1 = Context.getUnqualifiedArrayType(T1, Quals);
3337    T2 = Context.getUnqualifiedArrayType(T2, Quals);
3338  }
3339
3340  return Context.hasSameUnqualifiedType(T1, T2);
3341}
3342
3343// Per 13.3.3.2p3, compare the given standard conversion sequences to
3344// determine if one is a proper subset of the other.
3345static ImplicitConversionSequence::CompareKind
3346compareStandardConversionSubsets(ASTContext &Context,
3347                                 const StandardConversionSequence& SCS1,
3348                                 const StandardConversionSequence& SCS2) {
3349  ImplicitConversionSequence::CompareKind Result
3350    = ImplicitConversionSequence::Indistinguishable;
3351
3352  // the identity conversion sequence is considered to be a subsequence of
3353  // any non-identity conversion sequence
3354  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3355    return ImplicitConversionSequence::Better;
3356  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3357    return ImplicitConversionSequence::Worse;
3358
3359  if (SCS1.Second != SCS2.Second) {
3360    if (SCS1.Second == ICK_Identity)
3361      Result = ImplicitConversionSequence::Better;
3362    else if (SCS2.Second == ICK_Identity)
3363      Result = ImplicitConversionSequence::Worse;
3364    else
3365      return ImplicitConversionSequence::Indistinguishable;
3366  } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3367    return ImplicitConversionSequence::Indistinguishable;
3368
3369  if (SCS1.Third == SCS2.Third) {
3370    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3371                             : ImplicitConversionSequence::Indistinguishable;
3372  }
3373
3374  if (SCS1.Third == ICK_Identity)
3375    return Result == ImplicitConversionSequence::Worse
3376             ? ImplicitConversionSequence::Indistinguishable
3377             : ImplicitConversionSequence::Better;
3378
3379  if (SCS2.Third == ICK_Identity)
3380    return Result == ImplicitConversionSequence::Better
3381             ? ImplicitConversionSequence::Indistinguishable
3382             : ImplicitConversionSequence::Worse;
3383
3384  return ImplicitConversionSequence::Indistinguishable;
3385}
3386
3387/// \brief Determine whether one of the given reference bindings is better
3388/// than the other based on what kind of bindings they are.
3389static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3390                                       const StandardConversionSequence &SCS2) {
3391  // C++0x [over.ics.rank]p3b4:
3392  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3393  //      implicit object parameter of a non-static member function declared
3394  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3395  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3396  //      lvalue reference to a function lvalue and S2 binds an rvalue
3397  //      reference*.
3398  //
3399  // FIXME: Rvalue references. We're going rogue with the above edits,
3400  // because the semantics in the current C++0x working paper (N3225 at the
3401  // time of this writing) break the standard definition of std::forward
3402  // and std::reference_wrapper when dealing with references to functions.
3403  // Proposed wording changes submitted to CWG for consideration.
3404  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3405      SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3406    return false;
3407
3408  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3409          SCS2.IsLvalueReference) ||
3410         (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3411          !SCS2.IsLvalueReference);
3412}
3413
3414/// CompareStandardConversionSequences - Compare two standard
3415/// conversion sequences to determine whether one is better than the
3416/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3417static ImplicitConversionSequence::CompareKind
3418CompareStandardConversionSequences(Sema &S,
3419                                   const StandardConversionSequence& SCS1,
3420                                   const StandardConversionSequence& SCS2)
3421{
3422  // Standard conversion sequence S1 is a better conversion sequence
3423  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3424
3425  //  -- S1 is a proper subsequence of S2 (comparing the conversion
3426  //     sequences in the canonical form defined by 13.3.3.1.1,
3427  //     excluding any Lvalue Transformation; the identity conversion
3428  //     sequence is considered to be a subsequence of any
3429  //     non-identity conversion sequence) or, if not that,
3430  if (ImplicitConversionSequence::CompareKind CK
3431        = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3432    return CK;
3433
3434  //  -- the rank of S1 is better than the rank of S2 (by the rules
3435  //     defined below), or, if not that,
3436  ImplicitConversionRank Rank1 = SCS1.getRank();
3437  ImplicitConversionRank Rank2 = SCS2.getRank();
3438  if (Rank1 < Rank2)
3439    return ImplicitConversionSequence::Better;
3440  else if (Rank2 < Rank1)
3441    return ImplicitConversionSequence::Worse;
3442
3443  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3444  // are indistinguishable unless one of the following rules
3445  // applies:
3446
3447  //   A conversion that is not a conversion of a pointer, or
3448  //   pointer to member, to bool is better than another conversion
3449  //   that is such a conversion.
3450  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3451    return SCS2.isPointerConversionToBool()
3452             ? ImplicitConversionSequence::Better
3453             : ImplicitConversionSequence::Worse;
3454
3455  // C++ [over.ics.rank]p4b2:
3456  //
3457  //   If class B is derived directly or indirectly from class A,
3458  //   conversion of B* to A* is better than conversion of B* to
3459  //   void*, and conversion of A* to void* is better than conversion
3460  //   of B* to void*.
3461  bool SCS1ConvertsToVoid
3462    = SCS1.isPointerConversionToVoidPointer(S.Context);
3463  bool SCS2ConvertsToVoid
3464    = SCS2.isPointerConversionToVoidPointer(S.Context);
3465  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3466    // Exactly one of the conversion sequences is a conversion to
3467    // a void pointer; it's the worse conversion.
3468    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3469                              : ImplicitConversionSequence::Worse;
3470  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3471    // Neither conversion sequence converts to a void pointer; compare
3472    // their derived-to-base conversions.
3473    if (ImplicitConversionSequence::CompareKind DerivedCK
3474          = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3475      return DerivedCK;
3476  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3477             !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3478    // Both conversion sequences are conversions to void
3479    // pointers. Compare the source types to determine if there's an
3480    // inheritance relationship in their sources.
3481    QualType FromType1 = SCS1.getFromType();
3482    QualType FromType2 = SCS2.getFromType();
3483
3484    // Adjust the types we're converting from via the array-to-pointer
3485    // conversion, if we need to.
3486    if (SCS1.First == ICK_Array_To_Pointer)
3487      FromType1 = S.Context.getArrayDecayedType(FromType1);
3488    if (SCS2.First == ICK_Array_To_Pointer)
3489      FromType2 = S.Context.getArrayDecayedType(FromType2);
3490
3491    QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3492    QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3493
3494    if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3495      return ImplicitConversionSequence::Better;
3496    else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3497      return ImplicitConversionSequence::Worse;
3498
3499    // Objective-C++: If one interface is more specific than the
3500    // other, it is the better one.
3501    const ObjCObjectPointerType* FromObjCPtr1
3502      = FromType1->getAs<ObjCObjectPointerType>();
3503    const ObjCObjectPointerType* FromObjCPtr2
3504      = FromType2->getAs<ObjCObjectPointerType>();
3505    if (FromObjCPtr1 && FromObjCPtr2) {
3506      bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3507                                                          FromObjCPtr2);
3508      bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3509                                                           FromObjCPtr1);
3510      if (AssignLeft != AssignRight) {
3511        return AssignLeft? ImplicitConversionSequence::Better
3512                         : ImplicitConversionSequence::Worse;
3513      }
3514    }
3515  }
3516
3517  // Compare based on qualification conversions (C++ 13.3.3.2p3,
3518  // bullet 3).
3519  if (ImplicitConversionSequence::CompareKind QualCK
3520        = CompareQualificationConversions(S, SCS1, SCS2))
3521    return QualCK;
3522
3523  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3524    // Check for a better reference binding based on the kind of bindings.
3525    if (isBetterReferenceBindingKind(SCS1, SCS2))
3526      return ImplicitConversionSequence::Better;
3527    else if (isBetterReferenceBindingKind(SCS2, SCS1))
3528      return ImplicitConversionSequence::Worse;
3529
3530    // C++ [over.ics.rank]p3b4:
3531    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3532    //      which the references refer are the same type except for
3533    //      top-level cv-qualifiers, and the type to which the reference
3534    //      initialized by S2 refers is more cv-qualified than the type
3535    //      to which the reference initialized by S1 refers.
3536    QualType T1 = SCS1.getToType(2);
3537    QualType T2 = SCS2.getToType(2);
3538    T1 = S.Context.getCanonicalType(T1);
3539    T2 = S.Context.getCanonicalType(T2);
3540    Qualifiers T1Quals, T2Quals;
3541    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3542    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3543    if (UnqualT1 == UnqualT2) {
3544      // Objective-C++ ARC: If the references refer to objects with different
3545      // lifetimes, prefer bindings that don't change lifetime.
3546      if (SCS1.ObjCLifetimeConversionBinding !=
3547                                          SCS2.ObjCLifetimeConversionBinding) {
3548        return SCS1.ObjCLifetimeConversionBinding
3549                                           ? ImplicitConversionSequence::Worse
3550                                           : ImplicitConversionSequence::Better;
3551      }
3552
3553      // If the type is an array type, promote the element qualifiers to the
3554      // type for comparison.
3555      if (isa<ArrayType>(T1) && T1Quals)
3556        T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3557      if (isa<ArrayType>(T2) && T2Quals)
3558        T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3559      if (T2.isMoreQualifiedThan(T1))
3560        return ImplicitConversionSequence::Better;
3561      else if (T1.isMoreQualifiedThan(T2))
3562        return ImplicitConversionSequence::Worse;
3563    }
3564  }
3565
3566  // In Microsoft mode, prefer an integral conversion to a
3567  // floating-to-integral conversion if the integral conversion
3568  // is between types of the same size.
3569  // For example:
3570  // void f(float);
3571  // void f(int);
3572  // int main {
3573  //    long a;
3574  //    f(a);
3575  // }
3576  // Here, MSVC will call f(int) instead of generating a compile error
3577  // as clang will do in standard mode.
3578  if (S.getLangOpts().MicrosoftMode &&
3579      SCS1.Second == ICK_Integral_Conversion &&
3580      SCS2.Second == ICK_Floating_Integral &&
3581      S.Context.getTypeSize(SCS1.getFromType()) ==
3582      S.Context.getTypeSize(SCS1.getToType(2)))
3583    return ImplicitConversionSequence::Better;
3584
3585  return ImplicitConversionSequence::Indistinguishable;
3586}
3587
3588/// CompareQualificationConversions - Compares two standard conversion
3589/// sequences to determine whether they can be ranked based on their
3590/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3591ImplicitConversionSequence::CompareKind
3592CompareQualificationConversions(Sema &S,
3593                                const StandardConversionSequence& SCS1,
3594                                const StandardConversionSequence& SCS2) {
3595  // C++ 13.3.3.2p3:
3596  //  -- S1 and S2 differ only in their qualification conversion and
3597  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3598  //     cv-qualification signature of type T1 is a proper subset of
3599  //     the cv-qualification signature of type T2, and S1 is not the
3600  //     deprecated string literal array-to-pointer conversion (4.2).
3601  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3602      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3603    return ImplicitConversionSequence::Indistinguishable;
3604
3605  // FIXME: the example in the standard doesn't use a qualification
3606  // conversion (!)
3607  QualType T1 = SCS1.getToType(2);
3608  QualType T2 = SCS2.getToType(2);
3609  T1 = S.Context.getCanonicalType(T1);
3610  T2 = S.Context.getCanonicalType(T2);
3611  Qualifiers T1Quals, T2Quals;
3612  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3613  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3614
3615  // If the types are the same, we won't learn anything by unwrapped
3616  // them.
3617  if (UnqualT1 == UnqualT2)
3618    return ImplicitConversionSequence::Indistinguishable;
3619
3620  // If the type is an array type, promote the element qualifiers to the type
3621  // for comparison.
3622  if (isa<ArrayType>(T1) && T1Quals)
3623    T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3624  if (isa<ArrayType>(T2) && T2Quals)
3625    T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3626
3627  ImplicitConversionSequence::CompareKind Result
3628    = ImplicitConversionSequence::Indistinguishable;
3629
3630  // Objective-C++ ARC:
3631  //   Prefer qualification conversions not involving a change in lifetime
3632  //   to qualification conversions that do not change lifetime.
3633  if (SCS1.QualificationIncludesObjCLifetime !=
3634                                      SCS2.QualificationIncludesObjCLifetime) {
3635    Result = SCS1.QualificationIncludesObjCLifetime
3636               ? ImplicitConversionSequence::Worse
3637               : ImplicitConversionSequence::Better;
3638  }
3639
3640  while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3641    // Within each iteration of the loop, we check the qualifiers to
3642    // determine if this still looks like a qualification
3643    // conversion. Then, if all is well, we unwrap one more level of
3644    // pointers or pointers-to-members and do it all again
3645    // until there are no more pointers or pointers-to-members left
3646    // to unwrap. This essentially mimics what
3647    // IsQualificationConversion does, but here we're checking for a
3648    // strict subset of qualifiers.
3649    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3650      // The qualifiers are the same, so this doesn't tell us anything
3651      // about how the sequences rank.
3652      ;
3653    else if (T2.isMoreQualifiedThan(T1)) {
3654      // T1 has fewer qualifiers, so it could be the better sequence.
3655      if (Result == ImplicitConversionSequence::Worse)
3656        // Neither has qualifiers that are a subset of the other's
3657        // qualifiers.
3658        return ImplicitConversionSequence::Indistinguishable;
3659
3660      Result = ImplicitConversionSequence::Better;
3661    } else if (T1.isMoreQualifiedThan(T2)) {
3662      // T2 has fewer qualifiers, so it could be the better sequence.
3663      if (Result == ImplicitConversionSequence::Better)
3664        // Neither has qualifiers that are a subset of the other's
3665        // qualifiers.
3666        return ImplicitConversionSequence::Indistinguishable;
3667
3668      Result = ImplicitConversionSequence::Worse;
3669    } else {
3670      // Qualifiers are disjoint.
3671      return ImplicitConversionSequence::Indistinguishable;
3672    }
3673
3674    // If the types after this point are equivalent, we're done.
3675    if (S.Context.hasSameUnqualifiedType(T1, T2))
3676      break;
3677  }
3678
3679  // Check that the winning standard conversion sequence isn't using
3680  // the deprecated string literal array to pointer conversion.
3681  switch (Result) {
3682  case ImplicitConversionSequence::Better:
3683    if (SCS1.DeprecatedStringLiteralToCharPtr)
3684      Result = ImplicitConversionSequence::Indistinguishable;
3685    break;
3686
3687  case ImplicitConversionSequence::Indistinguishable:
3688    break;
3689
3690  case ImplicitConversionSequence::Worse:
3691    if (SCS2.DeprecatedStringLiteralToCharPtr)
3692      Result = ImplicitConversionSequence::Indistinguishable;
3693    break;
3694  }
3695
3696  return Result;
3697}
3698
3699/// CompareDerivedToBaseConversions - Compares two standard conversion
3700/// sequences to determine whether they can be ranked based on their
3701/// various kinds of derived-to-base conversions (C++
3702/// [over.ics.rank]p4b3).  As part of these checks, we also look at
3703/// conversions between Objective-C interface types.
3704ImplicitConversionSequence::CompareKind
3705CompareDerivedToBaseConversions(Sema &S,
3706                                const StandardConversionSequence& SCS1,
3707                                const StandardConversionSequence& SCS2) {
3708  QualType FromType1 = SCS1.getFromType();
3709  QualType ToType1 = SCS1.getToType(1);
3710  QualType FromType2 = SCS2.getFromType();
3711  QualType ToType2 = SCS2.getToType(1);
3712
3713  // Adjust the types we're converting from via the array-to-pointer
3714  // conversion, if we need to.
3715  if (SCS1.First == ICK_Array_To_Pointer)
3716    FromType1 = S.Context.getArrayDecayedType(FromType1);
3717  if (SCS2.First == ICK_Array_To_Pointer)
3718    FromType2 = S.Context.getArrayDecayedType(FromType2);
3719
3720  // Canonicalize all of the types.
3721  FromType1 = S.Context.getCanonicalType(FromType1);
3722  ToType1 = S.Context.getCanonicalType(ToType1);
3723  FromType2 = S.Context.getCanonicalType(FromType2);
3724  ToType2 = S.Context.getCanonicalType(ToType2);
3725
3726  // C++ [over.ics.rank]p4b3:
3727  //
3728  //   If class B is derived directly or indirectly from class A and
3729  //   class C is derived directly or indirectly from B,
3730  //
3731  // Compare based on pointer conversions.
3732  if (SCS1.Second == ICK_Pointer_Conversion &&
3733      SCS2.Second == ICK_Pointer_Conversion &&
3734      /*FIXME: Remove if Objective-C id conversions get their own rank*/
3735      FromType1->isPointerType() && FromType2->isPointerType() &&
3736      ToType1->isPointerType() && ToType2->isPointerType()) {
3737    QualType FromPointee1
3738      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3739    QualType ToPointee1
3740      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3741    QualType FromPointee2
3742      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3743    QualType ToPointee2
3744      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3745
3746    //   -- conversion of C* to B* is better than conversion of C* to A*,
3747    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3748      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3749        return ImplicitConversionSequence::Better;
3750      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3751        return ImplicitConversionSequence::Worse;
3752    }
3753
3754    //   -- conversion of B* to A* is better than conversion of C* to A*,
3755    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3756      if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3757        return ImplicitConversionSequence::Better;
3758      else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3759        return ImplicitConversionSequence::Worse;
3760    }
3761  } else if (SCS1.Second == ICK_Pointer_Conversion &&
3762             SCS2.Second == ICK_Pointer_Conversion) {
3763    const ObjCObjectPointerType *FromPtr1
3764      = FromType1->getAs<ObjCObjectPointerType>();
3765    const ObjCObjectPointerType *FromPtr2
3766      = FromType2->getAs<ObjCObjectPointerType>();
3767    const ObjCObjectPointerType *ToPtr1
3768      = ToType1->getAs<ObjCObjectPointerType>();
3769    const ObjCObjectPointerType *ToPtr2
3770      = ToType2->getAs<ObjCObjectPointerType>();
3771
3772    if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3773      // Apply the same conversion ranking rules for Objective-C pointer types
3774      // that we do for C++ pointers to class types. However, we employ the
3775      // Objective-C pseudo-subtyping relationship used for assignment of
3776      // Objective-C pointer types.
3777      bool FromAssignLeft
3778        = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3779      bool FromAssignRight
3780        = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3781      bool ToAssignLeft
3782        = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3783      bool ToAssignRight
3784        = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3785
3786      // A conversion to an a non-id object pointer type or qualified 'id'
3787      // type is better than a conversion to 'id'.
3788      if (ToPtr1->isObjCIdType() &&
3789          (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3790        return ImplicitConversionSequence::Worse;
3791      if (ToPtr2->isObjCIdType() &&
3792          (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3793        return ImplicitConversionSequence::Better;
3794
3795      // A conversion to a non-id object pointer type is better than a
3796      // conversion to a qualified 'id' type
3797      if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3798        return ImplicitConversionSequence::Worse;
3799      if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3800        return ImplicitConversionSequence::Better;
3801
3802      // A conversion to an a non-Class object pointer type or qualified 'Class'
3803      // type is better than a conversion to 'Class'.
3804      if (ToPtr1->isObjCClassType() &&
3805          (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3806        return ImplicitConversionSequence::Worse;
3807      if (ToPtr2->isObjCClassType() &&
3808          (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3809        return ImplicitConversionSequence::Better;
3810
3811      // A conversion to a non-Class object pointer type is better than a
3812      // conversion to a qualified 'Class' type.
3813      if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3814        return ImplicitConversionSequence::Worse;
3815      if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3816        return ImplicitConversionSequence::Better;
3817
3818      //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3819      if (S.Context.hasSameType(FromType1, FromType2) &&
3820          !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3821          (ToAssignLeft != ToAssignRight))
3822        return ToAssignLeft? ImplicitConversionSequence::Worse
3823                           : ImplicitConversionSequence::Better;
3824
3825      //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3826      if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3827          (FromAssignLeft != FromAssignRight))
3828        return FromAssignLeft? ImplicitConversionSequence::Better
3829        : ImplicitConversionSequence::Worse;
3830    }
3831  }
3832
3833  // Ranking of member-pointer types.
3834  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3835      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3836      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3837    const MemberPointerType * FromMemPointer1 =
3838                                        FromType1->getAs<MemberPointerType>();
3839    const MemberPointerType * ToMemPointer1 =
3840                                          ToType1->getAs<MemberPointerType>();
3841    const MemberPointerType * FromMemPointer2 =
3842                                          FromType2->getAs<MemberPointerType>();
3843    const MemberPointerType * ToMemPointer2 =
3844                                          ToType2->getAs<MemberPointerType>();
3845    const Type *FromPointeeType1 = FromMemPointer1->getClass();
3846    const Type *ToPointeeType1 = ToMemPointer1->getClass();
3847    const Type *FromPointeeType2 = FromMemPointer2->getClass();
3848    const Type *ToPointeeType2 = ToMemPointer2->getClass();
3849    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3850    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3851    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3852    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3853    // conversion of A::* to B::* is better than conversion of A::* to C::*,
3854    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3855      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3856        return ImplicitConversionSequence::Worse;
3857      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3858        return ImplicitConversionSequence::Better;
3859    }
3860    // conversion of B::* to C::* is better than conversion of A::* to C::*
3861    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3862      if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3863        return ImplicitConversionSequence::Better;
3864      else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3865        return ImplicitConversionSequence::Worse;
3866    }
3867  }
3868
3869  if (SCS1.Second == ICK_Derived_To_Base) {
3870    //   -- conversion of C to B is better than conversion of C to A,
3871    //   -- binding of an expression of type C to a reference of type
3872    //      B& is better than binding an expression of type C to a
3873    //      reference of type A&,
3874    if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3875        !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3876      if (S.IsDerivedFrom(ToType1, ToType2))
3877        return ImplicitConversionSequence::Better;
3878      else if (S.IsDerivedFrom(ToType2, ToType1))
3879        return ImplicitConversionSequence::Worse;
3880    }
3881
3882    //   -- conversion of B to A is better than conversion of C to A.
3883    //   -- binding of an expression of type B to a reference of type
3884    //      A& is better than binding an expression of type C to a
3885    //      reference of type A&,
3886    if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3887        S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3888      if (S.IsDerivedFrom(FromType2, FromType1))
3889        return ImplicitConversionSequence::Better;
3890      else if (S.IsDerivedFrom(FromType1, FromType2))
3891        return ImplicitConversionSequence::Worse;
3892    }
3893  }
3894
3895  return ImplicitConversionSequence::Indistinguishable;
3896}
3897
3898/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3899/// C++ class.
3900static bool isTypeValid(QualType T) {
3901  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3902    return !Record->isInvalidDecl();
3903
3904  return true;
3905}
3906
3907/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3908/// determine whether they are reference-related,
3909/// reference-compatible, reference-compatible with added
3910/// qualification, or incompatible, for use in C++ initialization by
3911/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3912/// type, and the first type (T1) is the pointee type of the reference
3913/// type being initialized.
3914Sema::ReferenceCompareResult
3915Sema::CompareReferenceRelationship(SourceLocation Loc,
3916                                   QualType OrigT1, QualType OrigT2,
3917                                   bool &DerivedToBase,
3918                                   bool &ObjCConversion,
3919                                   bool &ObjCLifetimeConversion) {
3920  assert(!OrigT1->isReferenceType() &&
3921    "T1 must be the pointee type of the reference type");
3922  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3923
3924  QualType T1 = Context.getCanonicalType(OrigT1);
3925  QualType T2 = Context.getCanonicalType(OrigT2);
3926  Qualifiers T1Quals, T2Quals;
3927  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3928  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3929
3930  // C++ [dcl.init.ref]p4:
3931  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3932  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3933  //   T1 is a base class of T2.
3934  DerivedToBase = false;
3935  ObjCConversion = false;
3936  ObjCLifetimeConversion = false;
3937  if (UnqualT1 == UnqualT2) {
3938    // Nothing to do.
3939  } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3940             isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3941             IsDerivedFrom(UnqualT2, UnqualT1))
3942    DerivedToBase = true;
3943  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3944           UnqualT2->isObjCObjectOrInterfaceType() &&
3945           Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3946    ObjCConversion = true;
3947  else
3948    return Ref_Incompatible;
3949
3950  // At this point, we know that T1 and T2 are reference-related (at
3951  // least).
3952
3953  // If the type is an array type, promote the element qualifiers to the type
3954  // for comparison.
3955  if (isa<ArrayType>(T1) && T1Quals)
3956    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3957  if (isa<ArrayType>(T2) && T2Quals)
3958    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3959
3960  // C++ [dcl.init.ref]p4:
3961  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3962  //   reference-related to T2 and cv1 is the same cv-qualification
3963  //   as, or greater cv-qualification than, cv2. For purposes of
3964  //   overload resolution, cases for which cv1 is greater
3965  //   cv-qualification than cv2 are identified as
3966  //   reference-compatible with added qualification (see 13.3.3.2).
3967  //
3968  // Note that we also require equivalence of Objective-C GC and address-space
3969  // qualifiers when performing these computations, so that e.g., an int in
3970  // address space 1 is not reference-compatible with an int in address
3971  // space 2.
3972  if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3973      T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3974    T1Quals.removeObjCLifetime();
3975    T2Quals.removeObjCLifetime();
3976    ObjCLifetimeConversion = true;
3977  }
3978
3979  if (T1Quals == T2Quals)
3980    return Ref_Compatible;
3981  else if (T1Quals.compatiblyIncludes(T2Quals))
3982    return Ref_Compatible_With_Added_Qualification;
3983  else
3984    return Ref_Related;
3985}
3986
3987/// \brief Look for a user-defined conversion to an value reference-compatible
3988///        with DeclType. Return true if something definite is found.
3989static bool
3990FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3991                         QualType DeclType, SourceLocation DeclLoc,
3992                         Expr *Init, QualType T2, bool AllowRvalues,
3993                         bool AllowExplicit) {
3994  assert(T2->isRecordType() && "Can only find conversions of record types.");
3995  CXXRecordDecl *T2RecordDecl
3996    = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3997
3998  OverloadCandidateSet CandidateSet(DeclLoc);
3999  std::pair<CXXRecordDecl::conversion_iterator,
4000            CXXRecordDecl::conversion_iterator>
4001    Conversions = T2RecordDecl->getVisibleConversionFunctions();
4002  for (CXXRecordDecl::conversion_iterator
4003         I = Conversions.first, E = Conversions.second; I != E; ++I) {
4004    NamedDecl *D = *I;
4005    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4006    if (isa<UsingShadowDecl>(D))
4007      D = cast<UsingShadowDecl>(D)->getTargetDecl();
4008
4009    FunctionTemplateDecl *ConvTemplate
4010      = dyn_cast<FunctionTemplateDecl>(D);
4011    CXXConversionDecl *Conv;
4012    if (ConvTemplate)
4013      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4014    else
4015      Conv = cast<CXXConversionDecl>(D);
4016
4017    // If this is an explicit conversion, and we're not allowed to consider
4018    // explicit conversions, skip it.
4019    if (!AllowExplicit && Conv->isExplicit())
4020      continue;
4021
4022    if (AllowRvalues) {
4023      bool DerivedToBase = false;
4024      bool ObjCConversion = false;
4025      bool ObjCLifetimeConversion = false;
4026
4027      // If we are initializing an rvalue reference, don't permit conversion
4028      // functions that return lvalues.
4029      if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4030        const ReferenceType *RefType
4031          = Conv->getConversionType()->getAs<LValueReferenceType>();
4032        if (RefType && !RefType->getPointeeType()->isFunctionType())
4033          continue;
4034      }
4035
4036      if (!ConvTemplate &&
4037          S.CompareReferenceRelationship(
4038            DeclLoc,
4039            Conv->getConversionType().getNonReferenceType()
4040              .getUnqualifiedType(),
4041            DeclType.getNonReferenceType().getUnqualifiedType(),
4042            DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4043          Sema::Ref_Incompatible)
4044        continue;
4045    } else {
4046      // If the conversion function doesn't return a reference type,
4047      // it can't be considered for this conversion. An rvalue reference
4048      // is only acceptable if its referencee is a function type.
4049
4050      const ReferenceType *RefType =
4051        Conv->getConversionType()->getAs<ReferenceType>();
4052      if (!RefType ||
4053          (!RefType->isLValueReferenceType() &&
4054           !RefType->getPointeeType()->isFunctionType()))
4055        continue;
4056    }
4057
4058    if (ConvTemplate)
4059      S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4060                                       Init, DeclType, CandidateSet);
4061    else
4062      S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4063                               DeclType, CandidateSet);
4064  }
4065
4066  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4067
4068  OverloadCandidateSet::iterator Best;
4069  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4070  case OR_Success:
4071    // C++ [over.ics.ref]p1:
4072    //
4073    //   [...] If the parameter binds directly to the result of
4074    //   applying a conversion function to the argument
4075    //   expression, the implicit conversion sequence is a
4076    //   user-defined conversion sequence (13.3.3.1.2), with the
4077    //   second standard conversion sequence either an identity
4078    //   conversion or, if the conversion function returns an
4079    //   entity of a type that is a derived class of the parameter
4080    //   type, a derived-to-base Conversion.
4081    if (!Best->FinalConversion.DirectBinding)
4082      return false;
4083
4084    ICS.setUserDefined();
4085    ICS.UserDefined.Before = Best->Conversions[0].Standard;
4086    ICS.UserDefined.After = Best->FinalConversion;
4087    ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4088    ICS.UserDefined.ConversionFunction = Best->Function;
4089    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4090    ICS.UserDefined.EllipsisConversion = false;
4091    assert(ICS.UserDefined.After.ReferenceBinding &&
4092           ICS.UserDefined.After.DirectBinding &&
4093           "Expected a direct reference binding!");
4094    return true;
4095
4096  case OR_Ambiguous:
4097    ICS.setAmbiguous();
4098    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4099         Cand != CandidateSet.end(); ++Cand)
4100      if (Cand->Viable)
4101        ICS.Ambiguous.addConversion(Cand->Function);
4102    return true;
4103
4104  case OR_No_Viable_Function:
4105  case OR_Deleted:
4106    // There was no suitable conversion, or we found a deleted
4107    // conversion; continue with other checks.
4108    return false;
4109  }
4110
4111  llvm_unreachable("Invalid OverloadResult!");
4112}
4113
4114/// \brief Compute an implicit conversion sequence for reference
4115/// initialization.
4116static ImplicitConversionSequence
4117TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4118                 SourceLocation DeclLoc,
4119                 bool SuppressUserConversions,
4120                 bool AllowExplicit) {
4121  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4122
4123  // Most paths end in a failed conversion.
4124  ImplicitConversionSequence ICS;
4125  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4126
4127  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4128  QualType T2 = Init->getType();
4129
4130  // If the initializer is the address of an overloaded function, try
4131  // to resolve the overloaded function. If all goes well, T2 is the
4132  // type of the resulting function.
4133  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4134    DeclAccessPair Found;
4135    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4136                                                                false, Found))
4137      T2 = Fn->getType();
4138  }
4139
4140  // Compute some basic properties of the types and the initializer.
4141  bool isRValRef = DeclType->isRValueReferenceType();
4142  bool DerivedToBase = false;
4143  bool ObjCConversion = false;
4144  bool ObjCLifetimeConversion = false;
4145  Expr::Classification InitCategory = Init->Classify(S.Context);
4146  Sema::ReferenceCompareResult RefRelationship
4147    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4148                                     ObjCConversion, ObjCLifetimeConversion);
4149
4150
4151  // C++0x [dcl.init.ref]p5:
4152  //   A reference to type "cv1 T1" is initialized by an expression
4153  //   of type "cv2 T2" as follows:
4154
4155  //     -- If reference is an lvalue reference and the initializer expression
4156  if (!isRValRef) {
4157    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4158    //        reference-compatible with "cv2 T2," or
4159    //
4160    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4161    if (InitCategory.isLValue() &&
4162        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4163      // C++ [over.ics.ref]p1:
4164      //   When a parameter of reference type binds directly (8.5.3)
4165      //   to an argument expression, the implicit conversion sequence
4166      //   is the identity conversion, unless the argument expression
4167      //   has a type that is a derived class of the parameter type,
4168      //   in which case the implicit conversion sequence is a
4169      //   derived-to-base Conversion (13.3.3.1).
4170      ICS.setStandard();
4171      ICS.Standard.First = ICK_Identity;
4172      ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4173                         : ObjCConversion? ICK_Compatible_Conversion
4174                         : ICK_Identity;
4175      ICS.Standard.Third = ICK_Identity;
4176      ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4177      ICS.Standard.setToType(0, T2);
4178      ICS.Standard.setToType(1, T1);
4179      ICS.Standard.setToType(2, T1);
4180      ICS.Standard.ReferenceBinding = true;
4181      ICS.Standard.DirectBinding = true;
4182      ICS.Standard.IsLvalueReference = !isRValRef;
4183      ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4184      ICS.Standard.BindsToRvalue = false;
4185      ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4186      ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4187      ICS.Standard.CopyConstructor = 0;
4188
4189      // Nothing more to do: the inaccessibility/ambiguity check for
4190      // derived-to-base conversions is suppressed when we're
4191      // computing the implicit conversion sequence (C++
4192      // [over.best.ics]p2).
4193      return ICS;
4194    }
4195
4196    //       -- has a class type (i.e., T2 is a class type), where T1 is
4197    //          not reference-related to T2, and can be implicitly
4198    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4199    //          is reference-compatible with "cv3 T3" 92) (this
4200    //          conversion is selected by enumerating the applicable
4201    //          conversion functions (13.3.1.6) and choosing the best
4202    //          one through overload resolution (13.3)),
4203    if (!SuppressUserConversions && T2->isRecordType() &&
4204        !S.RequireCompleteType(DeclLoc, T2, 0) &&
4205        RefRelationship == Sema::Ref_Incompatible) {
4206      if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4207                                   Init, T2, /*AllowRvalues=*/false,
4208                                   AllowExplicit))
4209        return ICS;
4210    }
4211  }
4212
4213  //     -- Otherwise, the reference shall be an lvalue reference to a
4214  //        non-volatile const type (i.e., cv1 shall be const), or the reference
4215  //        shall be an rvalue reference.
4216  //
4217  // We actually handle one oddity of C++ [over.ics.ref] at this
4218  // point, which is that, due to p2 (which short-circuits reference
4219  // binding by only attempting a simple conversion for non-direct
4220  // bindings) and p3's strange wording, we allow a const volatile
4221  // reference to bind to an rvalue. Hence the check for the presence
4222  // of "const" rather than checking for "const" being the only
4223  // qualifier.
4224  // This is also the point where rvalue references and lvalue inits no longer
4225  // go together.
4226  if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4227    return ICS;
4228
4229  //       -- If the initializer expression
4230  //
4231  //            -- is an xvalue, class prvalue, array prvalue or function
4232  //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4233  if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4234      (InitCategory.isXValue() ||
4235      (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4236      (InitCategory.isLValue() && T2->isFunctionType()))) {
4237    ICS.setStandard();
4238    ICS.Standard.First = ICK_Identity;
4239    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4240                      : ObjCConversion? ICK_Compatible_Conversion
4241                      : ICK_Identity;
4242    ICS.Standard.Third = ICK_Identity;
4243    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4244    ICS.Standard.setToType(0, T2);
4245    ICS.Standard.setToType(1, T1);
4246    ICS.Standard.setToType(2, T1);
4247    ICS.Standard.ReferenceBinding = true;
4248    // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4249    // binding unless we're binding to a class prvalue.
4250    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4251    // allow the use of rvalue references in C++98/03 for the benefit of
4252    // standard library implementors; therefore, we need the xvalue check here.
4253    ICS.Standard.DirectBinding =
4254      S.getLangOpts().CPlusPlus11 ||
4255      (InitCategory.isPRValue() && !T2->isRecordType());
4256    ICS.Standard.IsLvalueReference = !isRValRef;
4257    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4258    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4259    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4260    ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4261    ICS.Standard.CopyConstructor = 0;
4262    return ICS;
4263  }
4264
4265  //            -- has a class type (i.e., T2 is a class type), where T1 is not
4266  //               reference-related to T2, and can be implicitly converted to
4267  //               an xvalue, class prvalue, or function lvalue of type
4268  //               "cv3 T3", where "cv1 T1" is reference-compatible with
4269  //               "cv3 T3",
4270  //
4271  //          then the reference is bound to the value of the initializer
4272  //          expression in the first case and to the result of the conversion
4273  //          in the second case (or, in either case, to an appropriate base
4274  //          class subobject).
4275  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4276      T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4277      FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4278                               Init, T2, /*AllowRvalues=*/true,
4279                               AllowExplicit)) {
4280    // In the second case, if the reference is an rvalue reference
4281    // and the second standard conversion sequence of the
4282    // user-defined conversion sequence includes an lvalue-to-rvalue
4283    // conversion, the program is ill-formed.
4284    if (ICS.isUserDefined() && isRValRef &&
4285        ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4286      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4287
4288    return ICS;
4289  }
4290
4291  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4292  //          initialized from the initializer expression using the
4293  //          rules for a non-reference copy initialization (8.5). The
4294  //          reference is then bound to the temporary. If T1 is
4295  //          reference-related to T2, cv1 must be the same
4296  //          cv-qualification as, or greater cv-qualification than,
4297  //          cv2; otherwise, the program is ill-formed.
4298  if (RefRelationship == Sema::Ref_Related) {
4299    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4300    // we would be reference-compatible or reference-compatible with
4301    // added qualification. But that wasn't the case, so the reference
4302    // initialization fails.
4303    //
4304    // Note that we only want to check address spaces and cvr-qualifiers here.
4305    // ObjC GC and lifetime qualifiers aren't important.
4306    Qualifiers T1Quals = T1.getQualifiers();
4307    Qualifiers T2Quals = T2.getQualifiers();
4308    T1Quals.removeObjCGCAttr();
4309    T1Quals.removeObjCLifetime();
4310    T2Quals.removeObjCGCAttr();
4311    T2Quals.removeObjCLifetime();
4312    if (!T1Quals.compatiblyIncludes(T2Quals))
4313      return ICS;
4314  }
4315
4316  // If at least one of the types is a class type, the types are not
4317  // related, and we aren't allowed any user conversions, the
4318  // reference binding fails. This case is important for breaking
4319  // recursion, since TryImplicitConversion below will attempt to
4320  // create a temporary through the use of a copy constructor.
4321  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4322      (T1->isRecordType() || T2->isRecordType()))
4323    return ICS;
4324
4325  // If T1 is reference-related to T2 and the reference is an rvalue
4326  // reference, the initializer expression shall not be an lvalue.
4327  if (RefRelationship >= Sema::Ref_Related &&
4328      isRValRef && Init->Classify(S.Context).isLValue())
4329    return ICS;
4330
4331  // C++ [over.ics.ref]p2:
4332  //   When a parameter of reference type is not bound directly to
4333  //   an argument expression, the conversion sequence is the one
4334  //   required to convert the argument expression to the
4335  //   underlying type of the reference according to
4336  //   13.3.3.1. Conceptually, this conversion sequence corresponds
4337  //   to copy-initializing a temporary of the underlying type with
4338  //   the argument expression. Any difference in top-level
4339  //   cv-qualification is subsumed by the initialization itself
4340  //   and does not constitute a conversion.
4341  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4342                              /*AllowExplicit=*/false,
4343                              /*InOverloadResolution=*/false,
4344                              /*CStyle=*/false,
4345                              /*AllowObjCWritebackConversion=*/false);
4346
4347  // Of course, that's still a reference binding.
4348  if (ICS.isStandard()) {
4349    ICS.Standard.ReferenceBinding = true;
4350    ICS.Standard.IsLvalueReference = !isRValRef;
4351    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4352    ICS.Standard.BindsToRvalue = true;
4353    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4354    ICS.Standard.ObjCLifetimeConversionBinding = false;
4355  } else if (ICS.isUserDefined()) {
4356    // Don't allow rvalue references to bind to lvalues.
4357    if (DeclType->isRValueReferenceType()) {
4358      if (const ReferenceType *RefType
4359            = ICS.UserDefined.ConversionFunction->getResultType()
4360                ->getAs<LValueReferenceType>()) {
4361        if (!RefType->getPointeeType()->isFunctionType()) {
4362          ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4363                     DeclType);
4364          return ICS;
4365        }
4366      }
4367    }
4368
4369    ICS.UserDefined.After.ReferenceBinding = true;
4370    ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4371    ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4372    ICS.UserDefined.After.BindsToRvalue = true;
4373    ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4374    ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4375  }
4376
4377  return ICS;
4378}
4379
4380static ImplicitConversionSequence
4381TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4382                      bool SuppressUserConversions,
4383                      bool InOverloadResolution,
4384                      bool AllowObjCWritebackConversion,
4385                      bool AllowExplicit = false);
4386
4387/// TryListConversion - Try to copy-initialize a value of type ToType from the
4388/// initializer list From.
4389static ImplicitConversionSequence
4390TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4391                  bool SuppressUserConversions,
4392                  bool InOverloadResolution,
4393                  bool AllowObjCWritebackConversion) {
4394  // C++11 [over.ics.list]p1:
4395  //   When an argument is an initializer list, it is not an expression and
4396  //   special rules apply for converting it to a parameter type.
4397
4398  ImplicitConversionSequence Result;
4399  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4400
4401  // We need a complete type for what follows. Incomplete types can never be
4402  // initialized from init lists.
4403  if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4404    return Result;
4405
4406  // C++11 [over.ics.list]p2:
4407  //   If the parameter type is std::initializer_list<X> or "array of X" and
4408  //   all the elements can be implicitly converted to X, the implicit
4409  //   conversion sequence is the worst conversion necessary to convert an
4410  //   element of the list to X.
4411  bool toStdInitializerList = false;
4412  QualType X;
4413  if (ToType->isArrayType())
4414    X = S.Context.getAsArrayType(ToType)->getElementType();
4415  else
4416    toStdInitializerList = S.isStdInitializerList(ToType, &X);
4417  if (!X.isNull()) {
4418    for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4419      Expr *Init = From->getInit(i);
4420      ImplicitConversionSequence ICS =
4421          TryCopyInitialization(S, Init, X, SuppressUserConversions,
4422                                InOverloadResolution,
4423                                AllowObjCWritebackConversion);
4424      // If a single element isn't convertible, fail.
4425      if (ICS.isBad()) {
4426        Result = ICS;
4427        break;
4428      }
4429      // Otherwise, look for the worst conversion.
4430      if (Result.isBad() ||
4431          CompareImplicitConversionSequences(S, ICS, Result) ==
4432              ImplicitConversionSequence::Worse)
4433        Result = ICS;
4434    }
4435
4436    // For an empty list, we won't have computed any conversion sequence.
4437    // Introduce the identity conversion sequence.
4438    if (From->getNumInits() == 0) {
4439      Result.setStandard();
4440      Result.Standard.setAsIdentityConversion();
4441      Result.Standard.setFromType(ToType);
4442      Result.Standard.setAllToTypes(ToType);
4443    }
4444
4445    Result.setStdInitializerListElement(toStdInitializerList);
4446    return Result;
4447  }
4448
4449  // C++11 [over.ics.list]p3:
4450  //   Otherwise, if the parameter is a non-aggregate class X and overload
4451  //   resolution chooses a single best constructor [...] the implicit
4452  //   conversion sequence is a user-defined conversion sequence. If multiple
4453  //   constructors are viable but none is better than the others, the
4454  //   implicit conversion sequence is a user-defined conversion sequence.
4455  if (ToType->isRecordType() && !ToType->isAggregateType()) {
4456    // This function can deal with initializer lists.
4457    return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4458                                    /*AllowExplicit=*/false,
4459                                    InOverloadResolution, /*CStyle=*/false,
4460                                    AllowObjCWritebackConversion);
4461  }
4462
4463  // C++11 [over.ics.list]p4:
4464  //   Otherwise, if the parameter has an aggregate type which can be
4465  //   initialized from the initializer list [...] the implicit conversion
4466  //   sequence is a user-defined conversion sequence.
4467  if (ToType->isAggregateType()) {
4468    // Type is an aggregate, argument is an init list. At this point it comes
4469    // down to checking whether the initialization works.
4470    // FIXME: Find out whether this parameter is consumed or not.
4471    InitializedEntity Entity =
4472        InitializedEntity::InitializeParameter(S.Context, ToType,
4473                                               /*Consumed=*/false);
4474    if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4475      Result.setUserDefined();
4476      Result.UserDefined.Before.setAsIdentityConversion();
4477      // Initializer lists don't have a type.
4478      Result.UserDefined.Before.setFromType(QualType());
4479      Result.UserDefined.Before.setAllToTypes(QualType());
4480
4481      Result.UserDefined.After.setAsIdentityConversion();
4482      Result.UserDefined.After.setFromType(ToType);
4483      Result.UserDefined.After.setAllToTypes(ToType);
4484      Result.UserDefined.ConversionFunction = 0;
4485    }
4486    return Result;
4487  }
4488
4489  // C++11 [over.ics.list]p5:
4490  //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4491  if (ToType->isReferenceType()) {
4492    // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4493    // mention initializer lists in any way. So we go by what list-
4494    // initialization would do and try to extrapolate from that.
4495
4496    QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4497
4498    // If the initializer list has a single element that is reference-related
4499    // to the parameter type, we initialize the reference from that.
4500    if (From->getNumInits() == 1) {
4501      Expr *Init = From->getInit(0);
4502
4503      QualType T2 = Init->getType();
4504
4505      // If the initializer is the address of an overloaded function, try
4506      // to resolve the overloaded function. If all goes well, T2 is the
4507      // type of the resulting function.
4508      if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4509        DeclAccessPair Found;
4510        if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4511                                   Init, ToType, false, Found))
4512          T2 = Fn->getType();
4513      }
4514
4515      // Compute some basic properties of the types and the initializer.
4516      bool dummy1 = false;
4517      bool dummy2 = false;
4518      bool dummy3 = false;
4519      Sema::ReferenceCompareResult RefRelationship
4520        = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4521                                         dummy2, dummy3);
4522
4523      if (RefRelationship >= Sema::Ref_Related) {
4524        return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4525                                SuppressUserConversions,
4526                                /*AllowExplicit=*/false);
4527      }
4528    }
4529
4530    // Otherwise, we bind the reference to a temporary created from the
4531    // initializer list.
4532    Result = TryListConversion(S, From, T1, SuppressUserConversions,
4533                               InOverloadResolution,
4534                               AllowObjCWritebackConversion);
4535    if (Result.isFailure())
4536      return Result;
4537    assert(!Result.isEllipsis() &&
4538           "Sub-initialization cannot result in ellipsis conversion.");
4539
4540    // Can we even bind to a temporary?
4541    if (ToType->isRValueReferenceType() ||
4542        (T1.isConstQualified() && !T1.isVolatileQualified())) {
4543      StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4544                                            Result.UserDefined.After;
4545      SCS.ReferenceBinding = true;
4546      SCS.IsLvalueReference = ToType->isLValueReferenceType();
4547      SCS.BindsToRvalue = true;
4548      SCS.BindsToFunctionLvalue = false;
4549      SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4550      SCS.ObjCLifetimeConversionBinding = false;
4551    } else
4552      Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4553                    From, ToType);
4554    return Result;
4555  }
4556
4557  // C++11 [over.ics.list]p6:
4558  //   Otherwise, if the parameter type is not a class:
4559  if (!ToType->isRecordType()) {
4560    //    - if the initializer list has one element, the implicit conversion
4561    //      sequence is the one required to convert the element to the
4562    //      parameter type.
4563    unsigned NumInits = From->getNumInits();
4564    if (NumInits == 1)
4565      Result = TryCopyInitialization(S, From->getInit(0), ToType,
4566                                     SuppressUserConversions,
4567                                     InOverloadResolution,
4568                                     AllowObjCWritebackConversion);
4569    //    - if the initializer list has no elements, the implicit conversion
4570    //      sequence is the identity conversion.
4571    else if (NumInits == 0) {
4572      Result.setStandard();
4573      Result.Standard.setAsIdentityConversion();
4574      Result.Standard.setFromType(ToType);
4575      Result.Standard.setAllToTypes(ToType);
4576    }
4577    return Result;
4578  }
4579
4580  // C++11 [over.ics.list]p7:
4581  //   In all cases other than those enumerated above, no conversion is possible
4582  return Result;
4583}
4584
4585/// TryCopyInitialization - Try to copy-initialize a value of type
4586/// ToType from the expression From. Return the implicit conversion
4587/// sequence required to pass this argument, which may be a bad
4588/// conversion sequence (meaning that the argument cannot be passed to
4589/// a parameter of this type). If @p SuppressUserConversions, then we
4590/// do not permit any user-defined conversion sequences.
4591static ImplicitConversionSequence
4592TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4593                      bool SuppressUserConversions,
4594                      bool InOverloadResolution,
4595                      bool AllowObjCWritebackConversion,
4596                      bool AllowExplicit) {
4597  if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4598    return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4599                             InOverloadResolution,AllowObjCWritebackConversion);
4600
4601  if (ToType->isReferenceType())
4602    return TryReferenceInit(S, From, ToType,
4603                            /*FIXME:*/From->getLocStart(),
4604                            SuppressUserConversions,
4605                            AllowExplicit);
4606
4607  return TryImplicitConversion(S, From, ToType,
4608                               SuppressUserConversions,
4609                               /*AllowExplicit=*/false,
4610                               InOverloadResolution,
4611                               /*CStyle=*/false,
4612                               AllowObjCWritebackConversion);
4613}
4614
4615static bool TryCopyInitialization(const CanQualType FromQTy,
4616                                  const CanQualType ToQTy,
4617                                  Sema &S,
4618                                  SourceLocation Loc,
4619                                  ExprValueKind FromVK) {
4620  OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4621  ImplicitConversionSequence ICS =
4622    TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4623
4624  return !ICS.isBad();
4625}
4626
4627/// TryObjectArgumentInitialization - Try to initialize the object
4628/// parameter of the given member function (@c Method) from the
4629/// expression @p From.
4630static ImplicitConversionSequence
4631TryObjectArgumentInitialization(Sema &S, QualType FromType,
4632                                Expr::Classification FromClassification,
4633                                CXXMethodDecl *Method,
4634                                CXXRecordDecl *ActingContext) {
4635  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4636  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4637  //                 const volatile object.
4638  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4639    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4640  QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4641
4642  // Set up the conversion sequence as a "bad" conversion, to allow us
4643  // to exit early.
4644  ImplicitConversionSequence ICS;
4645
4646  // We need to have an object of class type.
4647  if (const PointerType *PT = FromType->getAs<PointerType>()) {
4648    FromType = PT->getPointeeType();
4649
4650    // When we had a pointer, it's implicitly dereferenced, so we
4651    // better have an lvalue.
4652    assert(FromClassification.isLValue());
4653  }
4654
4655  assert(FromType->isRecordType());
4656
4657  // C++0x [over.match.funcs]p4:
4658  //   For non-static member functions, the type of the implicit object
4659  //   parameter is
4660  //
4661  //     - "lvalue reference to cv X" for functions declared without a
4662  //        ref-qualifier or with the & ref-qualifier
4663  //     - "rvalue reference to cv X" for functions declared with the &&
4664  //        ref-qualifier
4665  //
4666  // where X is the class of which the function is a member and cv is the
4667  // cv-qualification on the member function declaration.
4668  //
4669  // However, when finding an implicit conversion sequence for the argument, we
4670  // are not allowed to create temporaries or perform user-defined conversions
4671  // (C++ [over.match.funcs]p5). We perform a simplified version of
4672  // reference binding here, that allows class rvalues to bind to
4673  // non-constant references.
4674
4675  // First check the qualifiers.
4676  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4677  if (ImplicitParamType.getCVRQualifiers()
4678                                    != FromTypeCanon.getLocalCVRQualifiers() &&
4679      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4680    ICS.setBad(BadConversionSequence::bad_qualifiers,
4681               FromType, ImplicitParamType);
4682    return ICS;
4683  }
4684
4685  // Check that we have either the same type or a derived type. It
4686  // affects the conversion rank.
4687  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4688  ImplicitConversionKind SecondKind;
4689  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4690    SecondKind = ICK_Identity;
4691  } else if (S.IsDerivedFrom(FromType, ClassType))
4692    SecondKind = ICK_Derived_To_Base;
4693  else {
4694    ICS.setBad(BadConversionSequence::unrelated_class,
4695               FromType, ImplicitParamType);
4696    return ICS;
4697  }
4698
4699  // Check the ref-qualifier.
4700  switch (Method->getRefQualifier()) {
4701  case RQ_None:
4702    // Do nothing; we don't care about lvalueness or rvalueness.
4703    break;
4704
4705  case RQ_LValue:
4706    if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4707      // non-const lvalue reference cannot bind to an rvalue
4708      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4709                 ImplicitParamType);
4710      return ICS;
4711    }
4712    break;
4713
4714  case RQ_RValue:
4715    if (!FromClassification.isRValue()) {
4716      // rvalue reference cannot bind to an lvalue
4717      ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4718                 ImplicitParamType);
4719      return ICS;
4720    }
4721    break;
4722  }
4723
4724  // Success. Mark this as a reference binding.
4725  ICS.setStandard();
4726  ICS.Standard.setAsIdentityConversion();
4727  ICS.Standard.Second = SecondKind;
4728  ICS.Standard.setFromType(FromType);
4729  ICS.Standard.setAllToTypes(ImplicitParamType);
4730  ICS.Standard.ReferenceBinding = true;
4731  ICS.Standard.DirectBinding = true;
4732  ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4733  ICS.Standard.BindsToFunctionLvalue = false;
4734  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4735  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4736    = (Method->getRefQualifier() == RQ_None);
4737  return ICS;
4738}
4739
4740/// PerformObjectArgumentInitialization - Perform initialization of
4741/// the implicit object parameter for the given Method with the given
4742/// expression.
4743ExprResult
4744Sema::PerformObjectArgumentInitialization(Expr *From,
4745                                          NestedNameSpecifier *Qualifier,
4746                                          NamedDecl *FoundDecl,
4747                                          CXXMethodDecl *Method) {
4748  QualType FromRecordType, DestType;
4749  QualType ImplicitParamRecordType  =
4750    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4751
4752  Expr::Classification FromClassification;
4753  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4754    FromRecordType = PT->getPointeeType();
4755    DestType = Method->getThisType(Context);
4756    FromClassification = Expr::Classification::makeSimpleLValue();
4757  } else {
4758    FromRecordType = From->getType();
4759    DestType = ImplicitParamRecordType;
4760    FromClassification = From->Classify(Context);
4761  }
4762
4763  // Note that we always use the true parent context when performing
4764  // the actual argument initialization.
4765  ImplicitConversionSequence ICS
4766    = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4767                                      Method, Method->getParent());
4768  if (ICS.isBad()) {
4769    if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4770      Qualifiers FromQs = FromRecordType.getQualifiers();
4771      Qualifiers ToQs = DestType.getQualifiers();
4772      unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4773      if (CVR) {
4774        Diag(From->getLocStart(),
4775             diag::err_member_function_call_bad_cvr)
4776          << Method->getDeclName() << FromRecordType << (CVR - 1)
4777          << From->getSourceRange();
4778        Diag(Method->getLocation(), diag::note_previous_decl)
4779          << Method->getDeclName();
4780        return ExprError();
4781      }
4782    }
4783
4784    return Diag(From->getLocStart(),
4785                diag::err_implicit_object_parameter_init)
4786       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4787  }
4788
4789  if (ICS.Standard.Second == ICK_Derived_To_Base) {
4790    ExprResult FromRes =
4791      PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4792    if (FromRes.isInvalid())
4793      return ExprError();
4794    From = FromRes.take();
4795  }
4796
4797  if (!Context.hasSameType(From->getType(), DestType))
4798    From = ImpCastExprToType(From, DestType, CK_NoOp,
4799                             From->getValueKind()).take();
4800  return Owned(From);
4801}
4802
4803/// TryContextuallyConvertToBool - Attempt to contextually convert the
4804/// expression From to bool (C++0x [conv]p3).
4805static ImplicitConversionSequence
4806TryContextuallyConvertToBool(Sema &S, Expr *From) {
4807  // FIXME: This is pretty broken.
4808  return TryImplicitConversion(S, From, S.Context.BoolTy,
4809                               // FIXME: Are these flags correct?
4810                               /*SuppressUserConversions=*/false,
4811                               /*AllowExplicit=*/true,
4812                               /*InOverloadResolution=*/false,
4813                               /*CStyle=*/false,
4814                               /*AllowObjCWritebackConversion=*/false);
4815}
4816
4817/// PerformContextuallyConvertToBool - Perform a contextual conversion
4818/// of the expression From to bool (C++0x [conv]p3).
4819ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4820  if (checkPlaceholderForOverload(*this, From))
4821    return ExprError();
4822
4823  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4824  if (!ICS.isBad())
4825    return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4826
4827  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4828    return Diag(From->getLocStart(),
4829                diag::err_typecheck_bool_condition)
4830                  << From->getType() << From->getSourceRange();
4831  return ExprError();
4832}
4833
4834/// Check that the specified conversion is permitted in a converted constant
4835/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4836/// is acceptable.
4837static bool CheckConvertedConstantConversions(Sema &S,
4838                                              StandardConversionSequence &SCS) {
4839  // Since we know that the target type is an integral or unscoped enumeration
4840  // type, most conversion kinds are impossible. All possible First and Third
4841  // conversions are fine.
4842  switch (SCS.Second) {
4843  case ICK_Identity:
4844  case ICK_Integral_Promotion:
4845  case ICK_Integral_Conversion:
4846  case ICK_Zero_Event_Conversion:
4847    return true;
4848
4849  case ICK_Boolean_Conversion:
4850    // Conversion from an integral or unscoped enumeration type to bool is
4851    // classified as ICK_Boolean_Conversion, but it's also an integral
4852    // conversion, so it's permitted in a converted constant expression.
4853    return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4854           SCS.getToType(2)->isBooleanType();
4855
4856  case ICK_Floating_Integral:
4857  case ICK_Complex_Real:
4858    return false;
4859
4860  case ICK_Lvalue_To_Rvalue:
4861  case ICK_Array_To_Pointer:
4862  case ICK_Function_To_Pointer:
4863  case ICK_NoReturn_Adjustment:
4864  case ICK_Qualification:
4865  case ICK_Compatible_Conversion:
4866  case ICK_Vector_Conversion:
4867  case ICK_Vector_Splat:
4868  case ICK_Derived_To_Base:
4869  case ICK_Pointer_Conversion:
4870  case ICK_Pointer_Member:
4871  case ICK_Block_Pointer_Conversion:
4872  case ICK_Writeback_Conversion:
4873  case ICK_Floating_Promotion:
4874  case ICK_Complex_Promotion:
4875  case ICK_Complex_Conversion:
4876  case ICK_Floating_Conversion:
4877  case ICK_TransparentUnionConversion:
4878    llvm_unreachable("unexpected second conversion kind");
4879
4880  case ICK_Num_Conversion_Kinds:
4881    break;
4882  }
4883
4884  llvm_unreachable("unknown conversion kind");
4885}
4886
4887/// CheckConvertedConstantExpression - Check that the expression From is a
4888/// converted constant expression of type T, perform the conversion and produce
4889/// the converted expression, per C++11 [expr.const]p3.
4890ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4891                                                  llvm::APSInt &Value,
4892                                                  CCEKind CCE) {
4893  assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4894  assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4895
4896  if (checkPlaceholderForOverload(*this, From))
4897    return ExprError();
4898
4899  // C++11 [expr.const]p3 with proposed wording fixes:
4900  //  A converted constant expression of type T is a core constant expression,
4901  //  implicitly converted to a prvalue of type T, where the converted
4902  //  expression is a literal constant expression and the implicit conversion
4903  //  sequence contains only user-defined conversions, lvalue-to-rvalue
4904  //  conversions, integral promotions, and integral conversions other than
4905  //  narrowing conversions.
4906  ImplicitConversionSequence ICS =
4907    TryImplicitConversion(From, T,
4908                          /*SuppressUserConversions=*/false,
4909                          /*AllowExplicit=*/false,
4910                          /*InOverloadResolution=*/false,
4911                          /*CStyle=*/false,
4912                          /*AllowObjcWritebackConversion=*/false);
4913  StandardConversionSequence *SCS = 0;
4914  switch (ICS.getKind()) {
4915  case ImplicitConversionSequence::StandardConversion:
4916    if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4917      return Diag(From->getLocStart(),
4918                  diag::err_typecheck_converted_constant_expression_disallowed)
4919               << From->getType() << From->getSourceRange() << T;
4920    SCS = &ICS.Standard;
4921    break;
4922  case ImplicitConversionSequence::UserDefinedConversion:
4923    // We are converting from class type to an integral or enumeration type, so
4924    // the Before sequence must be trivial.
4925    if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4926      return Diag(From->getLocStart(),
4927                  diag::err_typecheck_converted_constant_expression_disallowed)
4928               << From->getType() << From->getSourceRange() << T;
4929    SCS = &ICS.UserDefined.After;
4930    break;
4931  case ImplicitConversionSequence::AmbiguousConversion:
4932  case ImplicitConversionSequence::BadConversion:
4933    if (!DiagnoseMultipleUserDefinedConversion(From, T))
4934      return Diag(From->getLocStart(),
4935                  diag::err_typecheck_converted_constant_expression)
4936                    << From->getType() << From->getSourceRange() << T;
4937    return ExprError();
4938
4939  case ImplicitConversionSequence::EllipsisConversion:
4940    llvm_unreachable("ellipsis conversion in converted constant expression");
4941  }
4942
4943  ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4944  if (Result.isInvalid())
4945    return Result;
4946
4947  // Check for a narrowing implicit conversion.
4948  APValue PreNarrowingValue;
4949  QualType PreNarrowingType;
4950  switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4951                                PreNarrowingType)) {
4952  case NK_Variable_Narrowing:
4953    // Implicit conversion to a narrower type, and the value is not a constant
4954    // expression. We'll diagnose this in a moment.
4955  case NK_Not_Narrowing:
4956    break;
4957
4958  case NK_Constant_Narrowing:
4959    Diag(From->getLocStart(),
4960         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4961                             diag::err_cce_narrowing)
4962      << CCE << /*Constant*/1
4963      << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
4964    break;
4965
4966  case NK_Type_Narrowing:
4967    Diag(From->getLocStart(),
4968         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4969                             diag::err_cce_narrowing)
4970      << CCE << /*Constant*/0 << From->getType() << T;
4971    break;
4972  }
4973
4974  // Check the expression is a constant expression.
4975  SmallVector<PartialDiagnosticAt, 8> Notes;
4976  Expr::EvalResult Eval;
4977  Eval.Diag = &Notes;
4978
4979  if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
4980    // The expression can't be folded, so we can't keep it at this position in
4981    // the AST.
4982    Result = ExprError();
4983  } else {
4984    Value = Eval.Val.getInt();
4985
4986    if (Notes.empty()) {
4987      // It's a constant expression.
4988      return Result;
4989    }
4990  }
4991
4992  // It's not a constant expression. Produce an appropriate diagnostic.
4993  if (Notes.size() == 1 &&
4994      Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4995    Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4996  else {
4997    Diag(From->getLocStart(), diag::err_expr_not_cce)
4998      << CCE << From->getSourceRange();
4999    for (unsigned I = 0; I < Notes.size(); ++I)
5000      Diag(Notes[I].first, Notes[I].second);
5001  }
5002  return Result;
5003}
5004
5005/// dropPointerConversions - If the given standard conversion sequence
5006/// involves any pointer conversions, remove them.  This may change
5007/// the result type of the conversion sequence.
5008static void dropPointerConversion(StandardConversionSequence &SCS) {
5009  if (SCS.Second == ICK_Pointer_Conversion) {
5010    SCS.Second = ICK_Identity;
5011    SCS.Third = ICK_Identity;
5012    SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5013  }
5014}
5015
5016/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5017/// convert the expression From to an Objective-C pointer type.
5018static ImplicitConversionSequence
5019TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5020  // Do an implicit conversion to 'id'.
5021  QualType Ty = S.Context.getObjCIdType();
5022  ImplicitConversionSequence ICS
5023    = TryImplicitConversion(S, From, Ty,
5024                            // FIXME: Are these flags correct?
5025                            /*SuppressUserConversions=*/false,
5026                            /*AllowExplicit=*/true,
5027                            /*InOverloadResolution=*/false,
5028                            /*CStyle=*/false,
5029                            /*AllowObjCWritebackConversion=*/false);
5030
5031  // Strip off any final conversions to 'id'.
5032  switch (ICS.getKind()) {
5033  case ImplicitConversionSequence::BadConversion:
5034  case ImplicitConversionSequence::AmbiguousConversion:
5035  case ImplicitConversionSequence::EllipsisConversion:
5036    break;
5037
5038  case ImplicitConversionSequence::UserDefinedConversion:
5039    dropPointerConversion(ICS.UserDefined.After);
5040    break;
5041
5042  case ImplicitConversionSequence::StandardConversion:
5043    dropPointerConversion(ICS.Standard);
5044    break;
5045  }
5046
5047  return ICS;
5048}
5049
5050/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5051/// conversion of the expression From to an Objective-C pointer type.
5052ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5053  if (checkPlaceholderForOverload(*this, From))
5054    return ExprError();
5055
5056  QualType Ty = Context.getObjCIdType();
5057  ImplicitConversionSequence ICS =
5058    TryContextuallyConvertToObjCPointer(*this, From);
5059  if (!ICS.isBad())
5060    return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5061  return ExprError();
5062}
5063
5064/// Determine whether the provided type is an integral type, or an enumeration
5065/// type of a permitted flavor.
5066bool Sema::ICEConvertDiagnoser::match(QualType T) {
5067  return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5068                                 : T->isIntegralOrUnscopedEnumerationType();
5069}
5070
5071static ExprResult
5072diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5073                            Sema::ContextualImplicitConverter &Converter,
5074                            QualType T, UnresolvedSetImpl &ViableConversions) {
5075
5076  if (Converter.Suppress)
5077    return ExprError();
5078
5079  Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5080  for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5081    CXXConversionDecl *Conv =
5082        cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5083    QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5084    Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5085  }
5086  return SemaRef.Owned(From);
5087}
5088
5089static bool
5090diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5091                           Sema::ContextualImplicitConverter &Converter,
5092                           QualType T, bool HadMultipleCandidates,
5093                           UnresolvedSetImpl &ExplicitConversions) {
5094  if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5095    DeclAccessPair Found = ExplicitConversions[0];
5096    CXXConversionDecl *Conversion =
5097        cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5098
5099    // The user probably meant to invoke the given explicit
5100    // conversion; use it.
5101    QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5102    std::string TypeStr;
5103    ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5104
5105    Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5106        << FixItHint::CreateInsertion(From->getLocStart(),
5107                                      "static_cast<" + TypeStr + ">(")
5108        << FixItHint::CreateInsertion(
5109               SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5110    Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5111
5112    // If we aren't in a SFINAE context, build a call to the
5113    // explicit conversion function.
5114    if (SemaRef.isSFINAEContext())
5115      return true;
5116
5117    SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5118    ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5119                                                       HadMultipleCandidates);
5120    if (Result.isInvalid())
5121      return true;
5122    // Record usage of conversion in an implicit cast.
5123    From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5124                                    CK_UserDefinedConversion, Result.get(), 0,
5125                                    Result.get()->getValueKind());
5126  }
5127  return false;
5128}
5129
5130static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5131                             Sema::ContextualImplicitConverter &Converter,
5132                             QualType T, bool HadMultipleCandidates,
5133                             DeclAccessPair &Found) {
5134  CXXConversionDecl *Conversion =
5135      cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5136  SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5137
5138  QualType ToType = Conversion->getConversionType().getNonReferenceType();
5139  if (!Converter.SuppressConversion) {
5140    if (SemaRef.isSFINAEContext())
5141      return true;
5142
5143    Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5144        << From->getSourceRange();
5145  }
5146
5147  ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5148                                                     HadMultipleCandidates);
5149  if (Result.isInvalid())
5150    return true;
5151  // Record usage of conversion in an implicit cast.
5152  From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5153                                  CK_UserDefinedConversion, Result.get(), 0,
5154                                  Result.get()->getValueKind());
5155  return false;
5156}
5157
5158static ExprResult finishContextualImplicitConversion(
5159    Sema &SemaRef, SourceLocation Loc, Expr *From,
5160    Sema::ContextualImplicitConverter &Converter) {
5161  if (!Converter.match(From->getType()) && !Converter.Suppress)
5162    Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5163        << From->getSourceRange();
5164
5165  return SemaRef.DefaultLvalueConversion(From);
5166}
5167
5168static void
5169collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5170                                  UnresolvedSetImpl &ViableConversions,
5171                                  OverloadCandidateSet &CandidateSet) {
5172  for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5173    DeclAccessPair FoundDecl = ViableConversions[I];
5174    NamedDecl *D = FoundDecl.getDecl();
5175    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5176    if (isa<UsingShadowDecl>(D))
5177      D = cast<UsingShadowDecl>(D)->getTargetDecl();
5178
5179    CXXConversionDecl *Conv;
5180    FunctionTemplateDecl *ConvTemplate;
5181    if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5182      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5183    else
5184      Conv = cast<CXXConversionDecl>(D);
5185
5186    if (ConvTemplate)
5187      SemaRef.AddTemplateConversionCandidate(
5188          ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet);
5189    else
5190      SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5191                                     ToType, CandidateSet);
5192  }
5193}
5194
5195/// \brief Attempt to convert the given expression to a type which is accepted
5196/// by the given converter.
5197///
5198/// This routine will attempt to convert an expression of class type to a
5199/// type accepted by the specified converter. In C++11 and before, the class
5200/// must have a single non-explicit conversion function converting to a matching
5201/// type. In C++1y, there can be multiple such conversion functions, but only
5202/// one target type.
5203///
5204/// \param Loc The source location of the construct that requires the
5205/// conversion.
5206///
5207/// \param From The expression we're converting from.
5208///
5209/// \param Converter Used to control and diagnose the conversion process.
5210///
5211/// \returns The expression, converted to an integral or enumeration type if
5212/// successful.
5213ExprResult Sema::PerformContextualImplicitConversion(
5214    SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5215  // We can't perform any more checking for type-dependent expressions.
5216  if (From->isTypeDependent())
5217    return Owned(From);
5218
5219  // Process placeholders immediately.
5220  if (From->hasPlaceholderType()) {
5221    ExprResult result = CheckPlaceholderExpr(From);
5222    if (result.isInvalid())
5223      return result;
5224    From = result.take();
5225  }
5226
5227  // If the expression already has a matching type, we're golden.
5228  QualType T = From->getType();
5229  if (Converter.match(T))
5230    return DefaultLvalueConversion(From);
5231
5232  // FIXME: Check for missing '()' if T is a function type?
5233
5234  // We can only perform contextual implicit conversions on objects of class
5235  // type.
5236  const RecordType *RecordTy = T->getAs<RecordType>();
5237  if (!RecordTy || !getLangOpts().CPlusPlus) {
5238    if (!Converter.Suppress)
5239      Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5240    return Owned(From);
5241  }
5242
5243  // We must have a complete class type.
5244  struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5245    ContextualImplicitConverter &Converter;
5246    Expr *From;
5247
5248    TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5249        : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5250
5251    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5252      Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5253    }
5254  } IncompleteDiagnoser(Converter, From);
5255
5256  if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5257    return Owned(From);
5258
5259  // Look for a conversion to an integral or enumeration type.
5260  UnresolvedSet<4>
5261      ViableConversions; // These are *potentially* viable in C++1y.
5262  UnresolvedSet<4> ExplicitConversions;
5263  std::pair<CXXRecordDecl::conversion_iterator,
5264            CXXRecordDecl::conversion_iterator> Conversions =
5265      cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5266
5267  bool HadMultipleCandidates =
5268      (std::distance(Conversions.first, Conversions.second) > 1);
5269
5270  // To check that there is only one target type, in C++1y:
5271  QualType ToType;
5272  bool HasUniqueTargetType = true;
5273
5274  // Collect explicit or viable (potentially in C++1y) conversions.
5275  for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5276                                          E = Conversions.second;
5277       I != E; ++I) {
5278    NamedDecl *D = (*I)->getUnderlyingDecl();
5279    CXXConversionDecl *Conversion;
5280    FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5281    if (ConvTemplate) {
5282      if (getLangOpts().CPlusPlus1y)
5283        Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5284      else
5285        continue; // C++11 does not consider conversion operator templates(?).
5286    } else
5287      Conversion = cast<CXXConversionDecl>(D);
5288
5289    assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5290           "Conversion operator templates are considered potentially "
5291           "viable in C++1y");
5292
5293    QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5294    if (Converter.match(CurToType) || ConvTemplate) {
5295
5296      if (Conversion->isExplicit()) {
5297        // FIXME: For C++1y, do we need this restriction?
5298        // cf. diagnoseNoViableConversion()
5299        if (!ConvTemplate)
5300          ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5301      } else {
5302        if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5303          if (ToType.isNull())
5304            ToType = CurToType.getUnqualifiedType();
5305          else if (HasUniqueTargetType &&
5306                   (CurToType.getUnqualifiedType() != ToType))
5307            HasUniqueTargetType = false;
5308        }
5309        ViableConversions.addDecl(I.getDecl(), I.getAccess());
5310      }
5311    }
5312  }
5313
5314  if (getLangOpts().CPlusPlus1y) {
5315    // C++1y [conv]p6:
5316    // ... An expression e of class type E appearing in such a context
5317    // is said to be contextually implicitly converted to a specified
5318    // type T and is well-formed if and only if e can be implicitly
5319    // converted to a type T that is determined as follows: E is searched
5320    // for conversion functions whose return type is cv T or reference to
5321    // cv T such that T is allowed by the context. There shall be
5322    // exactly one such T.
5323
5324    // If no unique T is found:
5325    if (ToType.isNull()) {
5326      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5327                                     HadMultipleCandidates,
5328                                     ExplicitConversions))
5329        return ExprError();
5330      return finishContextualImplicitConversion(*this, Loc, From, Converter);
5331    }
5332
5333    // If more than one unique Ts are found:
5334    if (!HasUniqueTargetType)
5335      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5336                                         ViableConversions);
5337
5338    // If one unique T is found:
5339    // First, build a candidate set from the previously recorded
5340    // potentially viable conversions.
5341    OverloadCandidateSet CandidateSet(Loc);
5342    collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5343                                      CandidateSet);
5344
5345    // Then, perform overload resolution over the candidate set.
5346    OverloadCandidateSet::iterator Best;
5347    switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5348    case OR_Success: {
5349      // Apply this conversion.
5350      DeclAccessPair Found =
5351          DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5352      if (recordConversion(*this, Loc, From, Converter, T,
5353                           HadMultipleCandidates, Found))
5354        return ExprError();
5355      break;
5356    }
5357    case OR_Ambiguous:
5358      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5359                                         ViableConversions);
5360    case OR_No_Viable_Function:
5361      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5362                                     HadMultipleCandidates,
5363                                     ExplicitConversions))
5364        return ExprError();
5365    // fall through 'OR_Deleted' case.
5366    case OR_Deleted:
5367      // We'll complain below about a non-integral condition type.
5368      break;
5369    }
5370  } else {
5371    switch (ViableConversions.size()) {
5372    case 0: {
5373      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5374                                     HadMultipleCandidates,
5375                                     ExplicitConversions))
5376        return ExprError();
5377
5378      // We'll complain below about a non-integral condition type.
5379      break;
5380    }
5381    case 1: {
5382      // Apply this conversion.
5383      DeclAccessPair Found = ViableConversions[0];
5384      if (recordConversion(*this, Loc, From, Converter, T,
5385                           HadMultipleCandidates, Found))
5386        return ExprError();
5387      break;
5388    }
5389    default:
5390      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5391                                         ViableConversions);
5392    }
5393  }
5394
5395  return finishContextualImplicitConversion(*this, Loc, From, Converter);
5396}
5397
5398/// AddOverloadCandidate - Adds the given function to the set of
5399/// candidate functions, using the given function call arguments.  If
5400/// @p SuppressUserConversions, then don't allow user-defined
5401/// conversions via constructors or conversion operators.
5402///
5403/// \param PartialOverloading true if we are performing "partial" overloading
5404/// based on an incomplete set of function arguments. This feature is used by
5405/// code completion.
5406void
5407Sema::AddOverloadCandidate(FunctionDecl *Function,
5408                           DeclAccessPair FoundDecl,
5409                           ArrayRef<Expr *> Args,
5410                           OverloadCandidateSet& CandidateSet,
5411                           bool SuppressUserConversions,
5412                           bool PartialOverloading,
5413                           bool AllowExplicit) {
5414  const FunctionProtoType* Proto
5415    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5416  assert(Proto && "Functions without a prototype cannot be overloaded");
5417  assert(!Function->getDescribedFunctionTemplate() &&
5418         "Use AddTemplateOverloadCandidate for function templates");
5419
5420  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5421    if (!isa<CXXConstructorDecl>(Method)) {
5422      // If we get here, it's because we're calling a member function
5423      // that is named without a member access expression (e.g.,
5424      // "this->f") that was either written explicitly or created
5425      // implicitly. This can happen with a qualified call to a member
5426      // function, e.g., X::f(). We use an empty type for the implied
5427      // object argument (C++ [over.call.func]p3), and the acting context
5428      // is irrelevant.
5429      AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5430                         QualType(), Expr::Classification::makeSimpleLValue(),
5431                         Args, CandidateSet, SuppressUserConversions);
5432      return;
5433    }
5434    // We treat a constructor like a non-member function, since its object
5435    // argument doesn't participate in overload resolution.
5436  }
5437
5438  if (!CandidateSet.isNewCandidate(Function))
5439    return;
5440
5441  // Overload resolution is always an unevaluated context.
5442  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5443
5444  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5445    // C++ [class.copy]p3:
5446    //   A member function template is never instantiated to perform the copy
5447    //   of a class object to an object of its class type.
5448    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5449    if (Args.size() == 1 &&
5450        Constructor->isSpecializationCopyingObject() &&
5451        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5452         IsDerivedFrom(Args[0]->getType(), ClassType)))
5453      return;
5454  }
5455
5456  // Add this candidate
5457  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5458  Candidate.FoundDecl = FoundDecl;
5459  Candidate.Function = Function;
5460  Candidate.Viable = true;
5461  Candidate.IsSurrogate = false;
5462  Candidate.IgnoreObjectArgument = false;
5463  Candidate.ExplicitCallArguments = Args.size();
5464
5465  unsigned NumArgsInProto = Proto->getNumArgs();
5466
5467  // (C++ 13.3.2p2): A candidate function having fewer than m
5468  // parameters is viable only if it has an ellipsis in its parameter
5469  // list (8.3.5).
5470  if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5471      !Proto->isVariadic()) {
5472    Candidate.Viable = false;
5473    Candidate.FailureKind = ovl_fail_too_many_arguments;
5474    return;
5475  }
5476
5477  // (C++ 13.3.2p2): A candidate function having more than m parameters
5478  // is viable only if the (m+1)st parameter has a default argument
5479  // (8.3.6). For the purposes of overload resolution, the
5480  // parameter list is truncated on the right, so that there are
5481  // exactly m parameters.
5482  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5483  if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5484    // Not enough arguments.
5485    Candidate.Viable = false;
5486    Candidate.FailureKind = ovl_fail_too_few_arguments;
5487    return;
5488  }
5489
5490  // (CUDA B.1): Check for invalid calls between targets.
5491  if (getLangOpts().CUDA)
5492    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5493      if (CheckCUDATarget(Caller, Function)) {
5494        Candidate.Viable = false;
5495        Candidate.FailureKind = ovl_fail_bad_target;
5496        return;
5497      }
5498
5499  // Determine the implicit conversion sequences for each of the
5500  // arguments.
5501  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5502    if (ArgIdx < NumArgsInProto) {
5503      // (C++ 13.3.2p3): for F to be a viable function, there shall
5504      // exist for each argument an implicit conversion sequence
5505      // (13.3.3.1) that converts that argument to the corresponding
5506      // parameter of F.
5507      QualType ParamType = Proto->getArgType(ArgIdx);
5508      Candidate.Conversions[ArgIdx]
5509        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5510                                SuppressUserConversions,
5511                                /*InOverloadResolution=*/true,
5512                                /*AllowObjCWritebackConversion=*/
5513                                  getLangOpts().ObjCAutoRefCount,
5514                                AllowExplicit);
5515      if (Candidate.Conversions[ArgIdx].isBad()) {
5516        Candidate.Viable = false;
5517        Candidate.FailureKind = ovl_fail_bad_conversion;
5518        break;
5519      }
5520    } else {
5521      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5522      // argument for which there is no corresponding parameter is
5523      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5524      Candidate.Conversions[ArgIdx].setEllipsis();
5525    }
5526  }
5527}
5528
5529/// \brief Add all of the function declarations in the given function set to
5530/// the overload canddiate set.
5531void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5532                                 ArrayRef<Expr *> Args,
5533                                 OverloadCandidateSet& CandidateSet,
5534                                 bool SuppressUserConversions,
5535                               TemplateArgumentListInfo *ExplicitTemplateArgs) {
5536  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5537    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5538    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5539      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5540        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5541                           cast<CXXMethodDecl>(FD)->getParent(),
5542                           Args[0]->getType(), Args[0]->Classify(Context),
5543                           Args.slice(1), CandidateSet,
5544                           SuppressUserConversions);
5545      else
5546        AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5547                             SuppressUserConversions);
5548    } else {
5549      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5550      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5551          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5552        AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5553                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5554                                   ExplicitTemplateArgs,
5555                                   Args[0]->getType(),
5556                                   Args[0]->Classify(Context), Args.slice(1),
5557                                   CandidateSet, SuppressUserConversions);
5558      else
5559        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5560                                     ExplicitTemplateArgs, Args,
5561                                     CandidateSet, SuppressUserConversions);
5562    }
5563  }
5564}
5565
5566/// AddMethodCandidate - Adds a named decl (which is some kind of
5567/// method) as a method candidate to the given overload set.
5568void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5569                              QualType ObjectType,
5570                              Expr::Classification ObjectClassification,
5571                              ArrayRef<Expr *> Args,
5572                              OverloadCandidateSet& CandidateSet,
5573                              bool SuppressUserConversions) {
5574  NamedDecl *Decl = FoundDecl.getDecl();
5575  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5576
5577  if (isa<UsingShadowDecl>(Decl))
5578    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5579
5580  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5581    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5582           "Expected a member function template");
5583    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5584                               /*ExplicitArgs*/ 0,
5585                               ObjectType, ObjectClassification,
5586                               Args, CandidateSet,
5587                               SuppressUserConversions);
5588  } else {
5589    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5590                       ObjectType, ObjectClassification,
5591                       Args,
5592                       CandidateSet, SuppressUserConversions);
5593  }
5594}
5595
5596/// AddMethodCandidate - Adds the given C++ member function to the set
5597/// of candidate functions, using the given function call arguments
5598/// and the object argument (@c Object). For example, in a call
5599/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5600/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5601/// allow user-defined conversions via constructors or conversion
5602/// operators.
5603void
5604Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5605                         CXXRecordDecl *ActingContext, QualType ObjectType,
5606                         Expr::Classification ObjectClassification,
5607                         ArrayRef<Expr *> Args,
5608                         OverloadCandidateSet& CandidateSet,
5609                         bool SuppressUserConversions) {
5610  const FunctionProtoType* Proto
5611    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5612  assert(Proto && "Methods without a prototype cannot be overloaded");
5613  assert(!isa<CXXConstructorDecl>(Method) &&
5614         "Use AddOverloadCandidate for constructors");
5615
5616  if (!CandidateSet.isNewCandidate(Method))
5617    return;
5618
5619  // Overload resolution is always an unevaluated context.
5620  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5621
5622  // Add this candidate
5623  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5624  Candidate.FoundDecl = FoundDecl;
5625  Candidate.Function = Method;
5626  Candidate.IsSurrogate = false;
5627  Candidate.IgnoreObjectArgument = false;
5628  Candidate.ExplicitCallArguments = Args.size();
5629
5630  unsigned NumArgsInProto = Proto->getNumArgs();
5631
5632  // (C++ 13.3.2p2): A candidate function having fewer than m
5633  // parameters is viable only if it has an ellipsis in its parameter
5634  // list (8.3.5).
5635  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5636    Candidate.Viable = false;
5637    Candidate.FailureKind = ovl_fail_too_many_arguments;
5638    return;
5639  }
5640
5641  // (C++ 13.3.2p2): A candidate function having more than m parameters
5642  // is viable only if the (m+1)st parameter has a default argument
5643  // (8.3.6). For the purposes of overload resolution, the
5644  // parameter list is truncated on the right, so that there are
5645  // exactly m parameters.
5646  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5647  if (Args.size() < MinRequiredArgs) {
5648    // Not enough arguments.
5649    Candidate.Viable = false;
5650    Candidate.FailureKind = ovl_fail_too_few_arguments;
5651    return;
5652  }
5653
5654  Candidate.Viable = true;
5655
5656  if (Method->isStatic() || ObjectType.isNull())
5657    // The implicit object argument is ignored.
5658    Candidate.IgnoreObjectArgument = true;
5659  else {
5660    // Determine the implicit conversion sequence for the object
5661    // parameter.
5662    Candidate.Conversions[0]
5663      = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5664                                        Method, ActingContext);
5665    if (Candidate.Conversions[0].isBad()) {
5666      Candidate.Viable = false;
5667      Candidate.FailureKind = ovl_fail_bad_conversion;
5668      return;
5669    }
5670  }
5671
5672  // Determine the implicit conversion sequences for each of the
5673  // arguments.
5674  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5675    if (ArgIdx < NumArgsInProto) {
5676      // (C++ 13.3.2p3): for F to be a viable function, there shall
5677      // exist for each argument an implicit conversion sequence
5678      // (13.3.3.1) that converts that argument to the corresponding
5679      // parameter of F.
5680      QualType ParamType = Proto->getArgType(ArgIdx);
5681      Candidate.Conversions[ArgIdx + 1]
5682        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5683                                SuppressUserConversions,
5684                                /*InOverloadResolution=*/true,
5685                                /*AllowObjCWritebackConversion=*/
5686                                  getLangOpts().ObjCAutoRefCount);
5687      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5688        Candidate.Viable = false;
5689        Candidate.FailureKind = ovl_fail_bad_conversion;
5690        break;
5691      }
5692    } else {
5693      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5694      // argument for which there is no corresponding parameter is
5695      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5696      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5697    }
5698  }
5699}
5700
5701/// \brief Add a C++ member function template as a candidate to the candidate
5702/// set, using template argument deduction to produce an appropriate member
5703/// function template specialization.
5704void
5705Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5706                                 DeclAccessPair FoundDecl,
5707                                 CXXRecordDecl *ActingContext,
5708                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5709                                 QualType ObjectType,
5710                                 Expr::Classification ObjectClassification,
5711                                 ArrayRef<Expr *> Args,
5712                                 OverloadCandidateSet& CandidateSet,
5713                                 bool SuppressUserConversions) {
5714  if (!CandidateSet.isNewCandidate(MethodTmpl))
5715    return;
5716
5717  // C++ [over.match.funcs]p7:
5718  //   In each case where a candidate is a function template, candidate
5719  //   function template specializations are generated using template argument
5720  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5721  //   candidate functions in the usual way.113) A given name can refer to one
5722  //   or more function templates and also to a set of overloaded non-template
5723  //   functions. In such a case, the candidate functions generated from each
5724  //   function template are combined with the set of non-template candidate
5725  //   functions.
5726  TemplateDeductionInfo Info(CandidateSet.getLocation());
5727  FunctionDecl *Specialization = 0;
5728  if (TemplateDeductionResult Result
5729      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5730                                Specialization, Info)) {
5731    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5732    Candidate.FoundDecl = FoundDecl;
5733    Candidate.Function = MethodTmpl->getTemplatedDecl();
5734    Candidate.Viable = false;
5735    Candidate.FailureKind = ovl_fail_bad_deduction;
5736    Candidate.IsSurrogate = false;
5737    Candidate.IgnoreObjectArgument = false;
5738    Candidate.ExplicitCallArguments = Args.size();
5739    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5740                                                          Info);
5741    return;
5742  }
5743
5744  // Add the function template specialization produced by template argument
5745  // deduction as a candidate.
5746  assert(Specialization && "Missing member function template specialization?");
5747  assert(isa<CXXMethodDecl>(Specialization) &&
5748         "Specialization is not a member function?");
5749  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5750                     ActingContext, ObjectType, ObjectClassification, Args,
5751                     CandidateSet, SuppressUserConversions);
5752}
5753
5754/// \brief Add a C++ function template specialization as a candidate
5755/// in the candidate set, using template argument deduction to produce
5756/// an appropriate function template specialization.
5757void
5758Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5759                                   DeclAccessPair FoundDecl,
5760                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5761                                   ArrayRef<Expr *> Args,
5762                                   OverloadCandidateSet& CandidateSet,
5763                                   bool SuppressUserConversions) {
5764  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5765    return;
5766
5767  // C++ [over.match.funcs]p7:
5768  //   In each case where a candidate is a function template, candidate
5769  //   function template specializations are generated using template argument
5770  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5771  //   candidate functions in the usual way.113) A given name can refer to one
5772  //   or more function templates and also to a set of overloaded non-template
5773  //   functions. In such a case, the candidate functions generated from each
5774  //   function template are combined with the set of non-template candidate
5775  //   functions.
5776  TemplateDeductionInfo Info(CandidateSet.getLocation());
5777  FunctionDecl *Specialization = 0;
5778  if (TemplateDeductionResult Result
5779        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5780                                  Specialization, Info)) {
5781    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5782    Candidate.FoundDecl = FoundDecl;
5783    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5784    Candidate.Viable = false;
5785    Candidate.FailureKind = ovl_fail_bad_deduction;
5786    Candidate.IsSurrogate = false;
5787    Candidate.IgnoreObjectArgument = false;
5788    Candidate.ExplicitCallArguments = Args.size();
5789    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5790                                                          Info);
5791    return;
5792  }
5793
5794  // Add the function template specialization produced by template argument
5795  // deduction as a candidate.
5796  assert(Specialization && "Missing function template specialization?");
5797  AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5798                       SuppressUserConversions);
5799}
5800
5801/// AddConversionCandidate - Add a C++ conversion function as a
5802/// candidate in the candidate set (C++ [over.match.conv],
5803/// C++ [over.match.copy]). From is the expression we're converting from,
5804/// and ToType is the type that we're eventually trying to convert to
5805/// (which may or may not be the same type as the type that the
5806/// conversion function produces).
5807void
5808Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5809                             DeclAccessPair FoundDecl,
5810                             CXXRecordDecl *ActingContext,
5811                             Expr *From, QualType ToType,
5812                             OverloadCandidateSet& CandidateSet) {
5813  assert(!Conversion->getDescribedFunctionTemplate() &&
5814         "Conversion function templates use AddTemplateConversionCandidate");
5815  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5816  if (!CandidateSet.isNewCandidate(Conversion))
5817    return;
5818
5819  // If the conversion function has an undeduced return type, trigger its
5820  // deduction now.
5821  if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5822    if (DeduceReturnType(Conversion, From->getExprLoc()))
5823      return;
5824    ConvType = Conversion->getConversionType().getNonReferenceType();
5825  }
5826
5827  // Overload resolution is always an unevaluated context.
5828  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5829
5830  // Add this candidate
5831  OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5832  Candidate.FoundDecl = FoundDecl;
5833  Candidate.Function = Conversion;
5834  Candidate.IsSurrogate = false;
5835  Candidate.IgnoreObjectArgument = false;
5836  Candidate.FinalConversion.setAsIdentityConversion();
5837  Candidate.FinalConversion.setFromType(ConvType);
5838  Candidate.FinalConversion.setAllToTypes(ToType);
5839  Candidate.Viable = true;
5840  Candidate.ExplicitCallArguments = 1;
5841
5842  // C++ [over.match.funcs]p4:
5843  //   For conversion functions, the function is considered to be a member of
5844  //   the class of the implicit implied object argument for the purpose of
5845  //   defining the type of the implicit object parameter.
5846  //
5847  // Determine the implicit conversion sequence for the implicit
5848  // object parameter.
5849  QualType ImplicitParamType = From->getType();
5850  if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5851    ImplicitParamType = FromPtrType->getPointeeType();
5852  CXXRecordDecl *ConversionContext
5853    = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5854
5855  Candidate.Conversions[0]
5856    = TryObjectArgumentInitialization(*this, From->getType(),
5857                                      From->Classify(Context),
5858                                      Conversion, ConversionContext);
5859
5860  if (Candidate.Conversions[0].isBad()) {
5861    Candidate.Viable = false;
5862    Candidate.FailureKind = ovl_fail_bad_conversion;
5863    return;
5864  }
5865
5866  // We won't go through a user-define type conversion function to convert a
5867  // derived to base as such conversions are given Conversion Rank. They only
5868  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5869  QualType FromCanon
5870    = Context.getCanonicalType(From->getType().getUnqualifiedType());
5871  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5872  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5873    Candidate.Viable = false;
5874    Candidate.FailureKind = ovl_fail_trivial_conversion;
5875    return;
5876  }
5877
5878  // To determine what the conversion from the result of calling the
5879  // conversion function to the type we're eventually trying to
5880  // convert to (ToType), we need to synthesize a call to the
5881  // conversion function and attempt copy initialization from it. This
5882  // makes sure that we get the right semantics with respect to
5883  // lvalues/rvalues and the type. Fortunately, we can allocate this
5884  // call on the stack and we don't need its arguments to be
5885  // well-formed.
5886  DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5887                            VK_LValue, From->getLocStart());
5888  ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5889                                Context.getPointerType(Conversion->getType()),
5890                                CK_FunctionToPointerDecay,
5891                                &ConversionRef, VK_RValue);
5892
5893  QualType ConversionType = Conversion->getConversionType();
5894  if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5895    Candidate.Viable = false;
5896    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5897    return;
5898  }
5899
5900  ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5901
5902  // Note that it is safe to allocate CallExpr on the stack here because
5903  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5904  // allocator).
5905  QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5906  CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
5907                From->getLocStart());
5908  ImplicitConversionSequence ICS =
5909    TryCopyInitialization(*this, &Call, ToType,
5910                          /*SuppressUserConversions=*/true,
5911                          /*InOverloadResolution=*/false,
5912                          /*AllowObjCWritebackConversion=*/false);
5913
5914  switch (ICS.getKind()) {
5915  case ImplicitConversionSequence::StandardConversion:
5916    Candidate.FinalConversion = ICS.Standard;
5917
5918    // C++ [over.ics.user]p3:
5919    //   If the user-defined conversion is specified by a specialization of a
5920    //   conversion function template, the second standard conversion sequence
5921    //   shall have exact match rank.
5922    if (Conversion->getPrimaryTemplate() &&
5923        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5924      Candidate.Viable = false;
5925      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5926    }
5927
5928    // C++0x [dcl.init.ref]p5:
5929    //    In the second case, if the reference is an rvalue reference and
5930    //    the second standard conversion sequence of the user-defined
5931    //    conversion sequence includes an lvalue-to-rvalue conversion, the
5932    //    program is ill-formed.
5933    if (ToType->isRValueReferenceType() &&
5934        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5935      Candidate.Viable = false;
5936      Candidate.FailureKind = ovl_fail_bad_final_conversion;
5937    }
5938    break;
5939
5940  case ImplicitConversionSequence::BadConversion:
5941    Candidate.Viable = false;
5942    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5943    break;
5944
5945  default:
5946    llvm_unreachable(
5947           "Can only end up with a standard conversion sequence or failure");
5948  }
5949}
5950
5951/// \brief Adds a conversion function template specialization
5952/// candidate to the overload set, using template argument deduction
5953/// to deduce the template arguments of the conversion function
5954/// template from the type that we are converting to (C++
5955/// [temp.deduct.conv]).
5956void
5957Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
5958                                     DeclAccessPair FoundDecl,
5959                                     CXXRecordDecl *ActingDC,
5960                                     Expr *From, QualType ToType,
5961                                     OverloadCandidateSet &CandidateSet) {
5962  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5963         "Only conversion function templates permitted here");
5964
5965  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5966    return;
5967
5968  TemplateDeductionInfo Info(CandidateSet.getLocation());
5969  CXXConversionDecl *Specialization = 0;
5970  if (TemplateDeductionResult Result
5971        = DeduceTemplateArguments(FunctionTemplate, ToType,
5972                                  Specialization, Info)) {
5973    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5974    Candidate.FoundDecl = FoundDecl;
5975    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5976    Candidate.Viable = false;
5977    Candidate.FailureKind = ovl_fail_bad_deduction;
5978    Candidate.IsSurrogate = false;
5979    Candidate.IgnoreObjectArgument = false;
5980    Candidate.ExplicitCallArguments = 1;
5981    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5982                                                          Info);
5983    return;
5984  }
5985
5986  // Add the conversion function template specialization produced by
5987  // template argument deduction as a candidate.
5988  assert(Specialization && "Missing function template specialization?");
5989  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
5990                         CandidateSet);
5991}
5992
5993/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5994/// converts the given @c Object to a function pointer via the
5995/// conversion function @c Conversion, and then attempts to call it
5996/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5997/// the type of function that we'll eventually be calling.
5998void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
5999                                 DeclAccessPair FoundDecl,
6000                                 CXXRecordDecl *ActingContext,
6001                                 const FunctionProtoType *Proto,
6002                                 Expr *Object,
6003                                 ArrayRef<Expr *> Args,
6004                                 OverloadCandidateSet& CandidateSet) {
6005  if (!CandidateSet.isNewCandidate(Conversion))
6006    return;
6007
6008  // Overload resolution is always an unevaluated context.
6009  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6010
6011  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6012  Candidate.FoundDecl = FoundDecl;
6013  Candidate.Function = 0;
6014  Candidate.Surrogate = Conversion;
6015  Candidate.Viable = true;
6016  Candidate.IsSurrogate = true;
6017  Candidate.IgnoreObjectArgument = false;
6018  Candidate.ExplicitCallArguments = Args.size();
6019
6020  // Determine the implicit conversion sequence for the implicit
6021  // object parameter.
6022  ImplicitConversionSequence ObjectInit
6023    = TryObjectArgumentInitialization(*this, Object->getType(),
6024                                      Object->Classify(Context),
6025                                      Conversion, ActingContext);
6026  if (ObjectInit.isBad()) {
6027    Candidate.Viable = false;
6028    Candidate.FailureKind = ovl_fail_bad_conversion;
6029    Candidate.Conversions[0] = ObjectInit;
6030    return;
6031  }
6032
6033  // The first conversion is actually a user-defined conversion whose
6034  // first conversion is ObjectInit's standard conversion (which is
6035  // effectively a reference binding). Record it as such.
6036  Candidate.Conversions[0].setUserDefined();
6037  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6038  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6039  Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6040  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6041  Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6042  Candidate.Conversions[0].UserDefined.After
6043    = Candidate.Conversions[0].UserDefined.Before;
6044  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6045
6046  // Find the
6047  unsigned NumArgsInProto = Proto->getNumArgs();
6048
6049  // (C++ 13.3.2p2): A candidate function having fewer than m
6050  // parameters is viable only if it has an ellipsis in its parameter
6051  // list (8.3.5).
6052  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
6053    Candidate.Viable = false;
6054    Candidate.FailureKind = ovl_fail_too_many_arguments;
6055    return;
6056  }
6057
6058  // Function types don't have any default arguments, so just check if
6059  // we have enough arguments.
6060  if (Args.size() < NumArgsInProto) {
6061    // Not enough arguments.
6062    Candidate.Viable = false;
6063    Candidate.FailureKind = ovl_fail_too_few_arguments;
6064    return;
6065  }
6066
6067  // Determine the implicit conversion sequences for each of the
6068  // arguments.
6069  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6070    if (ArgIdx < NumArgsInProto) {
6071      // (C++ 13.3.2p3): for F to be a viable function, there shall
6072      // exist for each argument an implicit conversion sequence
6073      // (13.3.3.1) that converts that argument to the corresponding
6074      // parameter of F.
6075      QualType ParamType = Proto->getArgType(ArgIdx);
6076      Candidate.Conversions[ArgIdx + 1]
6077        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6078                                /*SuppressUserConversions=*/false,
6079                                /*InOverloadResolution=*/false,
6080                                /*AllowObjCWritebackConversion=*/
6081                                  getLangOpts().ObjCAutoRefCount);
6082      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6083        Candidate.Viable = false;
6084        Candidate.FailureKind = ovl_fail_bad_conversion;
6085        break;
6086      }
6087    } else {
6088      // (C++ 13.3.2p2): For the purposes of overload resolution, any
6089      // argument for which there is no corresponding parameter is
6090      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6091      Candidate.Conversions[ArgIdx + 1].setEllipsis();
6092    }
6093  }
6094}
6095
6096/// \brief Add overload candidates for overloaded operators that are
6097/// member functions.
6098///
6099/// Add the overloaded operator candidates that are member functions
6100/// for the operator Op that was used in an operator expression such
6101/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6102/// CandidateSet will store the added overload candidates. (C++
6103/// [over.match.oper]).
6104void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6105                                       SourceLocation OpLoc,
6106                                       ArrayRef<Expr *> Args,
6107                                       OverloadCandidateSet& CandidateSet,
6108                                       SourceRange OpRange) {
6109  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6110
6111  // C++ [over.match.oper]p3:
6112  //   For a unary operator @ with an operand of a type whose
6113  //   cv-unqualified version is T1, and for a binary operator @ with
6114  //   a left operand of a type whose cv-unqualified version is T1 and
6115  //   a right operand of a type whose cv-unqualified version is T2,
6116  //   three sets of candidate functions, designated member
6117  //   candidates, non-member candidates and built-in candidates, are
6118  //   constructed as follows:
6119  QualType T1 = Args[0]->getType();
6120
6121  //     -- If T1 is a complete class type or a class currently being
6122  //        defined, the set of member candidates is the result of the
6123  //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6124  //        the set of member candidates is empty.
6125  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6126    // Complete the type if it can be completed.
6127    RequireCompleteType(OpLoc, T1, 0);
6128    // If the type is neither complete nor being defined, bail out now.
6129    if (!T1Rec->getDecl()->getDefinition())
6130      return;
6131
6132    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6133    LookupQualifiedName(Operators, T1Rec->getDecl());
6134    Operators.suppressDiagnostics();
6135
6136    for (LookupResult::iterator Oper = Operators.begin(),
6137                             OperEnd = Operators.end();
6138         Oper != OperEnd;
6139         ++Oper)
6140      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6141                         Args[0]->Classify(Context),
6142                         Args.slice(1),
6143                         CandidateSet,
6144                         /* SuppressUserConversions = */ false);
6145  }
6146}
6147
6148/// AddBuiltinCandidate - Add a candidate for a built-in
6149/// operator. ResultTy and ParamTys are the result and parameter types
6150/// of the built-in candidate, respectively. Args and NumArgs are the
6151/// arguments being passed to the candidate. IsAssignmentOperator
6152/// should be true when this built-in candidate is an assignment
6153/// operator. NumContextualBoolArguments is the number of arguments
6154/// (at the beginning of the argument list) that will be contextually
6155/// converted to bool.
6156void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6157                               ArrayRef<Expr *> Args,
6158                               OverloadCandidateSet& CandidateSet,
6159                               bool IsAssignmentOperator,
6160                               unsigned NumContextualBoolArguments) {
6161  // Overload resolution is always an unevaluated context.
6162  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6163
6164  // Add this candidate
6165  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6166  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
6167  Candidate.Function = 0;
6168  Candidate.IsSurrogate = false;
6169  Candidate.IgnoreObjectArgument = false;
6170  Candidate.BuiltinTypes.ResultTy = ResultTy;
6171  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6172    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6173
6174  // Determine the implicit conversion sequences for each of the
6175  // arguments.
6176  Candidate.Viable = true;
6177  Candidate.ExplicitCallArguments = Args.size();
6178  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6179    // C++ [over.match.oper]p4:
6180    //   For the built-in assignment operators, conversions of the
6181    //   left operand are restricted as follows:
6182    //     -- no temporaries are introduced to hold the left operand, and
6183    //     -- no user-defined conversions are applied to the left
6184    //        operand to achieve a type match with the left-most
6185    //        parameter of a built-in candidate.
6186    //
6187    // We block these conversions by turning off user-defined
6188    // conversions, since that is the only way that initialization of
6189    // a reference to a non-class type can occur from something that
6190    // is not of the same type.
6191    if (ArgIdx < NumContextualBoolArguments) {
6192      assert(ParamTys[ArgIdx] == Context.BoolTy &&
6193             "Contextual conversion to bool requires bool type");
6194      Candidate.Conversions[ArgIdx]
6195        = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6196    } else {
6197      Candidate.Conversions[ArgIdx]
6198        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6199                                ArgIdx == 0 && IsAssignmentOperator,
6200                                /*InOverloadResolution=*/false,
6201                                /*AllowObjCWritebackConversion=*/
6202                                  getLangOpts().ObjCAutoRefCount);
6203    }
6204    if (Candidate.Conversions[ArgIdx].isBad()) {
6205      Candidate.Viable = false;
6206      Candidate.FailureKind = ovl_fail_bad_conversion;
6207      break;
6208    }
6209  }
6210}
6211
6212namespace {
6213
6214/// BuiltinCandidateTypeSet - A set of types that will be used for the
6215/// candidate operator functions for built-in operators (C++
6216/// [over.built]). The types are separated into pointer types and
6217/// enumeration types.
6218class BuiltinCandidateTypeSet  {
6219  /// TypeSet - A set of types.
6220  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6221
6222  /// PointerTypes - The set of pointer types that will be used in the
6223  /// built-in candidates.
6224  TypeSet PointerTypes;
6225
6226  /// MemberPointerTypes - The set of member pointer types that will be
6227  /// used in the built-in candidates.
6228  TypeSet MemberPointerTypes;
6229
6230  /// EnumerationTypes - The set of enumeration types that will be
6231  /// used in the built-in candidates.
6232  TypeSet EnumerationTypes;
6233
6234  /// \brief The set of vector types that will be used in the built-in
6235  /// candidates.
6236  TypeSet VectorTypes;
6237
6238  /// \brief A flag indicating non-record types are viable candidates
6239  bool HasNonRecordTypes;
6240
6241  /// \brief A flag indicating whether either arithmetic or enumeration types
6242  /// were present in the candidate set.
6243  bool HasArithmeticOrEnumeralTypes;
6244
6245  /// \brief A flag indicating whether the nullptr type was present in the
6246  /// candidate set.
6247  bool HasNullPtrType;
6248
6249  /// Sema - The semantic analysis instance where we are building the
6250  /// candidate type set.
6251  Sema &SemaRef;
6252
6253  /// Context - The AST context in which we will build the type sets.
6254  ASTContext &Context;
6255
6256  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6257                                               const Qualifiers &VisibleQuals);
6258  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6259
6260public:
6261  /// iterator - Iterates through the types that are part of the set.
6262  typedef TypeSet::iterator iterator;
6263
6264  BuiltinCandidateTypeSet(Sema &SemaRef)
6265    : HasNonRecordTypes(false),
6266      HasArithmeticOrEnumeralTypes(false),
6267      HasNullPtrType(false),
6268      SemaRef(SemaRef),
6269      Context(SemaRef.Context) { }
6270
6271  void AddTypesConvertedFrom(QualType Ty,
6272                             SourceLocation Loc,
6273                             bool AllowUserConversions,
6274                             bool AllowExplicitConversions,
6275                             const Qualifiers &VisibleTypeConversionsQuals);
6276
6277  /// pointer_begin - First pointer type found;
6278  iterator pointer_begin() { return PointerTypes.begin(); }
6279
6280  /// pointer_end - Past the last pointer type found;
6281  iterator pointer_end() { return PointerTypes.end(); }
6282
6283  /// member_pointer_begin - First member pointer type found;
6284  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6285
6286  /// member_pointer_end - Past the last member pointer type found;
6287  iterator member_pointer_end() { return MemberPointerTypes.end(); }
6288
6289  /// enumeration_begin - First enumeration type found;
6290  iterator enumeration_begin() { return EnumerationTypes.begin(); }
6291
6292  /// enumeration_end - Past the last enumeration type found;
6293  iterator enumeration_end() { return EnumerationTypes.end(); }
6294
6295  iterator vector_begin() { return VectorTypes.begin(); }
6296  iterator vector_end() { return VectorTypes.end(); }
6297
6298  bool hasNonRecordTypes() { return HasNonRecordTypes; }
6299  bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6300  bool hasNullPtrType() const { return HasNullPtrType; }
6301};
6302
6303} // end anonymous namespace
6304
6305/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6306/// the set of pointer types along with any more-qualified variants of
6307/// that type. For example, if @p Ty is "int const *", this routine
6308/// will add "int const *", "int const volatile *", "int const
6309/// restrict *", and "int const volatile restrict *" to the set of
6310/// pointer types. Returns true if the add of @p Ty itself succeeded,
6311/// false otherwise.
6312///
6313/// FIXME: what to do about extended qualifiers?
6314bool
6315BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6316                                             const Qualifiers &VisibleQuals) {
6317
6318  // Insert this type.
6319  if (!PointerTypes.insert(Ty))
6320    return false;
6321
6322  QualType PointeeTy;
6323  const PointerType *PointerTy = Ty->getAs<PointerType>();
6324  bool buildObjCPtr = false;
6325  if (!PointerTy) {
6326    const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6327    PointeeTy = PTy->getPointeeType();
6328    buildObjCPtr = true;
6329  } else {
6330    PointeeTy = PointerTy->getPointeeType();
6331  }
6332
6333  // Don't add qualified variants of arrays. For one, they're not allowed
6334  // (the qualifier would sink to the element type), and for another, the
6335  // only overload situation where it matters is subscript or pointer +- int,
6336  // and those shouldn't have qualifier variants anyway.
6337  if (PointeeTy->isArrayType())
6338    return true;
6339
6340  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6341  bool hasVolatile = VisibleQuals.hasVolatile();
6342  bool hasRestrict = VisibleQuals.hasRestrict();
6343
6344  // Iterate through all strict supersets of BaseCVR.
6345  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6346    if ((CVR | BaseCVR) != CVR) continue;
6347    // Skip over volatile if no volatile found anywhere in the types.
6348    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6349
6350    // Skip over restrict if no restrict found anywhere in the types, or if
6351    // the type cannot be restrict-qualified.
6352    if ((CVR & Qualifiers::Restrict) &&
6353        (!hasRestrict ||
6354         (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6355      continue;
6356
6357    // Build qualified pointee type.
6358    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6359
6360    // Build qualified pointer type.
6361    QualType QPointerTy;
6362    if (!buildObjCPtr)
6363      QPointerTy = Context.getPointerType(QPointeeTy);
6364    else
6365      QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6366
6367    // Insert qualified pointer type.
6368    PointerTypes.insert(QPointerTy);
6369  }
6370
6371  return true;
6372}
6373
6374/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6375/// to the set of pointer types along with any more-qualified variants of
6376/// that type. For example, if @p Ty is "int const *", this routine
6377/// will add "int const *", "int const volatile *", "int const
6378/// restrict *", and "int const volatile restrict *" to the set of
6379/// pointer types. Returns true if the add of @p Ty itself succeeded,
6380/// false otherwise.
6381///
6382/// FIXME: what to do about extended qualifiers?
6383bool
6384BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6385    QualType Ty) {
6386  // Insert this type.
6387  if (!MemberPointerTypes.insert(Ty))
6388    return false;
6389
6390  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6391  assert(PointerTy && "type was not a member pointer type!");
6392
6393  QualType PointeeTy = PointerTy->getPointeeType();
6394  // Don't add qualified variants of arrays. For one, they're not allowed
6395  // (the qualifier would sink to the element type), and for another, the
6396  // only overload situation where it matters is subscript or pointer +- int,
6397  // and those shouldn't have qualifier variants anyway.
6398  if (PointeeTy->isArrayType())
6399    return true;
6400  const Type *ClassTy = PointerTy->getClass();
6401
6402  // Iterate through all strict supersets of the pointee type's CVR
6403  // qualifiers.
6404  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6405  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6406    if ((CVR | BaseCVR) != CVR) continue;
6407
6408    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6409    MemberPointerTypes.insert(
6410      Context.getMemberPointerType(QPointeeTy, ClassTy));
6411  }
6412
6413  return true;
6414}
6415
6416/// AddTypesConvertedFrom - Add each of the types to which the type @p
6417/// Ty can be implicit converted to the given set of @p Types. We're
6418/// primarily interested in pointer types and enumeration types. We also
6419/// take member pointer types, for the conditional operator.
6420/// AllowUserConversions is true if we should look at the conversion
6421/// functions of a class type, and AllowExplicitConversions if we
6422/// should also include the explicit conversion functions of a class
6423/// type.
6424void
6425BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6426                                               SourceLocation Loc,
6427                                               bool AllowUserConversions,
6428                                               bool AllowExplicitConversions,
6429                                               const Qualifiers &VisibleQuals) {
6430  // Only deal with canonical types.
6431  Ty = Context.getCanonicalType(Ty);
6432
6433  // Look through reference types; they aren't part of the type of an
6434  // expression for the purposes of conversions.
6435  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6436    Ty = RefTy->getPointeeType();
6437
6438  // If we're dealing with an array type, decay to the pointer.
6439  if (Ty->isArrayType())
6440    Ty = SemaRef.Context.getArrayDecayedType(Ty);
6441
6442  // Otherwise, we don't care about qualifiers on the type.
6443  Ty = Ty.getLocalUnqualifiedType();
6444
6445  // Flag if we ever add a non-record type.
6446  const RecordType *TyRec = Ty->getAs<RecordType>();
6447  HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6448
6449  // Flag if we encounter an arithmetic type.
6450  HasArithmeticOrEnumeralTypes =
6451    HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6452
6453  if (Ty->isObjCIdType() || Ty->isObjCClassType())
6454    PointerTypes.insert(Ty);
6455  else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6456    // Insert our type, and its more-qualified variants, into the set
6457    // of types.
6458    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6459      return;
6460  } else if (Ty->isMemberPointerType()) {
6461    // Member pointers are far easier, since the pointee can't be converted.
6462    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6463      return;
6464  } else if (Ty->isEnumeralType()) {
6465    HasArithmeticOrEnumeralTypes = true;
6466    EnumerationTypes.insert(Ty);
6467  } else if (Ty->isVectorType()) {
6468    // We treat vector types as arithmetic types in many contexts as an
6469    // extension.
6470    HasArithmeticOrEnumeralTypes = true;
6471    VectorTypes.insert(Ty);
6472  } else if (Ty->isNullPtrType()) {
6473    HasNullPtrType = true;
6474  } else if (AllowUserConversions && TyRec) {
6475    // No conversion functions in incomplete types.
6476    if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6477      return;
6478
6479    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6480    std::pair<CXXRecordDecl::conversion_iterator,
6481              CXXRecordDecl::conversion_iterator>
6482      Conversions = ClassDecl->getVisibleConversionFunctions();
6483    for (CXXRecordDecl::conversion_iterator
6484           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6485      NamedDecl *D = I.getDecl();
6486      if (isa<UsingShadowDecl>(D))
6487        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6488
6489      // Skip conversion function templates; they don't tell us anything
6490      // about which builtin types we can convert to.
6491      if (isa<FunctionTemplateDecl>(D))
6492        continue;
6493
6494      CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6495      if (AllowExplicitConversions || !Conv->isExplicit()) {
6496        AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6497                              VisibleQuals);
6498      }
6499    }
6500  }
6501}
6502
6503/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6504/// the volatile- and non-volatile-qualified assignment operators for the
6505/// given type to the candidate set.
6506static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6507                                                   QualType T,
6508                                                   ArrayRef<Expr *> Args,
6509                                    OverloadCandidateSet &CandidateSet) {
6510  QualType ParamTypes[2];
6511
6512  // T& operator=(T&, T)
6513  ParamTypes[0] = S.Context.getLValueReferenceType(T);
6514  ParamTypes[1] = T;
6515  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6516                        /*IsAssignmentOperator=*/true);
6517
6518  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6519    // volatile T& operator=(volatile T&, T)
6520    ParamTypes[0]
6521      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6522    ParamTypes[1] = T;
6523    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6524                          /*IsAssignmentOperator=*/true);
6525  }
6526}
6527
6528/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6529/// if any, found in visible type conversion functions found in ArgExpr's type.
6530static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6531    Qualifiers VRQuals;
6532    const RecordType *TyRec;
6533    if (const MemberPointerType *RHSMPType =
6534        ArgExpr->getType()->getAs<MemberPointerType>())
6535      TyRec = RHSMPType->getClass()->getAs<RecordType>();
6536    else
6537      TyRec = ArgExpr->getType()->getAs<RecordType>();
6538    if (!TyRec) {
6539      // Just to be safe, assume the worst case.
6540      VRQuals.addVolatile();
6541      VRQuals.addRestrict();
6542      return VRQuals;
6543    }
6544
6545    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6546    if (!ClassDecl->hasDefinition())
6547      return VRQuals;
6548
6549    std::pair<CXXRecordDecl::conversion_iterator,
6550              CXXRecordDecl::conversion_iterator>
6551      Conversions = ClassDecl->getVisibleConversionFunctions();
6552
6553    for (CXXRecordDecl::conversion_iterator
6554           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6555      NamedDecl *D = I.getDecl();
6556      if (isa<UsingShadowDecl>(D))
6557        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6558      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6559        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6560        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6561          CanTy = ResTypeRef->getPointeeType();
6562        // Need to go down the pointer/mempointer chain and add qualifiers
6563        // as see them.
6564        bool done = false;
6565        while (!done) {
6566          if (CanTy.isRestrictQualified())
6567            VRQuals.addRestrict();
6568          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6569            CanTy = ResTypePtr->getPointeeType();
6570          else if (const MemberPointerType *ResTypeMPtr =
6571                CanTy->getAs<MemberPointerType>())
6572            CanTy = ResTypeMPtr->getPointeeType();
6573          else
6574            done = true;
6575          if (CanTy.isVolatileQualified())
6576            VRQuals.addVolatile();
6577          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6578            return VRQuals;
6579        }
6580      }
6581    }
6582    return VRQuals;
6583}
6584
6585namespace {
6586
6587/// \brief Helper class to manage the addition of builtin operator overload
6588/// candidates. It provides shared state and utility methods used throughout
6589/// the process, as well as a helper method to add each group of builtin
6590/// operator overloads from the standard to a candidate set.
6591class BuiltinOperatorOverloadBuilder {
6592  // Common instance state available to all overload candidate addition methods.
6593  Sema &S;
6594  ArrayRef<Expr *> Args;
6595  Qualifiers VisibleTypeConversionsQuals;
6596  bool HasArithmeticOrEnumeralCandidateType;
6597  SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6598  OverloadCandidateSet &CandidateSet;
6599
6600  // Define some constants used to index and iterate over the arithemetic types
6601  // provided via the getArithmeticType() method below.
6602  // The "promoted arithmetic types" are the arithmetic
6603  // types are that preserved by promotion (C++ [over.built]p2).
6604  static const unsigned FirstIntegralType = 3;
6605  static const unsigned LastIntegralType = 20;
6606  static const unsigned FirstPromotedIntegralType = 3,
6607                        LastPromotedIntegralType = 11;
6608  static const unsigned FirstPromotedArithmeticType = 0,
6609                        LastPromotedArithmeticType = 11;
6610  static const unsigned NumArithmeticTypes = 20;
6611
6612  /// \brief Get the canonical type for a given arithmetic type index.
6613  CanQualType getArithmeticType(unsigned index) {
6614    assert(index < NumArithmeticTypes);
6615    static CanQualType ASTContext::* const
6616      ArithmeticTypes[NumArithmeticTypes] = {
6617      // Start of promoted types.
6618      &ASTContext::FloatTy,
6619      &ASTContext::DoubleTy,
6620      &ASTContext::LongDoubleTy,
6621
6622      // Start of integral types.
6623      &ASTContext::IntTy,
6624      &ASTContext::LongTy,
6625      &ASTContext::LongLongTy,
6626      &ASTContext::Int128Ty,
6627      &ASTContext::UnsignedIntTy,
6628      &ASTContext::UnsignedLongTy,
6629      &ASTContext::UnsignedLongLongTy,
6630      &ASTContext::UnsignedInt128Ty,
6631      // End of promoted types.
6632
6633      &ASTContext::BoolTy,
6634      &ASTContext::CharTy,
6635      &ASTContext::WCharTy,
6636      &ASTContext::Char16Ty,
6637      &ASTContext::Char32Ty,
6638      &ASTContext::SignedCharTy,
6639      &ASTContext::ShortTy,
6640      &ASTContext::UnsignedCharTy,
6641      &ASTContext::UnsignedShortTy,
6642      // End of integral types.
6643      // FIXME: What about complex? What about half?
6644    };
6645    return S.Context.*ArithmeticTypes[index];
6646  }
6647
6648  /// \brief Gets the canonical type resulting from the usual arithemetic
6649  /// converions for the given arithmetic types.
6650  CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6651    // Accelerator table for performing the usual arithmetic conversions.
6652    // The rules are basically:
6653    //   - if either is floating-point, use the wider floating-point
6654    //   - if same signedness, use the higher rank
6655    //   - if same size, use unsigned of the higher rank
6656    //   - use the larger type
6657    // These rules, together with the axiom that higher ranks are
6658    // never smaller, are sufficient to precompute all of these results
6659    // *except* when dealing with signed types of higher rank.
6660    // (we could precompute SLL x UI for all known platforms, but it's
6661    // better not to make any assumptions).
6662    // We assume that int128 has a higher rank than long long on all platforms.
6663    enum PromotedType {
6664            Dep=-1,
6665            Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6666    };
6667    static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6668                                        [LastPromotedArithmeticType] = {
6669/* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6670/* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6671/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6672/*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6673/*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6674/* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6675/*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6676/*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6677/*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6678/* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6679/*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6680    };
6681
6682    assert(L < LastPromotedArithmeticType);
6683    assert(R < LastPromotedArithmeticType);
6684    int Idx = ConversionsTable[L][R];
6685
6686    // Fast path: the table gives us a concrete answer.
6687    if (Idx != Dep) return getArithmeticType(Idx);
6688
6689    // Slow path: we need to compare widths.
6690    // An invariant is that the signed type has higher rank.
6691    CanQualType LT = getArithmeticType(L),
6692                RT = getArithmeticType(R);
6693    unsigned LW = S.Context.getIntWidth(LT),
6694             RW = S.Context.getIntWidth(RT);
6695
6696    // If they're different widths, use the signed type.
6697    if (LW > RW) return LT;
6698    else if (LW < RW) return RT;
6699
6700    // Otherwise, use the unsigned type of the signed type's rank.
6701    if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6702    assert(L == SLL || R == SLL);
6703    return S.Context.UnsignedLongLongTy;
6704  }
6705
6706  /// \brief Helper method to factor out the common pattern of adding overloads
6707  /// for '++' and '--' builtin operators.
6708  void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6709                                           bool HasVolatile,
6710                                           bool HasRestrict) {
6711    QualType ParamTypes[2] = {
6712      S.Context.getLValueReferenceType(CandidateTy),
6713      S.Context.IntTy
6714    };
6715
6716    // Non-volatile version.
6717    if (Args.size() == 1)
6718      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6719    else
6720      S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6721
6722    // Use a heuristic to reduce number of builtin candidates in the set:
6723    // add volatile version only if there are conversions to a volatile type.
6724    if (HasVolatile) {
6725      ParamTypes[0] =
6726        S.Context.getLValueReferenceType(
6727          S.Context.getVolatileType(CandidateTy));
6728      if (Args.size() == 1)
6729        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6730      else
6731        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6732    }
6733
6734    // Add restrict version only if there are conversions to a restrict type
6735    // and our candidate type is a non-restrict-qualified pointer.
6736    if (HasRestrict && CandidateTy->isAnyPointerType() &&
6737        !CandidateTy.isRestrictQualified()) {
6738      ParamTypes[0]
6739        = S.Context.getLValueReferenceType(
6740            S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6741      if (Args.size() == 1)
6742        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6743      else
6744        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6745
6746      if (HasVolatile) {
6747        ParamTypes[0]
6748          = S.Context.getLValueReferenceType(
6749              S.Context.getCVRQualifiedType(CandidateTy,
6750                                            (Qualifiers::Volatile |
6751                                             Qualifiers::Restrict)));
6752        if (Args.size() == 1)
6753          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6754        else
6755          S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6756      }
6757    }
6758
6759  }
6760
6761public:
6762  BuiltinOperatorOverloadBuilder(
6763    Sema &S, ArrayRef<Expr *> Args,
6764    Qualifiers VisibleTypeConversionsQuals,
6765    bool HasArithmeticOrEnumeralCandidateType,
6766    SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6767    OverloadCandidateSet &CandidateSet)
6768    : S(S), Args(Args),
6769      VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6770      HasArithmeticOrEnumeralCandidateType(
6771        HasArithmeticOrEnumeralCandidateType),
6772      CandidateTypes(CandidateTypes),
6773      CandidateSet(CandidateSet) {
6774    // Validate some of our static helper constants in debug builds.
6775    assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6776           "Invalid first promoted integral type");
6777    assert(getArithmeticType(LastPromotedIntegralType - 1)
6778             == S.Context.UnsignedInt128Ty &&
6779           "Invalid last promoted integral type");
6780    assert(getArithmeticType(FirstPromotedArithmeticType)
6781             == S.Context.FloatTy &&
6782           "Invalid first promoted arithmetic type");
6783    assert(getArithmeticType(LastPromotedArithmeticType - 1)
6784             == S.Context.UnsignedInt128Ty &&
6785           "Invalid last promoted arithmetic type");
6786  }
6787
6788  // C++ [over.built]p3:
6789  //
6790  //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6791  //   is either volatile or empty, there exist candidate operator
6792  //   functions of the form
6793  //
6794  //       VQ T&      operator++(VQ T&);
6795  //       T          operator++(VQ T&, int);
6796  //
6797  // C++ [over.built]p4:
6798  //
6799  //   For every pair (T, VQ), where T is an arithmetic type other
6800  //   than bool, and VQ is either volatile or empty, there exist
6801  //   candidate operator functions of the form
6802  //
6803  //       VQ T&      operator--(VQ T&);
6804  //       T          operator--(VQ T&, int);
6805  void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6806    if (!HasArithmeticOrEnumeralCandidateType)
6807      return;
6808
6809    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6810         Arith < NumArithmeticTypes; ++Arith) {
6811      addPlusPlusMinusMinusStyleOverloads(
6812        getArithmeticType(Arith),
6813        VisibleTypeConversionsQuals.hasVolatile(),
6814        VisibleTypeConversionsQuals.hasRestrict());
6815    }
6816  }
6817
6818  // C++ [over.built]p5:
6819  //
6820  //   For every pair (T, VQ), where T is a cv-qualified or
6821  //   cv-unqualified object type, and VQ is either volatile or
6822  //   empty, there exist candidate operator functions of the form
6823  //
6824  //       T*VQ&      operator++(T*VQ&);
6825  //       T*VQ&      operator--(T*VQ&);
6826  //       T*         operator++(T*VQ&, int);
6827  //       T*         operator--(T*VQ&, int);
6828  void addPlusPlusMinusMinusPointerOverloads() {
6829    for (BuiltinCandidateTypeSet::iterator
6830              Ptr = CandidateTypes[0].pointer_begin(),
6831           PtrEnd = CandidateTypes[0].pointer_end();
6832         Ptr != PtrEnd; ++Ptr) {
6833      // Skip pointer types that aren't pointers to object types.
6834      if (!(*Ptr)->getPointeeType()->isObjectType())
6835        continue;
6836
6837      addPlusPlusMinusMinusStyleOverloads(*Ptr,
6838        (!(*Ptr).isVolatileQualified() &&
6839         VisibleTypeConversionsQuals.hasVolatile()),
6840        (!(*Ptr).isRestrictQualified() &&
6841         VisibleTypeConversionsQuals.hasRestrict()));
6842    }
6843  }
6844
6845  // C++ [over.built]p6:
6846  //   For every cv-qualified or cv-unqualified object type T, there
6847  //   exist candidate operator functions of the form
6848  //
6849  //       T&         operator*(T*);
6850  //
6851  // C++ [over.built]p7:
6852  //   For every function type T that does not have cv-qualifiers or a
6853  //   ref-qualifier, there exist candidate operator functions of the form
6854  //       T&         operator*(T*);
6855  void addUnaryStarPointerOverloads() {
6856    for (BuiltinCandidateTypeSet::iterator
6857              Ptr = CandidateTypes[0].pointer_begin(),
6858           PtrEnd = CandidateTypes[0].pointer_end();
6859         Ptr != PtrEnd; ++Ptr) {
6860      QualType ParamTy = *Ptr;
6861      QualType PointeeTy = ParamTy->getPointeeType();
6862      if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6863        continue;
6864
6865      if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6866        if (Proto->getTypeQuals() || Proto->getRefQualifier())
6867          continue;
6868
6869      S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6870                            &ParamTy, Args, CandidateSet);
6871    }
6872  }
6873
6874  // C++ [over.built]p9:
6875  //  For every promoted arithmetic type T, there exist candidate
6876  //  operator functions of the form
6877  //
6878  //       T         operator+(T);
6879  //       T         operator-(T);
6880  void addUnaryPlusOrMinusArithmeticOverloads() {
6881    if (!HasArithmeticOrEnumeralCandidateType)
6882      return;
6883
6884    for (unsigned Arith = FirstPromotedArithmeticType;
6885         Arith < LastPromotedArithmeticType; ++Arith) {
6886      QualType ArithTy = getArithmeticType(Arith);
6887      S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
6888    }
6889
6890    // Extension: We also add these operators for vector types.
6891    for (BuiltinCandidateTypeSet::iterator
6892              Vec = CandidateTypes[0].vector_begin(),
6893           VecEnd = CandidateTypes[0].vector_end();
6894         Vec != VecEnd; ++Vec) {
6895      QualType VecTy = *Vec;
6896      S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
6897    }
6898  }
6899
6900  // C++ [over.built]p8:
6901  //   For every type T, there exist candidate operator functions of
6902  //   the form
6903  //
6904  //       T*         operator+(T*);
6905  void addUnaryPlusPointerOverloads() {
6906    for (BuiltinCandidateTypeSet::iterator
6907              Ptr = CandidateTypes[0].pointer_begin(),
6908           PtrEnd = CandidateTypes[0].pointer_end();
6909         Ptr != PtrEnd; ++Ptr) {
6910      QualType ParamTy = *Ptr;
6911      S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
6912    }
6913  }
6914
6915  // C++ [over.built]p10:
6916  //   For every promoted integral type T, there exist candidate
6917  //   operator functions of the form
6918  //
6919  //        T         operator~(T);
6920  void addUnaryTildePromotedIntegralOverloads() {
6921    if (!HasArithmeticOrEnumeralCandidateType)
6922      return;
6923
6924    for (unsigned Int = FirstPromotedIntegralType;
6925         Int < LastPromotedIntegralType; ++Int) {
6926      QualType IntTy = getArithmeticType(Int);
6927      S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
6928    }
6929
6930    // Extension: We also add this operator for vector types.
6931    for (BuiltinCandidateTypeSet::iterator
6932              Vec = CandidateTypes[0].vector_begin(),
6933           VecEnd = CandidateTypes[0].vector_end();
6934         Vec != VecEnd; ++Vec) {
6935      QualType VecTy = *Vec;
6936      S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
6937    }
6938  }
6939
6940  // C++ [over.match.oper]p16:
6941  //   For every pointer to member type T, there exist candidate operator
6942  //   functions of the form
6943  //
6944  //        bool operator==(T,T);
6945  //        bool operator!=(T,T);
6946  void addEqualEqualOrNotEqualMemberPointerOverloads() {
6947    /// Set of (canonical) types that we've already handled.
6948    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6949
6950    for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6951      for (BuiltinCandidateTypeSet::iterator
6952                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6953             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6954           MemPtr != MemPtrEnd;
6955           ++MemPtr) {
6956        // Don't add the same builtin candidate twice.
6957        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6958          continue;
6959
6960        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6961        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
6962      }
6963    }
6964  }
6965
6966  // C++ [over.built]p15:
6967  //
6968  //   For every T, where T is an enumeration type, a pointer type, or
6969  //   std::nullptr_t, there exist candidate operator functions of the form
6970  //
6971  //        bool       operator<(T, T);
6972  //        bool       operator>(T, T);
6973  //        bool       operator<=(T, T);
6974  //        bool       operator>=(T, T);
6975  //        bool       operator==(T, T);
6976  //        bool       operator!=(T, T);
6977  void addRelationalPointerOrEnumeralOverloads() {
6978    // C++ [over.match.oper]p3:
6979    //   [...]the built-in candidates include all of the candidate operator
6980    //   functions defined in 13.6 that, compared to the given operator, [...]
6981    //   do not have the same parameter-type-list as any non-template non-member
6982    //   candidate.
6983    //
6984    // Note that in practice, this only affects enumeration types because there
6985    // aren't any built-in candidates of record type, and a user-defined operator
6986    // must have an operand of record or enumeration type. Also, the only other
6987    // overloaded operator with enumeration arguments, operator=,
6988    // cannot be overloaded for enumeration types, so this is the only place
6989    // where we must suppress candidates like this.
6990    llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6991      UserDefinedBinaryOperators;
6992
6993    for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6994      if (CandidateTypes[ArgIdx].enumeration_begin() !=
6995          CandidateTypes[ArgIdx].enumeration_end()) {
6996        for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6997                                         CEnd = CandidateSet.end();
6998             C != CEnd; ++C) {
6999          if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7000            continue;
7001
7002          if (C->Function->isFunctionTemplateSpecialization())
7003            continue;
7004
7005          QualType FirstParamType =
7006            C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7007          QualType SecondParamType =
7008            C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7009
7010          // Skip if either parameter isn't of enumeral type.
7011          if (!FirstParamType->isEnumeralType() ||
7012              !SecondParamType->isEnumeralType())
7013            continue;
7014
7015          // Add this operator to the set of known user-defined operators.
7016          UserDefinedBinaryOperators.insert(
7017            std::make_pair(S.Context.getCanonicalType(FirstParamType),
7018                           S.Context.getCanonicalType(SecondParamType)));
7019        }
7020      }
7021    }
7022
7023    /// Set of (canonical) types that we've already handled.
7024    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7025
7026    for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7027      for (BuiltinCandidateTypeSet::iterator
7028                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7029             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7030           Ptr != PtrEnd; ++Ptr) {
7031        // Don't add the same builtin candidate twice.
7032        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7033          continue;
7034
7035        QualType ParamTypes[2] = { *Ptr, *Ptr };
7036        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7037      }
7038      for (BuiltinCandidateTypeSet::iterator
7039                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7040             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7041           Enum != EnumEnd; ++Enum) {
7042        CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7043
7044        // Don't add the same builtin candidate twice, or if a user defined
7045        // candidate exists.
7046        if (!AddedTypes.insert(CanonType) ||
7047            UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7048                                                            CanonType)))
7049          continue;
7050
7051        QualType ParamTypes[2] = { *Enum, *Enum };
7052        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7053      }
7054
7055      if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7056        CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7057        if (AddedTypes.insert(NullPtrTy) &&
7058            !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7059                                                             NullPtrTy))) {
7060          QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7061          S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7062                                CandidateSet);
7063        }
7064      }
7065    }
7066  }
7067
7068  // C++ [over.built]p13:
7069  //
7070  //   For every cv-qualified or cv-unqualified object type T
7071  //   there exist candidate operator functions of the form
7072  //
7073  //      T*         operator+(T*, ptrdiff_t);
7074  //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7075  //      T*         operator-(T*, ptrdiff_t);
7076  //      T*         operator+(ptrdiff_t, T*);
7077  //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7078  //
7079  // C++ [over.built]p14:
7080  //
7081  //   For every T, where T is a pointer to object type, there
7082  //   exist candidate operator functions of the form
7083  //
7084  //      ptrdiff_t  operator-(T, T);
7085  void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7086    /// Set of (canonical) types that we've already handled.
7087    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7088
7089    for (int Arg = 0; Arg < 2; ++Arg) {
7090      QualType AsymetricParamTypes[2] = {
7091        S.Context.getPointerDiffType(),
7092        S.Context.getPointerDiffType(),
7093      };
7094      for (BuiltinCandidateTypeSet::iterator
7095                Ptr = CandidateTypes[Arg].pointer_begin(),
7096             PtrEnd = CandidateTypes[Arg].pointer_end();
7097           Ptr != PtrEnd; ++Ptr) {
7098        QualType PointeeTy = (*Ptr)->getPointeeType();
7099        if (!PointeeTy->isObjectType())
7100          continue;
7101
7102        AsymetricParamTypes[Arg] = *Ptr;
7103        if (Arg == 0 || Op == OO_Plus) {
7104          // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7105          // T* operator+(ptrdiff_t, T*);
7106          S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7107        }
7108        if (Op == OO_Minus) {
7109          // ptrdiff_t operator-(T, T);
7110          if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7111            continue;
7112
7113          QualType ParamTypes[2] = { *Ptr, *Ptr };
7114          S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7115                                Args, CandidateSet);
7116        }
7117      }
7118    }
7119  }
7120
7121  // C++ [over.built]p12:
7122  //
7123  //   For every pair of promoted arithmetic types L and R, there
7124  //   exist candidate operator functions of the form
7125  //
7126  //        LR         operator*(L, R);
7127  //        LR         operator/(L, R);
7128  //        LR         operator+(L, R);
7129  //        LR         operator-(L, R);
7130  //        bool       operator<(L, R);
7131  //        bool       operator>(L, R);
7132  //        bool       operator<=(L, R);
7133  //        bool       operator>=(L, R);
7134  //        bool       operator==(L, R);
7135  //        bool       operator!=(L, R);
7136  //
7137  //   where LR is the result of the usual arithmetic conversions
7138  //   between types L and R.
7139  //
7140  // C++ [over.built]p24:
7141  //
7142  //   For every pair of promoted arithmetic types L and R, there exist
7143  //   candidate operator functions of the form
7144  //
7145  //        LR       operator?(bool, L, R);
7146  //
7147  //   where LR is the result of the usual arithmetic conversions
7148  //   between types L and R.
7149  // Our candidates ignore the first parameter.
7150  void addGenericBinaryArithmeticOverloads(bool isComparison) {
7151    if (!HasArithmeticOrEnumeralCandidateType)
7152      return;
7153
7154    for (unsigned Left = FirstPromotedArithmeticType;
7155         Left < LastPromotedArithmeticType; ++Left) {
7156      for (unsigned Right = FirstPromotedArithmeticType;
7157           Right < LastPromotedArithmeticType; ++Right) {
7158        QualType LandR[2] = { getArithmeticType(Left),
7159                              getArithmeticType(Right) };
7160        QualType Result =
7161          isComparison ? S.Context.BoolTy
7162                       : getUsualArithmeticConversions(Left, Right);
7163        S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7164      }
7165    }
7166
7167    // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7168    // conditional operator for vector types.
7169    for (BuiltinCandidateTypeSet::iterator
7170              Vec1 = CandidateTypes[0].vector_begin(),
7171           Vec1End = CandidateTypes[0].vector_end();
7172         Vec1 != Vec1End; ++Vec1) {
7173      for (BuiltinCandidateTypeSet::iterator
7174                Vec2 = CandidateTypes[1].vector_begin(),
7175             Vec2End = CandidateTypes[1].vector_end();
7176           Vec2 != Vec2End; ++Vec2) {
7177        QualType LandR[2] = { *Vec1, *Vec2 };
7178        QualType Result = S.Context.BoolTy;
7179        if (!isComparison) {
7180          if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7181            Result = *Vec1;
7182          else
7183            Result = *Vec2;
7184        }
7185
7186        S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7187      }
7188    }
7189  }
7190
7191  // C++ [over.built]p17:
7192  //
7193  //   For every pair of promoted integral types L and R, there
7194  //   exist candidate operator functions of the form
7195  //
7196  //      LR         operator%(L, R);
7197  //      LR         operator&(L, R);
7198  //      LR         operator^(L, R);
7199  //      LR         operator|(L, R);
7200  //      L          operator<<(L, R);
7201  //      L          operator>>(L, R);
7202  //
7203  //   where LR is the result of the usual arithmetic conversions
7204  //   between types L and R.
7205  void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7206    if (!HasArithmeticOrEnumeralCandidateType)
7207      return;
7208
7209    for (unsigned Left = FirstPromotedIntegralType;
7210         Left < LastPromotedIntegralType; ++Left) {
7211      for (unsigned Right = FirstPromotedIntegralType;
7212           Right < LastPromotedIntegralType; ++Right) {
7213        QualType LandR[2] = { getArithmeticType(Left),
7214                              getArithmeticType(Right) };
7215        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7216            ? LandR[0]
7217            : getUsualArithmeticConversions(Left, Right);
7218        S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7219      }
7220    }
7221  }
7222
7223  // C++ [over.built]p20:
7224  //
7225  //   For every pair (T, VQ), where T is an enumeration or
7226  //   pointer to member type and VQ is either volatile or
7227  //   empty, there exist candidate operator functions of the form
7228  //
7229  //        VQ T&      operator=(VQ T&, T);
7230  void addAssignmentMemberPointerOrEnumeralOverloads() {
7231    /// Set of (canonical) types that we've already handled.
7232    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7233
7234    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7235      for (BuiltinCandidateTypeSet::iterator
7236                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7237             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7238           Enum != EnumEnd; ++Enum) {
7239        if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7240          continue;
7241
7242        AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7243      }
7244
7245      for (BuiltinCandidateTypeSet::iterator
7246                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7247             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7248           MemPtr != MemPtrEnd; ++MemPtr) {
7249        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7250          continue;
7251
7252        AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7253      }
7254    }
7255  }
7256
7257  // C++ [over.built]p19:
7258  //
7259  //   For every pair (T, VQ), where T is any type and VQ is either
7260  //   volatile or empty, there exist candidate operator functions
7261  //   of the form
7262  //
7263  //        T*VQ&      operator=(T*VQ&, T*);
7264  //
7265  // C++ [over.built]p21:
7266  //
7267  //   For every pair (T, VQ), where T is a cv-qualified or
7268  //   cv-unqualified object type and VQ is either volatile or
7269  //   empty, there exist candidate operator functions of the form
7270  //
7271  //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7272  //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7273  void addAssignmentPointerOverloads(bool isEqualOp) {
7274    /// Set of (canonical) types that we've already handled.
7275    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7276
7277    for (BuiltinCandidateTypeSet::iterator
7278              Ptr = CandidateTypes[0].pointer_begin(),
7279           PtrEnd = CandidateTypes[0].pointer_end();
7280         Ptr != PtrEnd; ++Ptr) {
7281      // If this is operator=, keep track of the builtin candidates we added.
7282      if (isEqualOp)
7283        AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7284      else if (!(*Ptr)->getPointeeType()->isObjectType())
7285        continue;
7286
7287      // non-volatile version
7288      QualType ParamTypes[2] = {
7289        S.Context.getLValueReferenceType(*Ptr),
7290        isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7291      };
7292      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7293                            /*IsAssigmentOperator=*/ isEqualOp);
7294
7295      bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7296                          VisibleTypeConversionsQuals.hasVolatile();
7297      if (NeedVolatile) {
7298        // volatile version
7299        ParamTypes[0] =
7300          S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7301        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7302                              /*IsAssigmentOperator=*/isEqualOp);
7303      }
7304
7305      if (!(*Ptr).isRestrictQualified() &&
7306          VisibleTypeConversionsQuals.hasRestrict()) {
7307        // restrict version
7308        ParamTypes[0]
7309          = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7310        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7311                              /*IsAssigmentOperator=*/isEqualOp);
7312
7313        if (NeedVolatile) {
7314          // volatile restrict version
7315          ParamTypes[0]
7316            = S.Context.getLValueReferenceType(
7317                S.Context.getCVRQualifiedType(*Ptr,
7318                                              (Qualifiers::Volatile |
7319                                               Qualifiers::Restrict)));
7320          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7321                                /*IsAssigmentOperator=*/isEqualOp);
7322        }
7323      }
7324    }
7325
7326    if (isEqualOp) {
7327      for (BuiltinCandidateTypeSet::iterator
7328                Ptr = CandidateTypes[1].pointer_begin(),
7329             PtrEnd = CandidateTypes[1].pointer_end();
7330           Ptr != PtrEnd; ++Ptr) {
7331        // Make sure we don't add the same candidate twice.
7332        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7333          continue;
7334
7335        QualType ParamTypes[2] = {
7336          S.Context.getLValueReferenceType(*Ptr),
7337          *Ptr,
7338        };
7339
7340        // non-volatile version
7341        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7342                              /*IsAssigmentOperator=*/true);
7343
7344        bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7345                           VisibleTypeConversionsQuals.hasVolatile();
7346        if (NeedVolatile) {
7347          // volatile version
7348          ParamTypes[0] =
7349            S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7350          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7351                                /*IsAssigmentOperator=*/true);
7352        }
7353
7354        if (!(*Ptr).isRestrictQualified() &&
7355            VisibleTypeConversionsQuals.hasRestrict()) {
7356          // restrict version
7357          ParamTypes[0]
7358            = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7359          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7360                                /*IsAssigmentOperator=*/true);
7361
7362          if (NeedVolatile) {
7363            // volatile restrict version
7364            ParamTypes[0]
7365              = S.Context.getLValueReferenceType(
7366                  S.Context.getCVRQualifiedType(*Ptr,
7367                                                (Qualifiers::Volatile |
7368                                                 Qualifiers::Restrict)));
7369            S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7370                                  /*IsAssigmentOperator=*/true);
7371          }
7372        }
7373      }
7374    }
7375  }
7376
7377  // C++ [over.built]p18:
7378  //
7379  //   For every triple (L, VQ, R), where L is an arithmetic type,
7380  //   VQ is either volatile or empty, and R is a promoted
7381  //   arithmetic type, there exist candidate operator functions of
7382  //   the form
7383  //
7384  //        VQ L&      operator=(VQ L&, R);
7385  //        VQ L&      operator*=(VQ L&, R);
7386  //        VQ L&      operator/=(VQ L&, R);
7387  //        VQ L&      operator+=(VQ L&, R);
7388  //        VQ L&      operator-=(VQ L&, R);
7389  void addAssignmentArithmeticOverloads(bool isEqualOp) {
7390    if (!HasArithmeticOrEnumeralCandidateType)
7391      return;
7392
7393    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7394      for (unsigned Right = FirstPromotedArithmeticType;
7395           Right < LastPromotedArithmeticType; ++Right) {
7396        QualType ParamTypes[2];
7397        ParamTypes[1] = getArithmeticType(Right);
7398
7399        // Add this built-in operator as a candidate (VQ is empty).
7400        ParamTypes[0] =
7401          S.Context.getLValueReferenceType(getArithmeticType(Left));
7402        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7403                              /*IsAssigmentOperator=*/isEqualOp);
7404
7405        // Add this built-in operator as a candidate (VQ is 'volatile').
7406        if (VisibleTypeConversionsQuals.hasVolatile()) {
7407          ParamTypes[0] =
7408            S.Context.getVolatileType(getArithmeticType(Left));
7409          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7410          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7411                                /*IsAssigmentOperator=*/isEqualOp);
7412        }
7413      }
7414    }
7415
7416    // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7417    for (BuiltinCandidateTypeSet::iterator
7418              Vec1 = CandidateTypes[0].vector_begin(),
7419           Vec1End = CandidateTypes[0].vector_end();
7420         Vec1 != Vec1End; ++Vec1) {
7421      for (BuiltinCandidateTypeSet::iterator
7422                Vec2 = CandidateTypes[1].vector_begin(),
7423             Vec2End = CandidateTypes[1].vector_end();
7424           Vec2 != Vec2End; ++Vec2) {
7425        QualType ParamTypes[2];
7426        ParamTypes[1] = *Vec2;
7427        // Add this built-in operator as a candidate (VQ is empty).
7428        ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7429        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7430                              /*IsAssigmentOperator=*/isEqualOp);
7431
7432        // Add this built-in operator as a candidate (VQ is 'volatile').
7433        if (VisibleTypeConversionsQuals.hasVolatile()) {
7434          ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7435          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7436          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7437                                /*IsAssigmentOperator=*/isEqualOp);
7438        }
7439      }
7440    }
7441  }
7442
7443  // C++ [over.built]p22:
7444  //
7445  //   For every triple (L, VQ, R), where L is an integral type, VQ
7446  //   is either volatile or empty, and R is a promoted integral
7447  //   type, there exist candidate operator functions of the form
7448  //
7449  //        VQ L&       operator%=(VQ L&, R);
7450  //        VQ L&       operator<<=(VQ L&, R);
7451  //        VQ L&       operator>>=(VQ L&, R);
7452  //        VQ L&       operator&=(VQ L&, R);
7453  //        VQ L&       operator^=(VQ L&, R);
7454  //        VQ L&       operator|=(VQ L&, R);
7455  void addAssignmentIntegralOverloads() {
7456    if (!HasArithmeticOrEnumeralCandidateType)
7457      return;
7458
7459    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7460      for (unsigned Right = FirstPromotedIntegralType;
7461           Right < LastPromotedIntegralType; ++Right) {
7462        QualType ParamTypes[2];
7463        ParamTypes[1] = getArithmeticType(Right);
7464
7465        // Add this built-in operator as a candidate (VQ is empty).
7466        ParamTypes[0] =
7467          S.Context.getLValueReferenceType(getArithmeticType(Left));
7468        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7469        if (VisibleTypeConversionsQuals.hasVolatile()) {
7470          // Add this built-in operator as a candidate (VQ is 'volatile').
7471          ParamTypes[0] = getArithmeticType(Left);
7472          ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7473          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7474          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7475        }
7476      }
7477    }
7478  }
7479
7480  // C++ [over.operator]p23:
7481  //
7482  //   There also exist candidate operator functions of the form
7483  //
7484  //        bool        operator!(bool);
7485  //        bool        operator&&(bool, bool);
7486  //        bool        operator||(bool, bool);
7487  void addExclaimOverload() {
7488    QualType ParamTy = S.Context.BoolTy;
7489    S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7490                          /*IsAssignmentOperator=*/false,
7491                          /*NumContextualBoolArguments=*/1);
7492  }
7493  void addAmpAmpOrPipePipeOverload() {
7494    QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7495    S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7496                          /*IsAssignmentOperator=*/false,
7497                          /*NumContextualBoolArguments=*/2);
7498  }
7499
7500  // C++ [over.built]p13:
7501  //
7502  //   For every cv-qualified or cv-unqualified object type T there
7503  //   exist candidate operator functions of the form
7504  //
7505  //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7506  //        T&         operator[](T*, ptrdiff_t);
7507  //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7508  //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7509  //        T&         operator[](ptrdiff_t, T*);
7510  void addSubscriptOverloads() {
7511    for (BuiltinCandidateTypeSet::iterator
7512              Ptr = CandidateTypes[0].pointer_begin(),
7513           PtrEnd = CandidateTypes[0].pointer_end();
7514         Ptr != PtrEnd; ++Ptr) {
7515      QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7516      QualType PointeeType = (*Ptr)->getPointeeType();
7517      if (!PointeeType->isObjectType())
7518        continue;
7519
7520      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7521
7522      // T& operator[](T*, ptrdiff_t)
7523      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7524    }
7525
7526    for (BuiltinCandidateTypeSet::iterator
7527              Ptr = CandidateTypes[1].pointer_begin(),
7528           PtrEnd = CandidateTypes[1].pointer_end();
7529         Ptr != PtrEnd; ++Ptr) {
7530      QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7531      QualType PointeeType = (*Ptr)->getPointeeType();
7532      if (!PointeeType->isObjectType())
7533        continue;
7534
7535      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7536
7537      // T& operator[](ptrdiff_t, T*)
7538      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7539    }
7540  }
7541
7542  // C++ [over.built]p11:
7543  //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7544  //    C1 is the same type as C2 or is a derived class of C2, T is an object
7545  //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7546  //    there exist candidate operator functions of the form
7547  //
7548  //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7549  //
7550  //    where CV12 is the union of CV1 and CV2.
7551  void addArrowStarOverloads() {
7552    for (BuiltinCandidateTypeSet::iterator
7553             Ptr = CandidateTypes[0].pointer_begin(),
7554           PtrEnd = CandidateTypes[0].pointer_end();
7555         Ptr != PtrEnd; ++Ptr) {
7556      QualType C1Ty = (*Ptr);
7557      QualType C1;
7558      QualifierCollector Q1;
7559      C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7560      if (!isa<RecordType>(C1))
7561        continue;
7562      // heuristic to reduce number of builtin candidates in the set.
7563      // Add volatile/restrict version only if there are conversions to a
7564      // volatile/restrict type.
7565      if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7566        continue;
7567      if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7568        continue;
7569      for (BuiltinCandidateTypeSet::iterator
7570                MemPtr = CandidateTypes[1].member_pointer_begin(),
7571             MemPtrEnd = CandidateTypes[1].member_pointer_end();
7572           MemPtr != MemPtrEnd; ++MemPtr) {
7573        const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7574        QualType C2 = QualType(mptr->getClass(), 0);
7575        C2 = C2.getUnqualifiedType();
7576        if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7577          break;
7578        QualType ParamTypes[2] = { *Ptr, *MemPtr };
7579        // build CV12 T&
7580        QualType T = mptr->getPointeeType();
7581        if (!VisibleTypeConversionsQuals.hasVolatile() &&
7582            T.isVolatileQualified())
7583          continue;
7584        if (!VisibleTypeConversionsQuals.hasRestrict() &&
7585            T.isRestrictQualified())
7586          continue;
7587        T = Q1.apply(S.Context, T);
7588        QualType ResultTy = S.Context.getLValueReferenceType(T);
7589        S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7590      }
7591    }
7592  }
7593
7594  // Note that we don't consider the first argument, since it has been
7595  // contextually converted to bool long ago. The candidates below are
7596  // therefore added as binary.
7597  //
7598  // C++ [over.built]p25:
7599  //   For every type T, where T is a pointer, pointer-to-member, or scoped
7600  //   enumeration type, there exist candidate operator functions of the form
7601  //
7602  //        T        operator?(bool, T, T);
7603  //
7604  void addConditionalOperatorOverloads() {
7605    /// Set of (canonical) types that we've already handled.
7606    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7607
7608    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7609      for (BuiltinCandidateTypeSet::iterator
7610                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7611             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7612           Ptr != PtrEnd; ++Ptr) {
7613        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7614          continue;
7615
7616        QualType ParamTypes[2] = { *Ptr, *Ptr };
7617        S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
7618      }
7619
7620      for (BuiltinCandidateTypeSet::iterator
7621                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7622             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7623           MemPtr != MemPtrEnd; ++MemPtr) {
7624        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7625          continue;
7626
7627        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7628        S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
7629      }
7630
7631      if (S.getLangOpts().CPlusPlus11) {
7632        for (BuiltinCandidateTypeSet::iterator
7633                  Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7634               EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7635             Enum != EnumEnd; ++Enum) {
7636          if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7637            continue;
7638
7639          if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7640            continue;
7641
7642          QualType ParamTypes[2] = { *Enum, *Enum };
7643          S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
7644        }
7645      }
7646    }
7647  }
7648};
7649
7650} // end anonymous namespace
7651
7652/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7653/// operator overloads to the candidate set (C++ [over.built]), based
7654/// on the operator @p Op and the arguments given. For example, if the
7655/// operator is a binary '+', this routine might add "int
7656/// operator+(int, int)" to cover integer addition.
7657void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7658                                        SourceLocation OpLoc,
7659                                        ArrayRef<Expr *> Args,
7660                                        OverloadCandidateSet &CandidateSet) {
7661  // Find all of the types that the arguments can convert to, but only
7662  // if the operator we're looking at has built-in operator candidates
7663  // that make use of these types. Also record whether we encounter non-record
7664  // candidate types or either arithmetic or enumeral candidate types.
7665  Qualifiers VisibleTypeConversionsQuals;
7666  VisibleTypeConversionsQuals.addConst();
7667  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7668    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7669
7670  bool HasNonRecordCandidateType = false;
7671  bool HasArithmeticOrEnumeralCandidateType = false;
7672  SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7673  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7674    CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7675    CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7676                                                 OpLoc,
7677                                                 true,
7678                                                 (Op == OO_Exclaim ||
7679                                                  Op == OO_AmpAmp ||
7680                                                  Op == OO_PipePipe),
7681                                                 VisibleTypeConversionsQuals);
7682    HasNonRecordCandidateType = HasNonRecordCandidateType ||
7683        CandidateTypes[ArgIdx].hasNonRecordTypes();
7684    HasArithmeticOrEnumeralCandidateType =
7685        HasArithmeticOrEnumeralCandidateType ||
7686        CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7687  }
7688
7689  // Exit early when no non-record types have been added to the candidate set
7690  // for any of the arguments to the operator.
7691  //
7692  // We can't exit early for !, ||, or &&, since there we have always have
7693  // 'bool' overloads.
7694  if (!HasNonRecordCandidateType &&
7695      !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7696    return;
7697
7698  // Setup an object to manage the common state for building overloads.
7699  BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
7700                                           VisibleTypeConversionsQuals,
7701                                           HasArithmeticOrEnumeralCandidateType,
7702                                           CandidateTypes, CandidateSet);
7703
7704  // Dispatch over the operation to add in only those overloads which apply.
7705  switch (Op) {
7706  case OO_None:
7707  case NUM_OVERLOADED_OPERATORS:
7708    llvm_unreachable("Expected an overloaded operator");
7709
7710  case OO_New:
7711  case OO_Delete:
7712  case OO_Array_New:
7713  case OO_Array_Delete:
7714  case OO_Call:
7715    llvm_unreachable(
7716                    "Special operators don't use AddBuiltinOperatorCandidates");
7717
7718  case OO_Comma:
7719  case OO_Arrow:
7720    // C++ [over.match.oper]p3:
7721    //   -- For the operator ',', the unary operator '&', or the
7722    //      operator '->', the built-in candidates set is empty.
7723    break;
7724
7725  case OO_Plus: // '+' is either unary or binary
7726    if (Args.size() == 1)
7727      OpBuilder.addUnaryPlusPointerOverloads();
7728    // Fall through.
7729
7730  case OO_Minus: // '-' is either unary or binary
7731    if (Args.size() == 1) {
7732      OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7733    } else {
7734      OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7735      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7736    }
7737    break;
7738
7739  case OO_Star: // '*' is either unary or binary
7740    if (Args.size() == 1)
7741      OpBuilder.addUnaryStarPointerOverloads();
7742    else
7743      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7744    break;
7745
7746  case OO_Slash:
7747    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7748    break;
7749
7750  case OO_PlusPlus:
7751  case OO_MinusMinus:
7752    OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7753    OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7754    break;
7755
7756  case OO_EqualEqual:
7757  case OO_ExclaimEqual:
7758    OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7759    // Fall through.
7760
7761  case OO_Less:
7762  case OO_Greater:
7763  case OO_LessEqual:
7764  case OO_GreaterEqual:
7765    OpBuilder.addRelationalPointerOrEnumeralOverloads();
7766    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7767    break;
7768
7769  case OO_Percent:
7770  case OO_Caret:
7771  case OO_Pipe:
7772  case OO_LessLess:
7773  case OO_GreaterGreater:
7774    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7775    break;
7776
7777  case OO_Amp: // '&' is either unary or binary
7778    if (Args.size() == 1)
7779      // C++ [over.match.oper]p3:
7780      //   -- For the operator ',', the unary operator '&', or the
7781      //      operator '->', the built-in candidates set is empty.
7782      break;
7783
7784    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7785    break;
7786
7787  case OO_Tilde:
7788    OpBuilder.addUnaryTildePromotedIntegralOverloads();
7789    break;
7790
7791  case OO_Equal:
7792    OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7793    // Fall through.
7794
7795  case OO_PlusEqual:
7796  case OO_MinusEqual:
7797    OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7798    // Fall through.
7799
7800  case OO_StarEqual:
7801  case OO_SlashEqual:
7802    OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7803    break;
7804
7805  case OO_PercentEqual:
7806  case OO_LessLessEqual:
7807  case OO_GreaterGreaterEqual:
7808  case OO_AmpEqual:
7809  case OO_CaretEqual:
7810  case OO_PipeEqual:
7811    OpBuilder.addAssignmentIntegralOverloads();
7812    break;
7813
7814  case OO_Exclaim:
7815    OpBuilder.addExclaimOverload();
7816    break;
7817
7818  case OO_AmpAmp:
7819  case OO_PipePipe:
7820    OpBuilder.addAmpAmpOrPipePipeOverload();
7821    break;
7822
7823  case OO_Subscript:
7824    OpBuilder.addSubscriptOverloads();
7825    break;
7826
7827  case OO_ArrowStar:
7828    OpBuilder.addArrowStarOverloads();
7829    break;
7830
7831  case OO_Conditional:
7832    OpBuilder.addConditionalOperatorOverloads();
7833    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7834    break;
7835  }
7836}
7837
7838/// \brief Add function candidates found via argument-dependent lookup
7839/// to the set of overloading candidates.
7840///
7841/// This routine performs argument-dependent name lookup based on the
7842/// given function name (which may also be an operator name) and adds
7843/// all of the overload candidates found by ADL to the overload
7844/// candidate set (C++ [basic.lookup.argdep]).
7845void
7846Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7847                                           bool Operator, SourceLocation Loc,
7848                                           ArrayRef<Expr *> Args,
7849                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
7850                                           OverloadCandidateSet& CandidateSet,
7851                                           bool PartialOverloading) {
7852  ADLResult Fns;
7853
7854  // FIXME: This approach for uniquing ADL results (and removing
7855  // redundant candidates from the set) relies on pointer-equality,
7856  // which means we need to key off the canonical decl.  However,
7857  // always going back to the canonical decl might not get us the
7858  // right set of default arguments.  What default arguments are
7859  // we supposed to consider on ADL candidates, anyway?
7860
7861  // FIXME: Pass in the explicit template arguments?
7862  ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
7863
7864  // Erase all of the candidates we already knew about.
7865  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7866                                   CandEnd = CandidateSet.end();
7867       Cand != CandEnd; ++Cand)
7868    if (Cand->Function) {
7869      Fns.erase(Cand->Function);
7870      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7871        Fns.erase(FunTmpl);
7872    }
7873
7874  // For each of the ADL candidates we found, add it to the overload
7875  // set.
7876  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7877    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7878    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7879      if (ExplicitTemplateArgs)
7880        continue;
7881
7882      AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7883                           PartialOverloading);
7884    } else
7885      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7886                                   FoundDecl, ExplicitTemplateArgs,
7887                                   Args, CandidateSet);
7888  }
7889}
7890
7891/// isBetterOverloadCandidate - Determines whether the first overload
7892/// candidate is a better candidate than the second (C++ 13.3.3p1).
7893bool
7894isBetterOverloadCandidate(Sema &S,
7895                          const OverloadCandidate &Cand1,
7896                          const OverloadCandidate &Cand2,
7897                          SourceLocation Loc,
7898                          bool UserDefinedConversion) {
7899  // Define viable functions to be better candidates than non-viable
7900  // functions.
7901  if (!Cand2.Viable)
7902    return Cand1.Viable;
7903  else if (!Cand1.Viable)
7904    return false;
7905
7906  // C++ [over.match.best]p1:
7907  //
7908  //   -- if F is a static member function, ICS1(F) is defined such
7909  //      that ICS1(F) is neither better nor worse than ICS1(G) for
7910  //      any function G, and, symmetrically, ICS1(G) is neither
7911  //      better nor worse than ICS1(F).
7912  unsigned StartArg = 0;
7913  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7914    StartArg = 1;
7915
7916  // C++ [over.match.best]p1:
7917  //   A viable function F1 is defined to be a better function than another
7918  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
7919  //   conversion sequence than ICSi(F2), and then...
7920  unsigned NumArgs = Cand1.NumConversions;
7921  assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7922  bool HasBetterConversion = false;
7923  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7924    switch (CompareImplicitConversionSequences(S,
7925                                               Cand1.Conversions[ArgIdx],
7926                                               Cand2.Conversions[ArgIdx])) {
7927    case ImplicitConversionSequence::Better:
7928      // Cand1 has a better conversion sequence.
7929      HasBetterConversion = true;
7930      break;
7931
7932    case ImplicitConversionSequence::Worse:
7933      // Cand1 can't be better than Cand2.
7934      return false;
7935
7936    case ImplicitConversionSequence::Indistinguishable:
7937      // Do nothing.
7938      break;
7939    }
7940  }
7941
7942  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
7943  //       ICSj(F2), or, if not that,
7944  if (HasBetterConversion)
7945    return true;
7946
7947  //     - F1 is a non-template function and F2 is a function template
7948  //       specialization, or, if not that,
7949  if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
7950      Cand2.Function && Cand2.Function->getPrimaryTemplate())
7951    return true;
7952
7953  //   -- F1 and F2 are function template specializations, and the function
7954  //      template for F1 is more specialized than the template for F2
7955  //      according to the partial ordering rules described in 14.5.5.2, or,
7956  //      if not that,
7957  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
7958      Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
7959    if (FunctionTemplateDecl *BetterTemplate
7960          = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7961                                         Cand2.Function->getPrimaryTemplate(),
7962                                         Loc,
7963                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
7964                                                             : TPOC_Call,
7965                                         Cand1.ExplicitCallArguments,
7966                                         Cand2.ExplicitCallArguments))
7967      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
7968  }
7969
7970  //   -- the context is an initialization by user-defined conversion
7971  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
7972  //      from the return type of F1 to the destination type (i.e.,
7973  //      the type of the entity being initialized) is a better
7974  //      conversion sequence than the standard conversion sequence
7975  //      from the return type of F2 to the destination type.
7976  if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
7977      isa<CXXConversionDecl>(Cand1.Function) &&
7978      isa<CXXConversionDecl>(Cand2.Function)) {
7979    // First check whether we prefer one of the conversion functions over the
7980    // other. This only distinguishes the results in non-standard, extension
7981    // cases such as the conversion from a lambda closure type to a function
7982    // pointer or block.
7983    ImplicitConversionSequence::CompareKind FuncResult
7984      = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7985    if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7986      return FuncResult;
7987
7988    switch (CompareStandardConversionSequences(S,
7989                                               Cand1.FinalConversion,
7990                                               Cand2.FinalConversion)) {
7991    case ImplicitConversionSequence::Better:
7992      // Cand1 has a better conversion sequence.
7993      return true;
7994
7995    case ImplicitConversionSequence::Worse:
7996      // Cand1 can't be better than Cand2.
7997      return false;
7998
7999    case ImplicitConversionSequence::Indistinguishable:
8000      // Do nothing
8001      break;
8002    }
8003  }
8004
8005  return false;
8006}
8007
8008/// \brief Computes the best viable function (C++ 13.3.3)
8009/// within an overload candidate set.
8010///
8011/// \param Loc The location of the function name (or operator symbol) for
8012/// which overload resolution occurs.
8013///
8014/// \param Best If overload resolution was successful or found a deleted
8015/// function, \p Best points to the candidate function found.
8016///
8017/// \returns The result of overload resolution.
8018OverloadingResult
8019OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8020                                         iterator &Best,
8021                                         bool UserDefinedConversion) {
8022  // Find the best viable function.
8023  Best = end();
8024  for (iterator Cand = begin(); Cand != end(); ++Cand) {
8025    if (Cand->Viable)
8026      if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8027                                                     UserDefinedConversion))
8028        Best = Cand;
8029  }
8030
8031  // If we didn't find any viable functions, abort.
8032  if (Best == end())
8033    return OR_No_Viable_Function;
8034
8035  // Make sure that this function is better than every other viable
8036  // function. If not, we have an ambiguity.
8037  for (iterator Cand = begin(); Cand != end(); ++Cand) {
8038    if (Cand->Viable &&
8039        Cand != Best &&
8040        !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8041                                   UserDefinedConversion)) {
8042      Best = end();
8043      return OR_Ambiguous;
8044    }
8045  }
8046
8047  // Best is the best viable function.
8048  if (Best->Function &&
8049      (Best->Function->isDeleted() ||
8050       S.isFunctionConsideredUnavailable(Best->Function)))
8051    return OR_Deleted;
8052
8053  return OR_Success;
8054}
8055
8056namespace {
8057
8058enum OverloadCandidateKind {
8059  oc_function,
8060  oc_method,
8061  oc_constructor,
8062  oc_function_template,
8063  oc_method_template,
8064  oc_constructor_template,
8065  oc_implicit_default_constructor,
8066  oc_implicit_copy_constructor,
8067  oc_implicit_move_constructor,
8068  oc_implicit_copy_assignment,
8069  oc_implicit_move_assignment,
8070  oc_implicit_inherited_constructor
8071};
8072
8073OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8074                                                FunctionDecl *Fn,
8075                                                std::string &Description) {
8076  bool isTemplate = false;
8077
8078  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8079    isTemplate = true;
8080    Description = S.getTemplateArgumentBindingsText(
8081      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8082  }
8083
8084  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8085    if (!Ctor->isImplicit())
8086      return isTemplate ? oc_constructor_template : oc_constructor;
8087
8088    if (Ctor->getInheritedConstructor())
8089      return oc_implicit_inherited_constructor;
8090
8091    if (Ctor->isDefaultConstructor())
8092      return oc_implicit_default_constructor;
8093
8094    if (Ctor->isMoveConstructor())
8095      return oc_implicit_move_constructor;
8096
8097    assert(Ctor->isCopyConstructor() &&
8098           "unexpected sort of implicit constructor");
8099    return oc_implicit_copy_constructor;
8100  }
8101
8102  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8103    // This actually gets spelled 'candidate function' for now, but
8104    // it doesn't hurt to split it out.
8105    if (!Meth->isImplicit())
8106      return isTemplate ? oc_method_template : oc_method;
8107
8108    if (Meth->isMoveAssignmentOperator())
8109      return oc_implicit_move_assignment;
8110
8111    if (Meth->isCopyAssignmentOperator())
8112      return oc_implicit_copy_assignment;
8113
8114    assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8115    return oc_method;
8116  }
8117
8118  return isTemplate ? oc_function_template : oc_function;
8119}
8120
8121void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8122  const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8123  if (!Ctor) return;
8124
8125  Ctor = Ctor->getInheritedConstructor();
8126  if (!Ctor) return;
8127
8128  S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8129}
8130
8131} // end anonymous namespace
8132
8133// Notes the location of an overload candidate.
8134void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8135  std::string FnDesc;
8136  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8137  PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8138                             << (unsigned) K << FnDesc;
8139  HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8140  Diag(Fn->getLocation(), PD);
8141  MaybeEmitInheritedConstructorNote(*this, Fn);
8142}
8143
8144//Notes the location of all overload candidates designated through
8145// OverloadedExpr
8146void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8147  assert(OverloadedExpr->getType() == Context.OverloadTy);
8148
8149  OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8150  OverloadExpr *OvlExpr = Ovl.Expression;
8151
8152  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8153                            IEnd = OvlExpr->decls_end();
8154       I != IEnd; ++I) {
8155    if (FunctionTemplateDecl *FunTmpl =
8156                dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8157      NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8158    } else if (FunctionDecl *Fun
8159                      = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8160      NoteOverloadCandidate(Fun, DestType);
8161    }
8162  }
8163}
8164
8165/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8166/// "lead" diagnostic; it will be given two arguments, the source and
8167/// target types of the conversion.
8168void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8169                                 Sema &S,
8170                                 SourceLocation CaretLoc,
8171                                 const PartialDiagnostic &PDiag) const {
8172  S.Diag(CaretLoc, PDiag)
8173    << Ambiguous.getFromType() << Ambiguous.getToType();
8174  // FIXME: The note limiting machinery is borrowed from
8175  // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8176  // refactoring here.
8177  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8178  unsigned CandsShown = 0;
8179  AmbiguousConversionSequence::const_iterator I, E;
8180  for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8181    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8182      break;
8183    ++CandsShown;
8184    S.NoteOverloadCandidate(*I);
8185  }
8186  if (I != E)
8187    S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8188}
8189
8190namespace {
8191
8192void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8193  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8194  assert(Conv.isBad());
8195  assert(Cand->Function && "for now, candidate must be a function");
8196  FunctionDecl *Fn = Cand->Function;
8197
8198  // There's a conversion slot for the object argument if this is a
8199  // non-constructor method.  Note that 'I' corresponds the
8200  // conversion-slot index.
8201  bool isObjectArgument = false;
8202  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8203    if (I == 0)
8204      isObjectArgument = true;
8205    else
8206      I--;
8207  }
8208
8209  std::string FnDesc;
8210  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8211
8212  Expr *FromExpr = Conv.Bad.FromExpr;
8213  QualType FromTy = Conv.Bad.getFromType();
8214  QualType ToTy = Conv.Bad.getToType();
8215
8216  if (FromTy == S.Context.OverloadTy) {
8217    assert(FromExpr && "overload set argument came from implicit argument?");
8218    Expr *E = FromExpr->IgnoreParens();
8219    if (isa<UnaryOperator>(E))
8220      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8221    DeclarationName Name = cast<OverloadExpr>(E)->getName();
8222
8223    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8224      << (unsigned) FnKind << FnDesc
8225      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8226      << ToTy << Name << I+1;
8227    MaybeEmitInheritedConstructorNote(S, Fn);
8228    return;
8229  }
8230
8231  // Do some hand-waving analysis to see if the non-viability is due
8232  // to a qualifier mismatch.
8233  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8234  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8235  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8236    CToTy = RT->getPointeeType();
8237  else {
8238    // TODO: detect and diagnose the full richness of const mismatches.
8239    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8240      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8241        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8242  }
8243
8244  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8245      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8246    Qualifiers FromQs = CFromTy.getQualifiers();
8247    Qualifiers ToQs = CToTy.getQualifiers();
8248
8249    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8250      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8251        << (unsigned) FnKind << FnDesc
8252        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8253        << FromTy
8254        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8255        << (unsigned) isObjectArgument << I+1;
8256      MaybeEmitInheritedConstructorNote(S, Fn);
8257      return;
8258    }
8259
8260    if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8261      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8262        << (unsigned) FnKind << FnDesc
8263        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8264        << FromTy
8265        << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8266        << (unsigned) isObjectArgument << I+1;
8267      MaybeEmitInheritedConstructorNote(S, Fn);
8268      return;
8269    }
8270
8271    if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8272      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8273      << (unsigned) FnKind << FnDesc
8274      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8275      << FromTy
8276      << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8277      << (unsigned) isObjectArgument << I+1;
8278      MaybeEmitInheritedConstructorNote(S, Fn);
8279      return;
8280    }
8281
8282    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8283    assert(CVR && "unexpected qualifiers mismatch");
8284
8285    if (isObjectArgument) {
8286      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8287        << (unsigned) FnKind << FnDesc
8288        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8289        << FromTy << (CVR - 1);
8290    } else {
8291      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8292        << (unsigned) FnKind << FnDesc
8293        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8294        << FromTy << (CVR - 1) << I+1;
8295    }
8296    MaybeEmitInheritedConstructorNote(S, Fn);
8297    return;
8298  }
8299
8300  // Special diagnostic for failure to convert an initializer list, since
8301  // telling the user that it has type void is not useful.
8302  if (FromExpr && isa<InitListExpr>(FromExpr)) {
8303    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8304      << (unsigned) FnKind << FnDesc
8305      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8306      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8307    MaybeEmitInheritedConstructorNote(S, Fn);
8308    return;
8309  }
8310
8311  // Diagnose references or pointers to incomplete types differently,
8312  // since it's far from impossible that the incompleteness triggered
8313  // the failure.
8314  QualType TempFromTy = FromTy.getNonReferenceType();
8315  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8316    TempFromTy = PTy->getPointeeType();
8317  if (TempFromTy->isIncompleteType()) {
8318    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8319      << (unsigned) FnKind << FnDesc
8320      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8321      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8322    MaybeEmitInheritedConstructorNote(S, Fn);
8323    return;
8324  }
8325
8326  // Diagnose base -> derived pointer conversions.
8327  unsigned BaseToDerivedConversion = 0;
8328  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8329    if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8330      if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8331                                               FromPtrTy->getPointeeType()) &&
8332          !FromPtrTy->getPointeeType()->isIncompleteType() &&
8333          !ToPtrTy->getPointeeType()->isIncompleteType() &&
8334          S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8335                          FromPtrTy->getPointeeType()))
8336        BaseToDerivedConversion = 1;
8337    }
8338  } else if (const ObjCObjectPointerType *FromPtrTy
8339                                    = FromTy->getAs<ObjCObjectPointerType>()) {
8340    if (const ObjCObjectPointerType *ToPtrTy
8341                                        = ToTy->getAs<ObjCObjectPointerType>())
8342      if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8343        if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8344          if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8345                                                FromPtrTy->getPointeeType()) &&
8346              FromIface->isSuperClassOf(ToIface))
8347            BaseToDerivedConversion = 2;
8348  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8349    if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8350        !FromTy->isIncompleteType() &&
8351        !ToRefTy->getPointeeType()->isIncompleteType() &&
8352        S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8353      BaseToDerivedConversion = 3;
8354    } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8355               ToTy.getNonReferenceType().getCanonicalType() ==
8356               FromTy.getNonReferenceType().getCanonicalType()) {
8357      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8358        << (unsigned) FnKind << FnDesc
8359        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8360        << (unsigned) isObjectArgument << I + 1;
8361      MaybeEmitInheritedConstructorNote(S, Fn);
8362      return;
8363    }
8364  }
8365
8366  if (BaseToDerivedConversion) {
8367    S.Diag(Fn->getLocation(),
8368           diag::note_ovl_candidate_bad_base_to_derived_conv)
8369      << (unsigned) FnKind << FnDesc
8370      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8371      << (BaseToDerivedConversion - 1)
8372      << FromTy << ToTy << I+1;
8373    MaybeEmitInheritedConstructorNote(S, Fn);
8374    return;
8375  }
8376
8377  if (isa<ObjCObjectPointerType>(CFromTy) &&
8378      isa<PointerType>(CToTy)) {
8379      Qualifiers FromQs = CFromTy.getQualifiers();
8380      Qualifiers ToQs = CToTy.getQualifiers();
8381      if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8382        S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8383        << (unsigned) FnKind << FnDesc
8384        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8385        << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8386        MaybeEmitInheritedConstructorNote(S, Fn);
8387        return;
8388      }
8389  }
8390
8391  // Emit the generic diagnostic and, optionally, add the hints to it.
8392  PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8393  FDiag << (unsigned) FnKind << FnDesc
8394    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8395    << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8396    << (unsigned) (Cand->Fix.Kind);
8397
8398  // If we can fix the conversion, suggest the FixIts.
8399  for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8400       HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8401    FDiag << *HI;
8402  S.Diag(Fn->getLocation(), FDiag);
8403
8404  MaybeEmitInheritedConstructorNote(S, Fn);
8405}
8406
8407/// Additional arity mismatch diagnosis specific to a function overload
8408/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8409/// over a candidate in any candidate set.
8410bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8411                        unsigned NumArgs) {
8412  FunctionDecl *Fn = Cand->Function;
8413  unsigned MinParams = Fn->getMinRequiredArguments();
8414
8415  // With invalid overloaded operators, it's possible that we think we
8416  // have an arity mismatch when in fact it looks like we have the
8417  // right number of arguments, because only overloaded operators have
8418  // the weird behavior of overloading member and non-member functions.
8419  // Just don't report anything.
8420  if (Fn->isInvalidDecl() &&
8421      Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8422    return true;
8423
8424  if (NumArgs < MinParams) {
8425    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8426           (Cand->FailureKind == ovl_fail_bad_deduction &&
8427            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8428  } else {
8429    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8430           (Cand->FailureKind == ovl_fail_bad_deduction &&
8431            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8432  }
8433
8434  return false;
8435}
8436
8437/// General arity mismatch diagnosis over a candidate in a candidate set.
8438void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8439  assert(isa<FunctionDecl>(D) &&
8440      "The templated declaration should at least be a function"
8441      " when diagnosing bad template argument deduction due to too many"
8442      " or too few arguments");
8443
8444  FunctionDecl *Fn = cast<FunctionDecl>(D);
8445
8446  // TODO: treat calls to a missing default constructor as a special case
8447  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8448  unsigned MinParams = Fn->getMinRequiredArguments();
8449
8450  // at least / at most / exactly
8451  unsigned mode, modeCount;
8452  if (NumFormalArgs < MinParams) {
8453    if (MinParams != FnTy->getNumArgs() ||
8454        FnTy->isVariadic() || FnTy->isTemplateVariadic())
8455      mode = 0; // "at least"
8456    else
8457      mode = 2; // "exactly"
8458    modeCount = MinParams;
8459  } else {
8460    if (MinParams != FnTy->getNumArgs())
8461      mode = 1; // "at most"
8462    else
8463      mode = 2; // "exactly"
8464    modeCount = FnTy->getNumArgs();
8465  }
8466
8467  std::string Description;
8468  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8469
8470  if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8471    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8472      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8473      << Fn->getParamDecl(0) << NumFormalArgs;
8474  else
8475    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8476      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8477      << modeCount << NumFormalArgs;
8478  MaybeEmitInheritedConstructorNote(S, Fn);
8479}
8480
8481/// Arity mismatch diagnosis specific to a function overload candidate.
8482void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8483                           unsigned NumFormalArgs) {
8484  if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8485    DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8486}
8487
8488TemplateDecl *getDescribedTemplate(Decl *Templated) {
8489  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8490    return FD->getDescribedFunctionTemplate();
8491  else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8492    return RD->getDescribedClassTemplate();
8493
8494  llvm_unreachable("Unsupported: Getting the described template declaration"
8495                   " for bad deduction diagnosis");
8496}
8497
8498/// Diagnose a failed template-argument deduction.
8499void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8500                          DeductionFailureInfo &DeductionFailure,
8501                          unsigned NumArgs) {
8502  TemplateParameter Param = DeductionFailure.getTemplateParameter();
8503  NamedDecl *ParamD;
8504  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8505  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8506  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8507  switch (DeductionFailure.Result) {
8508  case Sema::TDK_Success:
8509    llvm_unreachable("TDK_success while diagnosing bad deduction");
8510
8511  case Sema::TDK_Incomplete: {
8512    assert(ParamD && "no parameter found for incomplete deduction result");
8513    S.Diag(Templated->getLocation(),
8514           diag::note_ovl_candidate_incomplete_deduction)
8515        << ParamD->getDeclName();
8516    MaybeEmitInheritedConstructorNote(S, Templated);
8517    return;
8518  }
8519
8520  case Sema::TDK_Underqualified: {
8521    assert(ParamD && "no parameter found for bad qualifiers deduction result");
8522    TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8523
8524    QualType Param = DeductionFailure.getFirstArg()->getAsType();
8525
8526    // Param will have been canonicalized, but it should just be a
8527    // qualified version of ParamD, so move the qualifiers to that.
8528    QualifierCollector Qs;
8529    Qs.strip(Param);
8530    QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8531    assert(S.Context.hasSameType(Param, NonCanonParam));
8532
8533    // Arg has also been canonicalized, but there's nothing we can do
8534    // about that.  It also doesn't matter as much, because it won't
8535    // have any template parameters in it (because deduction isn't
8536    // done on dependent types).
8537    QualType Arg = DeductionFailure.getSecondArg()->getAsType();
8538
8539    S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8540        << ParamD->getDeclName() << Arg << NonCanonParam;
8541    MaybeEmitInheritedConstructorNote(S, Templated);
8542    return;
8543  }
8544
8545  case Sema::TDK_Inconsistent: {
8546    assert(ParamD && "no parameter found for inconsistent deduction result");
8547    int which = 0;
8548    if (isa<TemplateTypeParmDecl>(ParamD))
8549      which = 0;
8550    else if (isa<NonTypeTemplateParmDecl>(ParamD))
8551      which = 1;
8552    else {
8553      which = 2;
8554    }
8555
8556    S.Diag(Templated->getLocation(),
8557           diag::note_ovl_candidate_inconsistent_deduction)
8558        << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8559        << *DeductionFailure.getSecondArg();
8560    MaybeEmitInheritedConstructorNote(S, Templated);
8561    return;
8562  }
8563
8564  case Sema::TDK_InvalidExplicitArguments:
8565    assert(ParamD && "no parameter found for invalid explicit arguments");
8566    if (ParamD->getDeclName())
8567      S.Diag(Templated->getLocation(),
8568             diag::note_ovl_candidate_explicit_arg_mismatch_named)
8569          << ParamD->getDeclName();
8570    else {
8571      int index = 0;
8572      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8573        index = TTP->getIndex();
8574      else if (NonTypeTemplateParmDecl *NTTP
8575                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8576        index = NTTP->getIndex();
8577      else
8578        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8579      S.Diag(Templated->getLocation(),
8580             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8581          << (index + 1);
8582    }
8583    MaybeEmitInheritedConstructorNote(S, Templated);
8584    return;
8585
8586  case Sema::TDK_TooManyArguments:
8587  case Sema::TDK_TooFewArguments:
8588    DiagnoseArityMismatch(S, Templated, NumArgs);
8589    return;
8590
8591  case Sema::TDK_InstantiationDepth:
8592    S.Diag(Templated->getLocation(),
8593           diag::note_ovl_candidate_instantiation_depth);
8594    MaybeEmitInheritedConstructorNote(S, Templated);
8595    return;
8596
8597  case Sema::TDK_SubstitutionFailure: {
8598    // Format the template argument list into the argument string.
8599    SmallString<128> TemplateArgString;
8600    if (TemplateArgumentList *Args =
8601            DeductionFailure.getTemplateArgumentList()) {
8602      TemplateArgString = " ";
8603      TemplateArgString += S.getTemplateArgumentBindingsText(
8604          getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
8605    }
8606
8607    // If this candidate was disabled by enable_if, say so.
8608    PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
8609    if (PDiag && PDiag->second.getDiagID() ==
8610          diag::err_typename_nested_not_found_enable_if) {
8611      // FIXME: Use the source range of the condition, and the fully-qualified
8612      //        name of the enable_if template. These are both present in PDiag.
8613      S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8614        << "'enable_if'" << TemplateArgString;
8615      return;
8616    }
8617
8618    // Format the SFINAE diagnostic into the argument string.
8619    // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8620    //        formatted message in another diagnostic.
8621    SmallString<128> SFINAEArgString;
8622    SourceRange R;
8623    if (PDiag) {
8624      SFINAEArgString = ": ";
8625      R = SourceRange(PDiag->first, PDiag->first);
8626      PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8627    }
8628
8629    S.Diag(Templated->getLocation(),
8630           diag::note_ovl_candidate_substitution_failure)
8631        << TemplateArgString << SFINAEArgString << R;
8632    MaybeEmitInheritedConstructorNote(S, Templated);
8633    return;
8634  }
8635
8636  case Sema::TDK_FailedOverloadResolution: {
8637    OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8638    S.Diag(Templated->getLocation(),
8639           diag::note_ovl_candidate_failed_overload_resolution)
8640        << R.Expression->getName();
8641    return;
8642  }
8643
8644  case Sema::TDK_NonDeducedMismatch: {
8645    // FIXME: Provide a source location to indicate what we couldn't match.
8646    TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8647    TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
8648    if (FirstTA.getKind() == TemplateArgument::Template &&
8649        SecondTA.getKind() == TemplateArgument::Template) {
8650      TemplateName FirstTN = FirstTA.getAsTemplate();
8651      TemplateName SecondTN = SecondTA.getAsTemplate();
8652      if (FirstTN.getKind() == TemplateName::Template &&
8653          SecondTN.getKind() == TemplateName::Template) {
8654        if (FirstTN.getAsTemplateDecl()->getName() ==
8655            SecondTN.getAsTemplateDecl()->getName()) {
8656          // FIXME: This fixes a bad diagnostic where both templates are named
8657          // the same.  This particular case is a bit difficult since:
8658          // 1) It is passed as a string to the diagnostic printer.
8659          // 2) The diagnostic printer only attempts to find a better
8660          //    name for types, not decls.
8661          // Ideally, this should folded into the diagnostic printer.
8662          S.Diag(Templated->getLocation(),
8663                 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8664              << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8665          return;
8666        }
8667      }
8668    }
8669    S.Diag(Templated->getLocation(),
8670           diag::note_ovl_candidate_non_deduced_mismatch)
8671        << FirstTA << SecondTA;
8672    return;
8673  }
8674  // TODO: diagnose these individually, then kill off
8675  // note_ovl_candidate_bad_deduction, which is uselessly vague.
8676  case Sema::TDK_MiscellaneousDeductionFailure:
8677    S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8678    MaybeEmitInheritedConstructorNote(S, Templated);
8679    return;
8680  }
8681}
8682
8683/// Diagnose a failed template-argument deduction, for function calls.
8684void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8685  unsigned TDK = Cand->DeductionFailure.Result;
8686  if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8687    if (CheckArityMismatch(S, Cand, NumArgs))
8688      return;
8689  }
8690  DiagnoseBadDeduction(S, Cand->Function, // pattern
8691                       Cand->DeductionFailure, NumArgs);
8692}
8693
8694/// CUDA: diagnose an invalid call across targets.
8695void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8696  FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8697  FunctionDecl *Callee = Cand->Function;
8698
8699  Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8700                           CalleeTarget = S.IdentifyCUDATarget(Callee);
8701
8702  std::string FnDesc;
8703  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8704
8705  S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8706      << (unsigned) FnKind << CalleeTarget << CallerTarget;
8707}
8708
8709/// Generates a 'note' diagnostic for an overload candidate.  We've
8710/// already generated a primary error at the call site.
8711///
8712/// It really does need to be a single diagnostic with its caret
8713/// pointed at the candidate declaration.  Yes, this creates some
8714/// major challenges of technical writing.  Yes, this makes pointing
8715/// out problems with specific arguments quite awkward.  It's still
8716/// better than generating twenty screens of text for every failed
8717/// overload.
8718///
8719/// It would be great to be able to express per-candidate problems
8720/// more richly for those diagnostic clients that cared, but we'd
8721/// still have to be just as careful with the default diagnostics.
8722void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8723                           unsigned NumArgs) {
8724  FunctionDecl *Fn = Cand->Function;
8725
8726  // Note deleted candidates, but only if they're viable.
8727  if (Cand->Viable && (Fn->isDeleted() ||
8728      S.isFunctionConsideredUnavailable(Fn))) {
8729    std::string FnDesc;
8730    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8731
8732    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8733      << FnKind << FnDesc
8734      << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8735    MaybeEmitInheritedConstructorNote(S, Fn);
8736    return;
8737  }
8738
8739  // We don't really have anything else to say about viable candidates.
8740  if (Cand->Viable) {
8741    S.NoteOverloadCandidate(Fn);
8742    return;
8743  }
8744
8745  switch (Cand->FailureKind) {
8746  case ovl_fail_too_many_arguments:
8747  case ovl_fail_too_few_arguments:
8748    return DiagnoseArityMismatch(S, Cand, NumArgs);
8749
8750  case ovl_fail_bad_deduction:
8751    return DiagnoseBadDeduction(S, Cand, NumArgs);
8752
8753  case ovl_fail_trivial_conversion:
8754  case ovl_fail_bad_final_conversion:
8755  case ovl_fail_final_conversion_not_exact:
8756    return S.NoteOverloadCandidate(Fn);
8757
8758  case ovl_fail_bad_conversion: {
8759    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8760    for (unsigned N = Cand->NumConversions; I != N; ++I)
8761      if (Cand->Conversions[I].isBad())
8762        return DiagnoseBadConversion(S, Cand, I);
8763
8764    // FIXME: this currently happens when we're called from SemaInit
8765    // when user-conversion overload fails.  Figure out how to handle
8766    // those conditions and diagnose them well.
8767    return S.NoteOverloadCandidate(Fn);
8768  }
8769
8770  case ovl_fail_bad_target:
8771    return DiagnoseBadTarget(S, Cand);
8772  }
8773}
8774
8775void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8776  // Desugar the type of the surrogate down to a function type,
8777  // retaining as many typedefs as possible while still showing
8778  // the function type (and, therefore, its parameter types).
8779  QualType FnType = Cand->Surrogate->getConversionType();
8780  bool isLValueReference = false;
8781  bool isRValueReference = false;
8782  bool isPointer = false;
8783  if (const LValueReferenceType *FnTypeRef =
8784        FnType->getAs<LValueReferenceType>()) {
8785    FnType = FnTypeRef->getPointeeType();
8786    isLValueReference = true;
8787  } else if (const RValueReferenceType *FnTypeRef =
8788               FnType->getAs<RValueReferenceType>()) {
8789    FnType = FnTypeRef->getPointeeType();
8790    isRValueReference = true;
8791  }
8792  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8793    FnType = FnTypePtr->getPointeeType();
8794    isPointer = true;
8795  }
8796  // Desugar down to a function type.
8797  FnType = QualType(FnType->getAs<FunctionType>(), 0);
8798  // Reconstruct the pointer/reference as appropriate.
8799  if (isPointer) FnType = S.Context.getPointerType(FnType);
8800  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8801  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8802
8803  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8804    << FnType;
8805  MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8806}
8807
8808void NoteBuiltinOperatorCandidate(Sema &S,
8809                                  StringRef Opc,
8810                                  SourceLocation OpLoc,
8811                                  OverloadCandidate *Cand) {
8812  assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8813  std::string TypeStr("operator");
8814  TypeStr += Opc;
8815  TypeStr += "(";
8816  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8817  if (Cand->NumConversions == 1) {
8818    TypeStr += ")";
8819    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8820  } else {
8821    TypeStr += ", ";
8822    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8823    TypeStr += ")";
8824    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8825  }
8826}
8827
8828void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8829                                  OverloadCandidate *Cand) {
8830  unsigned NoOperands = Cand->NumConversions;
8831  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8832    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8833    if (ICS.isBad()) break; // all meaningless after first invalid
8834    if (!ICS.isAmbiguous()) continue;
8835
8836    ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8837                              S.PDiag(diag::note_ambiguous_type_conversion));
8838  }
8839}
8840
8841static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8842  if (Cand->Function)
8843    return Cand->Function->getLocation();
8844  if (Cand->IsSurrogate)
8845    return Cand->Surrogate->getLocation();
8846  return SourceLocation();
8847}
8848
8849static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
8850  switch ((Sema::TemplateDeductionResult)DFI.Result) {
8851  case Sema::TDK_Success:
8852    llvm_unreachable("TDK_success while diagnosing bad deduction");
8853
8854  case Sema::TDK_Invalid:
8855  case Sema::TDK_Incomplete:
8856    return 1;
8857
8858  case Sema::TDK_Underqualified:
8859  case Sema::TDK_Inconsistent:
8860    return 2;
8861
8862  case Sema::TDK_SubstitutionFailure:
8863  case Sema::TDK_NonDeducedMismatch:
8864  case Sema::TDK_MiscellaneousDeductionFailure:
8865    return 3;
8866
8867  case Sema::TDK_InstantiationDepth:
8868  case Sema::TDK_FailedOverloadResolution:
8869    return 4;
8870
8871  case Sema::TDK_InvalidExplicitArguments:
8872    return 5;
8873
8874  case Sema::TDK_TooManyArguments:
8875  case Sema::TDK_TooFewArguments:
8876    return 6;
8877  }
8878  llvm_unreachable("Unhandled deduction result");
8879}
8880
8881struct CompareOverloadCandidatesForDisplay {
8882  Sema &S;
8883  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8884
8885  bool operator()(const OverloadCandidate *L,
8886                  const OverloadCandidate *R) {
8887    // Fast-path this check.
8888    if (L == R) return false;
8889
8890    // Order first by viability.
8891    if (L->Viable) {
8892      if (!R->Viable) return true;
8893
8894      // TODO: introduce a tri-valued comparison for overload
8895      // candidates.  Would be more worthwhile if we had a sort
8896      // that could exploit it.
8897      if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8898      if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8899    } else if (R->Viable)
8900      return false;
8901
8902    assert(L->Viable == R->Viable);
8903
8904    // Criteria by which we can sort non-viable candidates:
8905    if (!L->Viable) {
8906      // 1. Arity mismatches come after other candidates.
8907      if (L->FailureKind == ovl_fail_too_many_arguments ||
8908          L->FailureKind == ovl_fail_too_few_arguments)
8909        return false;
8910      if (R->FailureKind == ovl_fail_too_many_arguments ||
8911          R->FailureKind == ovl_fail_too_few_arguments)
8912        return true;
8913
8914      // 2. Bad conversions come first and are ordered by the number
8915      // of bad conversions and quality of good conversions.
8916      if (L->FailureKind == ovl_fail_bad_conversion) {
8917        if (R->FailureKind != ovl_fail_bad_conversion)
8918          return true;
8919
8920        // The conversion that can be fixed with a smaller number of changes,
8921        // comes first.
8922        unsigned numLFixes = L->Fix.NumConversionsFixed;
8923        unsigned numRFixes = R->Fix.NumConversionsFixed;
8924        numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8925        numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8926        if (numLFixes != numRFixes) {
8927          if (numLFixes < numRFixes)
8928            return true;
8929          else
8930            return false;
8931        }
8932
8933        // If there's any ordering between the defined conversions...
8934        // FIXME: this might not be transitive.
8935        assert(L->NumConversions == R->NumConversions);
8936
8937        int leftBetter = 0;
8938        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8939        for (unsigned E = L->NumConversions; I != E; ++I) {
8940          switch (CompareImplicitConversionSequences(S,
8941                                                     L->Conversions[I],
8942                                                     R->Conversions[I])) {
8943          case ImplicitConversionSequence::Better:
8944            leftBetter++;
8945            break;
8946
8947          case ImplicitConversionSequence::Worse:
8948            leftBetter--;
8949            break;
8950
8951          case ImplicitConversionSequence::Indistinguishable:
8952            break;
8953          }
8954        }
8955        if (leftBetter > 0) return true;
8956        if (leftBetter < 0) return false;
8957
8958      } else if (R->FailureKind == ovl_fail_bad_conversion)
8959        return false;
8960
8961      if (L->FailureKind == ovl_fail_bad_deduction) {
8962        if (R->FailureKind != ovl_fail_bad_deduction)
8963          return true;
8964
8965        if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8966          return RankDeductionFailure(L->DeductionFailure)
8967               < RankDeductionFailure(R->DeductionFailure);
8968      } else if (R->FailureKind == ovl_fail_bad_deduction)
8969        return false;
8970
8971      // TODO: others?
8972    }
8973
8974    // Sort everything else by location.
8975    SourceLocation LLoc = GetLocationForCandidate(L);
8976    SourceLocation RLoc = GetLocationForCandidate(R);
8977
8978    // Put candidates without locations (e.g. builtins) at the end.
8979    if (LLoc.isInvalid()) return false;
8980    if (RLoc.isInvalid()) return true;
8981
8982    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8983  }
8984};
8985
8986/// CompleteNonViableCandidate - Normally, overload resolution only
8987/// computes up to the first. Produces the FixIt set if possible.
8988void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8989                                ArrayRef<Expr *> Args) {
8990  assert(!Cand->Viable);
8991
8992  // Don't do anything on failures other than bad conversion.
8993  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8994
8995  // We only want the FixIts if all the arguments can be corrected.
8996  bool Unfixable = false;
8997  // Use a implicit copy initialization to check conversion fixes.
8998  Cand->Fix.setConversionChecker(TryCopyInitialization);
8999
9000  // Skip forward to the first bad conversion.
9001  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9002  unsigned ConvCount = Cand->NumConversions;
9003  while (true) {
9004    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9005    ConvIdx++;
9006    if (Cand->Conversions[ConvIdx - 1].isBad()) {
9007      Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9008      break;
9009    }
9010  }
9011
9012  if (ConvIdx == ConvCount)
9013    return;
9014
9015  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9016         "remaining conversion is initialized?");
9017
9018  // FIXME: this should probably be preserved from the overload
9019  // operation somehow.
9020  bool SuppressUserConversions = false;
9021
9022  const FunctionProtoType* Proto;
9023  unsigned ArgIdx = ConvIdx;
9024
9025  if (Cand->IsSurrogate) {
9026    QualType ConvType
9027      = Cand->Surrogate->getConversionType().getNonReferenceType();
9028    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9029      ConvType = ConvPtrType->getPointeeType();
9030    Proto = ConvType->getAs<FunctionProtoType>();
9031    ArgIdx--;
9032  } else if (Cand->Function) {
9033    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9034    if (isa<CXXMethodDecl>(Cand->Function) &&
9035        !isa<CXXConstructorDecl>(Cand->Function))
9036      ArgIdx--;
9037  } else {
9038    // Builtin binary operator with a bad first conversion.
9039    assert(ConvCount <= 3);
9040    for (; ConvIdx != ConvCount; ++ConvIdx)
9041      Cand->Conversions[ConvIdx]
9042        = TryCopyInitialization(S, Args[ConvIdx],
9043                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
9044                                SuppressUserConversions,
9045                                /*InOverloadResolution*/ true,
9046                                /*AllowObjCWritebackConversion=*/
9047                                  S.getLangOpts().ObjCAutoRefCount);
9048    return;
9049  }
9050
9051  // Fill in the rest of the conversions.
9052  unsigned NumArgsInProto = Proto->getNumArgs();
9053  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9054    if (ArgIdx < NumArgsInProto) {
9055      Cand->Conversions[ConvIdx]
9056        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
9057                                SuppressUserConversions,
9058                                /*InOverloadResolution=*/true,
9059                                /*AllowObjCWritebackConversion=*/
9060                                  S.getLangOpts().ObjCAutoRefCount);
9061      // Store the FixIt in the candidate if it exists.
9062      if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9063        Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9064    }
9065    else
9066      Cand->Conversions[ConvIdx].setEllipsis();
9067  }
9068}
9069
9070} // end anonymous namespace
9071
9072/// PrintOverloadCandidates - When overload resolution fails, prints
9073/// diagnostic messages containing the candidates in the candidate
9074/// set.
9075void OverloadCandidateSet::NoteCandidates(Sema &S,
9076                                          OverloadCandidateDisplayKind OCD,
9077                                          ArrayRef<Expr *> Args,
9078                                          StringRef Opc,
9079                                          SourceLocation OpLoc) {
9080  // Sort the candidates by viability and position.  Sorting directly would
9081  // be prohibitive, so we make a set of pointers and sort those.
9082  SmallVector<OverloadCandidate*, 32> Cands;
9083  if (OCD == OCD_AllCandidates) Cands.reserve(size());
9084  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9085    if (Cand->Viable)
9086      Cands.push_back(Cand);
9087    else if (OCD == OCD_AllCandidates) {
9088      CompleteNonViableCandidate(S, Cand, Args);
9089      if (Cand->Function || Cand->IsSurrogate)
9090        Cands.push_back(Cand);
9091      // Otherwise, this a non-viable builtin candidate.  We do not, in general,
9092      // want to list every possible builtin candidate.
9093    }
9094  }
9095
9096  std::sort(Cands.begin(), Cands.end(),
9097            CompareOverloadCandidatesForDisplay(S));
9098
9099  bool ReportedAmbiguousConversions = false;
9100
9101  SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9102  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9103  unsigned CandsShown = 0;
9104  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9105    OverloadCandidate *Cand = *I;
9106
9107    // Set an arbitrary limit on the number of candidate functions we'll spam
9108    // the user with.  FIXME: This limit should depend on details of the
9109    // candidate list.
9110    if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9111      break;
9112    }
9113    ++CandsShown;
9114
9115    if (Cand->Function)
9116      NoteFunctionCandidate(S, Cand, Args.size());
9117    else if (Cand->IsSurrogate)
9118      NoteSurrogateCandidate(S, Cand);
9119    else {
9120      assert(Cand->Viable &&
9121             "Non-viable built-in candidates are not added to Cands.");
9122      // Generally we only see ambiguities including viable builtin
9123      // operators if overload resolution got screwed up by an
9124      // ambiguous user-defined conversion.
9125      //
9126      // FIXME: It's quite possible for different conversions to see
9127      // different ambiguities, though.
9128      if (!ReportedAmbiguousConversions) {
9129        NoteAmbiguousUserConversions(S, OpLoc, Cand);
9130        ReportedAmbiguousConversions = true;
9131      }
9132
9133      // If this is a viable builtin, print it.
9134      NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9135    }
9136  }
9137
9138  if (I != E)
9139    S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9140}
9141
9142static SourceLocation
9143GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9144  return Cand->Specialization ? Cand->Specialization->getLocation()
9145                              : SourceLocation();
9146}
9147
9148struct CompareTemplateSpecCandidatesForDisplay {
9149  Sema &S;
9150  CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9151
9152  bool operator()(const TemplateSpecCandidate *L,
9153                  const TemplateSpecCandidate *R) {
9154    // Fast-path this check.
9155    if (L == R)
9156      return false;
9157
9158    // Assuming that both candidates are not matches...
9159
9160    // Sort by the ranking of deduction failures.
9161    if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9162      return RankDeductionFailure(L->DeductionFailure) <
9163             RankDeductionFailure(R->DeductionFailure);
9164
9165    // Sort everything else by location.
9166    SourceLocation LLoc = GetLocationForCandidate(L);
9167    SourceLocation RLoc = GetLocationForCandidate(R);
9168
9169    // Put candidates without locations (e.g. builtins) at the end.
9170    if (LLoc.isInvalid())
9171      return false;
9172    if (RLoc.isInvalid())
9173      return true;
9174
9175    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9176  }
9177};
9178
9179/// Diagnose a template argument deduction failure.
9180/// We are treating these failures as overload failures due to bad
9181/// deductions.
9182void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9183  DiagnoseBadDeduction(S, Specialization, // pattern
9184                       DeductionFailure, /*NumArgs=*/0);
9185}
9186
9187void TemplateSpecCandidateSet::destroyCandidates() {
9188  for (iterator i = begin(), e = end(); i != e; ++i) {
9189    i->DeductionFailure.Destroy();
9190  }
9191}
9192
9193void TemplateSpecCandidateSet::clear() {
9194  destroyCandidates();
9195  Candidates.clear();
9196}
9197
9198/// NoteCandidates - When no template specialization match is found, prints
9199/// diagnostic messages containing the non-matching specializations that form
9200/// the candidate set.
9201/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9202/// OCD == OCD_AllCandidates and Cand->Viable == false.
9203void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9204  // Sort the candidates by position (assuming no candidate is a match).
9205  // Sorting directly would be prohibitive, so we make a set of pointers
9206  // and sort those.
9207  SmallVector<TemplateSpecCandidate *, 32> Cands;
9208  Cands.reserve(size());
9209  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9210    if (Cand->Specialization)
9211      Cands.push_back(Cand);
9212    // Otherwise, this is a non matching builtin candidate.  We do not,
9213    // in general, want to list every possible builtin candidate.
9214  }
9215
9216  std::sort(Cands.begin(), Cands.end(),
9217            CompareTemplateSpecCandidatesForDisplay(S));
9218
9219  // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9220  // for generalization purposes (?).
9221  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9222
9223  SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9224  unsigned CandsShown = 0;
9225  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9226    TemplateSpecCandidate *Cand = *I;
9227
9228    // Set an arbitrary limit on the number of candidates we'll spam
9229    // the user with.  FIXME: This limit should depend on details of the
9230    // candidate list.
9231    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9232      break;
9233    ++CandsShown;
9234
9235    assert(Cand->Specialization &&
9236           "Non-matching built-in candidates are not added to Cands.");
9237    Cand->NoteDeductionFailure(S);
9238  }
9239
9240  if (I != E)
9241    S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9242}
9243
9244// [PossiblyAFunctionType]  -->   [Return]
9245// NonFunctionType --> NonFunctionType
9246// R (A) --> R(A)
9247// R (*)(A) --> R (A)
9248// R (&)(A) --> R (A)
9249// R (S::*)(A) --> R (A)
9250QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9251  QualType Ret = PossiblyAFunctionType;
9252  if (const PointerType *ToTypePtr =
9253    PossiblyAFunctionType->getAs<PointerType>())
9254    Ret = ToTypePtr->getPointeeType();
9255  else if (const ReferenceType *ToTypeRef =
9256    PossiblyAFunctionType->getAs<ReferenceType>())
9257    Ret = ToTypeRef->getPointeeType();
9258  else if (const MemberPointerType *MemTypePtr =
9259    PossiblyAFunctionType->getAs<MemberPointerType>())
9260    Ret = MemTypePtr->getPointeeType();
9261  Ret =
9262    Context.getCanonicalType(Ret).getUnqualifiedType();
9263  return Ret;
9264}
9265
9266// A helper class to help with address of function resolution
9267// - allows us to avoid passing around all those ugly parameters
9268class AddressOfFunctionResolver
9269{
9270  Sema& S;
9271  Expr* SourceExpr;
9272  const QualType& TargetType;
9273  QualType TargetFunctionType; // Extracted function type from target type
9274
9275  bool Complain;
9276  //DeclAccessPair& ResultFunctionAccessPair;
9277  ASTContext& Context;
9278
9279  bool TargetTypeIsNonStaticMemberFunction;
9280  bool FoundNonTemplateFunction;
9281  bool StaticMemberFunctionFromBoundPointer;
9282
9283  OverloadExpr::FindResult OvlExprInfo;
9284  OverloadExpr *OvlExpr;
9285  TemplateArgumentListInfo OvlExplicitTemplateArgs;
9286  SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9287  TemplateSpecCandidateSet FailedCandidates;
9288
9289public:
9290  AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9291                            const QualType &TargetType, bool Complain)
9292      : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9293        Complain(Complain), Context(S.getASTContext()),
9294        TargetTypeIsNonStaticMemberFunction(
9295            !!TargetType->getAs<MemberPointerType>()),
9296        FoundNonTemplateFunction(false),
9297        StaticMemberFunctionFromBoundPointer(false),
9298        OvlExprInfo(OverloadExpr::find(SourceExpr)),
9299        OvlExpr(OvlExprInfo.Expression),
9300        FailedCandidates(OvlExpr->getNameLoc()) {
9301    ExtractUnqualifiedFunctionTypeFromTargetType();
9302
9303    if (TargetFunctionType->isFunctionType()) {
9304      if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9305        if (!UME->isImplicitAccess() &&
9306            !S.ResolveSingleFunctionTemplateSpecialization(UME))
9307          StaticMemberFunctionFromBoundPointer = true;
9308    } else if (OvlExpr->hasExplicitTemplateArgs()) {
9309      DeclAccessPair dap;
9310      if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9311              OvlExpr, false, &dap)) {
9312        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9313          if (!Method->isStatic()) {
9314            // If the target type is a non-function type and the function found
9315            // is a non-static member function, pretend as if that was the
9316            // target, it's the only possible type to end up with.
9317            TargetTypeIsNonStaticMemberFunction = true;
9318
9319            // And skip adding the function if its not in the proper form.
9320            // We'll diagnose this due to an empty set of functions.
9321            if (!OvlExprInfo.HasFormOfMemberPointer)
9322              return;
9323          }
9324
9325        Matches.push_back(std::make_pair(dap, Fn));
9326      }
9327      return;
9328    }
9329
9330    if (OvlExpr->hasExplicitTemplateArgs())
9331      OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9332
9333    if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9334      // C++ [over.over]p4:
9335      //   If more than one function is selected, [...]
9336      if (Matches.size() > 1) {
9337        if (FoundNonTemplateFunction)
9338          EliminateAllTemplateMatches();
9339        else
9340          EliminateAllExceptMostSpecializedTemplate();
9341      }
9342    }
9343  }
9344
9345private:
9346  bool isTargetTypeAFunction() const {
9347    return TargetFunctionType->isFunctionType();
9348  }
9349
9350  // [ToType]     [Return]
9351
9352  // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9353  // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9354  // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9355  void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9356    TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9357  }
9358
9359  // return true if any matching specializations were found
9360  bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9361                                   const DeclAccessPair& CurAccessFunPair) {
9362    if (CXXMethodDecl *Method
9363              = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9364      // Skip non-static function templates when converting to pointer, and
9365      // static when converting to member pointer.
9366      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9367        return false;
9368    }
9369    else if (TargetTypeIsNonStaticMemberFunction)
9370      return false;
9371
9372    // C++ [over.over]p2:
9373    //   If the name is a function template, template argument deduction is
9374    //   done (14.8.2.2), and if the argument deduction succeeds, the
9375    //   resulting template argument list is used to generate a single
9376    //   function template specialization, which is added to the set of
9377    //   overloaded functions considered.
9378    FunctionDecl *Specialization = 0;
9379    TemplateDeductionInfo Info(FailedCandidates.getLocation());
9380    if (Sema::TemplateDeductionResult Result
9381          = S.DeduceTemplateArguments(FunctionTemplate,
9382                                      &OvlExplicitTemplateArgs,
9383                                      TargetFunctionType, Specialization,
9384                                      Info, /*InOverloadResolution=*/true)) {
9385      // Make a note of the failed deduction for diagnostics.
9386      FailedCandidates.addCandidate()
9387          .set(FunctionTemplate->getTemplatedDecl(),
9388               MakeDeductionFailureInfo(Context, Result, Info));
9389      return false;
9390    }
9391
9392    // Template argument deduction ensures that we have an exact match or
9393    // compatible pointer-to-function arguments that would be adjusted by ICS.
9394    // This function template specicalization works.
9395    Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9396    assert(S.isSameOrCompatibleFunctionType(
9397              Context.getCanonicalType(Specialization->getType()),
9398              Context.getCanonicalType(TargetFunctionType)));
9399    Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9400    return true;
9401  }
9402
9403  bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9404                                      const DeclAccessPair& CurAccessFunPair) {
9405    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9406      // Skip non-static functions when converting to pointer, and static
9407      // when converting to member pointer.
9408      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9409        return false;
9410    }
9411    else if (TargetTypeIsNonStaticMemberFunction)
9412      return false;
9413
9414    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9415      if (S.getLangOpts().CUDA)
9416        if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9417          if (S.CheckCUDATarget(Caller, FunDecl))
9418            return false;
9419
9420      // If any candidate has a placeholder return type, trigger its deduction
9421      // now.
9422      if (S.getLangOpts().CPlusPlus1y &&
9423          FunDecl->getResultType()->isUndeducedType() &&
9424          S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9425        return false;
9426
9427      QualType ResultTy;
9428      if (Context.hasSameUnqualifiedType(TargetFunctionType,
9429                                         FunDecl->getType()) ||
9430          S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9431                                 ResultTy)) {
9432        Matches.push_back(std::make_pair(CurAccessFunPair,
9433          cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9434        FoundNonTemplateFunction = true;
9435        return true;
9436      }
9437    }
9438
9439    return false;
9440  }
9441
9442  bool FindAllFunctionsThatMatchTargetTypeExactly() {
9443    bool Ret = false;
9444
9445    // If the overload expression doesn't have the form of a pointer to
9446    // member, don't try to convert it to a pointer-to-member type.
9447    if (IsInvalidFormOfPointerToMemberFunction())
9448      return false;
9449
9450    for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9451                               E = OvlExpr->decls_end();
9452         I != E; ++I) {
9453      // Look through any using declarations to find the underlying function.
9454      NamedDecl *Fn = (*I)->getUnderlyingDecl();
9455
9456      // C++ [over.over]p3:
9457      //   Non-member functions and static member functions match
9458      //   targets of type "pointer-to-function" or "reference-to-function."
9459      //   Nonstatic member functions match targets of
9460      //   type "pointer-to-member-function."
9461      // Note that according to DR 247, the containing class does not matter.
9462      if (FunctionTemplateDecl *FunctionTemplate
9463                                        = dyn_cast<FunctionTemplateDecl>(Fn)) {
9464        if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9465          Ret = true;
9466      }
9467      // If we have explicit template arguments supplied, skip non-templates.
9468      else if (!OvlExpr->hasExplicitTemplateArgs() &&
9469               AddMatchingNonTemplateFunction(Fn, I.getPair()))
9470        Ret = true;
9471    }
9472    assert(Ret || Matches.empty());
9473    return Ret;
9474  }
9475
9476  void EliminateAllExceptMostSpecializedTemplate() {
9477    //   [...] and any given function template specialization F1 is
9478    //   eliminated if the set contains a second function template
9479    //   specialization whose function template is more specialized
9480    //   than the function template of F1 according to the partial
9481    //   ordering rules of 14.5.5.2.
9482
9483    // The algorithm specified above is quadratic. We instead use a
9484    // two-pass algorithm (similar to the one used to identify the
9485    // best viable function in an overload set) that identifies the
9486    // best function template (if it exists).
9487
9488    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9489    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9490      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9491
9492    // TODO: It looks like FailedCandidates does not serve much purpose
9493    // here, since the no_viable diagnostic has index 0.
9494    UnresolvedSetIterator Result = S.getMostSpecialized(
9495        MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
9496        SourceExpr->getLocStart(), S.PDiag(),
9497        S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9498                                                     .second->getDeclName(),
9499        S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9500        Complain, TargetFunctionType);
9501
9502    if (Result != MatchesCopy.end()) {
9503      // Make it the first and only element
9504      Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9505      Matches[0].second = cast<FunctionDecl>(*Result);
9506      Matches.resize(1);
9507    }
9508  }
9509
9510  void EliminateAllTemplateMatches() {
9511    //   [...] any function template specializations in the set are
9512    //   eliminated if the set also contains a non-template function, [...]
9513    for (unsigned I = 0, N = Matches.size(); I != N; ) {
9514      if (Matches[I].second->getPrimaryTemplate() == 0)
9515        ++I;
9516      else {
9517        Matches[I] = Matches[--N];
9518        Matches.set_size(N);
9519      }
9520    }
9521  }
9522
9523public:
9524  void ComplainNoMatchesFound() const {
9525    assert(Matches.empty());
9526    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9527        << OvlExpr->getName() << TargetFunctionType
9528        << OvlExpr->getSourceRange();
9529    if (FailedCandidates.empty())
9530      S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9531    else {
9532      // We have some deduction failure messages. Use them to diagnose
9533      // the function templates, and diagnose the non-template candidates
9534      // normally.
9535      for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9536                                 IEnd = OvlExpr->decls_end();
9537           I != IEnd; ++I)
9538        if (FunctionDecl *Fun =
9539                dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9540          S.NoteOverloadCandidate(Fun, TargetFunctionType);
9541      FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9542    }
9543  }
9544
9545  bool IsInvalidFormOfPointerToMemberFunction() const {
9546    return TargetTypeIsNonStaticMemberFunction &&
9547      !OvlExprInfo.HasFormOfMemberPointer;
9548  }
9549
9550  void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9551      // TODO: Should we condition this on whether any functions might
9552      // have matched, or is it more appropriate to do that in callers?
9553      // TODO: a fixit wouldn't hurt.
9554      S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9555        << TargetType << OvlExpr->getSourceRange();
9556  }
9557
9558  bool IsStaticMemberFunctionFromBoundPointer() const {
9559    return StaticMemberFunctionFromBoundPointer;
9560  }
9561
9562  void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9563    S.Diag(OvlExpr->getLocStart(),
9564           diag::err_invalid_form_pointer_member_function)
9565      << OvlExpr->getSourceRange();
9566  }
9567
9568  void ComplainOfInvalidConversion() const {
9569    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9570      << OvlExpr->getName() << TargetType;
9571  }
9572
9573  void ComplainMultipleMatchesFound() const {
9574    assert(Matches.size() > 1);
9575    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9576      << OvlExpr->getName()
9577      << OvlExpr->getSourceRange();
9578    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9579  }
9580
9581  bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9582
9583  int getNumMatches() const { return Matches.size(); }
9584
9585  FunctionDecl* getMatchingFunctionDecl() const {
9586    if (Matches.size() != 1) return 0;
9587    return Matches[0].second;
9588  }
9589
9590  const DeclAccessPair* getMatchingFunctionAccessPair() const {
9591    if (Matches.size() != 1) return 0;
9592    return &Matches[0].first;
9593  }
9594};
9595
9596/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9597/// an overloaded function (C++ [over.over]), where @p From is an
9598/// expression with overloaded function type and @p ToType is the type
9599/// we're trying to resolve to. For example:
9600///
9601/// @code
9602/// int f(double);
9603/// int f(int);
9604///
9605/// int (*pfd)(double) = f; // selects f(double)
9606/// @endcode
9607///
9608/// This routine returns the resulting FunctionDecl if it could be
9609/// resolved, and NULL otherwise. When @p Complain is true, this
9610/// routine will emit diagnostics if there is an error.
9611FunctionDecl *
9612Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9613                                         QualType TargetType,
9614                                         bool Complain,
9615                                         DeclAccessPair &FoundResult,
9616                                         bool *pHadMultipleCandidates) {
9617  assert(AddressOfExpr->getType() == Context.OverloadTy);
9618
9619  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9620                                     Complain);
9621  int NumMatches = Resolver.getNumMatches();
9622  FunctionDecl* Fn = 0;
9623  if (NumMatches == 0 && Complain) {
9624    if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9625      Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9626    else
9627      Resolver.ComplainNoMatchesFound();
9628  }
9629  else if (NumMatches > 1 && Complain)
9630    Resolver.ComplainMultipleMatchesFound();
9631  else if (NumMatches == 1) {
9632    Fn = Resolver.getMatchingFunctionDecl();
9633    assert(Fn);
9634    FoundResult = *Resolver.getMatchingFunctionAccessPair();
9635    if (Complain) {
9636      if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9637        Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9638      else
9639        CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9640    }
9641  }
9642
9643  if (pHadMultipleCandidates)
9644    *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9645  return Fn;
9646}
9647
9648/// \brief Given an expression that refers to an overloaded function, try to
9649/// resolve that overloaded function expression down to a single function.
9650///
9651/// This routine can only resolve template-ids that refer to a single function
9652/// template, where that template-id refers to a single template whose template
9653/// arguments are either provided by the template-id or have defaults,
9654/// as described in C++0x [temp.arg.explicit]p3.
9655FunctionDecl *
9656Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9657                                                  bool Complain,
9658                                                  DeclAccessPair *FoundResult) {
9659  // C++ [over.over]p1:
9660  //   [...] [Note: any redundant set of parentheses surrounding the
9661  //   overloaded function name is ignored (5.1). ]
9662  // C++ [over.over]p1:
9663  //   [...] The overloaded function name can be preceded by the &
9664  //   operator.
9665
9666  // If we didn't actually find any template-ids, we're done.
9667  if (!ovl->hasExplicitTemplateArgs())
9668    return 0;
9669
9670  TemplateArgumentListInfo ExplicitTemplateArgs;
9671  ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9672  TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
9673
9674  // Look through all of the overloaded functions, searching for one
9675  // whose type matches exactly.
9676  FunctionDecl *Matched = 0;
9677  for (UnresolvedSetIterator I = ovl->decls_begin(),
9678         E = ovl->decls_end(); I != E; ++I) {
9679    // C++0x [temp.arg.explicit]p3:
9680    //   [...] In contexts where deduction is done and fails, or in contexts
9681    //   where deduction is not done, if a template argument list is
9682    //   specified and it, along with any default template arguments,
9683    //   identifies a single function template specialization, then the
9684    //   template-id is an lvalue for the function template specialization.
9685    FunctionTemplateDecl *FunctionTemplate
9686      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9687
9688    // C++ [over.over]p2:
9689    //   If the name is a function template, template argument deduction is
9690    //   done (14.8.2.2), and if the argument deduction succeeds, the
9691    //   resulting template argument list is used to generate a single
9692    //   function template specialization, which is added to the set of
9693    //   overloaded functions considered.
9694    FunctionDecl *Specialization = 0;
9695    TemplateDeductionInfo Info(FailedCandidates.getLocation());
9696    if (TemplateDeductionResult Result
9697          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9698                                    Specialization, Info,
9699                                    /*InOverloadResolution=*/true)) {
9700      // Make a note of the failed deduction for diagnostics.
9701      // TODO: Actually use the failed-deduction info?
9702      FailedCandidates.addCandidate()
9703          .set(FunctionTemplate->getTemplatedDecl(),
9704               MakeDeductionFailureInfo(Context, Result, Info));
9705      continue;
9706    }
9707
9708    assert(Specialization && "no specialization and no error?");
9709
9710    // Multiple matches; we can't resolve to a single declaration.
9711    if (Matched) {
9712      if (Complain) {
9713        Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9714          << ovl->getName();
9715        NoteAllOverloadCandidates(ovl);
9716      }
9717      return 0;
9718    }
9719
9720    Matched = Specialization;
9721    if (FoundResult) *FoundResult = I.getPair();
9722  }
9723
9724  if (Matched && getLangOpts().CPlusPlus1y &&
9725      Matched->getResultType()->isUndeducedType() &&
9726      DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9727    return 0;
9728
9729  return Matched;
9730}
9731
9732
9733
9734
9735// Resolve and fix an overloaded expression that can be resolved
9736// because it identifies a single function template specialization.
9737//
9738// Last three arguments should only be supplied if Complain = true
9739//
9740// Return true if it was logically possible to so resolve the
9741// expression, regardless of whether or not it succeeded.  Always
9742// returns true if 'complain' is set.
9743bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9744                      ExprResult &SrcExpr, bool doFunctionPointerConverion,
9745                   bool complain, const SourceRange& OpRangeForComplaining,
9746                                           QualType DestTypeForComplaining,
9747                                            unsigned DiagIDForComplaining) {
9748  assert(SrcExpr.get()->getType() == Context.OverloadTy);
9749
9750  OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9751
9752  DeclAccessPair found;
9753  ExprResult SingleFunctionExpression;
9754  if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9755                           ovl.Expression, /*complain*/ false, &found)) {
9756    if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9757      SrcExpr = ExprError();
9758      return true;
9759    }
9760
9761    // It is only correct to resolve to an instance method if we're
9762    // resolving a form that's permitted to be a pointer to member.
9763    // Otherwise we'll end up making a bound member expression, which
9764    // is illegal in all the contexts we resolve like this.
9765    if (!ovl.HasFormOfMemberPointer &&
9766        isa<CXXMethodDecl>(fn) &&
9767        cast<CXXMethodDecl>(fn)->isInstance()) {
9768      if (!complain) return false;
9769
9770      Diag(ovl.Expression->getExprLoc(),
9771           diag::err_bound_member_function)
9772        << 0 << ovl.Expression->getSourceRange();
9773
9774      // TODO: I believe we only end up here if there's a mix of
9775      // static and non-static candidates (otherwise the expression
9776      // would have 'bound member' type, not 'overload' type).
9777      // Ideally we would note which candidate was chosen and why
9778      // the static candidates were rejected.
9779      SrcExpr = ExprError();
9780      return true;
9781    }
9782
9783    // Fix the expression to refer to 'fn'.
9784    SingleFunctionExpression =
9785      Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9786
9787    // If desired, do function-to-pointer decay.
9788    if (doFunctionPointerConverion) {
9789      SingleFunctionExpression =
9790        DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9791      if (SingleFunctionExpression.isInvalid()) {
9792        SrcExpr = ExprError();
9793        return true;
9794      }
9795    }
9796  }
9797
9798  if (!SingleFunctionExpression.isUsable()) {
9799    if (complain) {
9800      Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9801        << ovl.Expression->getName()
9802        << DestTypeForComplaining
9803        << OpRangeForComplaining
9804        << ovl.Expression->getQualifierLoc().getSourceRange();
9805      NoteAllOverloadCandidates(SrcExpr.get());
9806
9807      SrcExpr = ExprError();
9808      return true;
9809    }
9810
9811    return false;
9812  }
9813
9814  SrcExpr = SingleFunctionExpression;
9815  return true;
9816}
9817
9818/// \brief Add a single candidate to the overload set.
9819static void AddOverloadedCallCandidate(Sema &S,
9820                                       DeclAccessPair FoundDecl,
9821                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
9822                                       ArrayRef<Expr *> Args,
9823                                       OverloadCandidateSet &CandidateSet,
9824                                       bool PartialOverloading,
9825                                       bool KnownValid) {
9826  NamedDecl *Callee = FoundDecl.getDecl();
9827  if (isa<UsingShadowDecl>(Callee))
9828    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9829
9830  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9831    if (ExplicitTemplateArgs) {
9832      assert(!KnownValid && "Explicit template arguments?");
9833      return;
9834    }
9835    S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9836                           PartialOverloading);
9837    return;
9838  }
9839
9840  if (FunctionTemplateDecl *FuncTemplate
9841      = dyn_cast<FunctionTemplateDecl>(Callee)) {
9842    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9843                                   ExplicitTemplateArgs, Args, CandidateSet);
9844    return;
9845  }
9846
9847  assert(!KnownValid && "unhandled case in overloaded call candidate");
9848}
9849
9850/// \brief Add the overload candidates named by callee and/or found by argument
9851/// dependent lookup to the given overload set.
9852void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9853                                       ArrayRef<Expr *> Args,
9854                                       OverloadCandidateSet &CandidateSet,
9855                                       bool PartialOverloading) {
9856
9857#ifndef NDEBUG
9858  // Verify that ArgumentDependentLookup is consistent with the rules
9859  // in C++0x [basic.lookup.argdep]p3:
9860  //
9861  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9862  //   and let Y be the lookup set produced by argument dependent
9863  //   lookup (defined as follows). If X contains
9864  //
9865  //     -- a declaration of a class member, or
9866  //
9867  //     -- a block-scope function declaration that is not a
9868  //        using-declaration, or
9869  //
9870  //     -- a declaration that is neither a function or a function
9871  //        template
9872  //
9873  //   then Y is empty.
9874
9875  if (ULE->requiresADL()) {
9876    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9877           E = ULE->decls_end(); I != E; ++I) {
9878      assert(!(*I)->getDeclContext()->isRecord());
9879      assert(isa<UsingShadowDecl>(*I) ||
9880             !(*I)->getDeclContext()->isFunctionOrMethod());
9881      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9882    }
9883  }
9884#endif
9885
9886  // It would be nice to avoid this copy.
9887  TemplateArgumentListInfo TABuffer;
9888  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9889  if (ULE->hasExplicitTemplateArgs()) {
9890    ULE->copyTemplateArgumentsInto(TABuffer);
9891    ExplicitTemplateArgs = &TABuffer;
9892  }
9893
9894  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9895         E = ULE->decls_end(); I != E; ++I)
9896    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9897                               CandidateSet, PartialOverloading,
9898                               /*KnownValid*/ true);
9899
9900  if (ULE->requiresADL())
9901    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9902                                         ULE->getExprLoc(),
9903                                         Args, ExplicitTemplateArgs,
9904                                         CandidateSet, PartialOverloading);
9905}
9906
9907/// Determine whether a declaration with the specified name could be moved into
9908/// a different namespace.
9909static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
9910  switch (Name.getCXXOverloadedOperator()) {
9911  case OO_New: case OO_Array_New:
9912  case OO_Delete: case OO_Array_Delete:
9913    return false;
9914
9915  default:
9916    return true;
9917  }
9918}
9919
9920/// Attempt to recover from an ill-formed use of a non-dependent name in a
9921/// template, where the non-dependent name was declared after the template
9922/// was defined. This is common in code written for a compilers which do not
9923/// correctly implement two-stage name lookup.
9924///
9925/// Returns true if a viable candidate was found and a diagnostic was issued.
9926static bool
9927DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9928                       const CXXScopeSpec &SS, LookupResult &R,
9929                       TemplateArgumentListInfo *ExplicitTemplateArgs,
9930                       ArrayRef<Expr *> Args) {
9931  if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9932    return false;
9933
9934  for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9935    if (DC->isTransparentContext())
9936      continue;
9937
9938    SemaRef.LookupQualifiedName(R, DC);
9939
9940    if (!R.empty()) {
9941      R.suppressDiagnostics();
9942
9943      if (isa<CXXRecordDecl>(DC)) {
9944        // Don't diagnose names we find in classes; we get much better
9945        // diagnostics for these from DiagnoseEmptyLookup.
9946        R.clear();
9947        return false;
9948      }
9949
9950      OverloadCandidateSet Candidates(FnLoc);
9951      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9952        AddOverloadedCallCandidate(SemaRef, I.getPair(),
9953                                   ExplicitTemplateArgs, Args,
9954                                   Candidates, false, /*KnownValid*/ false);
9955
9956      OverloadCandidateSet::iterator Best;
9957      if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9958        // No viable functions. Don't bother the user with notes for functions
9959        // which don't work and shouldn't be found anyway.
9960        R.clear();
9961        return false;
9962      }
9963
9964      // Find the namespaces where ADL would have looked, and suggest
9965      // declaring the function there instead.
9966      Sema::AssociatedNamespaceSet AssociatedNamespaces;
9967      Sema::AssociatedClassSet AssociatedClasses;
9968      SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
9969                                                 AssociatedNamespaces,
9970                                                 AssociatedClasses);
9971      Sema::AssociatedNamespaceSet SuggestedNamespaces;
9972      if (canBeDeclaredInNamespace(R.getLookupName())) {
9973        DeclContext *Std = SemaRef.getStdNamespace();
9974        for (Sema::AssociatedNamespaceSet::iterator
9975               it = AssociatedNamespaces.begin(),
9976               end = AssociatedNamespaces.end(); it != end; ++it) {
9977          // Never suggest declaring a function within namespace 'std'.
9978          if (Std && Std->Encloses(*it))
9979            continue;
9980
9981          // Never suggest declaring a function within a namespace with a
9982          // reserved name, like __gnu_cxx.
9983          NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9984          if (NS &&
9985              NS->getQualifiedNameAsString().find("__") != std::string::npos)
9986            continue;
9987
9988          SuggestedNamespaces.insert(*it);
9989        }
9990      }
9991
9992      SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9993        << R.getLookupName();
9994      if (SuggestedNamespaces.empty()) {
9995        SemaRef.Diag(Best->Function->getLocation(),
9996                     diag::note_not_found_by_two_phase_lookup)
9997          << R.getLookupName() << 0;
9998      } else if (SuggestedNamespaces.size() == 1) {
9999        SemaRef.Diag(Best->Function->getLocation(),
10000                     diag::note_not_found_by_two_phase_lookup)
10001          << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10002      } else {
10003        // FIXME: It would be useful to list the associated namespaces here,
10004        // but the diagnostics infrastructure doesn't provide a way to produce
10005        // a localized representation of a list of items.
10006        SemaRef.Diag(Best->Function->getLocation(),
10007                     diag::note_not_found_by_two_phase_lookup)
10008          << R.getLookupName() << 2;
10009      }
10010
10011      // Try to recover by calling this function.
10012      return true;
10013    }
10014
10015    R.clear();
10016  }
10017
10018  return false;
10019}
10020
10021/// Attempt to recover from ill-formed use of a non-dependent operator in a
10022/// template, where the non-dependent operator was declared after the template
10023/// was defined.
10024///
10025/// Returns true if a viable candidate was found and a diagnostic was issued.
10026static bool
10027DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10028                               SourceLocation OpLoc,
10029                               ArrayRef<Expr *> Args) {
10030  DeclarationName OpName =
10031    SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10032  LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10033  return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10034                                /*ExplicitTemplateArgs=*/0, Args);
10035}
10036
10037namespace {
10038class BuildRecoveryCallExprRAII {
10039  Sema &SemaRef;
10040public:
10041  BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10042    assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10043    SemaRef.IsBuildingRecoveryCallExpr = true;
10044  }
10045
10046  ~BuildRecoveryCallExprRAII() {
10047    SemaRef.IsBuildingRecoveryCallExpr = false;
10048  }
10049};
10050
10051}
10052
10053/// Attempts to recover from a call where no functions were found.
10054///
10055/// Returns true if new candidates were found.
10056static ExprResult
10057BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10058                      UnresolvedLookupExpr *ULE,
10059                      SourceLocation LParenLoc,
10060                      llvm::MutableArrayRef<Expr *> Args,
10061                      SourceLocation RParenLoc,
10062                      bool EmptyLookup, bool AllowTypoCorrection) {
10063  // Do not try to recover if it is already building a recovery call.
10064  // This stops infinite loops for template instantiations like
10065  //
10066  // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10067  // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10068  //
10069  if (SemaRef.IsBuildingRecoveryCallExpr)
10070    return ExprError();
10071  BuildRecoveryCallExprRAII RCE(SemaRef);
10072
10073  CXXScopeSpec SS;
10074  SS.Adopt(ULE->getQualifierLoc());
10075  SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10076
10077  TemplateArgumentListInfo TABuffer;
10078  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
10079  if (ULE->hasExplicitTemplateArgs()) {
10080    ULE->copyTemplateArgumentsInto(TABuffer);
10081    ExplicitTemplateArgs = &TABuffer;
10082  }
10083
10084  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10085                 Sema::LookupOrdinaryName);
10086  FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10087                                  ExplicitTemplateArgs != 0);
10088  NoTypoCorrectionCCC RejectAll;
10089  CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10090      (CorrectionCandidateCallback*)&Validator :
10091      (CorrectionCandidateCallback*)&RejectAll;
10092  if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10093                              ExplicitTemplateArgs, Args) &&
10094      (!EmptyLookup ||
10095       SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
10096                                   ExplicitTemplateArgs, Args)))
10097    return ExprError();
10098
10099  assert(!R.empty() && "lookup results empty despite recovery");
10100
10101  // Build an implicit member call if appropriate.  Just drop the
10102  // casts and such from the call, we don't really care.
10103  ExprResult NewFn = ExprError();
10104  if ((*R.begin())->isCXXClassMember())
10105    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10106                                                    R, ExplicitTemplateArgs);
10107  else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10108    NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10109                                        ExplicitTemplateArgs);
10110  else
10111    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10112
10113  if (NewFn.isInvalid())
10114    return ExprError();
10115
10116  // This shouldn't cause an infinite loop because we're giving it
10117  // an expression with viable lookup results, which should never
10118  // end up here.
10119  return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
10120                               MultiExprArg(Args.data(), Args.size()),
10121                               RParenLoc);
10122}
10123
10124/// \brief Constructs and populates an OverloadedCandidateSet from
10125/// the given function.
10126/// \returns true when an the ExprResult output parameter has been set.
10127bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10128                                  UnresolvedLookupExpr *ULE,
10129                                  MultiExprArg Args,
10130                                  SourceLocation RParenLoc,
10131                                  OverloadCandidateSet *CandidateSet,
10132                                  ExprResult *Result) {
10133#ifndef NDEBUG
10134  if (ULE->requiresADL()) {
10135    // To do ADL, we must have found an unqualified name.
10136    assert(!ULE->getQualifier() && "qualified name with ADL");
10137
10138    // We don't perform ADL for implicit declarations of builtins.
10139    // Verify that this was correctly set up.
10140    FunctionDecl *F;
10141    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10142        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10143        F->getBuiltinID() && F->isImplicit())
10144      llvm_unreachable("performing ADL for builtin");
10145
10146    // We don't perform ADL in C.
10147    assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10148  }
10149#endif
10150
10151  UnbridgedCastsSet UnbridgedCasts;
10152  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10153    *Result = ExprError();
10154    return true;
10155  }
10156
10157  // Add the functions denoted by the callee to the set of candidate
10158  // functions, including those from argument-dependent lookup.
10159  AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10160
10161  // If we found nothing, try to recover.
10162  // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10163  // out if it fails.
10164  if (CandidateSet->empty()) {
10165    // In Microsoft mode, if we are inside a template class member function then
10166    // create a type dependent CallExpr. The goal is to postpone name lookup
10167    // to instantiation time to be able to search into type dependent base
10168    // classes.
10169    if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
10170        (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10171      CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10172                                            Context.DependentTy, VK_RValue,
10173                                            RParenLoc);
10174      CE->setTypeDependent(true);
10175      *Result = Owned(CE);
10176      return true;
10177    }
10178    return false;
10179  }
10180
10181  UnbridgedCasts.restore();
10182  return false;
10183}
10184
10185/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10186/// the completed call expression. If overload resolution fails, emits
10187/// diagnostics and returns ExprError()
10188static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10189                                           UnresolvedLookupExpr *ULE,
10190                                           SourceLocation LParenLoc,
10191                                           MultiExprArg Args,
10192                                           SourceLocation RParenLoc,
10193                                           Expr *ExecConfig,
10194                                           OverloadCandidateSet *CandidateSet,
10195                                           OverloadCandidateSet::iterator *Best,
10196                                           OverloadingResult OverloadResult,
10197                                           bool AllowTypoCorrection) {
10198  if (CandidateSet->empty())
10199    return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10200                                 RParenLoc, /*EmptyLookup=*/true,
10201                                 AllowTypoCorrection);
10202
10203  switch (OverloadResult) {
10204  case OR_Success: {
10205    FunctionDecl *FDecl = (*Best)->Function;
10206    SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10207    if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10208      return ExprError();
10209    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10210    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10211                                         ExecConfig);
10212  }
10213
10214  case OR_No_Viable_Function: {
10215    // Try to recover by looking for viable functions which the user might
10216    // have meant to call.
10217    ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10218                                                Args, RParenLoc,
10219                                                /*EmptyLookup=*/false,
10220                                                AllowTypoCorrection);
10221    if (!Recovery.isInvalid())
10222      return Recovery;
10223
10224    SemaRef.Diag(Fn->getLocStart(),
10225         diag::err_ovl_no_viable_function_in_call)
10226      << ULE->getName() << Fn->getSourceRange();
10227    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10228    break;
10229  }
10230
10231  case OR_Ambiguous:
10232    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10233      << ULE->getName() << Fn->getSourceRange();
10234    CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10235    break;
10236
10237  case OR_Deleted: {
10238    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10239      << (*Best)->Function->isDeleted()
10240      << ULE->getName()
10241      << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10242      << Fn->getSourceRange();
10243    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10244
10245    // We emitted an error for the unvailable/deleted function call but keep
10246    // the call in the AST.
10247    FunctionDecl *FDecl = (*Best)->Function;
10248    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10249    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10250                                         ExecConfig);
10251  }
10252  }
10253
10254  // Overload resolution failed.
10255  return ExprError();
10256}
10257
10258/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10259/// (which eventually refers to the declaration Func) and the call
10260/// arguments Args/NumArgs, attempt to resolve the function call down
10261/// to a specific function. If overload resolution succeeds, returns
10262/// the call expression produced by overload resolution.
10263/// Otherwise, emits diagnostics and returns ExprError.
10264ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10265                                         UnresolvedLookupExpr *ULE,
10266                                         SourceLocation LParenLoc,
10267                                         MultiExprArg Args,
10268                                         SourceLocation RParenLoc,
10269                                         Expr *ExecConfig,
10270                                         bool AllowTypoCorrection) {
10271  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10272  ExprResult result;
10273
10274  if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10275                             &result))
10276    return result;
10277
10278  OverloadCandidateSet::iterator Best;
10279  OverloadingResult OverloadResult =
10280      CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10281
10282  return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10283                                  RParenLoc, ExecConfig, &CandidateSet,
10284                                  &Best, OverloadResult,
10285                                  AllowTypoCorrection);
10286}
10287
10288static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10289  return Functions.size() > 1 ||
10290    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10291}
10292
10293/// \brief Create a unary operation that may resolve to an overloaded
10294/// operator.
10295///
10296/// \param OpLoc The location of the operator itself (e.g., '*').
10297///
10298/// \param OpcIn The UnaryOperator::Opcode that describes this
10299/// operator.
10300///
10301/// \param Fns The set of non-member functions that will be
10302/// considered by overload resolution. The caller needs to build this
10303/// set based on the context using, e.g.,
10304/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10305/// set should not contain any member functions; those will be added
10306/// by CreateOverloadedUnaryOp().
10307///
10308/// \param Input The input argument.
10309ExprResult
10310Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10311                              const UnresolvedSetImpl &Fns,
10312                              Expr *Input) {
10313  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10314
10315  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10316  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10317  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10318  // TODO: provide better source location info.
10319  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10320
10321  if (checkPlaceholderForOverload(*this, Input))
10322    return ExprError();
10323
10324  Expr *Args[2] = { Input, 0 };
10325  unsigned NumArgs = 1;
10326
10327  // For post-increment and post-decrement, add the implicit '0' as
10328  // the second argument, so that we know this is a post-increment or
10329  // post-decrement.
10330  if (Opc == UO_PostInc || Opc == UO_PostDec) {
10331    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10332    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10333                                     SourceLocation());
10334    NumArgs = 2;
10335  }
10336
10337  ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10338
10339  if (Input->isTypeDependent()) {
10340    if (Fns.empty())
10341      return Owned(new (Context) UnaryOperator(Input,
10342                                               Opc,
10343                                               Context.DependentTy,
10344                                               VK_RValue, OK_Ordinary,
10345                                               OpLoc));
10346
10347    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10348    UnresolvedLookupExpr *Fn
10349      = UnresolvedLookupExpr::Create(Context, NamingClass,
10350                                     NestedNameSpecifierLoc(), OpNameInfo,
10351                                     /*ADL*/ true, IsOverloaded(Fns),
10352                                     Fns.begin(), Fns.end());
10353    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
10354                                                   Context.DependentTy,
10355                                                   VK_RValue,
10356                                                   OpLoc, false));
10357  }
10358
10359  // Build an empty overload set.
10360  OverloadCandidateSet CandidateSet(OpLoc);
10361
10362  // Add the candidates from the given function set.
10363  AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
10364
10365  // Add operator candidates that are member functions.
10366  AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10367
10368  // Add candidates from ADL.
10369  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10370                                       ArgsArray, /*ExplicitTemplateArgs*/ 0,
10371                                       CandidateSet);
10372
10373  // Add builtin operator candidates.
10374  AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10375
10376  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10377
10378  // Perform overload resolution.
10379  OverloadCandidateSet::iterator Best;
10380  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10381  case OR_Success: {
10382    // We found a built-in operator or an overloaded operator.
10383    FunctionDecl *FnDecl = Best->Function;
10384
10385    if (FnDecl) {
10386      // We matched an overloaded operator. Build a call to that
10387      // operator.
10388
10389      // Convert the arguments.
10390      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10391        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
10392
10393        ExprResult InputRes =
10394          PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10395                                              Best->FoundDecl, Method);
10396        if (InputRes.isInvalid())
10397          return ExprError();
10398        Input = InputRes.take();
10399      } else {
10400        // Convert the arguments.
10401        ExprResult InputInit
10402          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10403                                                      Context,
10404                                                      FnDecl->getParamDecl(0)),
10405                                      SourceLocation(),
10406                                      Input);
10407        if (InputInit.isInvalid())
10408          return ExprError();
10409        Input = InputInit.take();
10410      }
10411
10412      // Determine the result type.
10413      QualType ResultTy = FnDecl->getResultType();
10414      ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10415      ResultTy = ResultTy.getNonLValueExprType(Context);
10416
10417      // Build the actual expression node.
10418      ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10419                                                HadMultipleCandidates, OpLoc);
10420      if (FnExpr.isInvalid())
10421        return ExprError();
10422
10423      Args[0] = Input;
10424      CallExpr *TheCall =
10425        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
10426                                          ResultTy, VK, OpLoc, false);
10427
10428      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10429                              FnDecl))
10430        return ExprError();
10431
10432      return MaybeBindToTemporary(TheCall);
10433    } else {
10434      // We matched a built-in operator. Convert the arguments, then
10435      // break out so that we will build the appropriate built-in
10436      // operator node.
10437      ExprResult InputRes =
10438        PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10439                                  Best->Conversions[0], AA_Passing);
10440      if (InputRes.isInvalid())
10441        return ExprError();
10442      Input = InputRes.take();
10443      break;
10444    }
10445  }
10446
10447  case OR_No_Viable_Function:
10448    // This is an erroneous use of an operator which can be overloaded by
10449    // a non-member function. Check for non-member operators which were
10450    // defined too late to be candidates.
10451    if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
10452      // FIXME: Recover by calling the found function.
10453      return ExprError();
10454
10455    // No viable function; fall through to handling this as a
10456    // built-in operator, which will produce an error message for us.
10457    break;
10458
10459  case OR_Ambiguous:
10460    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10461        << UnaryOperator::getOpcodeStr(Opc)
10462        << Input->getType()
10463        << Input->getSourceRange();
10464    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
10465                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10466    return ExprError();
10467
10468  case OR_Deleted:
10469    Diag(OpLoc, diag::err_ovl_deleted_oper)
10470      << Best->Function->isDeleted()
10471      << UnaryOperator::getOpcodeStr(Opc)
10472      << getDeletedOrUnavailableSuffix(Best->Function)
10473      << Input->getSourceRange();
10474    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
10475                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10476    return ExprError();
10477  }
10478
10479  // Either we found no viable overloaded operator or we matched a
10480  // built-in operator. In either case, fall through to trying to
10481  // build a built-in operation.
10482  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10483}
10484
10485/// \brief Create a binary operation that may resolve to an overloaded
10486/// operator.
10487///
10488/// \param OpLoc The location of the operator itself (e.g., '+').
10489///
10490/// \param OpcIn The BinaryOperator::Opcode that describes this
10491/// operator.
10492///
10493/// \param Fns The set of non-member functions that will be
10494/// considered by overload resolution. The caller needs to build this
10495/// set based on the context using, e.g.,
10496/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10497/// set should not contain any member functions; those will be added
10498/// by CreateOverloadedBinOp().
10499///
10500/// \param LHS Left-hand argument.
10501/// \param RHS Right-hand argument.
10502ExprResult
10503Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10504                            unsigned OpcIn,
10505                            const UnresolvedSetImpl &Fns,
10506                            Expr *LHS, Expr *RHS) {
10507  Expr *Args[2] = { LHS, RHS };
10508  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
10509
10510  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10511  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10512  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10513
10514  // If either side is type-dependent, create an appropriate dependent
10515  // expression.
10516  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10517    if (Fns.empty()) {
10518      // If there are no functions to store, just build a dependent
10519      // BinaryOperator or CompoundAssignment.
10520      if (Opc <= BO_Assign || Opc > BO_OrAssign)
10521        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
10522                                                  Context.DependentTy,
10523                                                  VK_RValue, OK_Ordinary,
10524                                                  OpLoc,
10525                                                  FPFeatures.fp_contract));
10526
10527      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10528                                                        Context.DependentTy,
10529                                                        VK_LValue,
10530                                                        OK_Ordinary,
10531                                                        Context.DependentTy,
10532                                                        Context.DependentTy,
10533                                                        OpLoc,
10534                                                        FPFeatures.fp_contract));
10535    }
10536
10537    // FIXME: save results of ADL from here?
10538    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10539    // TODO: provide better source location info in DNLoc component.
10540    DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10541    UnresolvedLookupExpr *Fn
10542      = UnresolvedLookupExpr::Create(Context, NamingClass,
10543                                     NestedNameSpecifierLoc(), OpNameInfo,
10544                                     /*ADL*/ true, IsOverloaded(Fns),
10545                                     Fns.begin(), Fns.end());
10546    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10547                                                Context.DependentTy, VK_RValue,
10548                                                OpLoc, FPFeatures.fp_contract));
10549  }
10550
10551  // Always do placeholder-like conversions on the RHS.
10552  if (checkPlaceholderForOverload(*this, Args[1]))
10553    return ExprError();
10554
10555  // Do placeholder-like conversion on the LHS; note that we should
10556  // not get here with a PseudoObject LHS.
10557  assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10558  if (checkPlaceholderForOverload(*this, Args[0]))
10559    return ExprError();
10560
10561  // If this is the assignment operator, we only perform overload resolution
10562  // if the left-hand side is a class or enumeration type. This is actually
10563  // a hack. The standard requires that we do overload resolution between the
10564  // various built-in candidates, but as DR507 points out, this can lead to
10565  // problems. So we do it this way, which pretty much follows what GCC does.
10566  // Note that we go the traditional code path for compound assignment forms.
10567  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10568    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10569
10570  // If this is the .* operator, which is not overloadable, just
10571  // create a built-in binary operator.
10572  if (Opc == BO_PtrMemD)
10573    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10574
10575  // Build an empty overload set.
10576  OverloadCandidateSet CandidateSet(OpLoc);
10577
10578  // Add the candidates from the given function set.
10579  AddFunctionCandidates(Fns, Args, CandidateSet, false);
10580
10581  // Add operator candidates that are member functions.
10582  AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10583
10584  // Add candidates from ADL.
10585  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10586                                       OpLoc, Args,
10587                                       /*ExplicitTemplateArgs*/ 0,
10588                                       CandidateSet);
10589
10590  // Add builtin operator candidates.
10591  AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10592
10593  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10594
10595  // Perform overload resolution.
10596  OverloadCandidateSet::iterator Best;
10597  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10598    case OR_Success: {
10599      // We found a built-in operator or an overloaded operator.
10600      FunctionDecl *FnDecl = Best->Function;
10601
10602      if (FnDecl) {
10603        // We matched an overloaded operator. Build a call to that
10604        // operator.
10605
10606        // Convert the arguments.
10607        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10608          // Best->Access is only meaningful for class members.
10609          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10610
10611          ExprResult Arg1 =
10612            PerformCopyInitialization(
10613              InitializedEntity::InitializeParameter(Context,
10614                                                     FnDecl->getParamDecl(0)),
10615              SourceLocation(), Owned(Args[1]));
10616          if (Arg1.isInvalid())
10617            return ExprError();
10618
10619          ExprResult Arg0 =
10620            PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10621                                                Best->FoundDecl, Method);
10622          if (Arg0.isInvalid())
10623            return ExprError();
10624          Args[0] = Arg0.takeAs<Expr>();
10625          Args[1] = RHS = Arg1.takeAs<Expr>();
10626        } else {
10627          // Convert the arguments.
10628          ExprResult Arg0 = PerformCopyInitialization(
10629            InitializedEntity::InitializeParameter(Context,
10630                                                   FnDecl->getParamDecl(0)),
10631            SourceLocation(), Owned(Args[0]));
10632          if (Arg0.isInvalid())
10633            return ExprError();
10634
10635          ExprResult Arg1 =
10636            PerformCopyInitialization(
10637              InitializedEntity::InitializeParameter(Context,
10638                                                     FnDecl->getParamDecl(1)),
10639              SourceLocation(), Owned(Args[1]));
10640          if (Arg1.isInvalid())
10641            return ExprError();
10642          Args[0] = LHS = Arg0.takeAs<Expr>();
10643          Args[1] = RHS = Arg1.takeAs<Expr>();
10644        }
10645
10646        // Determine the result type.
10647        QualType ResultTy = FnDecl->getResultType();
10648        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10649        ResultTy = ResultTy.getNonLValueExprType(Context);
10650
10651        // Build the actual expression node.
10652        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10653                                                  Best->FoundDecl,
10654                                                  HadMultipleCandidates, OpLoc);
10655        if (FnExpr.isInvalid())
10656          return ExprError();
10657
10658        CXXOperatorCallExpr *TheCall =
10659          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10660                                            Args, ResultTy, VK, OpLoc,
10661                                            FPFeatures.fp_contract);
10662
10663        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10664                                FnDecl))
10665          return ExprError();
10666
10667        ArrayRef<const Expr *> ArgsArray(Args, 2);
10668        // Cut off the implicit 'this'.
10669        if (isa<CXXMethodDecl>(FnDecl))
10670          ArgsArray = ArgsArray.slice(1);
10671        checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10672                  TheCall->getSourceRange(), VariadicDoesNotApply);
10673
10674        return MaybeBindToTemporary(TheCall);
10675      } else {
10676        // We matched a built-in operator. Convert the arguments, then
10677        // break out so that we will build the appropriate built-in
10678        // operator node.
10679        ExprResult ArgsRes0 =
10680          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10681                                    Best->Conversions[0], AA_Passing);
10682        if (ArgsRes0.isInvalid())
10683          return ExprError();
10684        Args[0] = ArgsRes0.take();
10685
10686        ExprResult ArgsRes1 =
10687          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10688                                    Best->Conversions[1], AA_Passing);
10689        if (ArgsRes1.isInvalid())
10690          return ExprError();
10691        Args[1] = ArgsRes1.take();
10692        break;
10693      }
10694    }
10695
10696    case OR_No_Viable_Function: {
10697      // C++ [over.match.oper]p9:
10698      //   If the operator is the operator , [...] and there are no
10699      //   viable functions, then the operator is assumed to be the
10700      //   built-in operator and interpreted according to clause 5.
10701      if (Opc == BO_Comma)
10702        break;
10703
10704      // For class as left operand for assignment or compound assigment
10705      // operator do not fall through to handling in built-in, but report that
10706      // no overloaded assignment operator found
10707      ExprResult Result = ExprError();
10708      if (Args[0]->getType()->isRecordType() &&
10709          Opc >= BO_Assign && Opc <= BO_OrAssign) {
10710        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10711             << BinaryOperator::getOpcodeStr(Opc)
10712             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10713        if (Args[0]->getType()->isIncompleteType()) {
10714          Diag(OpLoc, diag::note_assign_lhs_incomplete)
10715            << Args[0]->getType()
10716            << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10717        }
10718      } else {
10719        // This is an erroneous use of an operator which can be overloaded by
10720        // a non-member function. Check for non-member operators which were
10721        // defined too late to be candidates.
10722        if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10723          // FIXME: Recover by calling the found function.
10724          return ExprError();
10725
10726        // No viable function; try to create a built-in operation, which will
10727        // produce an error. Then, show the non-viable candidates.
10728        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10729      }
10730      assert(Result.isInvalid() &&
10731             "C++ binary operator overloading is missing candidates!");
10732      if (Result.isInvalid())
10733        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10734                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
10735      return Result;
10736    }
10737
10738    case OR_Ambiguous:
10739      Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10740          << BinaryOperator::getOpcodeStr(Opc)
10741          << Args[0]->getType() << Args[1]->getType()
10742          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10743      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10744                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10745      return ExprError();
10746
10747    case OR_Deleted:
10748      if (isImplicitlyDeleted(Best->Function)) {
10749        CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10750        Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10751          << Context.getRecordType(Method->getParent())
10752          << getSpecialMember(Method);
10753
10754        // The user probably meant to call this special member. Just
10755        // explain why it's deleted.
10756        NoteDeletedFunction(Method);
10757        return ExprError();
10758      } else {
10759        Diag(OpLoc, diag::err_ovl_deleted_oper)
10760          << Best->Function->isDeleted()
10761          << BinaryOperator::getOpcodeStr(Opc)
10762          << getDeletedOrUnavailableSuffix(Best->Function)
10763          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10764      }
10765      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10766                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10767      return ExprError();
10768  }
10769
10770  // We matched a built-in operator; build it.
10771  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10772}
10773
10774ExprResult
10775Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10776                                         SourceLocation RLoc,
10777                                         Expr *Base, Expr *Idx) {
10778  Expr *Args[2] = { Base, Idx };
10779  DeclarationName OpName =
10780      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10781
10782  // If either side is type-dependent, create an appropriate dependent
10783  // expression.
10784  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10785
10786    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10787    // CHECKME: no 'operator' keyword?
10788    DeclarationNameInfo OpNameInfo(OpName, LLoc);
10789    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10790    UnresolvedLookupExpr *Fn
10791      = UnresolvedLookupExpr::Create(Context, NamingClass,
10792                                     NestedNameSpecifierLoc(), OpNameInfo,
10793                                     /*ADL*/ true, /*Overloaded*/ false,
10794                                     UnresolvedSetIterator(),
10795                                     UnresolvedSetIterator());
10796    // Can't add any actual overloads yet
10797
10798    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10799                                                   Args,
10800                                                   Context.DependentTy,
10801                                                   VK_RValue,
10802                                                   RLoc, false));
10803  }
10804
10805  // Handle placeholders on both operands.
10806  if (checkPlaceholderForOverload(*this, Args[0]))
10807    return ExprError();
10808  if (checkPlaceholderForOverload(*this, Args[1]))
10809    return ExprError();
10810
10811  // Build an empty overload set.
10812  OverloadCandidateSet CandidateSet(LLoc);
10813
10814  // Subscript can only be overloaded as a member function.
10815
10816  // Add operator candidates that are member functions.
10817  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
10818
10819  // Add builtin operator candidates.
10820  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
10821
10822  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10823
10824  // Perform overload resolution.
10825  OverloadCandidateSet::iterator Best;
10826  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10827    case OR_Success: {
10828      // We found a built-in operator or an overloaded operator.
10829      FunctionDecl *FnDecl = Best->Function;
10830
10831      if (FnDecl) {
10832        // We matched an overloaded operator. Build a call to that
10833        // operator.
10834
10835        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10836
10837        // Convert the arguments.
10838        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10839        ExprResult Arg0 =
10840          PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10841                                              Best->FoundDecl, Method);
10842        if (Arg0.isInvalid())
10843          return ExprError();
10844        Args[0] = Arg0.take();
10845
10846        // Convert the arguments.
10847        ExprResult InputInit
10848          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10849                                                      Context,
10850                                                      FnDecl->getParamDecl(0)),
10851                                      SourceLocation(),
10852                                      Owned(Args[1]));
10853        if (InputInit.isInvalid())
10854          return ExprError();
10855
10856        Args[1] = InputInit.takeAs<Expr>();
10857
10858        // Determine the result type
10859        QualType ResultTy = FnDecl->getResultType();
10860        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10861        ResultTy = ResultTy.getNonLValueExprType(Context);
10862
10863        // Build the actual expression node.
10864        DeclarationNameInfo OpLocInfo(OpName, LLoc);
10865        OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10866        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10867                                                  Best->FoundDecl,
10868                                                  HadMultipleCandidates,
10869                                                  OpLocInfo.getLoc(),
10870                                                  OpLocInfo.getInfo());
10871        if (FnExpr.isInvalid())
10872          return ExprError();
10873
10874        CXXOperatorCallExpr *TheCall =
10875          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10876                                            FnExpr.take(), Args,
10877                                            ResultTy, VK, RLoc,
10878                                            false);
10879
10880        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10881                                FnDecl))
10882          return ExprError();
10883
10884        return MaybeBindToTemporary(TheCall);
10885      } else {
10886        // We matched a built-in operator. Convert the arguments, then
10887        // break out so that we will build the appropriate built-in
10888        // operator node.
10889        ExprResult ArgsRes0 =
10890          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10891                                    Best->Conversions[0], AA_Passing);
10892        if (ArgsRes0.isInvalid())
10893          return ExprError();
10894        Args[0] = ArgsRes0.take();
10895
10896        ExprResult ArgsRes1 =
10897          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10898                                    Best->Conversions[1], AA_Passing);
10899        if (ArgsRes1.isInvalid())
10900          return ExprError();
10901        Args[1] = ArgsRes1.take();
10902
10903        break;
10904      }
10905    }
10906
10907    case OR_No_Viable_Function: {
10908      if (CandidateSet.empty())
10909        Diag(LLoc, diag::err_ovl_no_oper)
10910          << Args[0]->getType() << /*subscript*/ 0
10911          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10912      else
10913        Diag(LLoc, diag::err_ovl_no_viable_subscript)
10914          << Args[0]->getType()
10915          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10916      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10917                                  "[]", LLoc);
10918      return ExprError();
10919    }
10920
10921    case OR_Ambiguous:
10922      Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10923          << "[]"
10924          << Args[0]->getType() << Args[1]->getType()
10925          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10926      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10927                                  "[]", LLoc);
10928      return ExprError();
10929
10930    case OR_Deleted:
10931      Diag(LLoc, diag::err_ovl_deleted_oper)
10932        << Best->Function->isDeleted() << "[]"
10933        << getDeletedOrUnavailableSuffix(Best->Function)
10934        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10935      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10936                                  "[]", LLoc);
10937      return ExprError();
10938    }
10939
10940  // We matched a built-in operator; build it.
10941  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10942}
10943
10944/// BuildCallToMemberFunction - Build a call to a member
10945/// function. MemExpr is the expression that refers to the member
10946/// function (and includes the object parameter), Args/NumArgs are the
10947/// arguments to the function call (not including the object
10948/// parameter). The caller needs to validate that the member
10949/// expression refers to a non-static member function or an overloaded
10950/// member function.
10951ExprResult
10952Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10953                                SourceLocation LParenLoc,
10954                                MultiExprArg Args,
10955                                SourceLocation RParenLoc) {
10956  assert(MemExprE->getType() == Context.BoundMemberTy ||
10957         MemExprE->getType() == Context.OverloadTy);
10958
10959  // Dig out the member expression. This holds both the object
10960  // argument and the member function we're referring to.
10961  Expr *NakedMemExpr = MemExprE->IgnoreParens();
10962
10963  // Determine whether this is a call to a pointer-to-member function.
10964  if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10965    assert(op->getType() == Context.BoundMemberTy);
10966    assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10967
10968    QualType fnType =
10969      op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10970
10971    const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10972    QualType resultType = proto->getCallResultType(Context);
10973    ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10974
10975    // Check that the object type isn't more qualified than the
10976    // member function we're calling.
10977    Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10978
10979    QualType objectType = op->getLHS()->getType();
10980    if (op->getOpcode() == BO_PtrMemI)
10981      objectType = objectType->castAs<PointerType>()->getPointeeType();
10982    Qualifiers objectQuals = objectType.getQualifiers();
10983
10984    Qualifiers difference = objectQuals - funcQuals;
10985    difference.removeObjCGCAttr();
10986    difference.removeAddressSpace();
10987    if (difference) {
10988      std::string qualsString = difference.getAsString();
10989      Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10990        << fnType.getUnqualifiedType()
10991        << qualsString
10992        << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10993    }
10994
10995    CXXMemberCallExpr *call
10996      = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
10997                                        resultType, valueKind, RParenLoc);
10998
10999    if (CheckCallReturnType(proto->getResultType(),
11000                            op->getRHS()->getLocStart(),
11001                            call, 0))
11002      return ExprError();
11003
11004    if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
11005      return ExprError();
11006
11007    if (CheckOtherCall(call, proto))
11008      return ExprError();
11009
11010    return MaybeBindToTemporary(call);
11011  }
11012
11013  UnbridgedCastsSet UnbridgedCasts;
11014  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11015    return ExprError();
11016
11017  MemberExpr *MemExpr;
11018  CXXMethodDecl *Method = 0;
11019  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
11020  NestedNameSpecifier *Qualifier = 0;
11021  if (isa<MemberExpr>(NakedMemExpr)) {
11022    MemExpr = cast<MemberExpr>(NakedMemExpr);
11023    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11024    FoundDecl = MemExpr->getFoundDecl();
11025    Qualifier = MemExpr->getQualifier();
11026    UnbridgedCasts.restore();
11027  } else {
11028    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11029    Qualifier = UnresExpr->getQualifier();
11030
11031    QualType ObjectType = UnresExpr->getBaseType();
11032    Expr::Classification ObjectClassification
11033      = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11034                            : UnresExpr->getBase()->Classify(Context);
11035
11036    // Add overload candidates
11037    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
11038
11039    // FIXME: avoid copy.
11040    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11041    if (UnresExpr->hasExplicitTemplateArgs()) {
11042      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11043      TemplateArgs = &TemplateArgsBuffer;
11044    }
11045
11046    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11047           E = UnresExpr->decls_end(); I != E; ++I) {
11048
11049      NamedDecl *Func = *I;
11050      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11051      if (isa<UsingShadowDecl>(Func))
11052        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11053
11054
11055      // Microsoft supports direct constructor calls.
11056      if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11057        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11058                             Args, CandidateSet);
11059      } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11060        // If explicit template arguments were provided, we can't call a
11061        // non-template member function.
11062        if (TemplateArgs)
11063          continue;
11064
11065        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11066                           ObjectClassification, Args, CandidateSet,
11067                           /*SuppressUserConversions=*/false);
11068      } else {
11069        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11070                                   I.getPair(), ActingDC, TemplateArgs,
11071                                   ObjectType,  ObjectClassification,
11072                                   Args, CandidateSet,
11073                                   /*SuppressUsedConversions=*/false);
11074      }
11075    }
11076
11077    DeclarationName DeclName = UnresExpr->getMemberName();
11078
11079    UnbridgedCasts.restore();
11080
11081    OverloadCandidateSet::iterator Best;
11082    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11083                                            Best)) {
11084    case OR_Success:
11085      Method = cast<CXXMethodDecl>(Best->Function);
11086      FoundDecl = Best->FoundDecl;
11087      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11088      if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11089        return ExprError();
11090      // If FoundDecl is different from Method (such as if one is a template
11091      // and the other a specialization), make sure DiagnoseUseOfDecl is
11092      // called on both.
11093      // FIXME: This would be more comprehensively addressed by modifying
11094      // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11095      // being used.
11096      if (Method != FoundDecl.getDecl() &&
11097                      DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11098        return ExprError();
11099      break;
11100
11101    case OR_No_Viable_Function:
11102      Diag(UnresExpr->getMemberLoc(),
11103           diag::err_ovl_no_viable_member_function_in_call)
11104        << DeclName << MemExprE->getSourceRange();
11105      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11106      // FIXME: Leaking incoming expressions!
11107      return ExprError();
11108
11109    case OR_Ambiguous:
11110      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11111        << DeclName << MemExprE->getSourceRange();
11112      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11113      // FIXME: Leaking incoming expressions!
11114      return ExprError();
11115
11116    case OR_Deleted:
11117      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11118        << Best->Function->isDeleted()
11119        << DeclName
11120        << getDeletedOrUnavailableSuffix(Best->Function)
11121        << MemExprE->getSourceRange();
11122      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11123      // FIXME: Leaking incoming expressions!
11124      return ExprError();
11125    }
11126
11127    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11128
11129    // If overload resolution picked a static member, build a
11130    // non-member call based on that function.
11131    if (Method->isStatic()) {
11132      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11133                                   RParenLoc);
11134    }
11135
11136    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11137  }
11138
11139  QualType ResultType = Method->getResultType();
11140  ExprValueKind VK = Expr::getValueKindForType(ResultType);
11141  ResultType = ResultType.getNonLValueExprType(Context);
11142
11143  assert(Method && "Member call to something that isn't a method?");
11144  CXXMemberCallExpr *TheCall =
11145    new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11146                                    ResultType, VK, RParenLoc);
11147
11148  // Check for a valid return type.
11149  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
11150                          TheCall, Method))
11151    return ExprError();
11152
11153  // Convert the object argument (for a non-static member function call).
11154  // We only need to do this if there was actually an overload; otherwise
11155  // it was done at lookup.
11156  if (!Method->isStatic()) {
11157    ExprResult ObjectArg =
11158      PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11159                                          FoundDecl, Method);
11160    if (ObjectArg.isInvalid())
11161      return ExprError();
11162    MemExpr->setBase(ObjectArg.take());
11163  }
11164
11165  // Convert the rest of the arguments
11166  const FunctionProtoType *Proto =
11167    Method->getType()->getAs<FunctionProtoType>();
11168  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11169                              RParenLoc))
11170    return ExprError();
11171
11172  DiagnoseSentinelCalls(Method, LParenLoc, Args);
11173
11174  if (CheckFunctionCall(Method, TheCall, Proto))
11175    return ExprError();
11176
11177  if ((isa<CXXConstructorDecl>(CurContext) ||
11178       isa<CXXDestructorDecl>(CurContext)) &&
11179      TheCall->getMethodDecl()->isPure()) {
11180    const CXXMethodDecl *MD = TheCall->getMethodDecl();
11181
11182    if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11183      Diag(MemExpr->getLocStart(),
11184           diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11185        << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11186        << MD->getParent()->getDeclName();
11187
11188      Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11189    }
11190  }
11191  return MaybeBindToTemporary(TheCall);
11192}
11193
11194/// BuildCallToObjectOfClassType - Build a call to an object of class
11195/// type (C++ [over.call.object]), which can end up invoking an
11196/// overloaded function call operator (@c operator()) or performing a
11197/// user-defined conversion on the object argument.
11198ExprResult
11199Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11200                                   SourceLocation LParenLoc,
11201                                   MultiExprArg Args,
11202                                   SourceLocation RParenLoc) {
11203  if (checkPlaceholderForOverload(*this, Obj))
11204    return ExprError();
11205  ExprResult Object = Owned(Obj);
11206
11207  UnbridgedCastsSet UnbridgedCasts;
11208  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11209    return ExprError();
11210
11211  assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11212  const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11213
11214  // C++ [over.call.object]p1:
11215  //  If the primary-expression E in the function call syntax
11216  //  evaluates to a class object of type "cv T", then the set of
11217  //  candidate functions includes at least the function call
11218  //  operators of T. The function call operators of T are obtained by
11219  //  ordinary lookup of the name operator() in the context of
11220  //  (E).operator().
11221  OverloadCandidateSet CandidateSet(LParenLoc);
11222  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11223
11224  if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11225                          diag::err_incomplete_object_call, Object.get()))
11226    return true;
11227
11228  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11229  LookupQualifiedName(R, Record->getDecl());
11230  R.suppressDiagnostics();
11231
11232  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11233       Oper != OperEnd; ++Oper) {
11234    AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11235                       Object.get()->Classify(Context),
11236                       Args, CandidateSet,
11237                       /*SuppressUserConversions=*/ false);
11238  }
11239
11240  // C++ [over.call.object]p2:
11241  //   In addition, for each (non-explicit in C++0x) conversion function
11242  //   declared in T of the form
11243  //
11244  //        operator conversion-type-id () cv-qualifier;
11245  //
11246  //   where cv-qualifier is the same cv-qualification as, or a
11247  //   greater cv-qualification than, cv, and where conversion-type-id
11248  //   denotes the type "pointer to function of (P1,...,Pn) returning
11249  //   R", or the type "reference to pointer to function of
11250  //   (P1,...,Pn) returning R", or the type "reference to function
11251  //   of (P1,...,Pn) returning R", a surrogate call function [...]
11252  //   is also considered as a candidate function. Similarly,
11253  //   surrogate call functions are added to the set of candidate
11254  //   functions for each conversion function declared in an
11255  //   accessible base class provided the function is not hidden
11256  //   within T by another intervening declaration.
11257  std::pair<CXXRecordDecl::conversion_iterator,
11258            CXXRecordDecl::conversion_iterator> Conversions
11259    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11260  for (CXXRecordDecl::conversion_iterator
11261         I = Conversions.first, E = Conversions.second; I != E; ++I) {
11262    NamedDecl *D = *I;
11263    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11264    if (isa<UsingShadowDecl>(D))
11265      D = cast<UsingShadowDecl>(D)->getTargetDecl();
11266
11267    // Skip over templated conversion functions; they aren't
11268    // surrogates.
11269    if (isa<FunctionTemplateDecl>(D))
11270      continue;
11271
11272    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11273    if (!Conv->isExplicit()) {
11274      // Strip the reference type (if any) and then the pointer type (if
11275      // any) to get down to what might be a function type.
11276      QualType ConvType = Conv->getConversionType().getNonReferenceType();
11277      if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11278        ConvType = ConvPtrType->getPointeeType();
11279
11280      if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11281      {
11282        AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11283                              Object.get(), Args, CandidateSet);
11284      }
11285    }
11286  }
11287
11288  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11289
11290  // Perform overload resolution.
11291  OverloadCandidateSet::iterator Best;
11292  switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11293                             Best)) {
11294  case OR_Success:
11295    // Overload resolution succeeded; we'll build the appropriate call
11296    // below.
11297    break;
11298
11299  case OR_No_Viable_Function:
11300    if (CandidateSet.empty())
11301      Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11302        << Object.get()->getType() << /*call*/ 1
11303        << Object.get()->getSourceRange();
11304    else
11305      Diag(Object.get()->getLocStart(),
11306           diag::err_ovl_no_viable_object_call)
11307        << Object.get()->getType() << Object.get()->getSourceRange();
11308    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11309    break;
11310
11311  case OR_Ambiguous:
11312    Diag(Object.get()->getLocStart(),
11313         diag::err_ovl_ambiguous_object_call)
11314      << Object.get()->getType() << Object.get()->getSourceRange();
11315    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11316    break;
11317
11318  case OR_Deleted:
11319    Diag(Object.get()->getLocStart(),
11320         diag::err_ovl_deleted_object_call)
11321      << Best->Function->isDeleted()
11322      << Object.get()->getType()
11323      << getDeletedOrUnavailableSuffix(Best->Function)
11324      << Object.get()->getSourceRange();
11325    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11326    break;
11327  }
11328
11329  if (Best == CandidateSet.end())
11330    return true;
11331
11332  UnbridgedCasts.restore();
11333
11334  if (Best->Function == 0) {
11335    // Since there is no function declaration, this is one of the
11336    // surrogate candidates. Dig out the conversion function.
11337    CXXConversionDecl *Conv
11338      = cast<CXXConversionDecl>(
11339                         Best->Conversions[0].UserDefined.ConversionFunction);
11340
11341    CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11342    if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11343      return ExprError();
11344    assert(Conv == Best->FoundDecl.getDecl() &&
11345             "Found Decl & conversion-to-functionptr should be same, right?!");
11346    // We selected one of the surrogate functions that converts the
11347    // object parameter to a function pointer. Perform the conversion
11348    // on the object argument, then let ActOnCallExpr finish the job.
11349
11350    // Create an implicit member expr to refer to the conversion operator.
11351    // and then call it.
11352    ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11353                                             Conv, HadMultipleCandidates);
11354    if (Call.isInvalid())
11355      return ExprError();
11356    // Record usage of conversion in an implicit cast.
11357    Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11358                                          CK_UserDefinedConversion,
11359                                          Call.get(), 0, VK_RValue));
11360
11361    return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11362  }
11363
11364  CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11365
11366  // We found an overloaded operator(). Build a CXXOperatorCallExpr
11367  // that calls this method, using Object for the implicit object
11368  // parameter and passing along the remaining arguments.
11369  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11370
11371  // An error diagnostic has already been printed when parsing the declaration.
11372  if (Method->isInvalidDecl())
11373    return ExprError();
11374
11375  const FunctionProtoType *Proto =
11376    Method->getType()->getAs<FunctionProtoType>();
11377
11378  unsigned NumArgsInProto = Proto->getNumArgs();
11379  unsigned NumArgsToCheck = Args.size();
11380
11381  // Build the full argument list for the method call (the
11382  // implicit object parameter is placed at the beginning of the
11383  // list).
11384  Expr **MethodArgs;
11385  if (Args.size() < NumArgsInProto) {
11386    NumArgsToCheck = NumArgsInProto;
11387    MethodArgs = new Expr*[NumArgsInProto + 1];
11388  } else {
11389    MethodArgs = new Expr*[Args.size() + 1];
11390  }
11391  MethodArgs[0] = Object.get();
11392  for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx)
11393    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
11394
11395  DeclarationNameInfo OpLocInfo(
11396               Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11397  OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11398  ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11399                                           HadMultipleCandidates,
11400                                           OpLocInfo.getLoc(),
11401                                           OpLocInfo.getInfo());
11402  if (NewFn.isInvalid())
11403    return true;
11404
11405  // Once we've built TheCall, all of the expressions are properly
11406  // owned.
11407  QualType ResultTy = Method->getResultType();
11408  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11409  ResultTy = ResultTy.getNonLValueExprType(Context);
11410
11411  CXXOperatorCallExpr *TheCall =
11412    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11413                                      llvm::makeArrayRef(MethodArgs, Args.size()+1),
11414                                      ResultTy, VK, RParenLoc, false);
11415  delete [] MethodArgs;
11416
11417  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
11418                          Method))
11419    return true;
11420
11421  // We may have default arguments. If so, we need to allocate more
11422  // slots in the call for them.
11423  if (Args.size() < NumArgsInProto)
11424    TheCall->setNumArgs(Context, NumArgsInProto + 1);
11425  else if (Args.size() > NumArgsInProto)
11426    NumArgsToCheck = NumArgsInProto;
11427
11428  bool IsError = false;
11429
11430  // Initialize the implicit object parameter.
11431  ExprResult ObjRes =
11432    PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11433                                        Best->FoundDecl, Method);
11434  if (ObjRes.isInvalid())
11435    IsError = true;
11436  else
11437    Object = ObjRes;
11438  TheCall->setArg(0, Object.take());
11439
11440  // Check the argument types.
11441  for (unsigned i = 0; i != NumArgsToCheck; i++) {
11442    Expr *Arg;
11443    if (i < Args.size()) {
11444      Arg = Args[i];
11445
11446      // Pass the argument.
11447
11448      ExprResult InputInit
11449        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11450                                                    Context,
11451                                                    Method->getParamDecl(i)),
11452                                    SourceLocation(), Arg);
11453
11454      IsError |= InputInit.isInvalid();
11455      Arg = InputInit.takeAs<Expr>();
11456    } else {
11457      ExprResult DefArg
11458        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11459      if (DefArg.isInvalid()) {
11460        IsError = true;
11461        break;
11462      }
11463
11464      Arg = DefArg.takeAs<Expr>();
11465    }
11466
11467    TheCall->setArg(i + 1, Arg);
11468  }
11469
11470  // If this is a variadic call, handle args passed through "...".
11471  if (Proto->isVariadic()) {
11472    // Promote the arguments (C99 6.5.2.2p7).
11473    for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
11474      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11475      IsError |= Arg.isInvalid();
11476      TheCall->setArg(i + 1, Arg.take());
11477    }
11478  }
11479
11480  if (IsError) return true;
11481
11482  DiagnoseSentinelCalls(Method, LParenLoc, Args);
11483
11484  if (CheckFunctionCall(Method, TheCall, Proto))
11485    return true;
11486
11487  return MaybeBindToTemporary(TheCall);
11488}
11489
11490/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11491///  (if one exists), where @c Base is an expression of class type and
11492/// @c Member is the name of the member we're trying to find.
11493ExprResult
11494Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11495                               bool *NoArrowOperatorFound) {
11496  assert(Base->getType()->isRecordType() &&
11497         "left-hand side must have class type");
11498
11499  if (checkPlaceholderForOverload(*this, Base))
11500    return ExprError();
11501
11502  SourceLocation Loc = Base->getExprLoc();
11503
11504  // C++ [over.ref]p1:
11505  //
11506  //   [...] An expression x->m is interpreted as (x.operator->())->m
11507  //   for a class object x of type T if T::operator->() exists and if
11508  //   the operator is selected as the best match function by the
11509  //   overload resolution mechanism (13.3).
11510  DeclarationName OpName =
11511    Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11512  OverloadCandidateSet CandidateSet(Loc);
11513  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11514
11515  if (RequireCompleteType(Loc, Base->getType(),
11516                          diag::err_typecheck_incomplete_tag, Base))
11517    return ExprError();
11518
11519  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11520  LookupQualifiedName(R, BaseRecord->getDecl());
11521  R.suppressDiagnostics();
11522
11523  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11524       Oper != OperEnd; ++Oper) {
11525    AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11526                       None, CandidateSet, /*SuppressUserConversions=*/false);
11527  }
11528
11529  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11530
11531  // Perform overload resolution.
11532  OverloadCandidateSet::iterator Best;
11533  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11534  case OR_Success:
11535    // Overload resolution succeeded; we'll build the call below.
11536    break;
11537
11538  case OR_No_Viable_Function:
11539    if (CandidateSet.empty()) {
11540      QualType BaseType = Base->getType();
11541      if (NoArrowOperatorFound) {
11542        // Report this specific error to the caller instead of emitting a
11543        // diagnostic, as requested.
11544        *NoArrowOperatorFound = true;
11545        return ExprError();
11546      }
11547      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11548        << BaseType << Base->getSourceRange();
11549      if (BaseType->isRecordType() && !BaseType->isPointerType()) {
11550        Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
11551          << FixItHint::CreateReplacement(OpLoc, ".");
11552      }
11553    } else
11554      Diag(OpLoc, diag::err_ovl_no_viable_oper)
11555        << "operator->" << Base->getSourceRange();
11556    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11557    return ExprError();
11558
11559  case OR_Ambiguous:
11560    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11561      << "->" << Base->getType() << Base->getSourceRange();
11562    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11563    return ExprError();
11564
11565  case OR_Deleted:
11566    Diag(OpLoc,  diag::err_ovl_deleted_oper)
11567      << Best->Function->isDeleted()
11568      << "->"
11569      << getDeletedOrUnavailableSuffix(Best->Function)
11570      << Base->getSourceRange();
11571    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11572    return ExprError();
11573  }
11574
11575  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11576
11577  // Convert the object parameter.
11578  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11579  ExprResult BaseResult =
11580    PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11581                                        Best->FoundDecl, Method);
11582  if (BaseResult.isInvalid())
11583    return ExprError();
11584  Base = BaseResult.take();
11585
11586  // Build the operator call.
11587  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11588                                            HadMultipleCandidates, OpLoc);
11589  if (FnExpr.isInvalid())
11590    return ExprError();
11591
11592  QualType ResultTy = Method->getResultType();
11593  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11594  ResultTy = ResultTy.getNonLValueExprType(Context);
11595  CXXOperatorCallExpr *TheCall =
11596    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11597                                      Base, ResultTy, VK, OpLoc, false);
11598
11599  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11600                          Method))
11601          return ExprError();
11602
11603  return MaybeBindToTemporary(TheCall);
11604}
11605
11606/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11607/// a literal operator described by the provided lookup results.
11608ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11609                                          DeclarationNameInfo &SuffixInfo,
11610                                          ArrayRef<Expr*> Args,
11611                                          SourceLocation LitEndLoc,
11612                                       TemplateArgumentListInfo *TemplateArgs) {
11613  SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11614
11615  OverloadCandidateSet CandidateSet(UDSuffixLoc);
11616  AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11617                        TemplateArgs);
11618
11619  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11620
11621  // Perform overload resolution. This will usually be trivial, but might need
11622  // to perform substitutions for a literal operator template.
11623  OverloadCandidateSet::iterator Best;
11624  switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11625  case OR_Success:
11626  case OR_Deleted:
11627    break;
11628
11629  case OR_No_Viable_Function:
11630    Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11631      << R.getLookupName();
11632    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11633    return ExprError();
11634
11635  case OR_Ambiguous:
11636    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11637    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11638    return ExprError();
11639  }
11640
11641  FunctionDecl *FD = Best->Function;
11642  ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11643                                        HadMultipleCandidates,
11644                                        SuffixInfo.getLoc(),
11645                                        SuffixInfo.getInfo());
11646  if (Fn.isInvalid())
11647    return true;
11648
11649  // Check the argument types. This should almost always be a no-op, except
11650  // that array-to-pointer decay is applied to string literals.
11651  Expr *ConvArgs[2];
11652  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
11653    ExprResult InputInit = PerformCopyInitialization(
11654      InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11655      SourceLocation(), Args[ArgIdx]);
11656    if (InputInit.isInvalid())
11657      return true;
11658    ConvArgs[ArgIdx] = InputInit.take();
11659  }
11660
11661  QualType ResultTy = FD->getResultType();
11662  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11663  ResultTy = ResultTy.getNonLValueExprType(Context);
11664
11665  UserDefinedLiteral *UDL =
11666    new (Context) UserDefinedLiteral(Context, Fn.take(),
11667                                     llvm::makeArrayRef(ConvArgs, Args.size()),
11668                                     ResultTy, VK, LitEndLoc, UDSuffixLoc);
11669
11670  if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11671    return ExprError();
11672
11673  if (CheckFunctionCall(FD, UDL, NULL))
11674    return ExprError();
11675
11676  return MaybeBindToTemporary(UDL);
11677}
11678
11679/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11680/// given LookupResult is non-empty, it is assumed to describe a member which
11681/// will be invoked. Otherwise, the function will be found via argument
11682/// dependent lookup.
11683/// CallExpr is set to a valid expression and FRS_Success returned on success,
11684/// otherwise CallExpr is set to ExprError() and some non-success value
11685/// is returned.
11686Sema::ForRangeStatus
11687Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11688                                SourceLocation RangeLoc, VarDecl *Decl,
11689                                BeginEndFunction BEF,
11690                                const DeclarationNameInfo &NameInfo,
11691                                LookupResult &MemberLookup,
11692                                OverloadCandidateSet *CandidateSet,
11693                                Expr *Range, ExprResult *CallExpr) {
11694  CandidateSet->clear();
11695  if (!MemberLookup.empty()) {
11696    ExprResult MemberRef =
11697        BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11698                                 /*IsPtr=*/false, CXXScopeSpec(),
11699                                 /*TemplateKWLoc=*/SourceLocation(),
11700                                 /*FirstQualifierInScope=*/0,
11701                                 MemberLookup,
11702                                 /*TemplateArgs=*/0);
11703    if (MemberRef.isInvalid()) {
11704      *CallExpr = ExprError();
11705      Diag(Range->getLocStart(), diag::note_in_for_range)
11706          << RangeLoc << BEF << Range->getType();
11707      return FRS_DiagnosticIssued;
11708    }
11709    *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
11710    if (CallExpr->isInvalid()) {
11711      *CallExpr = ExprError();
11712      Diag(Range->getLocStart(), diag::note_in_for_range)
11713          << RangeLoc << BEF << Range->getType();
11714      return FRS_DiagnosticIssued;
11715    }
11716  } else {
11717    UnresolvedSet<0> FoundNames;
11718    UnresolvedLookupExpr *Fn =
11719      UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11720                                   NestedNameSpecifierLoc(), NameInfo,
11721                                   /*NeedsADL=*/true, /*Overloaded=*/false,
11722                                   FoundNames.begin(), FoundNames.end());
11723
11724    bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
11725                                                    CandidateSet, CallExpr);
11726    if (CandidateSet->empty() || CandidateSetError) {
11727      *CallExpr = ExprError();
11728      return FRS_NoViableFunction;
11729    }
11730    OverloadCandidateSet::iterator Best;
11731    OverloadingResult OverloadResult =
11732        CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11733
11734    if (OverloadResult == OR_No_Viable_Function) {
11735      *CallExpr = ExprError();
11736      return FRS_NoViableFunction;
11737    }
11738    *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
11739                                         Loc, 0, CandidateSet, &Best,
11740                                         OverloadResult,
11741                                         /*AllowTypoCorrection=*/false);
11742    if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11743      *CallExpr = ExprError();
11744      Diag(Range->getLocStart(), diag::note_in_for_range)
11745          << RangeLoc << BEF << Range->getType();
11746      return FRS_DiagnosticIssued;
11747    }
11748  }
11749  return FRS_Success;
11750}
11751
11752
11753/// FixOverloadedFunctionReference - E is an expression that refers to
11754/// a C++ overloaded function (possibly with some parentheses and
11755/// perhaps a '&' around it). We have resolved the overloaded function
11756/// to the function declaration Fn, so patch up the expression E to
11757/// refer (possibly indirectly) to Fn. Returns the new expr.
11758Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11759                                           FunctionDecl *Fn) {
11760  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11761    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11762                                                   Found, Fn);
11763    if (SubExpr == PE->getSubExpr())
11764      return PE;
11765
11766    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11767  }
11768
11769  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11770    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11771                                                   Found, Fn);
11772    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11773                               SubExpr->getType()) &&
11774           "Implicit cast type cannot be determined from overload");
11775    assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11776    if (SubExpr == ICE->getSubExpr())
11777      return ICE;
11778
11779    return ImplicitCastExpr::Create(Context, ICE->getType(),
11780                                    ICE->getCastKind(),
11781                                    SubExpr, 0,
11782                                    ICE->getValueKind());
11783  }
11784
11785  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11786    assert(UnOp->getOpcode() == UO_AddrOf &&
11787           "Can only take the address of an overloaded function");
11788    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11789      if (Method->isStatic()) {
11790        // Do nothing: static member functions aren't any different
11791        // from non-member functions.
11792      } else {
11793        // Fix the sub expression, which really has to be an
11794        // UnresolvedLookupExpr holding an overloaded member function
11795        // or template.
11796        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11797                                                       Found, Fn);
11798        if (SubExpr == UnOp->getSubExpr())
11799          return UnOp;
11800
11801        assert(isa<DeclRefExpr>(SubExpr)
11802               && "fixed to something other than a decl ref");
11803        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11804               && "fixed to a member ref with no nested name qualifier");
11805
11806        // We have taken the address of a pointer to member
11807        // function. Perform the computation here so that we get the
11808        // appropriate pointer to member type.
11809        QualType ClassType
11810          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11811        QualType MemPtrType
11812          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11813
11814        return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11815                                           VK_RValue, OK_Ordinary,
11816                                           UnOp->getOperatorLoc());
11817      }
11818    }
11819    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11820                                                   Found, Fn);
11821    if (SubExpr == UnOp->getSubExpr())
11822      return UnOp;
11823
11824    return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11825                                     Context.getPointerType(SubExpr->getType()),
11826                                       VK_RValue, OK_Ordinary,
11827                                       UnOp->getOperatorLoc());
11828  }
11829
11830  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11831    // FIXME: avoid copy.
11832    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11833    if (ULE->hasExplicitTemplateArgs()) {
11834      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11835      TemplateArgs = &TemplateArgsBuffer;
11836    }
11837
11838    DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11839                                           ULE->getQualifierLoc(),
11840                                           ULE->getTemplateKeywordLoc(),
11841                                           Fn,
11842                                           /*enclosing*/ false, // FIXME?
11843                                           ULE->getNameLoc(),
11844                                           Fn->getType(),
11845                                           VK_LValue,
11846                                           Found.getDecl(),
11847                                           TemplateArgs);
11848    MarkDeclRefReferenced(DRE);
11849    DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11850    return DRE;
11851  }
11852
11853  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11854    // FIXME: avoid copy.
11855    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11856    if (MemExpr->hasExplicitTemplateArgs()) {
11857      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11858      TemplateArgs = &TemplateArgsBuffer;
11859    }
11860
11861    Expr *Base;
11862
11863    // If we're filling in a static method where we used to have an
11864    // implicit member access, rewrite to a simple decl ref.
11865    if (MemExpr->isImplicitAccess()) {
11866      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11867        DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11868                                               MemExpr->getQualifierLoc(),
11869                                               MemExpr->getTemplateKeywordLoc(),
11870                                               Fn,
11871                                               /*enclosing*/ false,
11872                                               MemExpr->getMemberLoc(),
11873                                               Fn->getType(),
11874                                               VK_LValue,
11875                                               Found.getDecl(),
11876                                               TemplateArgs);
11877        MarkDeclRefReferenced(DRE);
11878        DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11879        return DRE;
11880      } else {
11881        SourceLocation Loc = MemExpr->getMemberLoc();
11882        if (MemExpr->getQualifier())
11883          Loc = MemExpr->getQualifierLoc().getBeginLoc();
11884        CheckCXXThisCapture(Loc);
11885        Base = new (Context) CXXThisExpr(Loc,
11886                                         MemExpr->getBaseType(),
11887                                         /*isImplicit=*/true);
11888      }
11889    } else
11890      Base = MemExpr->getBase();
11891
11892    ExprValueKind valueKind;
11893    QualType type;
11894    if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11895      valueKind = VK_LValue;
11896      type = Fn->getType();
11897    } else {
11898      valueKind = VK_RValue;
11899      type = Context.BoundMemberTy;
11900    }
11901
11902    MemberExpr *ME = MemberExpr::Create(Context, Base,
11903                                        MemExpr->isArrow(),
11904                                        MemExpr->getQualifierLoc(),
11905                                        MemExpr->getTemplateKeywordLoc(),
11906                                        Fn,
11907                                        Found,
11908                                        MemExpr->getMemberNameInfo(),
11909                                        TemplateArgs,
11910                                        type, valueKind, OK_Ordinary);
11911    ME->setHadMultipleCandidates(true);
11912    MarkMemberReferenced(ME);
11913    return ME;
11914  }
11915
11916  llvm_unreachable("Invalid reference to overloaded function");
11917}
11918
11919ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11920                                                DeclAccessPair Found,
11921                                                FunctionDecl *Fn) {
11922  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11923}
11924
11925} // end namespace clang
11926