SemaOverload.cpp revision 5f2987c11491edb186401d4e8eced275f0ea7c5e
1//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
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/SemaInternal.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Template.h"
18#include "clang/Sema/TemplateDeduction.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/CXXInheritance.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/TypeOrdering.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "llvm/ADT/DenseSet.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/STLExtras.h"
32#include <algorithm>
33
34namespace clang {
35using namespace sema;
36
37/// A convenience routine for creating a decayed reference to a
38/// function.
39static ExprResult
40CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
41                      SourceLocation Loc = SourceLocation(),
42                      const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
43  DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, Fn->getType(),
44                                                 VK_LValue, Loc, LocInfo);
45  if (HadMultipleCandidates)
46    DRE->setHadMultipleCandidates(true);
47  ExprResult E = S.Owned(DRE);
48  E = S.DefaultFunctionArrayConversion(E.take());
49  if (E.isInvalid())
50    return ExprError();
51  return move(E);
52}
53
54static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55                                 bool InOverloadResolution,
56                                 StandardConversionSequence &SCS,
57                                 bool CStyle,
58                                 bool AllowObjCWritebackConversion);
59
60static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
61                                                 QualType &ToType,
62                                                 bool InOverloadResolution,
63                                                 StandardConversionSequence &SCS,
64                                                 bool CStyle);
65static OverloadingResult
66IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
67                        UserDefinedConversionSequence& User,
68                        OverloadCandidateSet& Conversions,
69                        bool AllowExplicit);
70
71
72static ImplicitConversionSequence::CompareKind
73CompareStandardConversionSequences(Sema &S,
74                                   const StandardConversionSequence& SCS1,
75                                   const StandardConversionSequence& SCS2);
76
77static ImplicitConversionSequence::CompareKind
78CompareQualificationConversions(Sema &S,
79                                const StandardConversionSequence& SCS1,
80                                const StandardConversionSequence& SCS2);
81
82static ImplicitConversionSequence::CompareKind
83CompareDerivedToBaseConversions(Sema &S,
84                                const StandardConversionSequence& SCS1,
85                                const StandardConversionSequence& SCS2);
86
87
88
89/// GetConversionCategory - Retrieve the implicit conversion
90/// category corresponding to the given implicit conversion kind.
91ImplicitConversionCategory
92GetConversionCategory(ImplicitConversionKind Kind) {
93  static const ImplicitConversionCategory
94    Category[(int)ICK_Num_Conversion_Kinds] = {
95    ICC_Identity,
96    ICC_Lvalue_Transformation,
97    ICC_Lvalue_Transformation,
98    ICC_Lvalue_Transformation,
99    ICC_Identity,
100    ICC_Qualification_Adjustment,
101    ICC_Promotion,
102    ICC_Promotion,
103    ICC_Promotion,
104    ICC_Conversion,
105    ICC_Conversion,
106    ICC_Conversion,
107    ICC_Conversion,
108    ICC_Conversion,
109    ICC_Conversion,
110    ICC_Conversion,
111    ICC_Conversion,
112    ICC_Conversion,
113    ICC_Conversion,
114    ICC_Conversion,
115    ICC_Conversion,
116    ICC_Conversion
117  };
118  return Category[(int)Kind];
119}
120
121/// GetConversionRank - Retrieve the implicit conversion rank
122/// corresponding to the given implicit conversion kind.
123ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
124  static const ImplicitConversionRank
125    Rank[(int)ICK_Num_Conversion_Kinds] = {
126    ICR_Exact_Match,
127    ICR_Exact_Match,
128    ICR_Exact_Match,
129    ICR_Exact_Match,
130    ICR_Exact_Match,
131    ICR_Exact_Match,
132    ICR_Promotion,
133    ICR_Promotion,
134    ICR_Promotion,
135    ICR_Conversion,
136    ICR_Conversion,
137    ICR_Conversion,
138    ICR_Conversion,
139    ICR_Conversion,
140    ICR_Conversion,
141    ICR_Conversion,
142    ICR_Conversion,
143    ICR_Conversion,
144    ICR_Conversion,
145    ICR_Conversion,
146    ICR_Complex_Real_Conversion,
147    ICR_Conversion,
148    ICR_Conversion,
149    ICR_Writeback_Conversion
150  };
151  return Rank[(int)Kind];
152}
153
154/// GetImplicitConversionName - Return the name of this kind of
155/// implicit conversion.
156const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
157  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
158    "No conversion",
159    "Lvalue-to-rvalue",
160    "Array-to-pointer",
161    "Function-to-pointer",
162    "Noreturn adjustment",
163    "Qualification",
164    "Integral promotion",
165    "Floating point promotion",
166    "Complex promotion",
167    "Integral conversion",
168    "Floating conversion",
169    "Complex conversion",
170    "Floating-integral conversion",
171    "Pointer conversion",
172    "Pointer-to-member conversion",
173    "Boolean conversion",
174    "Compatible-types conversion",
175    "Derived-to-base conversion",
176    "Vector conversion",
177    "Vector splat",
178    "Complex-real conversion",
179    "Block Pointer conversion",
180    "Transparent Union Conversion"
181    "Writeback conversion"
182  };
183  return Name[Kind];
184}
185
186/// StandardConversionSequence - Set the standard conversion
187/// sequence to the identity conversion.
188void StandardConversionSequence::setAsIdentityConversion() {
189  First = ICK_Identity;
190  Second = ICK_Identity;
191  Third = ICK_Identity;
192  DeprecatedStringLiteralToCharPtr = false;
193  QualificationIncludesObjCLifetime = false;
194  ReferenceBinding = false;
195  DirectBinding = false;
196  IsLvalueReference = true;
197  BindsToFunctionLvalue = false;
198  BindsToRvalue = false;
199  BindsImplicitObjectArgumentWithoutRefQualifier = false;
200  ObjCLifetimeConversionBinding = false;
201  CopyConstructor = 0;
202}
203
204/// getRank - Retrieve the rank of this standard conversion sequence
205/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206/// implicit conversions.
207ImplicitConversionRank StandardConversionSequence::getRank() const {
208  ImplicitConversionRank Rank = ICR_Exact_Match;
209  if  (GetConversionRank(First) > Rank)
210    Rank = GetConversionRank(First);
211  if  (GetConversionRank(Second) > Rank)
212    Rank = GetConversionRank(Second);
213  if  (GetConversionRank(Third) > Rank)
214    Rank = GetConversionRank(Third);
215  return Rank;
216}
217
218/// isPointerConversionToBool - Determines whether this conversion is
219/// a conversion of a pointer or pointer-to-member to bool. This is
220/// used as part of the ranking of standard conversion sequences
221/// (C++ 13.3.3.2p4).
222bool StandardConversionSequence::isPointerConversionToBool() const {
223  // Note that FromType has not necessarily been transformed by the
224  // array-to-pointer or function-to-pointer implicit conversions, so
225  // check for their presence as well as checking whether FromType is
226  // a pointer.
227  if (getToType(1)->isBooleanType() &&
228      (getFromType()->isPointerType() ||
229       getFromType()->isObjCObjectPointerType() ||
230       getFromType()->isBlockPointerType() ||
231       getFromType()->isNullPtrType() ||
232       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
233    return true;
234
235  return false;
236}
237
238/// isPointerConversionToVoidPointer - Determines whether this
239/// conversion is a conversion of a pointer to a void pointer. This is
240/// used as part of the ranking of standard conversion sequences (C++
241/// 13.3.3.2p4).
242bool
243StandardConversionSequence::
244isPointerConversionToVoidPointer(ASTContext& Context) const {
245  QualType FromType = getFromType();
246  QualType ToType = getToType(1);
247
248  // Note that FromType has not necessarily been transformed by the
249  // array-to-pointer implicit conversion, so check for its presence
250  // and redo the conversion to get a pointer.
251  if (First == ICK_Array_To_Pointer)
252    FromType = Context.getArrayDecayedType(FromType);
253
254  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
255    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
256      return ToPtrType->getPointeeType()->isVoidType();
257
258  return false;
259}
260
261/// Skip any implicit casts which could be either part of a narrowing conversion
262/// or after one in an implicit conversion.
263static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
264  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
265    switch (ICE->getCastKind()) {
266    case CK_NoOp:
267    case CK_IntegralCast:
268    case CK_IntegralToBoolean:
269    case CK_IntegralToFloating:
270    case CK_FloatingToIntegral:
271    case CK_FloatingToBoolean:
272    case CK_FloatingCast:
273      Converted = ICE->getSubExpr();
274      continue;
275
276    default:
277      return Converted;
278    }
279  }
280
281  return Converted;
282}
283
284/// Check if this standard conversion sequence represents a narrowing
285/// conversion, according to C++11 [dcl.init.list]p7.
286///
287/// \param Ctx  The AST context.
288/// \param Converted  The result of applying this standard conversion sequence.
289/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
290///        value of the expression prior to the narrowing conversion.
291NarrowingKind
292StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293                                             const Expr *Converted,
294                                             APValue &ConstantValue) const {
295  assert(Ctx.getLangOptions().CPlusPlus && "narrowing check outside C++");
296
297  // C++11 [dcl.init.list]p7:
298  //   A narrowing conversion is an implicit conversion ...
299  QualType FromType = getToType(0);
300  QualType ToType = getToType(1);
301  switch (Second) {
302  // -- from a floating-point type to an integer type, or
303  //
304  // -- from an integer type or unscoped enumeration type to a floating-point
305  //    type, except where the source is a constant expression and the actual
306  //    value after conversion will fit into the target type and will produce
307  //    the original value when converted back to the original type, or
308  case ICK_Floating_Integral:
309    if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
310      return NK_Type_Narrowing;
311    } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
312      llvm::APSInt IntConstantValue;
313      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
314      if (Initializer &&
315          Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
316        // Convert the integer to the floating type.
317        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
318        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
319                                llvm::APFloat::rmNearestTiesToEven);
320        // And back.
321        llvm::APSInt ConvertedValue = IntConstantValue;
322        bool ignored;
323        Result.convertToInteger(ConvertedValue,
324                                llvm::APFloat::rmTowardZero, &ignored);
325        // If the resulting value is different, this was a narrowing conversion.
326        if (IntConstantValue != ConvertedValue) {
327          ConstantValue = APValue(IntConstantValue);
328          return NK_Constant_Narrowing;
329        }
330      } else {
331        // Variables are always narrowings.
332        return NK_Variable_Narrowing;
333      }
334    }
335    return NK_Not_Narrowing;
336
337  // -- from long double to double or float, or from double to float, except
338  //    where the source is a constant expression and the actual value after
339  //    conversion is within the range of values that can be represented (even
340  //    if it cannot be represented exactly), or
341  case ICK_Floating_Conversion:
342    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
343        Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
344      // FromType is larger than ToType.
345      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
346      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
347        // Constant!
348        assert(ConstantValue.isFloat());
349        llvm::APFloat FloatVal = ConstantValue.getFloat();
350        // Convert the source value into the target type.
351        bool ignored;
352        llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
353          Ctx.getFloatTypeSemantics(ToType),
354          llvm::APFloat::rmNearestTiesToEven, &ignored);
355        // If there was no overflow, the source value is within the range of
356        // values that can be represented.
357        if (ConvertStatus & llvm::APFloat::opOverflow)
358          return NK_Constant_Narrowing;
359      } else {
360        return NK_Variable_Narrowing;
361      }
362    }
363    return NK_Not_Narrowing;
364
365  // -- from an integer type or unscoped enumeration type to an integer type
366  //    that cannot represent all the values of the original type, except where
367  //    the source is a constant expression and the actual value after
368  //    conversion will fit into the target type and will produce the original
369  //    value when converted back to the original type.
370  case ICK_Boolean_Conversion:  // Bools are integers too.
371    if (!FromType->isIntegralOrUnscopedEnumerationType()) {
372      // Boolean conversions can be from pointers and pointers to members
373      // [conv.bool], and those aren't considered narrowing conversions.
374      return NK_Not_Narrowing;
375    }  // Otherwise, fall through to the integral case.
376  case ICK_Integral_Conversion: {
377    assert(FromType->isIntegralOrUnscopedEnumerationType());
378    assert(ToType->isIntegralOrUnscopedEnumerationType());
379    const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
380    const unsigned FromWidth = Ctx.getIntWidth(FromType);
381    const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
382    const unsigned ToWidth = Ctx.getIntWidth(ToType);
383
384    if (FromWidth > ToWidth ||
385        (FromWidth == ToWidth && FromSigned != ToSigned)) {
386      // Not all values of FromType can be represented in ToType.
387      llvm::APSInt InitializerValue;
388      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
389      if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
390        ConstantValue = APValue(InitializerValue);
391
392        // Add a bit to the InitializerValue so we don't have to worry about
393        // signed vs. unsigned comparisons.
394        InitializerValue = InitializerValue.extend(
395          InitializerValue.getBitWidth() + 1);
396        // Convert the initializer to and from the target width and signed-ness.
397        llvm::APSInt ConvertedValue = InitializerValue;
398        ConvertedValue = ConvertedValue.trunc(ToWidth);
399        ConvertedValue.setIsSigned(ToSigned);
400        ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
401        ConvertedValue.setIsSigned(InitializerValue.isSigned());
402        // If the result is different, this was a narrowing conversion.
403        if (ConvertedValue != InitializerValue)
404          return NK_Constant_Narrowing;
405      } else {
406        // Variables are always narrowings.
407        return NK_Variable_Narrowing;
408      }
409    }
410    return NK_Not_Narrowing;
411  }
412
413  default:
414    // Other kinds of conversions are not narrowings.
415    return NK_Not_Narrowing;
416  }
417}
418
419/// DebugPrint - Print this standard conversion sequence to standard
420/// error. Useful for debugging overloading issues.
421void StandardConversionSequence::DebugPrint() const {
422  raw_ostream &OS = llvm::errs();
423  bool PrintedSomething = false;
424  if (First != ICK_Identity) {
425    OS << GetImplicitConversionName(First);
426    PrintedSomething = true;
427  }
428
429  if (Second != ICK_Identity) {
430    if (PrintedSomething) {
431      OS << " -> ";
432    }
433    OS << GetImplicitConversionName(Second);
434
435    if (CopyConstructor) {
436      OS << " (by copy constructor)";
437    } else if (DirectBinding) {
438      OS << " (direct reference binding)";
439    } else if (ReferenceBinding) {
440      OS << " (reference binding)";
441    }
442    PrintedSomething = true;
443  }
444
445  if (Third != ICK_Identity) {
446    if (PrintedSomething) {
447      OS << " -> ";
448    }
449    OS << GetImplicitConversionName(Third);
450    PrintedSomething = true;
451  }
452
453  if (!PrintedSomething) {
454    OS << "No conversions required";
455  }
456}
457
458/// DebugPrint - Print this user-defined conversion sequence to standard
459/// error. Useful for debugging overloading issues.
460void UserDefinedConversionSequence::DebugPrint() const {
461  raw_ostream &OS = llvm::errs();
462  if (Before.First || Before.Second || Before.Third) {
463    Before.DebugPrint();
464    OS << " -> ";
465  }
466  if (ConversionFunction)
467    OS << '\'' << *ConversionFunction << '\'';
468  else
469    OS << "aggregate initialization";
470  if (After.First || After.Second || After.Third) {
471    OS << " -> ";
472    After.DebugPrint();
473  }
474}
475
476/// DebugPrint - Print this implicit conversion sequence to standard
477/// error. Useful for debugging overloading issues.
478void ImplicitConversionSequence::DebugPrint() const {
479  raw_ostream &OS = llvm::errs();
480  switch (ConversionKind) {
481  case StandardConversion:
482    OS << "Standard conversion: ";
483    Standard.DebugPrint();
484    break;
485  case UserDefinedConversion:
486    OS << "User-defined conversion: ";
487    UserDefined.DebugPrint();
488    break;
489  case EllipsisConversion:
490    OS << "Ellipsis conversion";
491    break;
492  case AmbiguousConversion:
493    OS << "Ambiguous conversion";
494    break;
495  case BadConversion:
496    OS << "Bad conversion";
497    break;
498  }
499
500  OS << "\n";
501}
502
503void AmbiguousConversionSequence::construct() {
504  new (&conversions()) ConversionSet();
505}
506
507void AmbiguousConversionSequence::destruct() {
508  conversions().~ConversionSet();
509}
510
511void
512AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
513  FromTypePtr = O.FromTypePtr;
514  ToTypePtr = O.ToTypePtr;
515  new (&conversions()) ConversionSet(O.conversions());
516}
517
518namespace {
519  // Structure used by OverloadCandidate::DeductionFailureInfo to store
520  // template parameter and template argument information.
521  struct DFIParamWithArguments {
522    TemplateParameter Param;
523    TemplateArgument FirstArg;
524    TemplateArgument SecondArg;
525  };
526}
527
528/// \brief Convert from Sema's representation of template deduction information
529/// to the form used in overload-candidate information.
530OverloadCandidate::DeductionFailureInfo
531static MakeDeductionFailureInfo(ASTContext &Context,
532                                Sema::TemplateDeductionResult TDK,
533                                TemplateDeductionInfo &Info) {
534  OverloadCandidate::DeductionFailureInfo Result;
535  Result.Result = static_cast<unsigned>(TDK);
536  Result.Data = 0;
537  switch (TDK) {
538  case Sema::TDK_Success:
539  case Sema::TDK_InstantiationDepth:
540  case Sema::TDK_TooManyArguments:
541  case Sema::TDK_TooFewArguments:
542    break;
543
544  case Sema::TDK_Incomplete:
545  case Sema::TDK_InvalidExplicitArguments:
546    Result.Data = Info.Param.getOpaqueValue();
547    break;
548
549  case Sema::TDK_Inconsistent:
550  case Sema::TDK_Underqualified: {
551    // FIXME: Should allocate from normal heap so that we can free this later.
552    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
553    Saved->Param = Info.Param;
554    Saved->FirstArg = Info.FirstArg;
555    Saved->SecondArg = Info.SecondArg;
556    Result.Data = Saved;
557    break;
558  }
559
560  case Sema::TDK_SubstitutionFailure:
561    Result.Data = Info.take();
562    break;
563
564  case Sema::TDK_NonDeducedMismatch:
565  case Sema::TDK_FailedOverloadResolution:
566    break;
567  }
568
569  return Result;
570}
571
572void OverloadCandidate::DeductionFailureInfo::Destroy() {
573  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
574  case Sema::TDK_Success:
575  case Sema::TDK_InstantiationDepth:
576  case Sema::TDK_Incomplete:
577  case Sema::TDK_TooManyArguments:
578  case Sema::TDK_TooFewArguments:
579  case Sema::TDK_InvalidExplicitArguments:
580    break;
581
582  case Sema::TDK_Inconsistent:
583  case Sema::TDK_Underqualified:
584    // FIXME: Destroy the data?
585    Data = 0;
586    break;
587
588  case Sema::TDK_SubstitutionFailure:
589    // FIXME: Destroy the template arugment list?
590    Data = 0;
591    break;
592
593  // Unhandled
594  case Sema::TDK_NonDeducedMismatch:
595  case Sema::TDK_FailedOverloadResolution:
596    break;
597  }
598}
599
600TemplateParameter
601OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
602  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
603  case Sema::TDK_Success:
604  case Sema::TDK_InstantiationDepth:
605  case Sema::TDK_TooManyArguments:
606  case Sema::TDK_TooFewArguments:
607  case Sema::TDK_SubstitutionFailure:
608    return TemplateParameter();
609
610  case Sema::TDK_Incomplete:
611  case Sema::TDK_InvalidExplicitArguments:
612    return TemplateParameter::getFromOpaqueValue(Data);
613
614  case Sema::TDK_Inconsistent:
615  case Sema::TDK_Underqualified:
616    return static_cast<DFIParamWithArguments*>(Data)->Param;
617
618  // Unhandled
619  case Sema::TDK_NonDeducedMismatch:
620  case Sema::TDK_FailedOverloadResolution:
621    break;
622  }
623
624  return TemplateParameter();
625}
626
627TemplateArgumentList *
628OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
629  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
630    case Sema::TDK_Success:
631    case Sema::TDK_InstantiationDepth:
632    case Sema::TDK_TooManyArguments:
633    case Sema::TDK_TooFewArguments:
634    case Sema::TDK_Incomplete:
635    case Sema::TDK_InvalidExplicitArguments:
636    case Sema::TDK_Inconsistent:
637    case Sema::TDK_Underqualified:
638      return 0;
639
640    case Sema::TDK_SubstitutionFailure:
641      return static_cast<TemplateArgumentList*>(Data);
642
643    // Unhandled
644    case Sema::TDK_NonDeducedMismatch:
645    case Sema::TDK_FailedOverloadResolution:
646      break;
647  }
648
649  return 0;
650}
651
652const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
653  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
654  case Sema::TDK_Success:
655  case Sema::TDK_InstantiationDepth:
656  case Sema::TDK_Incomplete:
657  case Sema::TDK_TooManyArguments:
658  case Sema::TDK_TooFewArguments:
659  case Sema::TDK_InvalidExplicitArguments:
660  case Sema::TDK_SubstitutionFailure:
661    return 0;
662
663  case Sema::TDK_Inconsistent:
664  case Sema::TDK_Underqualified:
665    return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
666
667  // Unhandled
668  case Sema::TDK_NonDeducedMismatch:
669  case Sema::TDK_FailedOverloadResolution:
670    break;
671  }
672
673  return 0;
674}
675
676const TemplateArgument *
677OverloadCandidate::DeductionFailureInfo::getSecondArg() {
678  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
679  case Sema::TDK_Success:
680  case Sema::TDK_InstantiationDepth:
681  case Sema::TDK_Incomplete:
682  case Sema::TDK_TooManyArguments:
683  case Sema::TDK_TooFewArguments:
684  case Sema::TDK_InvalidExplicitArguments:
685  case Sema::TDK_SubstitutionFailure:
686    return 0;
687
688  case Sema::TDK_Inconsistent:
689  case Sema::TDK_Underqualified:
690    return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
691
692  // Unhandled
693  case Sema::TDK_NonDeducedMismatch:
694  case Sema::TDK_FailedOverloadResolution:
695    break;
696  }
697
698  return 0;
699}
700
701void OverloadCandidateSet::clear() {
702  for (iterator i = begin(), e = end(); i != e; ++i)
703    for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
704      i->Conversions[ii].~ImplicitConversionSequence();
705  NumInlineSequences = 0;
706  Candidates.clear();
707  Functions.clear();
708}
709
710namespace {
711  class UnbridgedCastsSet {
712    struct Entry {
713      Expr **Addr;
714      Expr *Saved;
715    };
716    SmallVector<Entry, 2> Entries;
717
718  public:
719    void save(Sema &S, Expr *&E) {
720      assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
721      Entry entry = { &E, E };
722      Entries.push_back(entry);
723      E = S.stripARCUnbridgedCast(E);
724    }
725
726    void restore() {
727      for (SmallVectorImpl<Entry>::iterator
728             i = Entries.begin(), e = Entries.end(); i != e; ++i)
729        *i->Addr = i->Saved;
730    }
731  };
732}
733
734/// checkPlaceholderForOverload - Do any interesting placeholder-like
735/// preprocessing on the given expression.
736///
737/// \param unbridgedCasts a collection to which to add unbridged casts;
738///   without this, they will be immediately diagnosed as errors
739///
740/// Return true on unrecoverable error.
741static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
742                                        UnbridgedCastsSet *unbridgedCasts = 0) {
743  if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
744    // We can't handle overloaded expressions here because overload
745    // resolution might reasonably tweak them.
746    if (placeholder->getKind() == BuiltinType::Overload) return false;
747
748    // If the context potentially accepts unbridged ARC casts, strip
749    // the unbridged cast and add it to the collection for later restoration.
750    if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
751        unbridgedCasts) {
752      unbridgedCasts->save(S, E);
753      return false;
754    }
755
756    // Go ahead and check everything else.
757    ExprResult result = S.CheckPlaceholderExpr(E);
758    if (result.isInvalid())
759      return true;
760
761    E = result.take();
762    return false;
763  }
764
765  // Nothing to do.
766  return false;
767}
768
769/// checkArgPlaceholdersForOverload - Check a set of call operands for
770/// placeholders.
771static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
772                                            unsigned numArgs,
773                                            UnbridgedCastsSet &unbridged) {
774  for (unsigned i = 0; i != numArgs; ++i)
775    if (checkPlaceholderForOverload(S, args[i], &unbridged))
776      return true;
777
778  return false;
779}
780
781// IsOverload - Determine whether the given New declaration is an
782// overload of the declarations in Old. This routine returns false if
783// New and Old cannot be overloaded, e.g., if New has the same
784// signature as some function in Old (C++ 1.3.10) or if the Old
785// declarations aren't functions (or function templates) at all. When
786// it does return false, MatchedDecl will point to the decl that New
787// cannot be overloaded with.  This decl may be a UsingShadowDecl on
788// top of the underlying declaration.
789//
790// Example: Given the following input:
791//
792//   void f(int, float); // #1
793//   void f(int, int); // #2
794//   int f(int, int); // #3
795//
796// When we process #1, there is no previous declaration of "f",
797// so IsOverload will not be used.
798//
799// When we process #2, Old contains only the FunctionDecl for #1.  By
800// comparing the parameter types, we see that #1 and #2 are overloaded
801// (since they have different signatures), so this routine returns
802// false; MatchedDecl is unchanged.
803//
804// When we process #3, Old is an overload set containing #1 and #2. We
805// compare the signatures of #3 to #1 (they're overloaded, so we do
806// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
807// identical (return types of functions are not part of the
808// signature), IsOverload returns false and MatchedDecl will be set to
809// point to the FunctionDecl for #2.
810//
811// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
812// into a class by a using declaration.  The rules for whether to hide
813// shadow declarations ignore some properties which otherwise figure
814// into a function template's signature.
815Sema::OverloadKind
816Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
817                    NamedDecl *&Match, bool NewIsUsingDecl) {
818  for (LookupResult::iterator I = Old.begin(), E = Old.end();
819         I != E; ++I) {
820    NamedDecl *OldD = *I;
821
822    bool OldIsUsingDecl = false;
823    if (isa<UsingShadowDecl>(OldD)) {
824      OldIsUsingDecl = true;
825
826      // We can always introduce two using declarations into the same
827      // context, even if they have identical signatures.
828      if (NewIsUsingDecl) continue;
829
830      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
831    }
832
833    // If either declaration was introduced by a using declaration,
834    // we'll need to use slightly different rules for matching.
835    // Essentially, these rules are the normal rules, except that
836    // function templates hide function templates with different
837    // return types or template parameter lists.
838    bool UseMemberUsingDeclRules =
839      (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
840
841    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
842      if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
843        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
844          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
845          continue;
846        }
847
848        Match = *I;
849        return Ovl_Match;
850      }
851    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
852      if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
853        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
854          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
855          continue;
856        }
857
858        Match = *I;
859        return Ovl_Match;
860      }
861    } else if (isa<UsingDecl>(OldD)) {
862      // We can overload with these, which can show up when doing
863      // redeclaration checks for UsingDecls.
864      assert(Old.getLookupKind() == LookupUsingDeclName);
865    } else if (isa<TagDecl>(OldD)) {
866      // We can always overload with tags by hiding them.
867    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
868      // Optimistically assume that an unresolved using decl will
869      // overload; if it doesn't, we'll have to diagnose during
870      // template instantiation.
871    } else {
872      // (C++ 13p1):
873      //   Only function declarations can be overloaded; object and type
874      //   declarations cannot be overloaded.
875      Match = *I;
876      return Ovl_NonFunction;
877    }
878  }
879
880  return Ovl_Overload;
881}
882
883bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
884                      bool UseUsingDeclRules) {
885  // If both of the functions are extern "C", then they are not
886  // overloads.
887  if (Old->isExternC() && New->isExternC())
888    return false;
889
890  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
891  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
892
893  // C++ [temp.fct]p2:
894  //   A function template can be overloaded with other function templates
895  //   and with normal (non-template) functions.
896  if ((OldTemplate == 0) != (NewTemplate == 0))
897    return true;
898
899  // Is the function New an overload of the function Old?
900  QualType OldQType = Context.getCanonicalType(Old->getType());
901  QualType NewQType = Context.getCanonicalType(New->getType());
902
903  // Compare the signatures (C++ 1.3.10) of the two functions to
904  // determine whether they are overloads. If we find any mismatch
905  // in the signature, they are overloads.
906
907  // If either of these functions is a K&R-style function (no
908  // prototype), then we consider them to have matching signatures.
909  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
910      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
911    return false;
912
913  const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
914  const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
915
916  // The signature of a function includes the types of its
917  // parameters (C++ 1.3.10), which includes the presence or absence
918  // of the ellipsis; see C++ DR 357).
919  if (OldQType != NewQType &&
920      (OldType->getNumArgs() != NewType->getNumArgs() ||
921       OldType->isVariadic() != NewType->isVariadic() ||
922       !FunctionArgTypesAreEqual(OldType, NewType)))
923    return true;
924
925  // C++ [temp.over.link]p4:
926  //   The signature of a function template consists of its function
927  //   signature, its return type and its template parameter list. The names
928  //   of the template parameters are significant only for establishing the
929  //   relationship between the template parameters and the rest of the
930  //   signature.
931  //
932  // We check the return type and template parameter lists for function
933  // templates first; the remaining checks follow.
934  //
935  // However, we don't consider either of these when deciding whether
936  // a member introduced by a shadow declaration is hidden.
937  if (!UseUsingDeclRules && NewTemplate &&
938      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
939                                       OldTemplate->getTemplateParameters(),
940                                       false, TPL_TemplateMatch) ||
941       OldType->getResultType() != NewType->getResultType()))
942    return true;
943
944  // If the function is a class member, its signature includes the
945  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
946  //
947  // As part of this, also check whether one of the member functions
948  // is static, in which case they are not overloads (C++
949  // 13.1p2). While not part of the definition of the signature,
950  // this check is important to determine whether these functions
951  // can be overloaded.
952  CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
953  CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
954  if (OldMethod && NewMethod &&
955      !OldMethod->isStatic() && !NewMethod->isStatic() &&
956      (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
957       OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
958    if (!UseUsingDeclRules &&
959        OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
960        (OldMethod->getRefQualifier() == RQ_None ||
961         NewMethod->getRefQualifier() == RQ_None)) {
962      // C++0x [over.load]p2:
963      //   - Member function declarations with the same name and the same
964      //     parameter-type-list as well as member function template
965      //     declarations with the same name, the same parameter-type-list, and
966      //     the same template parameter lists cannot be overloaded if any of
967      //     them, but not all, have a ref-qualifier (8.3.5).
968      Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
969        << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
970      Diag(OldMethod->getLocation(), diag::note_previous_declaration);
971    }
972
973    return true;
974  }
975
976  // The signatures match; this is not an overload.
977  return false;
978}
979
980/// \brief Checks availability of the function depending on the current
981/// function context. Inside an unavailable function, unavailability is ignored.
982///
983/// \returns true if \arg FD is unavailable and current context is inside
984/// an available function, false otherwise.
985bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
986  return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
987}
988
989/// \brief Tries a user-defined conversion from From to ToType.
990///
991/// Produces an implicit conversion sequence for when a standard conversion
992/// is not an option. See TryImplicitConversion for more information.
993static ImplicitConversionSequence
994TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
995                         bool SuppressUserConversions,
996                         bool AllowExplicit,
997                         bool InOverloadResolution,
998                         bool CStyle,
999                         bool AllowObjCWritebackConversion) {
1000  ImplicitConversionSequence ICS;
1001
1002  if (SuppressUserConversions) {
1003    // We're not in the case above, so there is no conversion that
1004    // we can perform.
1005    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1006    return ICS;
1007  }
1008
1009  // Attempt user-defined conversion.
1010  OverloadCandidateSet Conversions(From->getExprLoc());
1011  OverloadingResult UserDefResult
1012    = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1013                              AllowExplicit);
1014
1015  if (UserDefResult == OR_Success) {
1016    ICS.setUserDefined();
1017    // C++ [over.ics.user]p4:
1018    //   A conversion of an expression of class type to the same class
1019    //   type is given Exact Match rank, and a conversion of an
1020    //   expression of class type to a base class of that type is
1021    //   given Conversion rank, in spite of the fact that a copy
1022    //   constructor (i.e., a user-defined conversion function) is
1023    //   called for those cases.
1024    if (CXXConstructorDecl *Constructor
1025          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1026      QualType FromCanon
1027        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1028      QualType ToCanon
1029        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1030      if (Constructor->isCopyConstructor() &&
1031          (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1032        // Turn this into a "standard" conversion sequence, so that it
1033        // gets ranked with standard conversion sequences.
1034        ICS.setStandard();
1035        ICS.Standard.setAsIdentityConversion();
1036        ICS.Standard.setFromType(From->getType());
1037        ICS.Standard.setAllToTypes(ToType);
1038        ICS.Standard.CopyConstructor = Constructor;
1039        if (ToCanon != FromCanon)
1040          ICS.Standard.Second = ICK_Derived_To_Base;
1041      }
1042    }
1043
1044    // C++ [over.best.ics]p4:
1045    //   However, when considering the argument of a user-defined
1046    //   conversion function that is a candidate by 13.3.1.3 when
1047    //   invoked for the copying of the temporary in the second step
1048    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1049    //   13.3.1.6 in all cases, only standard conversion sequences and
1050    //   ellipsis conversion sequences are allowed.
1051    if (SuppressUserConversions && ICS.isUserDefined()) {
1052      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1053    }
1054  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1055    ICS.setAmbiguous();
1056    ICS.Ambiguous.setFromType(From->getType());
1057    ICS.Ambiguous.setToType(ToType);
1058    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1059         Cand != Conversions.end(); ++Cand)
1060      if (Cand->Viable)
1061        ICS.Ambiguous.addConversion(Cand->Function);
1062  } else {
1063    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1064  }
1065
1066  return ICS;
1067}
1068
1069/// TryImplicitConversion - Attempt to perform an implicit conversion
1070/// from the given expression (Expr) to the given type (ToType). This
1071/// function returns an implicit conversion sequence that can be used
1072/// to perform the initialization. Given
1073///
1074///   void f(float f);
1075///   void g(int i) { f(i); }
1076///
1077/// this routine would produce an implicit conversion sequence to
1078/// describe the initialization of f from i, which will be a standard
1079/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1080/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1081//
1082/// Note that this routine only determines how the conversion can be
1083/// performed; it does not actually perform the conversion. As such,
1084/// it will not produce any diagnostics if no conversion is available,
1085/// but will instead return an implicit conversion sequence of kind
1086/// "BadConversion".
1087///
1088/// If @p SuppressUserConversions, then user-defined conversions are
1089/// not permitted.
1090/// If @p AllowExplicit, then explicit user-defined conversions are
1091/// permitted.
1092///
1093/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1094/// writeback conversion, which allows __autoreleasing id* parameters to
1095/// be initialized with __strong id* or __weak id* arguments.
1096static ImplicitConversionSequence
1097TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1098                      bool SuppressUserConversions,
1099                      bool AllowExplicit,
1100                      bool InOverloadResolution,
1101                      bool CStyle,
1102                      bool AllowObjCWritebackConversion) {
1103  ImplicitConversionSequence ICS;
1104  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1105                           ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1106    ICS.setStandard();
1107    return ICS;
1108  }
1109
1110  if (!S.getLangOptions().CPlusPlus) {
1111    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1112    return ICS;
1113  }
1114
1115  // C++ [over.ics.user]p4:
1116  //   A conversion of an expression of class type to the same class
1117  //   type is given Exact Match rank, and a conversion of an
1118  //   expression of class type to a base class of that type is
1119  //   given Conversion rank, in spite of the fact that a copy/move
1120  //   constructor (i.e., a user-defined conversion function) is
1121  //   called for those cases.
1122  QualType FromType = From->getType();
1123  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1124      (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1125       S.IsDerivedFrom(FromType, ToType))) {
1126    ICS.setStandard();
1127    ICS.Standard.setAsIdentityConversion();
1128    ICS.Standard.setFromType(FromType);
1129    ICS.Standard.setAllToTypes(ToType);
1130
1131    // We don't actually check at this point whether there is a valid
1132    // copy/move constructor, since overloading just assumes that it
1133    // exists. When we actually perform initialization, we'll find the
1134    // appropriate constructor to copy the returned object, if needed.
1135    ICS.Standard.CopyConstructor = 0;
1136
1137    // Determine whether this is considered a derived-to-base conversion.
1138    if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1139      ICS.Standard.Second = ICK_Derived_To_Base;
1140
1141    return ICS;
1142  }
1143
1144  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1145                                  AllowExplicit, InOverloadResolution, CStyle,
1146                                  AllowObjCWritebackConversion);
1147}
1148
1149ImplicitConversionSequence
1150Sema::TryImplicitConversion(Expr *From, QualType ToType,
1151                            bool SuppressUserConversions,
1152                            bool AllowExplicit,
1153                            bool InOverloadResolution,
1154                            bool CStyle,
1155                            bool AllowObjCWritebackConversion) {
1156  return clang::TryImplicitConversion(*this, From, ToType,
1157                                      SuppressUserConversions, AllowExplicit,
1158                                      InOverloadResolution, CStyle,
1159                                      AllowObjCWritebackConversion);
1160}
1161
1162/// PerformImplicitConversion - Perform an implicit conversion of the
1163/// expression From to the type ToType. Returns the
1164/// converted expression. Flavor is the kind of conversion we're
1165/// performing, used in the error message. If @p AllowExplicit,
1166/// explicit user-defined conversions are permitted.
1167ExprResult
1168Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1169                                AssignmentAction Action, bool AllowExplicit) {
1170  ImplicitConversionSequence ICS;
1171  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1172}
1173
1174ExprResult
1175Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1176                                AssignmentAction Action, bool AllowExplicit,
1177                                ImplicitConversionSequence& ICS) {
1178  if (checkPlaceholderForOverload(*this, From))
1179    return ExprError();
1180
1181  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1182  bool AllowObjCWritebackConversion
1183    = getLangOptions().ObjCAutoRefCount &&
1184      (Action == AA_Passing || Action == AA_Sending);
1185
1186  ICS = clang::TryImplicitConversion(*this, From, ToType,
1187                                     /*SuppressUserConversions=*/false,
1188                                     AllowExplicit,
1189                                     /*InOverloadResolution=*/false,
1190                                     /*CStyle=*/false,
1191                                     AllowObjCWritebackConversion);
1192  return PerformImplicitConversion(From, ToType, ICS, Action);
1193}
1194
1195/// \brief Determine whether the conversion from FromType to ToType is a valid
1196/// conversion that strips "noreturn" off the nested function type.
1197bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1198                                QualType &ResultTy) {
1199  if (Context.hasSameUnqualifiedType(FromType, ToType))
1200    return false;
1201
1202  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1203  // where F adds one of the following at most once:
1204  //   - a pointer
1205  //   - a member pointer
1206  //   - a block pointer
1207  CanQualType CanTo = Context.getCanonicalType(ToType);
1208  CanQualType CanFrom = Context.getCanonicalType(FromType);
1209  Type::TypeClass TyClass = CanTo->getTypeClass();
1210  if (TyClass != CanFrom->getTypeClass()) return false;
1211  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1212    if (TyClass == Type::Pointer) {
1213      CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1214      CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1215    } else if (TyClass == Type::BlockPointer) {
1216      CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1217      CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1218    } else if (TyClass == Type::MemberPointer) {
1219      CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1220      CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1221    } else {
1222      return false;
1223    }
1224
1225    TyClass = CanTo->getTypeClass();
1226    if (TyClass != CanFrom->getTypeClass()) return false;
1227    if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1228      return false;
1229  }
1230
1231  const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1232  FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1233  if (!EInfo.getNoReturn()) return false;
1234
1235  FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1236  assert(QualType(FromFn, 0).isCanonical());
1237  if (QualType(FromFn, 0) != CanTo) return false;
1238
1239  ResultTy = ToType;
1240  return true;
1241}
1242
1243/// \brief Determine whether the conversion from FromType to ToType is a valid
1244/// vector conversion.
1245///
1246/// \param ICK Will be set to the vector conversion kind, if this is a vector
1247/// conversion.
1248static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1249                               QualType ToType, ImplicitConversionKind &ICK) {
1250  // We need at least one of these types to be a vector type to have a vector
1251  // conversion.
1252  if (!ToType->isVectorType() && !FromType->isVectorType())
1253    return false;
1254
1255  // Identical types require no conversions.
1256  if (Context.hasSameUnqualifiedType(FromType, ToType))
1257    return false;
1258
1259  // There are no conversions between extended vector types, only identity.
1260  if (ToType->isExtVectorType()) {
1261    // There are no conversions between extended vector types other than the
1262    // identity conversion.
1263    if (FromType->isExtVectorType())
1264      return false;
1265
1266    // Vector splat from any arithmetic type to a vector.
1267    if (FromType->isArithmeticType()) {
1268      ICK = ICK_Vector_Splat;
1269      return true;
1270    }
1271  }
1272
1273  // We can perform the conversion between vector types in the following cases:
1274  // 1)vector types are equivalent AltiVec and GCC vector types
1275  // 2)lax vector conversions are permitted and the vector types are of the
1276  //   same size
1277  if (ToType->isVectorType() && FromType->isVectorType()) {
1278    if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1279        (Context.getLangOptions().LaxVectorConversions &&
1280         (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1281      ICK = ICK_Vector_Conversion;
1282      return true;
1283    }
1284  }
1285
1286  return false;
1287}
1288
1289/// IsStandardConversion - Determines whether there is a standard
1290/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1291/// expression From to the type ToType. Standard conversion sequences
1292/// only consider non-class types; for conversions that involve class
1293/// types, use TryImplicitConversion. If a conversion exists, SCS will
1294/// contain the standard conversion sequence required to perform this
1295/// conversion and this routine will return true. Otherwise, this
1296/// routine will return false and the value of SCS is unspecified.
1297static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1298                                 bool InOverloadResolution,
1299                                 StandardConversionSequence &SCS,
1300                                 bool CStyle,
1301                                 bool AllowObjCWritebackConversion) {
1302  QualType FromType = From->getType();
1303
1304  // Standard conversions (C++ [conv])
1305  SCS.setAsIdentityConversion();
1306  SCS.DeprecatedStringLiteralToCharPtr = false;
1307  SCS.IncompatibleObjC = false;
1308  SCS.setFromType(FromType);
1309  SCS.CopyConstructor = 0;
1310
1311  // There are no standard conversions for class types in C++, so
1312  // abort early. When overloading in C, however, we do permit
1313  if (FromType->isRecordType() || ToType->isRecordType()) {
1314    if (S.getLangOptions().CPlusPlus)
1315      return false;
1316
1317    // When we're overloading in C, we allow, as standard conversions,
1318  }
1319
1320  // The first conversion can be an lvalue-to-rvalue conversion,
1321  // array-to-pointer conversion, or function-to-pointer conversion
1322  // (C++ 4p1).
1323
1324  if (FromType == S.Context.OverloadTy) {
1325    DeclAccessPair AccessPair;
1326    if (FunctionDecl *Fn
1327          = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1328                                                 AccessPair)) {
1329      // We were able to resolve the address of the overloaded function,
1330      // so we can convert to the type of that function.
1331      FromType = Fn->getType();
1332
1333      // we can sometimes resolve &foo<int> regardless of ToType, so check
1334      // if the type matches (identity) or we are converting to bool
1335      if (!S.Context.hasSameUnqualifiedType(
1336                      S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1337        QualType resultTy;
1338        // if the function type matches except for [[noreturn]], it's ok
1339        if (!S.IsNoReturnConversion(FromType,
1340              S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1341          // otherwise, only a boolean conversion is standard
1342          if (!ToType->isBooleanType())
1343            return false;
1344      }
1345
1346      // Check if the "from" expression is taking the address of an overloaded
1347      // function and recompute the FromType accordingly. Take advantage of the
1348      // fact that non-static member functions *must* have such an address-of
1349      // expression.
1350      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1351      if (Method && !Method->isStatic()) {
1352        assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1353               "Non-unary operator on non-static member address");
1354        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1355               == UO_AddrOf &&
1356               "Non-address-of operator on non-static member address");
1357        const Type *ClassType
1358          = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1359        FromType = S.Context.getMemberPointerType(FromType, ClassType);
1360      } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1361        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1362               UO_AddrOf &&
1363               "Non-address-of operator for overloaded function expression");
1364        FromType = S.Context.getPointerType(FromType);
1365      }
1366
1367      // Check that we've computed the proper type after overload resolution.
1368      assert(S.Context.hasSameType(
1369        FromType,
1370        S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1371    } else {
1372      return false;
1373    }
1374  }
1375  // Lvalue-to-rvalue conversion (C++11 4.1):
1376  //   A glvalue (3.10) of a non-function, non-array type T can
1377  //   be converted to a prvalue.
1378  bool argIsLValue = From->isGLValue();
1379  if (argIsLValue &&
1380      !FromType->isFunctionType() && !FromType->isArrayType() &&
1381      S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1382    SCS.First = ICK_Lvalue_To_Rvalue;
1383
1384    // If T is a non-class type, the type of the rvalue is the
1385    // cv-unqualified version of T. Otherwise, the type of the rvalue
1386    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1387    // just strip the qualifiers because they don't matter.
1388    FromType = FromType.getUnqualifiedType();
1389  } else if (FromType->isArrayType()) {
1390    // Array-to-pointer conversion (C++ 4.2)
1391    SCS.First = ICK_Array_To_Pointer;
1392
1393    // An lvalue or rvalue of type "array of N T" or "array of unknown
1394    // bound of T" can be converted to an rvalue of type "pointer to
1395    // T" (C++ 4.2p1).
1396    FromType = S.Context.getArrayDecayedType(FromType);
1397
1398    if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1399      // This conversion is deprecated. (C++ D.4).
1400      SCS.DeprecatedStringLiteralToCharPtr = true;
1401
1402      // For the purpose of ranking in overload resolution
1403      // (13.3.3.1.1), this conversion is considered an
1404      // array-to-pointer conversion followed by a qualification
1405      // conversion (4.4). (C++ 4.2p2)
1406      SCS.Second = ICK_Identity;
1407      SCS.Third = ICK_Qualification;
1408      SCS.QualificationIncludesObjCLifetime = false;
1409      SCS.setAllToTypes(FromType);
1410      return true;
1411    }
1412  } else if (FromType->isFunctionType() && argIsLValue) {
1413    // Function-to-pointer conversion (C++ 4.3).
1414    SCS.First = ICK_Function_To_Pointer;
1415
1416    // An lvalue of function type T can be converted to an rvalue of
1417    // type "pointer to T." The result is a pointer to the
1418    // function. (C++ 4.3p1).
1419    FromType = S.Context.getPointerType(FromType);
1420  } else {
1421    // We don't require any conversions for the first step.
1422    SCS.First = ICK_Identity;
1423  }
1424  SCS.setToType(0, FromType);
1425
1426  // The second conversion can be an integral promotion, floating
1427  // point promotion, integral conversion, floating point conversion,
1428  // floating-integral conversion, pointer conversion,
1429  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1430  // For overloading in C, this can also be a "compatible-type"
1431  // conversion.
1432  bool IncompatibleObjC = false;
1433  ImplicitConversionKind SecondICK = ICK_Identity;
1434  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1435    // The unqualified versions of the types are the same: there's no
1436    // conversion to do.
1437    SCS.Second = ICK_Identity;
1438  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1439    // Integral promotion (C++ 4.5).
1440    SCS.Second = ICK_Integral_Promotion;
1441    FromType = ToType.getUnqualifiedType();
1442  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1443    // Floating point promotion (C++ 4.6).
1444    SCS.Second = ICK_Floating_Promotion;
1445    FromType = ToType.getUnqualifiedType();
1446  } else if (S.IsComplexPromotion(FromType, ToType)) {
1447    // Complex promotion (Clang extension)
1448    SCS.Second = ICK_Complex_Promotion;
1449    FromType = ToType.getUnqualifiedType();
1450  } else if (ToType->isBooleanType() &&
1451             (FromType->isArithmeticType() ||
1452              FromType->isAnyPointerType() ||
1453              FromType->isBlockPointerType() ||
1454              FromType->isMemberPointerType() ||
1455              FromType->isNullPtrType())) {
1456    // Boolean conversions (C++ 4.12).
1457    SCS.Second = ICK_Boolean_Conversion;
1458    FromType = S.Context.BoolTy;
1459  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1460             ToType->isIntegralType(S.Context)) {
1461    // Integral conversions (C++ 4.7).
1462    SCS.Second = ICK_Integral_Conversion;
1463    FromType = ToType.getUnqualifiedType();
1464  } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1465    // Complex conversions (C99 6.3.1.6)
1466    SCS.Second = ICK_Complex_Conversion;
1467    FromType = ToType.getUnqualifiedType();
1468  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1469             (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1470    // Complex-real conversions (C99 6.3.1.7)
1471    SCS.Second = ICK_Complex_Real;
1472    FromType = ToType.getUnqualifiedType();
1473  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1474    // Floating point conversions (C++ 4.8).
1475    SCS.Second = ICK_Floating_Conversion;
1476    FromType = ToType.getUnqualifiedType();
1477  } else if ((FromType->isRealFloatingType() &&
1478              ToType->isIntegralType(S.Context)) ||
1479             (FromType->isIntegralOrUnscopedEnumerationType() &&
1480              ToType->isRealFloatingType())) {
1481    // Floating-integral conversions (C++ 4.9).
1482    SCS.Second = ICK_Floating_Integral;
1483    FromType = ToType.getUnqualifiedType();
1484  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1485    SCS.Second = ICK_Block_Pointer_Conversion;
1486  } else if (AllowObjCWritebackConversion &&
1487             S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1488    SCS.Second = ICK_Writeback_Conversion;
1489  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1490                                   FromType, IncompatibleObjC)) {
1491    // Pointer conversions (C++ 4.10).
1492    SCS.Second = ICK_Pointer_Conversion;
1493    SCS.IncompatibleObjC = IncompatibleObjC;
1494    FromType = FromType.getUnqualifiedType();
1495  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1496                                         InOverloadResolution, FromType)) {
1497    // Pointer to member conversions (4.11).
1498    SCS.Second = ICK_Pointer_Member;
1499  } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1500    SCS.Second = SecondICK;
1501    FromType = ToType.getUnqualifiedType();
1502  } else if (!S.getLangOptions().CPlusPlus &&
1503             S.Context.typesAreCompatible(ToType, FromType)) {
1504    // Compatible conversions (Clang extension for C function overloading)
1505    SCS.Second = ICK_Compatible_Conversion;
1506    FromType = ToType.getUnqualifiedType();
1507  } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1508    // Treat a conversion that strips "noreturn" as an identity conversion.
1509    SCS.Second = ICK_NoReturn_Adjustment;
1510  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1511                                             InOverloadResolution,
1512                                             SCS, CStyle)) {
1513    SCS.Second = ICK_TransparentUnionConversion;
1514    FromType = ToType;
1515  } else {
1516    // No second conversion required.
1517    SCS.Second = ICK_Identity;
1518  }
1519  SCS.setToType(1, FromType);
1520
1521  QualType CanonFrom;
1522  QualType CanonTo;
1523  // The third conversion can be a qualification conversion (C++ 4p1).
1524  bool ObjCLifetimeConversion;
1525  if (S.IsQualificationConversion(FromType, ToType, CStyle,
1526                                  ObjCLifetimeConversion)) {
1527    SCS.Third = ICK_Qualification;
1528    SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1529    FromType = ToType;
1530    CanonFrom = S.Context.getCanonicalType(FromType);
1531    CanonTo = S.Context.getCanonicalType(ToType);
1532  } else {
1533    // No conversion required
1534    SCS.Third = ICK_Identity;
1535
1536    // C++ [over.best.ics]p6:
1537    //   [...] Any difference in top-level cv-qualification is
1538    //   subsumed by the initialization itself and does not constitute
1539    //   a conversion. [...]
1540    CanonFrom = S.Context.getCanonicalType(FromType);
1541    CanonTo = S.Context.getCanonicalType(ToType);
1542    if (CanonFrom.getLocalUnqualifiedType()
1543                                       == CanonTo.getLocalUnqualifiedType() &&
1544        (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1545         || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1546         || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
1547      FromType = ToType;
1548      CanonFrom = CanonTo;
1549    }
1550  }
1551  SCS.setToType(2, FromType);
1552
1553  // If we have not converted the argument type to the parameter type,
1554  // this is a bad conversion sequence.
1555  if (CanonFrom != CanonTo)
1556    return false;
1557
1558  return true;
1559}
1560
1561static bool
1562IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1563                                     QualType &ToType,
1564                                     bool InOverloadResolution,
1565                                     StandardConversionSequence &SCS,
1566                                     bool CStyle) {
1567
1568  const RecordType *UT = ToType->getAsUnionType();
1569  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1570    return false;
1571  // The field to initialize within the transparent union.
1572  RecordDecl *UD = UT->getDecl();
1573  // It's compatible if the expression matches any of the fields.
1574  for (RecordDecl::field_iterator it = UD->field_begin(),
1575       itend = UD->field_end();
1576       it != itend; ++it) {
1577    if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1578                             CStyle, /*ObjCWritebackConversion=*/false)) {
1579      ToType = it->getType();
1580      return true;
1581    }
1582  }
1583  return false;
1584}
1585
1586/// IsIntegralPromotion - Determines whether the conversion from the
1587/// expression From (whose potentially-adjusted type is FromType) to
1588/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1589/// sets PromotedType to the promoted type.
1590bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1591  const BuiltinType *To = ToType->getAs<BuiltinType>();
1592  // All integers are built-in.
1593  if (!To) {
1594    return false;
1595  }
1596
1597  // An rvalue of type char, signed char, unsigned char, short int, or
1598  // unsigned short int can be converted to an rvalue of type int if
1599  // int can represent all the values of the source type; otherwise,
1600  // the source rvalue can be converted to an rvalue of type unsigned
1601  // int (C++ 4.5p1).
1602  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1603      !FromType->isEnumeralType()) {
1604    if (// We can promote any signed, promotable integer type to an int
1605        (FromType->isSignedIntegerType() ||
1606         // We can promote any unsigned integer type whose size is
1607         // less than int to an int.
1608         (!FromType->isSignedIntegerType() &&
1609          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1610      return To->getKind() == BuiltinType::Int;
1611    }
1612
1613    return To->getKind() == BuiltinType::UInt;
1614  }
1615
1616  // C++0x [conv.prom]p3:
1617  //   A prvalue of an unscoped enumeration type whose underlying type is not
1618  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1619  //   following types that can represent all the values of the enumeration
1620  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1621  //   unsigned int, long int, unsigned long int, long long int, or unsigned
1622  //   long long int. If none of the types in that list can represent all the
1623  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1624  //   type can be converted to an rvalue a prvalue of the extended integer type
1625  //   with lowest integer conversion rank (4.13) greater than the rank of long
1626  //   long in which all the values of the enumeration can be represented. If
1627  //   there are two such extended types, the signed one is chosen.
1628  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1629    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1630    // provided for a scoped enumeration.
1631    if (FromEnumType->getDecl()->isScoped())
1632      return false;
1633
1634    // We have already pre-calculated the promotion type, so this is trivial.
1635    if (ToType->isIntegerType() &&
1636        !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
1637      return Context.hasSameUnqualifiedType(ToType,
1638                                FromEnumType->getDecl()->getPromotionType());
1639  }
1640
1641  // C++0x [conv.prom]p2:
1642  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1643  //   to an rvalue a prvalue of the first of the following types that can
1644  //   represent all the values of its underlying type: int, unsigned int,
1645  //   long int, unsigned long int, long long int, or unsigned long long int.
1646  //   If none of the types in that list can represent all the values of its
1647  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1648  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1649  //   type.
1650  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1651      ToType->isIntegerType()) {
1652    // Determine whether the type we're converting from is signed or
1653    // unsigned.
1654    bool FromIsSigned = FromType->isSignedIntegerType();
1655    uint64_t FromSize = Context.getTypeSize(FromType);
1656
1657    // The types we'll try to promote to, in the appropriate
1658    // order. Try each of these types.
1659    QualType PromoteTypes[6] = {
1660      Context.IntTy, Context.UnsignedIntTy,
1661      Context.LongTy, Context.UnsignedLongTy ,
1662      Context.LongLongTy, Context.UnsignedLongLongTy
1663    };
1664    for (int Idx = 0; Idx < 6; ++Idx) {
1665      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1666      if (FromSize < ToSize ||
1667          (FromSize == ToSize &&
1668           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1669        // We found the type that we can promote to. If this is the
1670        // type we wanted, we have a promotion. Otherwise, no
1671        // promotion.
1672        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1673      }
1674    }
1675  }
1676
1677  // An rvalue for an integral bit-field (9.6) can be converted to an
1678  // rvalue of type int if int can represent all the values of the
1679  // bit-field; otherwise, it can be converted to unsigned int if
1680  // unsigned int can represent all the values of the bit-field. If
1681  // the bit-field is larger yet, no integral promotion applies to
1682  // it. If the bit-field has an enumerated type, it is treated as any
1683  // other value of that type for promotion purposes (C++ 4.5p3).
1684  // FIXME: We should delay checking of bit-fields until we actually perform the
1685  // conversion.
1686  using llvm::APSInt;
1687  if (From)
1688    if (FieldDecl *MemberDecl = From->getBitField()) {
1689      APSInt BitWidth;
1690      if (FromType->isIntegralType(Context) &&
1691          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1692        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1693        ToSize = Context.getTypeSize(ToType);
1694
1695        // Are we promoting to an int from a bitfield that fits in an int?
1696        if (BitWidth < ToSize ||
1697            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1698          return To->getKind() == BuiltinType::Int;
1699        }
1700
1701        // Are we promoting to an unsigned int from an unsigned bitfield
1702        // that fits into an unsigned int?
1703        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1704          return To->getKind() == BuiltinType::UInt;
1705        }
1706
1707        return false;
1708      }
1709    }
1710
1711  // An rvalue of type bool can be converted to an rvalue of type int,
1712  // with false becoming zero and true becoming one (C++ 4.5p4).
1713  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1714    return true;
1715  }
1716
1717  return false;
1718}
1719
1720/// IsFloatingPointPromotion - Determines whether the conversion from
1721/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1722/// returns true and sets PromotedType to the promoted type.
1723bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1724  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1725    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1726      /// An rvalue of type float can be converted to an rvalue of type
1727      /// double. (C++ 4.6p1).
1728      if (FromBuiltin->getKind() == BuiltinType::Float &&
1729          ToBuiltin->getKind() == BuiltinType::Double)
1730        return true;
1731
1732      // C99 6.3.1.5p1:
1733      //   When a float is promoted to double or long double, or a
1734      //   double is promoted to long double [...].
1735      if (!getLangOptions().CPlusPlus &&
1736          (FromBuiltin->getKind() == BuiltinType::Float ||
1737           FromBuiltin->getKind() == BuiltinType::Double) &&
1738          (ToBuiltin->getKind() == BuiltinType::LongDouble))
1739        return true;
1740
1741      // Half can be promoted to float.
1742      if (FromBuiltin->getKind() == BuiltinType::Half &&
1743          ToBuiltin->getKind() == BuiltinType::Float)
1744        return true;
1745    }
1746
1747  return false;
1748}
1749
1750/// \brief Determine if a conversion is a complex promotion.
1751///
1752/// A complex promotion is defined as a complex -> complex conversion
1753/// where the conversion between the underlying real types is a
1754/// floating-point or integral promotion.
1755bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1756  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1757  if (!FromComplex)
1758    return false;
1759
1760  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1761  if (!ToComplex)
1762    return false;
1763
1764  return IsFloatingPointPromotion(FromComplex->getElementType(),
1765                                  ToComplex->getElementType()) ||
1766    IsIntegralPromotion(0, FromComplex->getElementType(),
1767                        ToComplex->getElementType());
1768}
1769
1770/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1771/// the pointer type FromPtr to a pointer to type ToPointee, with the
1772/// same type qualifiers as FromPtr has on its pointee type. ToType,
1773/// if non-empty, will be a pointer to ToType that may or may not have
1774/// the right set of qualifiers on its pointee.
1775///
1776static QualType
1777BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1778                                   QualType ToPointee, QualType ToType,
1779                                   ASTContext &Context,
1780                                   bool StripObjCLifetime = false) {
1781  assert((FromPtr->getTypeClass() == Type::Pointer ||
1782          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1783         "Invalid similarly-qualified pointer type");
1784
1785  /// Conversions to 'id' subsume cv-qualifier conversions.
1786  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1787    return ToType.getUnqualifiedType();
1788
1789  QualType CanonFromPointee
1790    = Context.getCanonicalType(FromPtr->getPointeeType());
1791  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1792  Qualifiers Quals = CanonFromPointee.getQualifiers();
1793
1794  if (StripObjCLifetime)
1795    Quals.removeObjCLifetime();
1796
1797  // Exact qualifier match -> return the pointer type we're converting to.
1798  if (CanonToPointee.getLocalQualifiers() == Quals) {
1799    // ToType is exactly what we need. Return it.
1800    if (!ToType.isNull())
1801      return ToType.getUnqualifiedType();
1802
1803    // Build a pointer to ToPointee. It has the right qualifiers
1804    // already.
1805    if (isa<ObjCObjectPointerType>(ToType))
1806      return Context.getObjCObjectPointerType(ToPointee);
1807    return Context.getPointerType(ToPointee);
1808  }
1809
1810  // Just build a canonical type that has the right qualifiers.
1811  QualType QualifiedCanonToPointee
1812    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1813
1814  if (isa<ObjCObjectPointerType>(ToType))
1815    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1816  return Context.getPointerType(QualifiedCanonToPointee);
1817}
1818
1819static bool isNullPointerConstantForConversion(Expr *Expr,
1820                                               bool InOverloadResolution,
1821                                               ASTContext &Context) {
1822  // Handle value-dependent integral null pointer constants correctly.
1823  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1824  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1825      Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1826    return !InOverloadResolution;
1827
1828  return Expr->isNullPointerConstant(Context,
1829                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1830                                        : Expr::NPC_ValueDependentIsNull);
1831}
1832
1833/// IsPointerConversion - Determines whether the conversion of the
1834/// expression From, which has the (possibly adjusted) type FromType,
1835/// can be converted to the type ToType via a pointer conversion (C++
1836/// 4.10). If so, returns true and places the converted type (that
1837/// might differ from ToType in its cv-qualifiers at some level) into
1838/// ConvertedType.
1839///
1840/// This routine also supports conversions to and from block pointers
1841/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1842/// pointers to interfaces. FIXME: Once we've determined the
1843/// appropriate overloading rules for Objective-C, we may want to
1844/// split the Objective-C checks into a different routine; however,
1845/// GCC seems to consider all of these conversions to be pointer
1846/// conversions, so for now they live here. IncompatibleObjC will be
1847/// set if the conversion is an allowed Objective-C conversion that
1848/// should result in a warning.
1849bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1850                               bool InOverloadResolution,
1851                               QualType& ConvertedType,
1852                               bool &IncompatibleObjC) {
1853  IncompatibleObjC = false;
1854  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1855                              IncompatibleObjC))
1856    return true;
1857
1858  // Conversion from a null pointer constant to any Objective-C pointer type.
1859  if (ToType->isObjCObjectPointerType() &&
1860      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1861    ConvertedType = ToType;
1862    return true;
1863  }
1864
1865  // Blocks: Block pointers can be converted to void*.
1866  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1867      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1868    ConvertedType = ToType;
1869    return true;
1870  }
1871  // Blocks: A null pointer constant can be converted to a block
1872  // pointer type.
1873  if (ToType->isBlockPointerType() &&
1874      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1875    ConvertedType = ToType;
1876    return true;
1877  }
1878
1879  // If the left-hand-side is nullptr_t, the right side can be a null
1880  // pointer constant.
1881  if (ToType->isNullPtrType() &&
1882      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1883    ConvertedType = ToType;
1884    return true;
1885  }
1886
1887  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
1888  if (!ToTypePtr)
1889    return false;
1890
1891  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
1892  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1893    ConvertedType = ToType;
1894    return true;
1895  }
1896
1897  // Beyond this point, both types need to be pointers
1898  // , including objective-c pointers.
1899  QualType ToPointeeType = ToTypePtr->getPointeeType();
1900  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1901      !getLangOptions().ObjCAutoRefCount) {
1902    ConvertedType = BuildSimilarlyQualifiedPointerType(
1903                                      FromType->getAs<ObjCObjectPointerType>(),
1904                                                       ToPointeeType,
1905                                                       ToType, Context);
1906    return true;
1907  }
1908  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
1909  if (!FromTypePtr)
1910    return false;
1911
1912  QualType FromPointeeType = FromTypePtr->getPointeeType();
1913
1914  // If the unqualified pointee types are the same, this can't be a
1915  // pointer conversion, so don't do all of the work below.
1916  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1917    return false;
1918
1919  // An rvalue of type "pointer to cv T," where T is an object type,
1920  // can be converted to an rvalue of type "pointer to cv void" (C++
1921  // 4.10p2).
1922  if (FromPointeeType->isIncompleteOrObjectType() &&
1923      ToPointeeType->isVoidType()) {
1924    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1925                                                       ToPointeeType,
1926                                                       ToType, Context,
1927                                                   /*StripObjCLifetime=*/true);
1928    return true;
1929  }
1930
1931  // MSVC allows implicit function to void* type conversion.
1932  if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
1933      ToPointeeType->isVoidType()) {
1934    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1935                                                       ToPointeeType,
1936                                                       ToType, Context);
1937    return true;
1938  }
1939
1940  // When we're overloading in C, we allow a special kind of pointer
1941  // conversion for compatible-but-not-identical pointee types.
1942  if (!getLangOptions().CPlusPlus &&
1943      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
1944    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1945                                                       ToPointeeType,
1946                                                       ToType, Context);
1947    return true;
1948  }
1949
1950  // C++ [conv.ptr]p3:
1951  //
1952  //   An rvalue of type "pointer to cv D," where D is a class type,
1953  //   can be converted to an rvalue of type "pointer to cv B," where
1954  //   B is a base class (clause 10) of D. If B is an inaccessible
1955  //   (clause 11) or ambiguous (10.2) base class of D, a program that
1956  //   necessitates this conversion is ill-formed. The result of the
1957  //   conversion is a pointer to the base class sub-object of the
1958  //   derived class object. The null pointer value is converted to
1959  //   the null pointer value of the destination type.
1960  //
1961  // Note that we do not check for ambiguity or inaccessibility
1962  // here. That is handled by CheckPointerConversion.
1963  if (getLangOptions().CPlusPlus &&
1964      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1965      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
1966      !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
1967      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
1968    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1969                                                       ToPointeeType,
1970                                                       ToType, Context);
1971    return true;
1972  }
1973
1974  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1975      Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1976    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1977                                                       ToPointeeType,
1978                                                       ToType, Context);
1979    return true;
1980  }
1981
1982  return false;
1983}
1984
1985/// \brief Adopt the given qualifiers for the given type.
1986static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1987  Qualifiers TQs = T.getQualifiers();
1988
1989  // Check whether qualifiers already match.
1990  if (TQs == Qs)
1991    return T;
1992
1993  if (Qs.compatiblyIncludes(TQs))
1994    return Context.getQualifiedType(T, Qs);
1995
1996  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1997}
1998
1999/// isObjCPointerConversion - Determines whether this is an
2000/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2001/// with the same arguments and return values.
2002bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2003                                   QualType& ConvertedType,
2004                                   bool &IncompatibleObjC) {
2005  if (!getLangOptions().ObjC1)
2006    return false;
2007
2008  // The set of qualifiers on the type we're converting from.
2009  Qualifiers FromQualifiers = FromType.getQualifiers();
2010
2011  // First, we handle all conversions on ObjC object pointer types.
2012  const ObjCObjectPointerType* ToObjCPtr =
2013    ToType->getAs<ObjCObjectPointerType>();
2014  const ObjCObjectPointerType *FromObjCPtr =
2015    FromType->getAs<ObjCObjectPointerType>();
2016
2017  if (ToObjCPtr && FromObjCPtr) {
2018    // If the pointee types are the same (ignoring qualifications),
2019    // then this is not a pointer conversion.
2020    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2021                                       FromObjCPtr->getPointeeType()))
2022      return false;
2023
2024    // Check for compatible
2025    // Objective C++: We're able to convert between "id" or "Class" and a
2026    // pointer to any interface (in both directions).
2027    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2028      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2029      return true;
2030    }
2031    // Conversions with Objective-C's id<...>.
2032    if ((FromObjCPtr->isObjCQualifiedIdType() ||
2033         ToObjCPtr->isObjCQualifiedIdType()) &&
2034        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2035                                                  /*compare=*/false)) {
2036      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2037      return true;
2038    }
2039    // Objective C++: We're able to convert from a pointer to an
2040    // interface to a pointer to a different interface.
2041    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2042      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2043      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2044      if (getLangOptions().CPlusPlus && LHS && RHS &&
2045          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2046                                                FromObjCPtr->getPointeeType()))
2047        return false;
2048      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2049                                                   ToObjCPtr->getPointeeType(),
2050                                                         ToType, Context);
2051      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2052      return true;
2053    }
2054
2055    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2056      // Okay: this is some kind of implicit downcast of Objective-C
2057      // interfaces, which is permitted. However, we're going to
2058      // complain about it.
2059      IncompatibleObjC = true;
2060      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2061                                                   ToObjCPtr->getPointeeType(),
2062                                                         ToType, Context);
2063      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2064      return true;
2065    }
2066  }
2067  // Beyond this point, both types need to be C pointers or block pointers.
2068  QualType ToPointeeType;
2069  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2070    ToPointeeType = ToCPtr->getPointeeType();
2071  else if (const BlockPointerType *ToBlockPtr =
2072            ToType->getAs<BlockPointerType>()) {
2073    // Objective C++: We're able to convert from a pointer to any object
2074    // to a block pointer type.
2075    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2076      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2077      return true;
2078    }
2079    ToPointeeType = ToBlockPtr->getPointeeType();
2080  }
2081  else if (FromType->getAs<BlockPointerType>() &&
2082           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2083    // Objective C++: We're able to convert from a block pointer type to a
2084    // pointer to any object.
2085    ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2086    return true;
2087  }
2088  else
2089    return false;
2090
2091  QualType FromPointeeType;
2092  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2093    FromPointeeType = FromCPtr->getPointeeType();
2094  else if (const BlockPointerType *FromBlockPtr =
2095           FromType->getAs<BlockPointerType>())
2096    FromPointeeType = FromBlockPtr->getPointeeType();
2097  else
2098    return false;
2099
2100  // If we have pointers to pointers, recursively check whether this
2101  // is an Objective-C conversion.
2102  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2103      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2104                              IncompatibleObjC)) {
2105    // We always complain about this conversion.
2106    IncompatibleObjC = true;
2107    ConvertedType = Context.getPointerType(ConvertedType);
2108    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2109    return true;
2110  }
2111  // Allow conversion of pointee being objective-c pointer to another one;
2112  // as in I* to id.
2113  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2114      ToPointeeType->getAs<ObjCObjectPointerType>() &&
2115      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2116                              IncompatibleObjC)) {
2117
2118    ConvertedType = Context.getPointerType(ConvertedType);
2119    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2120    return true;
2121  }
2122
2123  // If we have pointers to functions or blocks, check whether the only
2124  // differences in the argument and result types are in Objective-C
2125  // pointer conversions. If so, we permit the conversion (but
2126  // complain about it).
2127  const FunctionProtoType *FromFunctionType
2128    = FromPointeeType->getAs<FunctionProtoType>();
2129  const FunctionProtoType *ToFunctionType
2130    = ToPointeeType->getAs<FunctionProtoType>();
2131  if (FromFunctionType && ToFunctionType) {
2132    // If the function types are exactly the same, this isn't an
2133    // Objective-C pointer conversion.
2134    if (Context.getCanonicalType(FromPointeeType)
2135          == Context.getCanonicalType(ToPointeeType))
2136      return false;
2137
2138    // Perform the quick checks that will tell us whether these
2139    // function types are obviously different.
2140    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2141        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2142        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2143      return false;
2144
2145    bool HasObjCConversion = false;
2146    if (Context.getCanonicalType(FromFunctionType->getResultType())
2147          == Context.getCanonicalType(ToFunctionType->getResultType())) {
2148      // Okay, the types match exactly. Nothing to do.
2149    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2150                                       ToFunctionType->getResultType(),
2151                                       ConvertedType, IncompatibleObjC)) {
2152      // Okay, we have an Objective-C pointer conversion.
2153      HasObjCConversion = true;
2154    } else {
2155      // Function types are too different. Abort.
2156      return false;
2157    }
2158
2159    // Check argument types.
2160    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2161         ArgIdx != NumArgs; ++ArgIdx) {
2162      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2163      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2164      if (Context.getCanonicalType(FromArgType)
2165            == Context.getCanonicalType(ToArgType)) {
2166        // Okay, the types match exactly. Nothing to do.
2167      } else if (isObjCPointerConversion(FromArgType, ToArgType,
2168                                         ConvertedType, IncompatibleObjC)) {
2169        // Okay, we have an Objective-C pointer conversion.
2170        HasObjCConversion = true;
2171      } else {
2172        // Argument types are too different. Abort.
2173        return false;
2174      }
2175    }
2176
2177    if (HasObjCConversion) {
2178      // We had an Objective-C conversion. Allow this pointer
2179      // conversion, but complain about it.
2180      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2181      IncompatibleObjC = true;
2182      return true;
2183    }
2184  }
2185
2186  return false;
2187}
2188
2189/// \brief Determine whether this is an Objective-C writeback conversion,
2190/// used for parameter passing when performing automatic reference counting.
2191///
2192/// \param FromType The type we're converting form.
2193///
2194/// \param ToType The type we're converting to.
2195///
2196/// \param ConvertedType The type that will be produced after applying
2197/// this conversion.
2198bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2199                                     QualType &ConvertedType) {
2200  if (!getLangOptions().ObjCAutoRefCount ||
2201      Context.hasSameUnqualifiedType(FromType, ToType))
2202    return false;
2203
2204  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2205  QualType ToPointee;
2206  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2207    ToPointee = ToPointer->getPointeeType();
2208  else
2209    return false;
2210
2211  Qualifiers ToQuals = ToPointee.getQualifiers();
2212  if (!ToPointee->isObjCLifetimeType() ||
2213      ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2214      !ToQuals.withoutObjCGLifetime().empty())
2215    return false;
2216
2217  // Argument must be a pointer to __strong to __weak.
2218  QualType FromPointee;
2219  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2220    FromPointee = FromPointer->getPointeeType();
2221  else
2222    return false;
2223
2224  Qualifiers FromQuals = FromPointee.getQualifiers();
2225  if (!FromPointee->isObjCLifetimeType() ||
2226      (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2227       FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2228    return false;
2229
2230  // Make sure that we have compatible qualifiers.
2231  FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2232  if (!ToQuals.compatiblyIncludes(FromQuals))
2233    return false;
2234
2235  // Remove qualifiers from the pointee type we're converting from; they
2236  // aren't used in the compatibility check belong, and we'll be adding back
2237  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2238  FromPointee = FromPointee.getUnqualifiedType();
2239
2240  // The unqualified form of the pointee types must be compatible.
2241  ToPointee = ToPointee.getUnqualifiedType();
2242  bool IncompatibleObjC;
2243  if (Context.typesAreCompatible(FromPointee, ToPointee))
2244    FromPointee = ToPointee;
2245  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2246                                    IncompatibleObjC))
2247    return false;
2248
2249  /// \brief Construct the type we're converting to, which is a pointer to
2250  /// __autoreleasing pointee.
2251  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2252  ConvertedType = Context.getPointerType(FromPointee);
2253  return true;
2254}
2255
2256bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2257                                    QualType& ConvertedType) {
2258  QualType ToPointeeType;
2259  if (const BlockPointerType *ToBlockPtr =
2260        ToType->getAs<BlockPointerType>())
2261    ToPointeeType = ToBlockPtr->getPointeeType();
2262  else
2263    return false;
2264
2265  QualType FromPointeeType;
2266  if (const BlockPointerType *FromBlockPtr =
2267      FromType->getAs<BlockPointerType>())
2268    FromPointeeType = FromBlockPtr->getPointeeType();
2269  else
2270    return false;
2271  // We have pointer to blocks, check whether the only
2272  // differences in the argument and result types are in Objective-C
2273  // pointer conversions. If so, we permit the conversion.
2274
2275  const FunctionProtoType *FromFunctionType
2276    = FromPointeeType->getAs<FunctionProtoType>();
2277  const FunctionProtoType *ToFunctionType
2278    = ToPointeeType->getAs<FunctionProtoType>();
2279
2280  if (!FromFunctionType || !ToFunctionType)
2281    return false;
2282
2283  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2284    return true;
2285
2286  // Perform the quick checks that will tell us whether these
2287  // function types are obviously different.
2288  if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2289      FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2290    return false;
2291
2292  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2293  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2294  if (FromEInfo != ToEInfo)
2295    return false;
2296
2297  bool IncompatibleObjC = false;
2298  if (Context.hasSameType(FromFunctionType->getResultType(),
2299                          ToFunctionType->getResultType())) {
2300    // Okay, the types match exactly. Nothing to do.
2301  } else {
2302    QualType RHS = FromFunctionType->getResultType();
2303    QualType LHS = ToFunctionType->getResultType();
2304    if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2305        !RHS.hasQualifiers() && LHS.hasQualifiers())
2306       LHS = LHS.getUnqualifiedType();
2307
2308     if (Context.hasSameType(RHS,LHS)) {
2309       // OK exact match.
2310     } else if (isObjCPointerConversion(RHS, LHS,
2311                                        ConvertedType, IncompatibleObjC)) {
2312     if (IncompatibleObjC)
2313       return false;
2314     // Okay, we have an Objective-C pointer conversion.
2315     }
2316     else
2317       return false;
2318   }
2319
2320   // Check argument types.
2321   for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2322        ArgIdx != NumArgs; ++ArgIdx) {
2323     IncompatibleObjC = false;
2324     QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2325     QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2326     if (Context.hasSameType(FromArgType, ToArgType)) {
2327       // Okay, the types match exactly. Nothing to do.
2328     } else if (isObjCPointerConversion(ToArgType, FromArgType,
2329                                        ConvertedType, IncompatibleObjC)) {
2330       if (IncompatibleObjC)
2331         return false;
2332       // Okay, we have an Objective-C pointer conversion.
2333     } else
2334       // Argument types are too different. Abort.
2335       return false;
2336   }
2337   if (LangOpts.ObjCAutoRefCount &&
2338       !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2339                                                    ToFunctionType))
2340     return false;
2341
2342   ConvertedType = ToType;
2343   return true;
2344}
2345
2346enum {
2347  ft_default,
2348  ft_different_class,
2349  ft_parameter_arity,
2350  ft_parameter_mismatch,
2351  ft_return_type,
2352  ft_qualifer_mismatch
2353};
2354
2355/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2356/// function types.  Catches different number of parameter, mismatch in
2357/// parameter types, and different return types.
2358void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2359                                      QualType FromType, QualType ToType) {
2360  // If either type is not valid, include no extra info.
2361  if (FromType.isNull() || ToType.isNull()) {
2362    PDiag << ft_default;
2363    return;
2364  }
2365
2366  // Get the function type from the pointers.
2367  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2368    const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2369                            *ToMember = ToType->getAs<MemberPointerType>();
2370    if (FromMember->getClass() != ToMember->getClass()) {
2371      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2372            << QualType(FromMember->getClass(), 0);
2373      return;
2374    }
2375    FromType = FromMember->getPointeeType();
2376    ToType = ToMember->getPointeeType();
2377  }
2378
2379  if (FromType->isPointerType())
2380    FromType = FromType->getPointeeType();
2381  if (ToType->isPointerType())
2382    ToType = ToType->getPointeeType();
2383
2384  // Remove references.
2385  FromType = FromType.getNonReferenceType();
2386  ToType = ToType.getNonReferenceType();
2387
2388  // Don't print extra info for non-specialized template functions.
2389  if (FromType->isInstantiationDependentType() &&
2390      !FromType->getAs<TemplateSpecializationType>()) {
2391    PDiag << ft_default;
2392    return;
2393  }
2394
2395  // No extra info for same types.
2396  if (Context.hasSameType(FromType, ToType)) {
2397    PDiag << ft_default;
2398    return;
2399  }
2400
2401  const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2402                          *ToFunction = ToType->getAs<FunctionProtoType>();
2403
2404  // Both types need to be function types.
2405  if (!FromFunction || !ToFunction) {
2406    PDiag << ft_default;
2407    return;
2408  }
2409
2410  if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2411    PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2412          << FromFunction->getNumArgs();
2413    return;
2414  }
2415
2416  // Handle different parameter types.
2417  unsigned ArgPos;
2418  if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2419    PDiag << ft_parameter_mismatch << ArgPos + 1
2420          << ToFunction->getArgType(ArgPos)
2421          << FromFunction->getArgType(ArgPos);
2422    return;
2423  }
2424
2425  // Handle different return type.
2426  if (!Context.hasSameType(FromFunction->getResultType(),
2427                           ToFunction->getResultType())) {
2428    PDiag << ft_return_type << ToFunction->getResultType()
2429          << FromFunction->getResultType();
2430    return;
2431  }
2432
2433  unsigned FromQuals = FromFunction->getTypeQuals(),
2434           ToQuals = ToFunction->getTypeQuals();
2435  if (FromQuals != ToQuals) {
2436    PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2437    return;
2438  }
2439
2440  // Unable to find a difference, so add no extra info.
2441  PDiag << ft_default;
2442}
2443
2444/// FunctionArgTypesAreEqual - This routine checks two function proto types
2445/// for equality of their argument types. Caller has already checked that
2446/// they have same number of arguments. This routine assumes that Objective-C
2447/// pointer types which only differ in their protocol qualifiers are equal.
2448/// If the parameters are different, ArgPos will have the the parameter index
2449/// of the first different parameter.
2450bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2451                                    const FunctionProtoType *NewType,
2452                                    unsigned *ArgPos) {
2453  if (!getLangOptions().ObjC1) {
2454    for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2455         N = NewType->arg_type_begin(),
2456         E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2457      if (!Context.hasSameType(*O, *N)) {
2458        if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2459        return false;
2460      }
2461    }
2462    return true;
2463  }
2464
2465  for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2466       N = NewType->arg_type_begin(),
2467       E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2468    QualType ToType = (*O);
2469    QualType FromType = (*N);
2470    if (!Context.hasSameType(ToType, FromType)) {
2471      if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2472        if (const PointerType *PTFr = FromType->getAs<PointerType>())
2473          if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2474               PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2475              (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2476               PTFr->getPointeeType()->isObjCQualifiedClassType()))
2477            continue;
2478      }
2479      else if (const ObjCObjectPointerType *PTTo =
2480                 ToType->getAs<ObjCObjectPointerType>()) {
2481        if (const ObjCObjectPointerType *PTFr =
2482              FromType->getAs<ObjCObjectPointerType>())
2483          if (Context.hasSameUnqualifiedType(
2484                PTTo->getObjectType()->getBaseType(),
2485                PTFr->getObjectType()->getBaseType()))
2486            continue;
2487      }
2488      if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2489      return false;
2490    }
2491  }
2492  return true;
2493}
2494
2495/// CheckPointerConversion - Check the pointer conversion from the
2496/// expression From to the type ToType. This routine checks for
2497/// ambiguous or inaccessible derived-to-base pointer
2498/// conversions for which IsPointerConversion has already returned
2499/// true. It returns true and produces a diagnostic if there was an
2500/// error, or returns false otherwise.
2501bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2502                                  CastKind &Kind,
2503                                  CXXCastPath& BasePath,
2504                                  bool IgnoreBaseAccess) {
2505  QualType FromType = From->getType();
2506  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2507
2508  Kind = CK_BitCast;
2509
2510  if (!IsCStyleOrFunctionalCast &&
2511      Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2512      From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2513    DiagRuntimeBehavior(From->getExprLoc(), From,
2514                        PDiag(diag::warn_impcast_bool_to_null_pointer)
2515                          << ToType << From->getSourceRange());
2516
2517  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2518    if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2519      QualType FromPointeeType = FromPtrType->getPointeeType(),
2520               ToPointeeType   = ToPtrType->getPointeeType();
2521
2522      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2523          !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2524        // We must have a derived-to-base conversion. Check an
2525        // ambiguous or inaccessible conversion.
2526        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2527                                         From->getExprLoc(),
2528                                         From->getSourceRange(), &BasePath,
2529                                         IgnoreBaseAccess))
2530          return true;
2531
2532        // The conversion was successful.
2533        Kind = CK_DerivedToBase;
2534      }
2535    }
2536  } else if (const ObjCObjectPointerType *ToPtrType =
2537               ToType->getAs<ObjCObjectPointerType>()) {
2538    if (const ObjCObjectPointerType *FromPtrType =
2539          FromType->getAs<ObjCObjectPointerType>()) {
2540      // Objective-C++ conversions are always okay.
2541      // FIXME: We should have a different class of conversions for the
2542      // Objective-C++ implicit conversions.
2543      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2544        return false;
2545    } else if (FromType->isBlockPointerType()) {
2546      Kind = CK_BlockPointerToObjCPointerCast;
2547    } else {
2548      Kind = CK_CPointerToObjCPointerCast;
2549    }
2550  } else if (ToType->isBlockPointerType()) {
2551    if (!FromType->isBlockPointerType())
2552      Kind = CK_AnyPointerToBlockPointerCast;
2553  }
2554
2555  // We shouldn't fall into this case unless it's valid for other
2556  // reasons.
2557  if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2558    Kind = CK_NullToPointer;
2559
2560  return false;
2561}
2562
2563/// IsMemberPointerConversion - Determines whether the conversion of the
2564/// expression From, which has the (possibly adjusted) type FromType, can be
2565/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2566/// If so, returns true and places the converted type (that might differ from
2567/// ToType in its cv-qualifiers at some level) into ConvertedType.
2568bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2569                                     QualType ToType,
2570                                     bool InOverloadResolution,
2571                                     QualType &ConvertedType) {
2572  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2573  if (!ToTypePtr)
2574    return false;
2575
2576  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2577  if (From->isNullPointerConstant(Context,
2578                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2579                                        : Expr::NPC_ValueDependentIsNull)) {
2580    ConvertedType = ToType;
2581    return true;
2582  }
2583
2584  // Otherwise, both types have to be member pointers.
2585  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2586  if (!FromTypePtr)
2587    return false;
2588
2589  // A pointer to member of B can be converted to a pointer to member of D,
2590  // where D is derived from B (C++ 4.11p2).
2591  QualType FromClass(FromTypePtr->getClass(), 0);
2592  QualType ToClass(ToTypePtr->getClass(), 0);
2593
2594  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2595      !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2596      IsDerivedFrom(ToClass, FromClass)) {
2597    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2598                                                 ToClass.getTypePtr());
2599    return true;
2600  }
2601
2602  return false;
2603}
2604
2605/// CheckMemberPointerConversion - Check the member pointer conversion from the
2606/// expression From to the type ToType. This routine checks for ambiguous or
2607/// virtual or inaccessible base-to-derived member pointer conversions
2608/// for which IsMemberPointerConversion has already returned true. It returns
2609/// true and produces a diagnostic if there was an error, or returns false
2610/// otherwise.
2611bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2612                                        CastKind &Kind,
2613                                        CXXCastPath &BasePath,
2614                                        bool IgnoreBaseAccess) {
2615  QualType FromType = From->getType();
2616  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2617  if (!FromPtrType) {
2618    // This must be a null pointer to member pointer conversion
2619    assert(From->isNullPointerConstant(Context,
2620                                       Expr::NPC_ValueDependentIsNull) &&
2621           "Expr must be null pointer constant!");
2622    Kind = CK_NullToMemberPointer;
2623    return false;
2624  }
2625
2626  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2627  assert(ToPtrType && "No member pointer cast has a target type "
2628                      "that is not a member pointer.");
2629
2630  QualType FromClass = QualType(FromPtrType->getClass(), 0);
2631  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2632
2633  // FIXME: What about dependent types?
2634  assert(FromClass->isRecordType() && "Pointer into non-class.");
2635  assert(ToClass->isRecordType() && "Pointer into non-class.");
2636
2637  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2638                     /*DetectVirtual=*/true);
2639  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2640  assert(DerivationOkay &&
2641         "Should not have been called if derivation isn't OK.");
2642  (void)DerivationOkay;
2643
2644  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2645                                  getUnqualifiedType())) {
2646    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2647    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2648      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2649    return true;
2650  }
2651
2652  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2653    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2654      << FromClass << ToClass << QualType(VBase, 0)
2655      << From->getSourceRange();
2656    return true;
2657  }
2658
2659  if (!IgnoreBaseAccess)
2660    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2661                         Paths.front(),
2662                         diag::err_downcast_from_inaccessible_base);
2663
2664  // Must be a base to derived member conversion.
2665  BuildBasePathArray(Paths, BasePath);
2666  Kind = CK_BaseToDerivedMemberPointer;
2667  return false;
2668}
2669
2670/// IsQualificationConversion - Determines whether the conversion from
2671/// an rvalue of type FromType to ToType is a qualification conversion
2672/// (C++ 4.4).
2673///
2674/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2675/// when the qualification conversion involves a change in the Objective-C
2676/// object lifetime.
2677bool
2678Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2679                                bool CStyle, bool &ObjCLifetimeConversion) {
2680  FromType = Context.getCanonicalType(FromType);
2681  ToType = Context.getCanonicalType(ToType);
2682  ObjCLifetimeConversion = false;
2683
2684  // If FromType and ToType are the same type, this is not a
2685  // qualification conversion.
2686  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2687    return false;
2688
2689  // (C++ 4.4p4):
2690  //   A conversion can add cv-qualifiers at levels other than the first
2691  //   in multi-level pointers, subject to the following rules: [...]
2692  bool PreviousToQualsIncludeConst = true;
2693  bool UnwrappedAnyPointer = false;
2694  while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2695    // Within each iteration of the loop, we check the qualifiers to
2696    // determine if this still looks like a qualification
2697    // conversion. Then, if all is well, we unwrap one more level of
2698    // pointers or pointers-to-members and do it all again
2699    // until there are no more pointers or pointers-to-members left to
2700    // unwrap.
2701    UnwrappedAnyPointer = true;
2702
2703    Qualifiers FromQuals = FromType.getQualifiers();
2704    Qualifiers ToQuals = ToType.getQualifiers();
2705
2706    // Objective-C ARC:
2707    //   Check Objective-C lifetime conversions.
2708    if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2709        UnwrappedAnyPointer) {
2710      if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2711        ObjCLifetimeConversion = true;
2712        FromQuals.removeObjCLifetime();
2713        ToQuals.removeObjCLifetime();
2714      } else {
2715        // Qualification conversions cannot cast between different
2716        // Objective-C lifetime qualifiers.
2717        return false;
2718      }
2719    }
2720
2721    // Allow addition/removal of GC attributes but not changing GC attributes.
2722    if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2723        (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2724      FromQuals.removeObjCGCAttr();
2725      ToQuals.removeObjCGCAttr();
2726    }
2727
2728    //   -- for every j > 0, if const is in cv 1,j then const is in cv
2729    //      2,j, and similarly for volatile.
2730    if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2731      return false;
2732
2733    //   -- if the cv 1,j and cv 2,j are different, then const is in
2734    //      every cv for 0 < k < j.
2735    if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2736        && !PreviousToQualsIncludeConst)
2737      return false;
2738
2739    // Keep track of whether all prior cv-qualifiers in the "to" type
2740    // include const.
2741    PreviousToQualsIncludeConst
2742      = PreviousToQualsIncludeConst && ToQuals.hasConst();
2743  }
2744
2745  // We are left with FromType and ToType being the pointee types
2746  // after unwrapping the original FromType and ToType the same number
2747  // of types. If we unwrapped any pointers, and if FromType and
2748  // ToType have the same unqualified type (since we checked
2749  // qualifiers above), then this is a qualification conversion.
2750  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2751}
2752
2753/// Determines whether there is a user-defined conversion sequence
2754/// (C++ [over.ics.user]) that converts expression From to the type
2755/// ToType. If such a conversion exists, User will contain the
2756/// user-defined conversion sequence that performs such a conversion
2757/// and this routine will return true. Otherwise, this routine returns
2758/// false and User is unspecified.
2759///
2760/// \param AllowExplicit  true if the conversion should consider C++0x
2761/// "explicit" conversion functions as well as non-explicit conversion
2762/// functions (C++0x [class.conv.fct]p2).
2763static OverloadingResult
2764IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2765                        UserDefinedConversionSequence& User,
2766                        OverloadCandidateSet& CandidateSet,
2767                        bool AllowExplicit) {
2768  // Whether we will only visit constructors.
2769  bool ConstructorsOnly = false;
2770
2771  // If the type we are conversion to is a class type, enumerate its
2772  // constructors.
2773  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2774    // C++ [over.match.ctor]p1:
2775    //   When objects of class type are direct-initialized (8.5), or
2776    //   copy-initialized from an expression of the same or a
2777    //   derived class type (8.5), overload resolution selects the
2778    //   constructor. [...] For copy-initialization, the candidate
2779    //   functions are all the converting constructors (12.3.1) of
2780    //   that class. The argument list is the expression-list within
2781    //   the parentheses of the initializer.
2782    if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
2783        (From->getType()->getAs<RecordType>() &&
2784         S.IsDerivedFrom(From->getType(), ToType)))
2785      ConstructorsOnly = true;
2786
2787    S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2788    // RequireCompleteType may have returned true due to some invalid decl
2789    // during template instantiation, but ToType may be complete enough now
2790    // to try to recover.
2791    if (ToType->isIncompleteType()) {
2792      // We're not going to find any constructors.
2793    } else if (CXXRecordDecl *ToRecordDecl
2794                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
2795
2796      Expr **Args = &From;
2797      unsigned NumArgs = 1;
2798      bool ListInitializing = false;
2799      // If we're list-initializing, we pass the individual elements as
2800      // arguments, not the entire list.
2801      if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
2802        Args = InitList->getInits();
2803        NumArgs = InitList->getNumInits();
2804        ListInitializing = true;
2805      }
2806
2807      DeclContext::lookup_iterator Con, ConEnd;
2808      for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
2809           Con != ConEnd; ++Con) {
2810        NamedDecl *D = *Con;
2811        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2812
2813        // Find the constructor (which may be a template).
2814        CXXConstructorDecl *Constructor = 0;
2815        FunctionTemplateDecl *ConstructorTmpl
2816          = dyn_cast<FunctionTemplateDecl>(D);
2817        if (ConstructorTmpl)
2818          Constructor
2819            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2820        else
2821          Constructor = cast<CXXConstructorDecl>(D);
2822
2823        bool Usable = !Constructor->isInvalidDecl();
2824        if (ListInitializing)
2825          Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2826        else
2827          Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2828        if (Usable) {
2829          if (ConstructorTmpl)
2830            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2831                                           /*ExplicitArgs*/ 0,
2832                                           Args, NumArgs, CandidateSet,
2833                                           /*SuppressUserConversions=*/
2834                                           !ConstructorsOnly &&
2835                                             !ListInitializing);
2836          else
2837            // Allow one user-defined conversion when user specifies a
2838            // From->ToType conversion via an static cast (c-style, etc).
2839            S.AddOverloadCandidate(Constructor, FoundDecl,
2840                                   Args, NumArgs, CandidateSet,
2841                                   /*SuppressUserConversions=*/
2842                                   !ConstructorsOnly && !ListInitializing);
2843        }
2844      }
2845    }
2846  }
2847
2848  // Enumerate conversion functions, if we're allowed to.
2849  if (ConstructorsOnly || isa<InitListExpr>(From)) {
2850  } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2851                                   S.PDiag(0) << From->getSourceRange())) {
2852    // No conversion functions from incomplete types.
2853  } else if (const RecordType *FromRecordType
2854                                   = From->getType()->getAs<RecordType>()) {
2855    if (CXXRecordDecl *FromRecordDecl
2856         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2857      // Add all of the conversion functions as candidates.
2858      const UnresolvedSetImpl *Conversions
2859        = FromRecordDecl->getVisibleConversionFunctions();
2860      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2861             E = Conversions->end(); I != E; ++I) {
2862        DeclAccessPair FoundDecl = I.getPair();
2863        NamedDecl *D = FoundDecl.getDecl();
2864        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2865        if (isa<UsingShadowDecl>(D))
2866          D = cast<UsingShadowDecl>(D)->getTargetDecl();
2867
2868        CXXConversionDecl *Conv;
2869        FunctionTemplateDecl *ConvTemplate;
2870        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2871          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2872        else
2873          Conv = cast<CXXConversionDecl>(D);
2874
2875        if (AllowExplicit || !Conv->isExplicit()) {
2876          if (ConvTemplate)
2877            S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2878                                             ActingContext, From, ToType,
2879                                             CandidateSet);
2880          else
2881            S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2882                                     From, ToType, CandidateSet);
2883        }
2884      }
2885    }
2886  }
2887
2888  bool HadMultipleCandidates = (CandidateSet.size() > 1);
2889
2890  OverloadCandidateSet::iterator Best;
2891  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2892  case OR_Success:
2893    // Record the standard conversion we used and the conversion function.
2894    if (CXXConstructorDecl *Constructor
2895          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2896      S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2897
2898      // C++ [over.ics.user]p1:
2899      //   If the user-defined conversion is specified by a
2900      //   constructor (12.3.1), the initial standard conversion
2901      //   sequence converts the source type to the type required by
2902      //   the argument of the constructor.
2903      //
2904      QualType ThisType = Constructor->getThisType(S.Context);
2905      if (isa<InitListExpr>(From)) {
2906        // Initializer lists don't have conversions as such.
2907        User.Before.setAsIdentityConversion();
2908      } else {
2909        if (Best->Conversions[0].isEllipsis())
2910          User.EllipsisConversion = true;
2911        else {
2912          User.Before = Best->Conversions[0].Standard;
2913          User.EllipsisConversion = false;
2914        }
2915      }
2916      User.HadMultipleCandidates = HadMultipleCandidates;
2917      User.ConversionFunction = Constructor;
2918      User.FoundConversionFunction = Best->FoundDecl;
2919      User.After.setAsIdentityConversion();
2920      User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2921      User.After.setAllToTypes(ToType);
2922      return OR_Success;
2923    }
2924    if (CXXConversionDecl *Conversion
2925                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2926      S.MarkFunctionReferenced(From->getLocStart(), Conversion);
2927
2928      // C++ [over.ics.user]p1:
2929      //
2930      //   [...] If the user-defined conversion is specified by a
2931      //   conversion function (12.3.2), the initial standard
2932      //   conversion sequence converts the source type to the
2933      //   implicit object parameter of the conversion function.
2934      User.Before = Best->Conversions[0].Standard;
2935      User.HadMultipleCandidates = HadMultipleCandidates;
2936      User.ConversionFunction = Conversion;
2937      User.FoundConversionFunction = Best->FoundDecl;
2938      User.EllipsisConversion = false;
2939
2940      // C++ [over.ics.user]p2:
2941      //   The second standard conversion sequence converts the
2942      //   result of the user-defined conversion to the target type
2943      //   for the sequence. Since an implicit conversion sequence
2944      //   is an initialization, the special rules for
2945      //   initialization by user-defined conversion apply when
2946      //   selecting the best user-defined conversion for a
2947      //   user-defined conversion sequence (see 13.3.3 and
2948      //   13.3.3.1).
2949      User.After = Best->FinalConversion;
2950      return OR_Success;
2951    }
2952    llvm_unreachable("Not a constructor or conversion function?");
2953
2954  case OR_No_Viable_Function:
2955    return OR_No_Viable_Function;
2956  case OR_Deleted:
2957    // No conversion here! We're done.
2958    return OR_Deleted;
2959
2960  case OR_Ambiguous:
2961    return OR_Ambiguous;
2962  }
2963
2964  llvm_unreachable("Invalid OverloadResult!");
2965}
2966
2967bool
2968Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
2969  ImplicitConversionSequence ICS;
2970  OverloadCandidateSet CandidateSet(From->getExprLoc());
2971  OverloadingResult OvResult =
2972    IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
2973                            CandidateSet, false);
2974  if (OvResult == OR_Ambiguous)
2975    Diag(From->getSourceRange().getBegin(),
2976         diag::err_typecheck_ambiguous_condition)
2977          << From->getType() << ToType << From->getSourceRange();
2978  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2979    Diag(From->getSourceRange().getBegin(),
2980         diag::err_typecheck_nonviable_condition)
2981    << From->getType() << ToType << From->getSourceRange();
2982  else
2983    return false;
2984  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
2985  return true;
2986}
2987
2988/// CompareImplicitConversionSequences - Compare two implicit
2989/// conversion sequences to determine whether one is better than the
2990/// other or if they are indistinguishable (C++ 13.3.3.2).
2991static ImplicitConversionSequence::CompareKind
2992CompareImplicitConversionSequences(Sema &S,
2993                                   const ImplicitConversionSequence& ICS1,
2994                                   const ImplicitConversionSequence& ICS2)
2995{
2996  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2997  // conversion sequences (as defined in 13.3.3.1)
2998  //   -- a standard conversion sequence (13.3.3.1.1) is a better
2999  //      conversion sequence than a user-defined conversion sequence or
3000  //      an ellipsis conversion sequence, and
3001  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3002  //      conversion sequence than an ellipsis conversion sequence
3003  //      (13.3.3.1.3).
3004  //
3005  // C++0x [over.best.ics]p10:
3006  //   For the purpose of ranking implicit conversion sequences as
3007  //   described in 13.3.3.2, the ambiguous conversion sequence is
3008  //   treated as a user-defined sequence that is indistinguishable
3009  //   from any other user-defined conversion sequence.
3010  if (ICS1.getKindRank() < ICS2.getKindRank())
3011    return ImplicitConversionSequence::Better;
3012  if (ICS2.getKindRank() < ICS1.getKindRank())
3013    return ImplicitConversionSequence::Worse;
3014
3015  // The following checks require both conversion sequences to be of
3016  // the same kind.
3017  if (ICS1.getKind() != ICS2.getKind())
3018    return ImplicitConversionSequence::Indistinguishable;
3019
3020  ImplicitConversionSequence::CompareKind Result =
3021      ImplicitConversionSequence::Indistinguishable;
3022
3023  // Two implicit conversion sequences of the same form are
3024  // indistinguishable conversion sequences unless one of the
3025  // following rules apply: (C++ 13.3.3.2p3):
3026  if (ICS1.isStandard())
3027    Result = CompareStandardConversionSequences(S,
3028                                                ICS1.Standard, ICS2.Standard);
3029  else if (ICS1.isUserDefined()) {
3030    // User-defined conversion sequence U1 is a better conversion
3031    // sequence than another user-defined conversion sequence U2 if
3032    // they contain the same user-defined conversion function or
3033    // constructor and if the second standard conversion sequence of
3034    // U1 is better than the second standard conversion sequence of
3035    // U2 (C++ 13.3.3.2p3).
3036    if (ICS1.UserDefined.ConversionFunction ==
3037          ICS2.UserDefined.ConversionFunction)
3038      Result = CompareStandardConversionSequences(S,
3039                                                  ICS1.UserDefined.After,
3040                                                  ICS2.UserDefined.After);
3041  }
3042
3043  // List-initialization sequence L1 is a better conversion sequence than
3044  // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3045  // for some X and L2 does not.
3046  if (Result == ImplicitConversionSequence::Indistinguishable &&
3047      ICS1.isListInitializationSequence() &&
3048      ICS2.isListInitializationSequence()) {
3049    // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
3050  }
3051
3052  return Result;
3053}
3054
3055static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3056  while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3057    Qualifiers Quals;
3058    T1 = Context.getUnqualifiedArrayType(T1, Quals);
3059    T2 = Context.getUnqualifiedArrayType(T2, Quals);
3060  }
3061
3062  return Context.hasSameUnqualifiedType(T1, T2);
3063}
3064
3065// Per 13.3.3.2p3, compare the given standard conversion sequences to
3066// determine if one is a proper subset of the other.
3067static ImplicitConversionSequence::CompareKind
3068compareStandardConversionSubsets(ASTContext &Context,
3069                                 const StandardConversionSequence& SCS1,
3070                                 const StandardConversionSequence& SCS2) {
3071  ImplicitConversionSequence::CompareKind Result
3072    = ImplicitConversionSequence::Indistinguishable;
3073
3074  // the identity conversion sequence is considered to be a subsequence of
3075  // any non-identity conversion sequence
3076  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3077    return ImplicitConversionSequence::Better;
3078  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3079    return ImplicitConversionSequence::Worse;
3080
3081  if (SCS1.Second != SCS2.Second) {
3082    if (SCS1.Second == ICK_Identity)
3083      Result = ImplicitConversionSequence::Better;
3084    else if (SCS2.Second == ICK_Identity)
3085      Result = ImplicitConversionSequence::Worse;
3086    else
3087      return ImplicitConversionSequence::Indistinguishable;
3088  } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3089    return ImplicitConversionSequence::Indistinguishable;
3090
3091  if (SCS1.Third == SCS2.Third) {
3092    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3093                             : ImplicitConversionSequence::Indistinguishable;
3094  }
3095
3096  if (SCS1.Third == ICK_Identity)
3097    return Result == ImplicitConversionSequence::Worse
3098             ? ImplicitConversionSequence::Indistinguishable
3099             : ImplicitConversionSequence::Better;
3100
3101  if (SCS2.Third == ICK_Identity)
3102    return Result == ImplicitConversionSequence::Better
3103             ? ImplicitConversionSequence::Indistinguishable
3104             : ImplicitConversionSequence::Worse;
3105
3106  return ImplicitConversionSequence::Indistinguishable;
3107}
3108
3109/// \brief Determine whether one of the given reference bindings is better
3110/// than the other based on what kind of bindings they are.
3111static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3112                                       const StandardConversionSequence &SCS2) {
3113  // C++0x [over.ics.rank]p3b4:
3114  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3115  //      implicit object parameter of a non-static member function declared
3116  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3117  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3118  //      lvalue reference to a function lvalue and S2 binds an rvalue
3119  //      reference*.
3120  //
3121  // FIXME: Rvalue references. We're going rogue with the above edits,
3122  // because the semantics in the current C++0x working paper (N3225 at the
3123  // time of this writing) break the standard definition of std::forward
3124  // and std::reference_wrapper when dealing with references to functions.
3125  // Proposed wording changes submitted to CWG for consideration.
3126  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3127      SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3128    return false;
3129
3130  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3131          SCS2.IsLvalueReference) ||
3132         (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3133          !SCS2.IsLvalueReference);
3134}
3135
3136/// CompareStandardConversionSequences - Compare two standard
3137/// conversion sequences to determine whether one is better than the
3138/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3139static ImplicitConversionSequence::CompareKind
3140CompareStandardConversionSequences(Sema &S,
3141                                   const StandardConversionSequence& SCS1,
3142                                   const StandardConversionSequence& SCS2)
3143{
3144  // Standard conversion sequence S1 is a better conversion sequence
3145  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3146
3147  //  -- S1 is a proper subsequence of S2 (comparing the conversion
3148  //     sequences in the canonical form defined by 13.3.3.1.1,
3149  //     excluding any Lvalue Transformation; the identity conversion
3150  //     sequence is considered to be a subsequence of any
3151  //     non-identity conversion sequence) or, if not that,
3152  if (ImplicitConversionSequence::CompareKind CK
3153        = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3154    return CK;
3155
3156  //  -- the rank of S1 is better than the rank of S2 (by the rules
3157  //     defined below), or, if not that,
3158  ImplicitConversionRank Rank1 = SCS1.getRank();
3159  ImplicitConversionRank Rank2 = SCS2.getRank();
3160  if (Rank1 < Rank2)
3161    return ImplicitConversionSequence::Better;
3162  else if (Rank2 < Rank1)
3163    return ImplicitConversionSequence::Worse;
3164
3165  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3166  // are indistinguishable unless one of the following rules
3167  // applies:
3168
3169  //   A conversion that is not a conversion of a pointer, or
3170  //   pointer to member, to bool is better than another conversion
3171  //   that is such a conversion.
3172  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3173    return SCS2.isPointerConversionToBool()
3174             ? ImplicitConversionSequence::Better
3175             : ImplicitConversionSequence::Worse;
3176
3177  // C++ [over.ics.rank]p4b2:
3178  //
3179  //   If class B is derived directly or indirectly from class A,
3180  //   conversion of B* to A* is better than conversion of B* to
3181  //   void*, and conversion of A* to void* is better than conversion
3182  //   of B* to void*.
3183  bool SCS1ConvertsToVoid
3184    = SCS1.isPointerConversionToVoidPointer(S.Context);
3185  bool SCS2ConvertsToVoid
3186    = SCS2.isPointerConversionToVoidPointer(S.Context);
3187  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3188    // Exactly one of the conversion sequences is a conversion to
3189    // a void pointer; it's the worse conversion.
3190    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3191                              : ImplicitConversionSequence::Worse;
3192  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3193    // Neither conversion sequence converts to a void pointer; compare
3194    // their derived-to-base conversions.
3195    if (ImplicitConversionSequence::CompareKind DerivedCK
3196          = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3197      return DerivedCK;
3198  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3199             !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3200    // Both conversion sequences are conversions to void
3201    // pointers. Compare the source types to determine if there's an
3202    // inheritance relationship in their sources.
3203    QualType FromType1 = SCS1.getFromType();
3204    QualType FromType2 = SCS2.getFromType();
3205
3206    // Adjust the types we're converting from via the array-to-pointer
3207    // conversion, if we need to.
3208    if (SCS1.First == ICK_Array_To_Pointer)
3209      FromType1 = S.Context.getArrayDecayedType(FromType1);
3210    if (SCS2.First == ICK_Array_To_Pointer)
3211      FromType2 = S.Context.getArrayDecayedType(FromType2);
3212
3213    QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3214    QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3215
3216    if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3217      return ImplicitConversionSequence::Better;
3218    else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3219      return ImplicitConversionSequence::Worse;
3220
3221    // Objective-C++: If one interface is more specific than the
3222    // other, it is the better one.
3223    const ObjCObjectPointerType* FromObjCPtr1
3224      = FromType1->getAs<ObjCObjectPointerType>();
3225    const ObjCObjectPointerType* FromObjCPtr2
3226      = FromType2->getAs<ObjCObjectPointerType>();
3227    if (FromObjCPtr1 && FromObjCPtr2) {
3228      bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3229                                                          FromObjCPtr2);
3230      bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3231                                                           FromObjCPtr1);
3232      if (AssignLeft != AssignRight) {
3233        return AssignLeft? ImplicitConversionSequence::Better
3234                         : ImplicitConversionSequence::Worse;
3235      }
3236    }
3237  }
3238
3239  // Compare based on qualification conversions (C++ 13.3.3.2p3,
3240  // bullet 3).
3241  if (ImplicitConversionSequence::CompareKind QualCK
3242        = CompareQualificationConversions(S, SCS1, SCS2))
3243    return QualCK;
3244
3245  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3246    // Check for a better reference binding based on the kind of bindings.
3247    if (isBetterReferenceBindingKind(SCS1, SCS2))
3248      return ImplicitConversionSequence::Better;
3249    else if (isBetterReferenceBindingKind(SCS2, SCS1))
3250      return ImplicitConversionSequence::Worse;
3251
3252    // C++ [over.ics.rank]p3b4:
3253    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3254    //      which the references refer are the same type except for
3255    //      top-level cv-qualifiers, and the type to which the reference
3256    //      initialized by S2 refers is more cv-qualified than the type
3257    //      to which the reference initialized by S1 refers.
3258    QualType T1 = SCS1.getToType(2);
3259    QualType T2 = SCS2.getToType(2);
3260    T1 = S.Context.getCanonicalType(T1);
3261    T2 = S.Context.getCanonicalType(T2);
3262    Qualifiers T1Quals, T2Quals;
3263    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3264    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3265    if (UnqualT1 == UnqualT2) {
3266      // Objective-C++ ARC: If the references refer to objects with different
3267      // lifetimes, prefer bindings that don't change lifetime.
3268      if (SCS1.ObjCLifetimeConversionBinding !=
3269                                          SCS2.ObjCLifetimeConversionBinding) {
3270        return SCS1.ObjCLifetimeConversionBinding
3271                                           ? ImplicitConversionSequence::Worse
3272                                           : ImplicitConversionSequence::Better;
3273      }
3274
3275      // If the type is an array type, promote the element qualifiers to the
3276      // type for comparison.
3277      if (isa<ArrayType>(T1) && T1Quals)
3278        T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3279      if (isa<ArrayType>(T2) && T2Quals)
3280        T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3281      if (T2.isMoreQualifiedThan(T1))
3282        return ImplicitConversionSequence::Better;
3283      else if (T1.isMoreQualifiedThan(T2))
3284        return ImplicitConversionSequence::Worse;
3285    }
3286  }
3287
3288  // In Microsoft mode, prefer an integral conversion to a
3289  // floating-to-integral conversion if the integral conversion
3290  // is between types of the same size.
3291  // For example:
3292  // void f(float);
3293  // void f(int);
3294  // int main {
3295  //    long a;
3296  //    f(a);
3297  // }
3298  // Here, MSVC will call f(int) instead of generating a compile error
3299  // as clang will do in standard mode.
3300  if (S.getLangOptions().MicrosoftMode &&
3301      SCS1.Second == ICK_Integral_Conversion &&
3302      SCS2.Second == ICK_Floating_Integral &&
3303      S.Context.getTypeSize(SCS1.getFromType()) ==
3304      S.Context.getTypeSize(SCS1.getToType(2)))
3305    return ImplicitConversionSequence::Better;
3306
3307  return ImplicitConversionSequence::Indistinguishable;
3308}
3309
3310/// CompareQualificationConversions - Compares two standard conversion
3311/// sequences to determine whether they can be ranked based on their
3312/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3313ImplicitConversionSequence::CompareKind
3314CompareQualificationConversions(Sema &S,
3315                                const StandardConversionSequence& SCS1,
3316                                const StandardConversionSequence& SCS2) {
3317  // C++ 13.3.3.2p3:
3318  //  -- S1 and S2 differ only in their qualification conversion and
3319  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3320  //     cv-qualification signature of type T1 is a proper subset of
3321  //     the cv-qualification signature of type T2, and S1 is not the
3322  //     deprecated string literal array-to-pointer conversion (4.2).
3323  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3324      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3325    return ImplicitConversionSequence::Indistinguishable;
3326
3327  // FIXME: the example in the standard doesn't use a qualification
3328  // conversion (!)
3329  QualType T1 = SCS1.getToType(2);
3330  QualType T2 = SCS2.getToType(2);
3331  T1 = S.Context.getCanonicalType(T1);
3332  T2 = S.Context.getCanonicalType(T2);
3333  Qualifiers T1Quals, T2Quals;
3334  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3335  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3336
3337  // If the types are the same, we won't learn anything by unwrapped
3338  // them.
3339  if (UnqualT1 == UnqualT2)
3340    return ImplicitConversionSequence::Indistinguishable;
3341
3342  // If the type is an array type, promote the element qualifiers to the type
3343  // for comparison.
3344  if (isa<ArrayType>(T1) && T1Quals)
3345    T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3346  if (isa<ArrayType>(T2) && T2Quals)
3347    T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3348
3349  ImplicitConversionSequence::CompareKind Result
3350    = ImplicitConversionSequence::Indistinguishable;
3351
3352  // Objective-C++ ARC:
3353  //   Prefer qualification conversions not involving a change in lifetime
3354  //   to qualification conversions that do not change lifetime.
3355  if (SCS1.QualificationIncludesObjCLifetime !=
3356                                      SCS2.QualificationIncludesObjCLifetime) {
3357    Result = SCS1.QualificationIncludesObjCLifetime
3358               ? ImplicitConversionSequence::Worse
3359               : ImplicitConversionSequence::Better;
3360  }
3361
3362  while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3363    // Within each iteration of the loop, we check the qualifiers to
3364    // determine if this still looks like a qualification
3365    // conversion. Then, if all is well, we unwrap one more level of
3366    // pointers or pointers-to-members and do it all again
3367    // until there are no more pointers or pointers-to-members left
3368    // to unwrap. This essentially mimics what
3369    // IsQualificationConversion does, but here we're checking for a
3370    // strict subset of qualifiers.
3371    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3372      // The qualifiers are the same, so this doesn't tell us anything
3373      // about how the sequences rank.
3374      ;
3375    else if (T2.isMoreQualifiedThan(T1)) {
3376      // T1 has fewer qualifiers, so it could be the better sequence.
3377      if (Result == ImplicitConversionSequence::Worse)
3378        // Neither has qualifiers that are a subset of the other's
3379        // qualifiers.
3380        return ImplicitConversionSequence::Indistinguishable;
3381
3382      Result = ImplicitConversionSequence::Better;
3383    } else if (T1.isMoreQualifiedThan(T2)) {
3384      // T2 has fewer qualifiers, so it could be the better sequence.
3385      if (Result == ImplicitConversionSequence::Better)
3386        // Neither has qualifiers that are a subset of the other's
3387        // qualifiers.
3388        return ImplicitConversionSequence::Indistinguishable;
3389
3390      Result = ImplicitConversionSequence::Worse;
3391    } else {
3392      // Qualifiers are disjoint.
3393      return ImplicitConversionSequence::Indistinguishable;
3394    }
3395
3396    // If the types after this point are equivalent, we're done.
3397    if (S.Context.hasSameUnqualifiedType(T1, T2))
3398      break;
3399  }
3400
3401  // Check that the winning standard conversion sequence isn't using
3402  // the deprecated string literal array to pointer conversion.
3403  switch (Result) {
3404  case ImplicitConversionSequence::Better:
3405    if (SCS1.DeprecatedStringLiteralToCharPtr)
3406      Result = ImplicitConversionSequence::Indistinguishable;
3407    break;
3408
3409  case ImplicitConversionSequence::Indistinguishable:
3410    break;
3411
3412  case ImplicitConversionSequence::Worse:
3413    if (SCS2.DeprecatedStringLiteralToCharPtr)
3414      Result = ImplicitConversionSequence::Indistinguishable;
3415    break;
3416  }
3417
3418  return Result;
3419}
3420
3421/// CompareDerivedToBaseConversions - Compares two standard conversion
3422/// sequences to determine whether they can be ranked based on their
3423/// various kinds of derived-to-base conversions (C++
3424/// [over.ics.rank]p4b3).  As part of these checks, we also look at
3425/// conversions between Objective-C interface types.
3426ImplicitConversionSequence::CompareKind
3427CompareDerivedToBaseConversions(Sema &S,
3428                                const StandardConversionSequence& SCS1,
3429                                const StandardConversionSequence& SCS2) {
3430  QualType FromType1 = SCS1.getFromType();
3431  QualType ToType1 = SCS1.getToType(1);
3432  QualType FromType2 = SCS2.getFromType();
3433  QualType ToType2 = SCS2.getToType(1);
3434
3435  // Adjust the types we're converting from via the array-to-pointer
3436  // conversion, if we need to.
3437  if (SCS1.First == ICK_Array_To_Pointer)
3438    FromType1 = S.Context.getArrayDecayedType(FromType1);
3439  if (SCS2.First == ICK_Array_To_Pointer)
3440    FromType2 = S.Context.getArrayDecayedType(FromType2);
3441
3442  // Canonicalize all of the types.
3443  FromType1 = S.Context.getCanonicalType(FromType1);
3444  ToType1 = S.Context.getCanonicalType(ToType1);
3445  FromType2 = S.Context.getCanonicalType(FromType2);
3446  ToType2 = S.Context.getCanonicalType(ToType2);
3447
3448  // C++ [over.ics.rank]p4b3:
3449  //
3450  //   If class B is derived directly or indirectly from class A and
3451  //   class C is derived directly or indirectly from B,
3452  //
3453  // Compare based on pointer conversions.
3454  if (SCS1.Second == ICK_Pointer_Conversion &&
3455      SCS2.Second == ICK_Pointer_Conversion &&
3456      /*FIXME: Remove if Objective-C id conversions get their own rank*/
3457      FromType1->isPointerType() && FromType2->isPointerType() &&
3458      ToType1->isPointerType() && ToType2->isPointerType()) {
3459    QualType FromPointee1
3460      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3461    QualType ToPointee1
3462      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3463    QualType FromPointee2
3464      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3465    QualType ToPointee2
3466      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3467
3468    //   -- conversion of C* to B* is better than conversion of C* to A*,
3469    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3470      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3471        return ImplicitConversionSequence::Better;
3472      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3473        return ImplicitConversionSequence::Worse;
3474    }
3475
3476    //   -- conversion of B* to A* is better than conversion of C* to A*,
3477    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3478      if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3479        return ImplicitConversionSequence::Better;
3480      else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3481        return ImplicitConversionSequence::Worse;
3482    }
3483  } else if (SCS1.Second == ICK_Pointer_Conversion &&
3484             SCS2.Second == ICK_Pointer_Conversion) {
3485    const ObjCObjectPointerType *FromPtr1
3486      = FromType1->getAs<ObjCObjectPointerType>();
3487    const ObjCObjectPointerType *FromPtr2
3488      = FromType2->getAs<ObjCObjectPointerType>();
3489    const ObjCObjectPointerType *ToPtr1
3490      = ToType1->getAs<ObjCObjectPointerType>();
3491    const ObjCObjectPointerType *ToPtr2
3492      = ToType2->getAs<ObjCObjectPointerType>();
3493
3494    if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3495      // Apply the same conversion ranking rules for Objective-C pointer types
3496      // that we do for C++ pointers to class types. However, we employ the
3497      // Objective-C pseudo-subtyping relationship used for assignment of
3498      // Objective-C pointer types.
3499      bool FromAssignLeft
3500        = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3501      bool FromAssignRight
3502        = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3503      bool ToAssignLeft
3504        = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3505      bool ToAssignRight
3506        = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3507
3508      // A conversion to an a non-id object pointer type or qualified 'id'
3509      // type is better than a conversion to 'id'.
3510      if (ToPtr1->isObjCIdType() &&
3511          (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3512        return ImplicitConversionSequence::Worse;
3513      if (ToPtr2->isObjCIdType() &&
3514          (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3515        return ImplicitConversionSequence::Better;
3516
3517      // A conversion to a non-id object pointer type is better than a
3518      // conversion to a qualified 'id' type
3519      if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3520        return ImplicitConversionSequence::Worse;
3521      if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3522        return ImplicitConversionSequence::Better;
3523
3524      // A conversion to an a non-Class object pointer type or qualified 'Class'
3525      // type is better than a conversion to 'Class'.
3526      if (ToPtr1->isObjCClassType() &&
3527          (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3528        return ImplicitConversionSequence::Worse;
3529      if (ToPtr2->isObjCClassType() &&
3530          (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3531        return ImplicitConversionSequence::Better;
3532
3533      // A conversion to a non-Class object pointer type is better than a
3534      // conversion to a qualified 'Class' type.
3535      if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3536        return ImplicitConversionSequence::Worse;
3537      if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3538        return ImplicitConversionSequence::Better;
3539
3540      //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3541      if (S.Context.hasSameType(FromType1, FromType2) &&
3542          !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3543          (ToAssignLeft != ToAssignRight))
3544        return ToAssignLeft? ImplicitConversionSequence::Worse
3545                           : ImplicitConversionSequence::Better;
3546
3547      //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3548      if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3549          (FromAssignLeft != FromAssignRight))
3550        return FromAssignLeft? ImplicitConversionSequence::Better
3551        : ImplicitConversionSequence::Worse;
3552    }
3553  }
3554
3555  // Ranking of member-pointer types.
3556  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3557      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3558      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3559    const MemberPointerType * FromMemPointer1 =
3560                                        FromType1->getAs<MemberPointerType>();
3561    const MemberPointerType * ToMemPointer1 =
3562                                          ToType1->getAs<MemberPointerType>();
3563    const MemberPointerType * FromMemPointer2 =
3564                                          FromType2->getAs<MemberPointerType>();
3565    const MemberPointerType * ToMemPointer2 =
3566                                          ToType2->getAs<MemberPointerType>();
3567    const Type *FromPointeeType1 = FromMemPointer1->getClass();
3568    const Type *ToPointeeType1 = ToMemPointer1->getClass();
3569    const Type *FromPointeeType2 = FromMemPointer2->getClass();
3570    const Type *ToPointeeType2 = ToMemPointer2->getClass();
3571    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3572    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3573    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3574    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3575    // conversion of A::* to B::* is better than conversion of A::* to C::*,
3576    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3577      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3578        return ImplicitConversionSequence::Worse;
3579      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3580        return ImplicitConversionSequence::Better;
3581    }
3582    // conversion of B::* to C::* is better than conversion of A::* to C::*
3583    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3584      if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3585        return ImplicitConversionSequence::Better;
3586      else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3587        return ImplicitConversionSequence::Worse;
3588    }
3589  }
3590
3591  if (SCS1.Second == ICK_Derived_To_Base) {
3592    //   -- conversion of C to B is better than conversion of C to A,
3593    //   -- binding of an expression of type C to a reference of type
3594    //      B& is better than binding an expression of type C to a
3595    //      reference of type A&,
3596    if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3597        !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3598      if (S.IsDerivedFrom(ToType1, ToType2))
3599        return ImplicitConversionSequence::Better;
3600      else if (S.IsDerivedFrom(ToType2, ToType1))
3601        return ImplicitConversionSequence::Worse;
3602    }
3603
3604    //   -- conversion of B to A is better than conversion of C to A.
3605    //   -- binding of an expression of type B to a reference of type
3606    //      A& is better than binding an expression of type C to a
3607    //      reference of type A&,
3608    if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3609        S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3610      if (S.IsDerivedFrom(FromType2, FromType1))
3611        return ImplicitConversionSequence::Better;
3612      else if (S.IsDerivedFrom(FromType1, FromType2))
3613        return ImplicitConversionSequence::Worse;
3614    }
3615  }
3616
3617  return ImplicitConversionSequence::Indistinguishable;
3618}
3619
3620/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3621/// determine whether they are reference-related,
3622/// reference-compatible, reference-compatible with added
3623/// qualification, or incompatible, for use in C++ initialization by
3624/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3625/// type, and the first type (T1) is the pointee type of the reference
3626/// type being initialized.
3627Sema::ReferenceCompareResult
3628Sema::CompareReferenceRelationship(SourceLocation Loc,
3629                                   QualType OrigT1, QualType OrigT2,
3630                                   bool &DerivedToBase,
3631                                   bool &ObjCConversion,
3632                                   bool &ObjCLifetimeConversion) {
3633  assert(!OrigT1->isReferenceType() &&
3634    "T1 must be the pointee type of the reference type");
3635  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3636
3637  QualType T1 = Context.getCanonicalType(OrigT1);
3638  QualType T2 = Context.getCanonicalType(OrigT2);
3639  Qualifiers T1Quals, T2Quals;
3640  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3641  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3642
3643  // C++ [dcl.init.ref]p4:
3644  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3645  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3646  //   T1 is a base class of T2.
3647  DerivedToBase = false;
3648  ObjCConversion = false;
3649  ObjCLifetimeConversion = false;
3650  if (UnqualT1 == UnqualT2) {
3651    // Nothing to do.
3652  } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
3653           IsDerivedFrom(UnqualT2, UnqualT1))
3654    DerivedToBase = true;
3655  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3656           UnqualT2->isObjCObjectOrInterfaceType() &&
3657           Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3658    ObjCConversion = true;
3659  else
3660    return Ref_Incompatible;
3661
3662  // At this point, we know that T1 and T2 are reference-related (at
3663  // least).
3664
3665  // If the type is an array type, promote the element qualifiers to the type
3666  // for comparison.
3667  if (isa<ArrayType>(T1) && T1Quals)
3668    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3669  if (isa<ArrayType>(T2) && T2Quals)
3670    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3671
3672  // C++ [dcl.init.ref]p4:
3673  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3674  //   reference-related to T2 and cv1 is the same cv-qualification
3675  //   as, or greater cv-qualification than, cv2. For purposes of
3676  //   overload resolution, cases for which cv1 is greater
3677  //   cv-qualification than cv2 are identified as
3678  //   reference-compatible with added qualification (see 13.3.3.2).
3679  //
3680  // Note that we also require equivalence of Objective-C GC and address-space
3681  // qualifiers when performing these computations, so that e.g., an int in
3682  // address space 1 is not reference-compatible with an int in address
3683  // space 2.
3684  if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3685      T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3686    T1Quals.removeObjCLifetime();
3687    T2Quals.removeObjCLifetime();
3688    ObjCLifetimeConversion = true;
3689  }
3690
3691  if (T1Quals == T2Quals)
3692    return Ref_Compatible;
3693  else if (T1Quals.compatiblyIncludes(T2Quals))
3694    return Ref_Compatible_With_Added_Qualification;
3695  else
3696    return Ref_Related;
3697}
3698
3699/// \brief Look for a user-defined conversion to an value reference-compatible
3700///        with DeclType. Return true if something definite is found.
3701static bool
3702FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3703                         QualType DeclType, SourceLocation DeclLoc,
3704                         Expr *Init, QualType T2, bool AllowRvalues,
3705                         bool AllowExplicit) {
3706  assert(T2->isRecordType() && "Can only find conversions of record types.");
3707  CXXRecordDecl *T2RecordDecl
3708    = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3709
3710  OverloadCandidateSet CandidateSet(DeclLoc);
3711  const UnresolvedSetImpl *Conversions
3712    = T2RecordDecl->getVisibleConversionFunctions();
3713  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3714         E = Conversions->end(); I != E; ++I) {
3715    NamedDecl *D = *I;
3716    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3717    if (isa<UsingShadowDecl>(D))
3718      D = cast<UsingShadowDecl>(D)->getTargetDecl();
3719
3720    FunctionTemplateDecl *ConvTemplate
3721      = dyn_cast<FunctionTemplateDecl>(D);
3722    CXXConversionDecl *Conv;
3723    if (ConvTemplate)
3724      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3725    else
3726      Conv = cast<CXXConversionDecl>(D);
3727
3728    // If this is an explicit conversion, and we're not allowed to consider
3729    // explicit conversions, skip it.
3730    if (!AllowExplicit && Conv->isExplicit())
3731      continue;
3732
3733    if (AllowRvalues) {
3734      bool DerivedToBase = false;
3735      bool ObjCConversion = false;
3736      bool ObjCLifetimeConversion = false;
3737
3738      // If we are initializing an rvalue reference, don't permit conversion
3739      // functions that return lvalues.
3740      if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3741        const ReferenceType *RefType
3742          = Conv->getConversionType()->getAs<LValueReferenceType>();
3743        if (RefType && !RefType->getPointeeType()->isFunctionType())
3744          continue;
3745      }
3746
3747      if (!ConvTemplate &&
3748          S.CompareReferenceRelationship(
3749            DeclLoc,
3750            Conv->getConversionType().getNonReferenceType()
3751              .getUnqualifiedType(),
3752            DeclType.getNonReferenceType().getUnqualifiedType(),
3753            DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
3754          Sema::Ref_Incompatible)
3755        continue;
3756    } else {
3757      // If the conversion function doesn't return a reference type,
3758      // it can't be considered for this conversion. An rvalue reference
3759      // is only acceptable if its referencee is a function type.
3760
3761      const ReferenceType *RefType =
3762        Conv->getConversionType()->getAs<ReferenceType>();
3763      if (!RefType ||
3764          (!RefType->isLValueReferenceType() &&
3765           !RefType->getPointeeType()->isFunctionType()))
3766        continue;
3767    }
3768
3769    if (ConvTemplate)
3770      S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
3771                                       Init, DeclType, CandidateSet);
3772    else
3773      S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
3774                               DeclType, CandidateSet);
3775  }
3776
3777  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3778
3779  OverloadCandidateSet::iterator Best;
3780  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
3781  case OR_Success:
3782    // C++ [over.ics.ref]p1:
3783    //
3784    //   [...] If the parameter binds directly to the result of
3785    //   applying a conversion function to the argument
3786    //   expression, the implicit conversion sequence is a
3787    //   user-defined conversion sequence (13.3.3.1.2), with the
3788    //   second standard conversion sequence either an identity
3789    //   conversion or, if the conversion function returns an
3790    //   entity of a type that is a derived class of the parameter
3791    //   type, a derived-to-base Conversion.
3792    if (!Best->FinalConversion.DirectBinding)
3793      return false;
3794
3795    if (Best->Function)
3796      S.MarkFunctionReferenced(DeclLoc, Best->Function);
3797    ICS.setUserDefined();
3798    ICS.UserDefined.Before = Best->Conversions[0].Standard;
3799    ICS.UserDefined.After = Best->FinalConversion;
3800    ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
3801    ICS.UserDefined.ConversionFunction = Best->Function;
3802    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
3803    ICS.UserDefined.EllipsisConversion = false;
3804    assert(ICS.UserDefined.After.ReferenceBinding &&
3805           ICS.UserDefined.After.DirectBinding &&
3806           "Expected a direct reference binding!");
3807    return true;
3808
3809  case OR_Ambiguous:
3810    ICS.setAmbiguous();
3811    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3812         Cand != CandidateSet.end(); ++Cand)
3813      if (Cand->Viable)
3814        ICS.Ambiguous.addConversion(Cand->Function);
3815    return true;
3816
3817  case OR_No_Viable_Function:
3818  case OR_Deleted:
3819    // There was no suitable conversion, or we found a deleted
3820    // conversion; continue with other checks.
3821    return false;
3822  }
3823
3824  llvm_unreachable("Invalid OverloadResult!");
3825}
3826
3827/// \brief Compute an implicit conversion sequence for reference
3828/// initialization.
3829static ImplicitConversionSequence
3830TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
3831                 SourceLocation DeclLoc,
3832                 bool SuppressUserConversions,
3833                 bool AllowExplicit) {
3834  assert(DeclType->isReferenceType() && "Reference init needs a reference");
3835
3836  // Most paths end in a failed conversion.
3837  ImplicitConversionSequence ICS;
3838  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3839
3840  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3841  QualType T2 = Init->getType();
3842
3843  // If the initializer is the address of an overloaded function, try
3844  // to resolve the overloaded function. If all goes well, T2 is the
3845  // type of the resulting function.
3846  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3847    DeclAccessPair Found;
3848    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3849                                                                false, Found))
3850      T2 = Fn->getType();
3851  }
3852
3853  // Compute some basic properties of the types and the initializer.
3854  bool isRValRef = DeclType->isRValueReferenceType();
3855  bool DerivedToBase = false;
3856  bool ObjCConversion = false;
3857  bool ObjCLifetimeConversion = false;
3858  Expr::Classification InitCategory = Init->Classify(S.Context);
3859  Sema::ReferenceCompareResult RefRelationship
3860    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3861                                     ObjCConversion, ObjCLifetimeConversion);
3862
3863
3864  // C++0x [dcl.init.ref]p5:
3865  //   A reference to type "cv1 T1" is initialized by an expression
3866  //   of type "cv2 T2" as follows:
3867
3868  //     -- If reference is an lvalue reference and the initializer expression
3869  if (!isRValRef) {
3870    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3871    //        reference-compatible with "cv2 T2," or
3872    //
3873    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3874    if (InitCategory.isLValue() &&
3875        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
3876      // C++ [over.ics.ref]p1:
3877      //   When a parameter of reference type binds directly (8.5.3)
3878      //   to an argument expression, the implicit conversion sequence
3879      //   is the identity conversion, unless the argument expression
3880      //   has a type that is a derived class of the parameter type,
3881      //   in which case the implicit conversion sequence is a
3882      //   derived-to-base Conversion (13.3.3.1).
3883      ICS.setStandard();
3884      ICS.Standard.First = ICK_Identity;
3885      ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3886                         : ObjCConversion? ICK_Compatible_Conversion
3887                         : ICK_Identity;
3888      ICS.Standard.Third = ICK_Identity;
3889      ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3890      ICS.Standard.setToType(0, T2);
3891      ICS.Standard.setToType(1, T1);
3892      ICS.Standard.setToType(2, T1);
3893      ICS.Standard.ReferenceBinding = true;
3894      ICS.Standard.DirectBinding = true;
3895      ICS.Standard.IsLvalueReference = !isRValRef;
3896      ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3897      ICS.Standard.BindsToRvalue = false;
3898      ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3899      ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
3900      ICS.Standard.CopyConstructor = 0;
3901
3902      // Nothing more to do: the inaccessibility/ambiguity check for
3903      // derived-to-base conversions is suppressed when we're
3904      // computing the implicit conversion sequence (C++
3905      // [over.best.ics]p2).
3906      return ICS;
3907    }
3908
3909    //       -- has a class type (i.e., T2 is a class type), where T1 is
3910    //          not reference-related to T2, and can be implicitly
3911    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
3912    //          is reference-compatible with "cv3 T3" 92) (this
3913    //          conversion is selected by enumerating the applicable
3914    //          conversion functions (13.3.1.6) and choosing the best
3915    //          one through overload resolution (13.3)),
3916    if (!SuppressUserConversions && T2->isRecordType() &&
3917        !S.RequireCompleteType(DeclLoc, T2, 0) &&
3918        RefRelationship == Sema::Ref_Incompatible) {
3919      if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3920                                   Init, T2, /*AllowRvalues=*/false,
3921                                   AllowExplicit))
3922        return ICS;
3923    }
3924  }
3925
3926  //     -- Otherwise, the reference shall be an lvalue reference to a
3927  //        non-volatile const type (i.e., cv1 shall be const), or the reference
3928  //        shall be an rvalue reference.
3929  //
3930  // We actually handle one oddity of C++ [over.ics.ref] at this
3931  // point, which is that, due to p2 (which short-circuits reference
3932  // binding by only attempting a simple conversion for non-direct
3933  // bindings) and p3's strange wording, we allow a const volatile
3934  // reference to bind to an rvalue. Hence the check for the presence
3935  // of "const" rather than checking for "const" being the only
3936  // qualifier.
3937  // This is also the point where rvalue references and lvalue inits no longer
3938  // go together.
3939  if (!isRValRef && !T1.isConstQualified())
3940    return ICS;
3941
3942  //       -- If the initializer expression
3943  //
3944  //            -- is an xvalue, class prvalue, array prvalue or function
3945  //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
3946  if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3947      (InitCategory.isXValue() ||
3948      (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3949      (InitCategory.isLValue() && T2->isFunctionType()))) {
3950    ICS.setStandard();
3951    ICS.Standard.First = ICK_Identity;
3952    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3953                      : ObjCConversion? ICK_Compatible_Conversion
3954                      : ICK_Identity;
3955    ICS.Standard.Third = ICK_Identity;
3956    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3957    ICS.Standard.setToType(0, T2);
3958    ICS.Standard.setToType(1, T1);
3959    ICS.Standard.setToType(2, T1);
3960    ICS.Standard.ReferenceBinding = true;
3961    // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3962    // binding unless we're binding to a class prvalue.
3963    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3964    // allow the use of rvalue references in C++98/03 for the benefit of
3965    // standard library implementors; therefore, we need the xvalue check here.
3966    ICS.Standard.DirectBinding =
3967      S.getLangOptions().CPlusPlus0x ||
3968      (InitCategory.isPRValue() && !T2->isRecordType());
3969    ICS.Standard.IsLvalueReference = !isRValRef;
3970    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3971    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
3972    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3973    ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
3974    ICS.Standard.CopyConstructor = 0;
3975    return ICS;
3976  }
3977
3978  //            -- has a class type (i.e., T2 is a class type), where T1 is not
3979  //               reference-related to T2, and can be implicitly converted to
3980  //               an xvalue, class prvalue, or function lvalue of type
3981  //               "cv3 T3", where "cv1 T1" is reference-compatible with
3982  //               "cv3 T3",
3983  //
3984  //          then the reference is bound to the value of the initializer
3985  //          expression in the first case and to the result of the conversion
3986  //          in the second case (or, in either case, to an appropriate base
3987  //          class subobject).
3988  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3989      T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
3990      FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3991                               Init, T2, /*AllowRvalues=*/true,
3992                               AllowExplicit)) {
3993    // In the second case, if the reference is an rvalue reference
3994    // and the second standard conversion sequence of the
3995    // user-defined conversion sequence includes an lvalue-to-rvalue
3996    // conversion, the program is ill-formed.
3997    if (ICS.isUserDefined() && isRValRef &&
3998        ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3999      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4000
4001    return ICS;
4002  }
4003
4004  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4005  //          initialized from the initializer expression using the
4006  //          rules for a non-reference copy initialization (8.5). The
4007  //          reference is then bound to the temporary. If T1 is
4008  //          reference-related to T2, cv1 must be the same
4009  //          cv-qualification as, or greater cv-qualification than,
4010  //          cv2; otherwise, the program is ill-formed.
4011  if (RefRelationship == Sema::Ref_Related) {
4012    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4013    // we would be reference-compatible or reference-compatible with
4014    // added qualification. But that wasn't the case, so the reference
4015    // initialization fails.
4016    //
4017    // Note that we only want to check address spaces and cvr-qualifiers here.
4018    // ObjC GC and lifetime qualifiers aren't important.
4019    Qualifiers T1Quals = T1.getQualifiers();
4020    Qualifiers T2Quals = T2.getQualifiers();
4021    T1Quals.removeObjCGCAttr();
4022    T1Quals.removeObjCLifetime();
4023    T2Quals.removeObjCGCAttr();
4024    T2Quals.removeObjCLifetime();
4025    if (!T1Quals.compatiblyIncludes(T2Quals))
4026      return ICS;
4027  }
4028
4029  // If at least one of the types is a class type, the types are not
4030  // related, and we aren't allowed any user conversions, the
4031  // reference binding fails. This case is important for breaking
4032  // recursion, since TryImplicitConversion below will attempt to
4033  // create a temporary through the use of a copy constructor.
4034  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4035      (T1->isRecordType() || T2->isRecordType()))
4036    return ICS;
4037
4038  // If T1 is reference-related to T2 and the reference is an rvalue
4039  // reference, the initializer expression shall not be an lvalue.
4040  if (RefRelationship >= Sema::Ref_Related &&
4041      isRValRef && Init->Classify(S.Context).isLValue())
4042    return ICS;
4043
4044  // C++ [over.ics.ref]p2:
4045  //   When a parameter of reference type is not bound directly to
4046  //   an argument expression, the conversion sequence is the one
4047  //   required to convert the argument expression to the
4048  //   underlying type of the reference according to
4049  //   13.3.3.1. Conceptually, this conversion sequence corresponds
4050  //   to copy-initializing a temporary of the underlying type with
4051  //   the argument expression. Any difference in top-level
4052  //   cv-qualification is subsumed by the initialization itself
4053  //   and does not constitute a conversion.
4054  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4055                              /*AllowExplicit=*/false,
4056                              /*InOverloadResolution=*/false,
4057                              /*CStyle=*/false,
4058                              /*AllowObjCWritebackConversion=*/false);
4059
4060  // Of course, that's still a reference binding.
4061  if (ICS.isStandard()) {
4062    ICS.Standard.ReferenceBinding = true;
4063    ICS.Standard.IsLvalueReference = !isRValRef;
4064    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4065    ICS.Standard.BindsToRvalue = true;
4066    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4067    ICS.Standard.ObjCLifetimeConversionBinding = false;
4068  } else if (ICS.isUserDefined()) {
4069    // Don't allow rvalue references to bind to lvalues.
4070    if (DeclType->isRValueReferenceType()) {
4071      if (const ReferenceType *RefType
4072            = ICS.UserDefined.ConversionFunction->getResultType()
4073                ->getAs<LValueReferenceType>()) {
4074        if (!RefType->getPointeeType()->isFunctionType()) {
4075          ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4076                     DeclType);
4077          return ICS;
4078        }
4079      }
4080    }
4081
4082    ICS.UserDefined.After.ReferenceBinding = true;
4083    ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4084    ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4085    ICS.UserDefined.After.BindsToRvalue = true;
4086    ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4087    ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4088  }
4089
4090  return ICS;
4091}
4092
4093static ImplicitConversionSequence
4094TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4095                      bool SuppressUserConversions,
4096                      bool InOverloadResolution,
4097                      bool AllowObjCWritebackConversion);
4098
4099/// TryListConversion - Try to copy-initialize a value of type ToType from the
4100/// initializer list From.
4101static ImplicitConversionSequence
4102TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4103                  bool SuppressUserConversions,
4104                  bool InOverloadResolution,
4105                  bool AllowObjCWritebackConversion) {
4106  // C++11 [over.ics.list]p1:
4107  //   When an argument is an initializer list, it is not an expression and
4108  //   special rules apply for converting it to a parameter type.
4109
4110  ImplicitConversionSequence Result;
4111  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4112  Result.setListInitializationSequence();
4113
4114  // We need a complete type for what follows. Incomplete types can never be
4115  // initialized from init lists.
4116  if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
4117    return Result;
4118
4119  // C++11 [over.ics.list]p2:
4120  //   If the parameter type is std::initializer_list<X> or "array of X" and
4121  //   all the elements can be implicitly converted to X, the implicit
4122  //   conversion sequence is the worst conversion necessary to convert an
4123  //   element of the list to X.
4124  QualType X;
4125  if (ToType->isArrayType())
4126    X = S.Context.getBaseElementType(ToType);
4127  else
4128    (void)S.isStdInitializerList(ToType, &X);
4129  if (!X.isNull()) {
4130    for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4131      Expr *Init = From->getInit(i);
4132      ImplicitConversionSequence ICS =
4133          TryCopyInitialization(S, Init, X, SuppressUserConversions,
4134                                InOverloadResolution,
4135                                AllowObjCWritebackConversion);
4136      // If a single element isn't convertible, fail.
4137      if (ICS.isBad()) {
4138        Result = ICS;
4139        break;
4140      }
4141      // Otherwise, look for the worst conversion.
4142      if (Result.isBad() ||
4143          CompareImplicitConversionSequences(S, ICS, Result) ==
4144              ImplicitConversionSequence::Worse)
4145        Result = ICS;
4146    }
4147    Result.setListInitializationSequence();
4148    return Result;
4149  }
4150
4151  // C++11 [over.ics.list]p3:
4152  //   Otherwise, if the parameter is a non-aggregate class X and overload
4153  //   resolution chooses a single best constructor [...] the implicit
4154  //   conversion sequence is a user-defined conversion sequence. If multiple
4155  //   constructors are viable but none is better than the others, the
4156  //   implicit conversion sequence is a user-defined conversion sequence.
4157  if (ToType->isRecordType() && !ToType->isAggregateType()) {
4158    // This function can deal with initializer lists.
4159    Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4160                                      /*AllowExplicit=*/false,
4161                                      InOverloadResolution, /*CStyle=*/false,
4162                                      AllowObjCWritebackConversion);
4163    Result.setListInitializationSequence();
4164    return Result;
4165  }
4166
4167  // C++11 [over.ics.list]p4:
4168  //   Otherwise, if the parameter has an aggregate type which can be
4169  //   initialized from the initializer list [...] the implicit conversion
4170  //   sequence is a user-defined conversion sequence.
4171  if (ToType->isAggregateType()) {
4172    // Type is an aggregate, argument is an init list. At this point it comes
4173    // down to checking whether the initialization works.
4174    // FIXME: Find out whether this parameter is consumed or not.
4175    InitializedEntity Entity =
4176        InitializedEntity::InitializeParameter(S.Context, ToType,
4177                                               /*Consumed=*/false);
4178    if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4179      Result.setUserDefined();
4180      Result.UserDefined.Before.setAsIdentityConversion();
4181      // Initializer lists don't have a type.
4182      Result.UserDefined.Before.setFromType(QualType());
4183      Result.UserDefined.Before.setAllToTypes(QualType());
4184
4185      Result.UserDefined.After.setAsIdentityConversion();
4186      Result.UserDefined.After.setFromType(ToType);
4187      Result.UserDefined.After.setAllToTypes(ToType);
4188    }
4189    return Result;
4190  }
4191
4192  // C++11 [over.ics.list]p5:
4193  //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4194  if (ToType->isReferenceType()) {
4195    // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4196    // mention initializer lists in any way. So we go by what list-
4197    // initialization would do and try to extrapolate from that.
4198
4199    QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4200
4201    // If the initializer list has a single element that is reference-related
4202    // to the parameter type, we initialize the reference from that.
4203    if (From->getNumInits() == 1) {
4204      Expr *Init = From->getInit(0);
4205
4206      QualType T2 = Init->getType();
4207
4208      // If the initializer is the address of an overloaded function, try
4209      // to resolve the overloaded function. If all goes well, T2 is the
4210      // type of the resulting function.
4211      if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4212        DeclAccessPair Found;
4213        if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4214                                   Init, ToType, false, Found))
4215          T2 = Fn->getType();
4216      }
4217
4218      // Compute some basic properties of the types and the initializer.
4219      bool dummy1 = false;
4220      bool dummy2 = false;
4221      bool dummy3 = false;
4222      Sema::ReferenceCompareResult RefRelationship
4223        = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4224                                         dummy2, dummy3);
4225
4226      if (RefRelationship >= Sema::Ref_Related)
4227        return TryReferenceInit(S, Init, ToType,
4228                                /*FIXME:*/From->getLocStart(),
4229                                SuppressUserConversions,
4230                                /*AllowExplicit=*/false);
4231    }
4232
4233    // Otherwise, we bind the reference to a temporary created from the
4234    // initializer list.
4235    Result = TryListConversion(S, From, T1, SuppressUserConversions,
4236                               InOverloadResolution,
4237                               AllowObjCWritebackConversion);
4238    if (Result.isFailure())
4239      return Result;
4240    assert(!Result.isEllipsis() &&
4241           "Sub-initialization cannot result in ellipsis conversion.");
4242
4243    // Can we even bind to a temporary?
4244    if (ToType->isRValueReferenceType() ||
4245        (T1.isConstQualified() && !T1.isVolatileQualified())) {
4246      StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4247                                            Result.UserDefined.After;
4248      SCS.ReferenceBinding = true;
4249      SCS.IsLvalueReference = ToType->isLValueReferenceType();
4250      SCS.BindsToRvalue = true;
4251      SCS.BindsToFunctionLvalue = false;
4252      SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4253      SCS.ObjCLifetimeConversionBinding = false;
4254    } else
4255      Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4256                    From, ToType);
4257    return Result;
4258  }
4259
4260  // C++11 [over.ics.list]p6:
4261  //   Otherwise, if the parameter type is not a class:
4262  if (!ToType->isRecordType()) {
4263    //    - if the initializer list has one element, the implicit conversion
4264    //      sequence is the one required to convert the element to the
4265    //      parameter type.
4266    unsigned NumInits = From->getNumInits();
4267    if (NumInits == 1)
4268      Result = TryCopyInitialization(S, From->getInit(0), ToType,
4269                                     SuppressUserConversions,
4270                                     InOverloadResolution,
4271                                     AllowObjCWritebackConversion);
4272    //    - if the initializer list has no elements, the implicit conversion
4273    //      sequence is the identity conversion.
4274    else if (NumInits == 0) {
4275      Result.setStandard();
4276      Result.Standard.setAsIdentityConversion();
4277    }
4278    return Result;
4279  }
4280
4281  // C++11 [over.ics.list]p7:
4282  //   In all cases other than those enumerated above, no conversion is possible
4283  return Result;
4284}
4285
4286/// TryCopyInitialization - Try to copy-initialize a value of type
4287/// ToType from the expression From. Return the implicit conversion
4288/// sequence required to pass this argument, which may be a bad
4289/// conversion sequence (meaning that the argument cannot be passed to
4290/// a parameter of this type). If @p SuppressUserConversions, then we
4291/// do not permit any user-defined conversion sequences.
4292static ImplicitConversionSequence
4293TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4294                      bool SuppressUserConversions,
4295                      bool InOverloadResolution,
4296                      bool AllowObjCWritebackConversion) {
4297  if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4298    return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4299                             InOverloadResolution,AllowObjCWritebackConversion);
4300
4301  if (ToType->isReferenceType())
4302    return TryReferenceInit(S, From, ToType,
4303                            /*FIXME:*/From->getLocStart(),
4304                            SuppressUserConversions,
4305                            /*AllowExplicit=*/false);
4306
4307  return TryImplicitConversion(S, From, ToType,
4308                               SuppressUserConversions,
4309                               /*AllowExplicit=*/false,
4310                               InOverloadResolution,
4311                               /*CStyle=*/false,
4312                               AllowObjCWritebackConversion);
4313}
4314
4315static bool TryCopyInitialization(const CanQualType FromQTy,
4316                                  const CanQualType ToQTy,
4317                                  Sema &S,
4318                                  SourceLocation Loc,
4319                                  ExprValueKind FromVK) {
4320  OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4321  ImplicitConversionSequence ICS =
4322    TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4323
4324  return !ICS.isBad();
4325}
4326
4327/// TryObjectArgumentInitialization - Try to initialize the object
4328/// parameter of the given member function (@c Method) from the
4329/// expression @p From.
4330static ImplicitConversionSequence
4331TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
4332                                Expr::Classification FromClassification,
4333                                CXXMethodDecl *Method,
4334                                CXXRecordDecl *ActingContext) {
4335  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4336  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4337  //                 const volatile object.
4338  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4339    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4340  QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4341
4342  // Set up the conversion sequence as a "bad" conversion, to allow us
4343  // to exit early.
4344  ImplicitConversionSequence ICS;
4345
4346  // We need to have an object of class type.
4347  QualType FromType = OrigFromType;
4348  if (const PointerType *PT = FromType->getAs<PointerType>()) {
4349    FromType = PT->getPointeeType();
4350
4351    // When we had a pointer, it's implicitly dereferenced, so we
4352    // better have an lvalue.
4353    assert(FromClassification.isLValue());
4354  }
4355
4356  assert(FromType->isRecordType());
4357
4358  // C++0x [over.match.funcs]p4:
4359  //   For non-static member functions, the type of the implicit object
4360  //   parameter is
4361  //
4362  //     - "lvalue reference to cv X" for functions declared without a
4363  //        ref-qualifier or with the & ref-qualifier
4364  //     - "rvalue reference to cv X" for functions declared with the &&
4365  //        ref-qualifier
4366  //
4367  // where X is the class of which the function is a member and cv is the
4368  // cv-qualification on the member function declaration.
4369  //
4370  // However, when finding an implicit conversion sequence for the argument, we
4371  // are not allowed to create temporaries or perform user-defined conversions
4372  // (C++ [over.match.funcs]p5). We perform a simplified version of
4373  // reference binding here, that allows class rvalues to bind to
4374  // non-constant references.
4375
4376  // First check the qualifiers.
4377  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4378  if (ImplicitParamType.getCVRQualifiers()
4379                                    != FromTypeCanon.getLocalCVRQualifiers() &&
4380      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4381    ICS.setBad(BadConversionSequence::bad_qualifiers,
4382               OrigFromType, ImplicitParamType);
4383    return ICS;
4384  }
4385
4386  // Check that we have either the same type or a derived type. It
4387  // affects the conversion rank.
4388  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4389  ImplicitConversionKind SecondKind;
4390  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4391    SecondKind = ICK_Identity;
4392  } else if (S.IsDerivedFrom(FromType, ClassType))
4393    SecondKind = ICK_Derived_To_Base;
4394  else {
4395    ICS.setBad(BadConversionSequence::unrelated_class,
4396               FromType, ImplicitParamType);
4397    return ICS;
4398  }
4399
4400  // Check the ref-qualifier.
4401  switch (Method->getRefQualifier()) {
4402  case RQ_None:
4403    // Do nothing; we don't care about lvalueness or rvalueness.
4404    break;
4405
4406  case RQ_LValue:
4407    if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4408      // non-const lvalue reference cannot bind to an rvalue
4409      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4410                 ImplicitParamType);
4411      return ICS;
4412    }
4413    break;
4414
4415  case RQ_RValue:
4416    if (!FromClassification.isRValue()) {
4417      // rvalue reference cannot bind to an lvalue
4418      ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4419                 ImplicitParamType);
4420      return ICS;
4421    }
4422    break;
4423  }
4424
4425  // Success. Mark this as a reference binding.
4426  ICS.setStandard();
4427  ICS.Standard.setAsIdentityConversion();
4428  ICS.Standard.Second = SecondKind;
4429  ICS.Standard.setFromType(FromType);
4430  ICS.Standard.setAllToTypes(ImplicitParamType);
4431  ICS.Standard.ReferenceBinding = true;
4432  ICS.Standard.DirectBinding = true;
4433  ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4434  ICS.Standard.BindsToFunctionLvalue = false;
4435  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4436  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4437    = (Method->getRefQualifier() == RQ_None);
4438  return ICS;
4439}
4440
4441/// PerformObjectArgumentInitialization - Perform initialization of
4442/// the implicit object parameter for the given Method with the given
4443/// expression.
4444ExprResult
4445Sema::PerformObjectArgumentInitialization(Expr *From,
4446                                          NestedNameSpecifier *Qualifier,
4447                                          NamedDecl *FoundDecl,
4448                                          CXXMethodDecl *Method) {
4449  QualType FromRecordType, DestType;
4450  QualType ImplicitParamRecordType  =
4451    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4452
4453  Expr::Classification FromClassification;
4454  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4455    FromRecordType = PT->getPointeeType();
4456    DestType = Method->getThisType(Context);
4457    FromClassification = Expr::Classification::makeSimpleLValue();
4458  } else {
4459    FromRecordType = From->getType();
4460    DestType = ImplicitParamRecordType;
4461    FromClassification = From->Classify(Context);
4462  }
4463
4464  // Note that we always use the true parent context when performing
4465  // the actual argument initialization.
4466  ImplicitConversionSequence ICS
4467    = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4468                                      Method, Method->getParent());
4469  if (ICS.isBad()) {
4470    if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4471      Qualifiers FromQs = FromRecordType.getQualifiers();
4472      Qualifiers ToQs = DestType.getQualifiers();
4473      unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4474      if (CVR) {
4475        Diag(From->getSourceRange().getBegin(),
4476             diag::err_member_function_call_bad_cvr)
4477          << Method->getDeclName() << FromRecordType << (CVR - 1)
4478          << From->getSourceRange();
4479        Diag(Method->getLocation(), diag::note_previous_decl)
4480          << Method->getDeclName();
4481        return ExprError();
4482      }
4483    }
4484
4485    return Diag(From->getSourceRange().getBegin(),
4486                diag::err_implicit_object_parameter_init)
4487       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4488  }
4489
4490  if (ICS.Standard.Second == ICK_Derived_To_Base) {
4491    ExprResult FromRes =
4492      PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4493    if (FromRes.isInvalid())
4494      return ExprError();
4495    From = FromRes.take();
4496  }
4497
4498  if (!Context.hasSameType(From->getType(), DestType))
4499    From = ImpCastExprToType(From, DestType, CK_NoOp,
4500                             From->getValueKind()).take();
4501  return Owned(From);
4502}
4503
4504/// TryContextuallyConvertToBool - Attempt to contextually convert the
4505/// expression From to bool (C++0x [conv]p3).
4506static ImplicitConversionSequence
4507TryContextuallyConvertToBool(Sema &S, Expr *From) {
4508  // FIXME: This is pretty broken.
4509  return TryImplicitConversion(S, From, S.Context.BoolTy,
4510                               // FIXME: Are these flags correct?
4511                               /*SuppressUserConversions=*/false,
4512                               /*AllowExplicit=*/true,
4513                               /*InOverloadResolution=*/false,
4514                               /*CStyle=*/false,
4515                               /*AllowObjCWritebackConversion=*/false);
4516}
4517
4518/// PerformContextuallyConvertToBool - Perform a contextual conversion
4519/// of the expression From to bool (C++0x [conv]p3).
4520ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4521  if (checkPlaceholderForOverload(*this, From))
4522    return ExprError();
4523
4524  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4525  if (!ICS.isBad())
4526    return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4527
4528  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4529    return Diag(From->getSourceRange().getBegin(),
4530                diag::err_typecheck_bool_condition)
4531                  << From->getType() << From->getSourceRange();
4532  return ExprError();
4533}
4534
4535/// Check that the specified conversion is permitted in a converted constant
4536/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4537/// is acceptable.
4538static bool CheckConvertedConstantConversions(Sema &S,
4539                                              StandardConversionSequence &SCS) {
4540  // Since we know that the target type is an integral or unscoped enumeration
4541  // type, most conversion kinds are impossible. All possible First and Third
4542  // conversions are fine.
4543  switch (SCS.Second) {
4544  case ICK_Identity:
4545  case ICK_Integral_Promotion:
4546  case ICK_Integral_Conversion:
4547    return true;
4548
4549  case ICK_Boolean_Conversion:
4550    // Conversion from an integral or unscoped enumeration type to bool is
4551    // classified as ICK_Boolean_Conversion, but it's also an integral
4552    // conversion, so it's permitted in a converted constant expression.
4553    return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4554           SCS.getToType(2)->isBooleanType();
4555
4556  case ICK_Floating_Integral:
4557  case ICK_Complex_Real:
4558    return false;
4559
4560  case ICK_Lvalue_To_Rvalue:
4561  case ICK_Array_To_Pointer:
4562  case ICK_Function_To_Pointer:
4563  case ICK_NoReturn_Adjustment:
4564  case ICK_Qualification:
4565  case ICK_Compatible_Conversion:
4566  case ICK_Vector_Conversion:
4567  case ICK_Vector_Splat:
4568  case ICK_Derived_To_Base:
4569  case ICK_Pointer_Conversion:
4570  case ICK_Pointer_Member:
4571  case ICK_Block_Pointer_Conversion:
4572  case ICK_Writeback_Conversion:
4573  case ICK_Floating_Promotion:
4574  case ICK_Complex_Promotion:
4575  case ICK_Complex_Conversion:
4576  case ICK_Floating_Conversion:
4577  case ICK_TransparentUnionConversion:
4578    llvm_unreachable("unexpected second conversion kind");
4579
4580  case ICK_Num_Conversion_Kinds:
4581    break;
4582  }
4583
4584  llvm_unreachable("unknown conversion kind");
4585}
4586
4587/// CheckConvertedConstantExpression - Check that the expression From is a
4588/// converted constant expression of type T, perform the conversion and produce
4589/// the converted expression, per C++11 [expr.const]p3.
4590ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4591                                                  llvm::APSInt &Value,
4592                                                  CCEKind CCE) {
4593  assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4594  assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4595
4596  if (checkPlaceholderForOverload(*this, From))
4597    return ExprError();
4598
4599  // C++11 [expr.const]p3 with proposed wording fixes:
4600  //  A converted constant expression of type T is a core constant expression,
4601  //  implicitly converted to a prvalue of type T, where the converted
4602  //  expression is a literal constant expression and the implicit conversion
4603  //  sequence contains only user-defined conversions, lvalue-to-rvalue
4604  //  conversions, integral promotions, and integral conversions other than
4605  //  narrowing conversions.
4606  ImplicitConversionSequence ICS =
4607    TryImplicitConversion(From, T,
4608                          /*SuppressUserConversions=*/false,
4609                          /*AllowExplicit=*/false,
4610                          /*InOverloadResolution=*/false,
4611                          /*CStyle=*/false,
4612                          /*AllowObjcWritebackConversion=*/false);
4613  StandardConversionSequence *SCS = 0;
4614  switch (ICS.getKind()) {
4615  case ImplicitConversionSequence::StandardConversion:
4616    if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4617      return Diag(From->getSourceRange().getBegin(),
4618                  diag::err_typecheck_converted_constant_expression_disallowed)
4619               << From->getType() << From->getSourceRange() << T;
4620    SCS = &ICS.Standard;
4621    break;
4622  case ImplicitConversionSequence::UserDefinedConversion:
4623    // We are converting from class type to an integral or enumeration type, so
4624    // the Before sequence must be trivial.
4625    if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4626      return Diag(From->getSourceRange().getBegin(),
4627                  diag::err_typecheck_converted_constant_expression_disallowed)
4628               << From->getType() << From->getSourceRange() << T;
4629    SCS = &ICS.UserDefined.After;
4630    break;
4631  case ImplicitConversionSequence::AmbiguousConversion:
4632  case ImplicitConversionSequence::BadConversion:
4633    if (!DiagnoseMultipleUserDefinedConversion(From, T))
4634      return Diag(From->getSourceRange().getBegin(),
4635                  diag::err_typecheck_converted_constant_expression)
4636                    << From->getType() << From->getSourceRange() << T;
4637    return ExprError();
4638
4639  case ImplicitConversionSequence::EllipsisConversion:
4640    llvm_unreachable("ellipsis conversion in converted constant expression");
4641  }
4642
4643  ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4644  if (Result.isInvalid())
4645    return Result;
4646
4647  // Check for a narrowing implicit conversion.
4648  APValue PreNarrowingValue;
4649  bool Diagnosed = false;
4650  switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue)) {
4651  case NK_Variable_Narrowing:
4652    // Implicit conversion to a narrower type, and the value is not a constant
4653    // expression. We'll diagnose this in a moment.
4654  case NK_Not_Narrowing:
4655    break;
4656
4657  case NK_Constant_Narrowing:
4658    Diag(From->getSourceRange().getBegin(), diag::err_cce_narrowing)
4659      << CCE << /*Constant*/1
4660      << PreNarrowingValue.getAsString(Context, QualType()) << T;
4661    Diagnosed = true;
4662    break;
4663
4664  case NK_Type_Narrowing:
4665    Diag(From->getSourceRange().getBegin(), diag::err_cce_narrowing)
4666      << CCE << /*Constant*/0 << From->getType() << T;
4667    Diagnosed = true;
4668    break;
4669  }
4670
4671  // Check the expression is a constant expression.
4672  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4673  Expr::EvalResult Eval;
4674  Eval.Diag = &Notes;
4675
4676  if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4677    // The expression can't be folded, so we can't keep it at this position in
4678    // the AST.
4679    Result = ExprError();
4680  } else {
4681    Value = Eval.Val.getInt();
4682
4683    if (Notes.empty()) {
4684      // It's a constant expression.
4685      return Result;
4686    }
4687  }
4688
4689  // Only issue one narrowing diagnostic.
4690  if (Diagnosed)
4691    return Result;
4692
4693  // It's not a constant expression. Produce an appropriate diagnostic.
4694  if (Notes.size() == 1 &&
4695      Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4696    Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4697  else {
4698    Diag(From->getSourceRange().getBegin(), diag::err_expr_not_cce)
4699      << CCE << From->getSourceRange();
4700    for (unsigned I = 0; I < Notes.size(); ++I)
4701      Diag(Notes[I].first, Notes[I].second);
4702  }
4703  return Result;
4704}
4705
4706/// dropPointerConversions - If the given standard conversion sequence
4707/// involves any pointer conversions, remove them.  This may change
4708/// the result type of the conversion sequence.
4709static void dropPointerConversion(StandardConversionSequence &SCS) {
4710  if (SCS.Second == ICK_Pointer_Conversion) {
4711    SCS.Second = ICK_Identity;
4712    SCS.Third = ICK_Identity;
4713    SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4714  }
4715}
4716
4717/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4718/// convert the expression From to an Objective-C pointer type.
4719static ImplicitConversionSequence
4720TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4721  // Do an implicit conversion to 'id'.
4722  QualType Ty = S.Context.getObjCIdType();
4723  ImplicitConversionSequence ICS
4724    = TryImplicitConversion(S, From, Ty,
4725                            // FIXME: Are these flags correct?
4726                            /*SuppressUserConversions=*/false,
4727                            /*AllowExplicit=*/true,
4728                            /*InOverloadResolution=*/false,
4729                            /*CStyle=*/false,
4730                            /*AllowObjCWritebackConversion=*/false);
4731
4732  // Strip off any final conversions to 'id'.
4733  switch (ICS.getKind()) {
4734  case ImplicitConversionSequence::BadConversion:
4735  case ImplicitConversionSequence::AmbiguousConversion:
4736  case ImplicitConversionSequence::EllipsisConversion:
4737    break;
4738
4739  case ImplicitConversionSequence::UserDefinedConversion:
4740    dropPointerConversion(ICS.UserDefined.After);
4741    break;
4742
4743  case ImplicitConversionSequence::StandardConversion:
4744    dropPointerConversion(ICS.Standard);
4745    break;
4746  }
4747
4748  return ICS;
4749}
4750
4751/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4752/// conversion of the expression From to an Objective-C pointer type.
4753ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
4754  if (checkPlaceholderForOverload(*this, From))
4755    return ExprError();
4756
4757  QualType Ty = Context.getObjCIdType();
4758  ImplicitConversionSequence ICS =
4759    TryContextuallyConvertToObjCPointer(*this, From);
4760  if (!ICS.isBad())
4761    return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
4762  return ExprError();
4763}
4764
4765/// \brief Attempt to convert the given expression to an integral or
4766/// enumeration type.
4767///
4768/// This routine will attempt to convert an expression of class type to an
4769/// integral or enumeration type, if that class type only has a single
4770/// conversion to an integral or enumeration type.
4771///
4772/// \param Loc The source location of the construct that requires the
4773/// conversion.
4774///
4775/// \param FromE The expression we're converting from.
4776///
4777/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4778/// have integral or enumeration type.
4779///
4780/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4781/// incomplete class type.
4782///
4783/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4784/// explicit conversion function (because no implicit conversion functions
4785/// were available). This is a recovery mode.
4786///
4787/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4788/// showing which conversion was picked.
4789///
4790/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4791/// conversion function that could convert to integral or enumeration type.
4792///
4793/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
4794/// usable conversion function.
4795///
4796/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4797/// function, which may be an extension in this case.
4798///
4799/// \returns The expression, converted to an integral or enumeration type if
4800/// successful.
4801ExprResult
4802Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
4803                                         const PartialDiagnostic &NotIntDiag,
4804                                       const PartialDiagnostic &IncompleteDiag,
4805                                     const PartialDiagnostic &ExplicitConvDiag,
4806                                     const PartialDiagnostic &ExplicitConvNote,
4807                                         const PartialDiagnostic &AmbigDiag,
4808                                         const PartialDiagnostic &AmbigNote,
4809                                         const PartialDiagnostic &ConvDiag) {
4810  // We can't perform any more checking for type-dependent expressions.
4811  if (From->isTypeDependent())
4812    return Owned(From);
4813
4814  // Process placeholders immediately.
4815  if (From->hasPlaceholderType()) {
4816    ExprResult result = CheckPlaceholderExpr(From);
4817    if (result.isInvalid()) return result;
4818    From = result.take();
4819  }
4820
4821  // If the expression already has integral or enumeration type, we're golden.
4822  QualType T = From->getType();
4823  if (T->isIntegralOrEnumerationType())
4824    return DefaultLvalueConversion(From);
4825
4826  // FIXME: Check for missing '()' if T is a function type?
4827
4828  // If we don't have a class type in C++, there's no way we can get an
4829  // expression of integral or enumeration type.
4830  const RecordType *RecordTy = T->getAs<RecordType>();
4831  if (!RecordTy || !getLangOptions().CPlusPlus) {
4832    Diag(Loc, NotIntDiag)
4833      << T << From->getSourceRange();
4834    return Owned(From);
4835  }
4836
4837  // We must have a complete class type.
4838  if (RequireCompleteType(Loc, T, IncompleteDiag))
4839    return Owned(From);
4840
4841  // Look for a conversion to an integral or enumeration type.
4842  UnresolvedSet<4> ViableConversions;
4843  UnresolvedSet<4> ExplicitConversions;
4844  const UnresolvedSetImpl *Conversions
4845    = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
4846
4847  bool HadMultipleCandidates = (Conversions->size() > 1);
4848
4849  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4850                                   E = Conversions->end();
4851       I != E;
4852       ++I) {
4853    if (CXXConversionDecl *Conversion
4854          = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4855      if (Conversion->getConversionType().getNonReferenceType()
4856            ->isIntegralOrEnumerationType()) {
4857        if (Conversion->isExplicit())
4858          ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4859        else
4860          ViableConversions.addDecl(I.getDecl(), I.getAccess());
4861      }
4862  }
4863
4864  switch (ViableConversions.size()) {
4865  case 0:
4866    if (ExplicitConversions.size() == 1) {
4867      DeclAccessPair Found = ExplicitConversions[0];
4868      CXXConversionDecl *Conversion
4869        = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4870
4871      // The user probably meant to invoke the given explicit
4872      // conversion; use it.
4873      QualType ConvTy
4874        = Conversion->getConversionType().getNonReferenceType();
4875      std::string TypeStr;
4876      ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
4877
4878      Diag(Loc, ExplicitConvDiag)
4879        << T << ConvTy
4880        << FixItHint::CreateInsertion(From->getLocStart(),
4881                                      "static_cast<" + TypeStr + ">(")
4882        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4883                                      ")");
4884      Diag(Conversion->getLocation(), ExplicitConvNote)
4885        << ConvTy->isEnumeralType() << ConvTy;
4886
4887      // If we aren't in a SFINAE context, build a call to the
4888      // explicit conversion function.
4889      if (isSFINAEContext())
4890        return ExprError();
4891
4892      CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
4893      ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4894                                                 HadMultipleCandidates);
4895      if (Result.isInvalid())
4896        return ExprError();
4897      // Record usage of conversion in an implicit cast.
4898      From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4899                                      CK_UserDefinedConversion,
4900                                      Result.get(), 0,
4901                                      Result.get()->getValueKind());
4902    }
4903
4904    // We'll complain below about a non-integral condition type.
4905    break;
4906
4907  case 1: {
4908    // Apply this conversion.
4909    DeclAccessPair Found = ViableConversions[0];
4910    CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
4911
4912    CXXConversionDecl *Conversion
4913      = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4914    QualType ConvTy
4915      = Conversion->getConversionType().getNonReferenceType();
4916    if (ConvDiag.getDiagID()) {
4917      if (isSFINAEContext())
4918        return ExprError();
4919
4920      Diag(Loc, ConvDiag)
4921        << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4922    }
4923
4924    ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4925                                               HadMultipleCandidates);
4926    if (Result.isInvalid())
4927      return ExprError();
4928    // Record usage of conversion in an implicit cast.
4929    From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4930                                    CK_UserDefinedConversion,
4931                                    Result.get(), 0,
4932                                    Result.get()->getValueKind());
4933    break;
4934  }
4935
4936  default:
4937    Diag(Loc, AmbigDiag)
4938      << T << From->getSourceRange();
4939    for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4940      CXXConversionDecl *Conv
4941        = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4942      QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4943      Diag(Conv->getLocation(), AmbigNote)
4944        << ConvTy->isEnumeralType() << ConvTy;
4945    }
4946    return Owned(From);
4947  }
4948
4949  if (!From->getType()->isIntegralOrEnumerationType())
4950    Diag(Loc, NotIntDiag)
4951      << From->getType() << From->getSourceRange();
4952
4953  return DefaultLvalueConversion(From);
4954}
4955
4956/// AddOverloadCandidate - Adds the given function to the set of
4957/// candidate functions, using the given function call arguments.  If
4958/// @p SuppressUserConversions, then don't allow user-defined
4959/// conversions via constructors or conversion operators.
4960///
4961/// \para PartialOverloading true if we are performing "partial" overloading
4962/// based on an incomplete set of function arguments. This feature is used by
4963/// code completion.
4964void
4965Sema::AddOverloadCandidate(FunctionDecl *Function,
4966                           DeclAccessPair FoundDecl,
4967                           Expr **Args, unsigned NumArgs,
4968                           OverloadCandidateSet& CandidateSet,
4969                           bool SuppressUserConversions,
4970                           bool PartialOverloading) {
4971  const FunctionProtoType* Proto
4972    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
4973  assert(Proto && "Functions without a prototype cannot be overloaded");
4974  assert(!Function->getDescribedFunctionTemplate() &&
4975         "Use AddTemplateOverloadCandidate for function templates");
4976
4977  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
4978    if (!isa<CXXConstructorDecl>(Method)) {
4979      // If we get here, it's because we're calling a member function
4980      // that is named without a member access expression (e.g.,
4981      // "this->f") that was either written explicitly or created
4982      // implicitly. This can happen with a qualified call to a member
4983      // function, e.g., X::f(). We use an empty type for the implied
4984      // object argument (C++ [over.call.func]p3), and the acting context
4985      // is irrelevant.
4986      AddMethodCandidate(Method, FoundDecl, Method->getParent(),
4987                         QualType(), Expr::Classification::makeSimpleLValue(),
4988                         Args, NumArgs, CandidateSet,
4989                         SuppressUserConversions);
4990      return;
4991    }
4992    // We treat a constructor like a non-member function, since its object
4993    // argument doesn't participate in overload resolution.
4994  }
4995
4996  if (!CandidateSet.isNewCandidate(Function))
4997    return;
4998
4999  // Overload resolution is always an unevaluated context.
5000  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5001
5002  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5003    // C++ [class.copy]p3:
5004    //   A member function template is never instantiated to perform the copy
5005    //   of a class object to an object of its class type.
5006    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5007    if (NumArgs == 1 &&
5008        Constructor->isSpecializationCopyingObject() &&
5009        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5010         IsDerivedFrom(Args[0]->getType(), ClassType)))
5011      return;
5012  }
5013
5014  // Add this candidate
5015  OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
5016  Candidate.FoundDecl = FoundDecl;
5017  Candidate.Function = Function;
5018  Candidate.Viable = true;
5019  Candidate.IsSurrogate = false;
5020  Candidate.IgnoreObjectArgument = false;
5021  Candidate.ExplicitCallArguments = NumArgs;
5022
5023  unsigned NumArgsInProto = Proto->getNumArgs();
5024
5025  // (C++ 13.3.2p2): A candidate function having fewer than m
5026  // parameters is viable only if it has an ellipsis in its parameter
5027  // list (8.3.5).
5028  if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
5029      !Proto->isVariadic()) {
5030    Candidate.Viable = false;
5031    Candidate.FailureKind = ovl_fail_too_many_arguments;
5032    return;
5033  }
5034
5035  // (C++ 13.3.2p2): A candidate function having more than m parameters
5036  // is viable only if the (m+1)st parameter has a default argument
5037  // (8.3.6). For the purposes of overload resolution, the
5038  // parameter list is truncated on the right, so that there are
5039  // exactly m parameters.
5040  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5041  if (NumArgs < MinRequiredArgs && !PartialOverloading) {
5042    // Not enough arguments.
5043    Candidate.Viable = false;
5044    Candidate.FailureKind = ovl_fail_too_few_arguments;
5045    return;
5046  }
5047
5048  // (CUDA B.1): Check for invalid calls between targets.
5049  if (getLangOptions().CUDA)
5050    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5051      if (CheckCUDATarget(Caller, Function)) {
5052        Candidate.Viable = false;
5053        Candidate.FailureKind = ovl_fail_bad_target;
5054        return;
5055      }
5056
5057  // Determine the implicit conversion sequences for each of the
5058  // arguments.
5059  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5060    if (ArgIdx < NumArgsInProto) {
5061      // (C++ 13.3.2p3): for F to be a viable function, there shall
5062      // exist for each argument an implicit conversion sequence
5063      // (13.3.3.1) that converts that argument to the corresponding
5064      // parameter of F.
5065      QualType ParamType = Proto->getArgType(ArgIdx);
5066      Candidate.Conversions[ArgIdx]
5067        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5068                                SuppressUserConversions,
5069                                /*InOverloadResolution=*/true,
5070                                /*AllowObjCWritebackConversion=*/
5071                                  getLangOptions().ObjCAutoRefCount);
5072      if (Candidate.Conversions[ArgIdx].isBad()) {
5073        Candidate.Viable = false;
5074        Candidate.FailureKind = ovl_fail_bad_conversion;
5075        break;
5076      }
5077    } else {
5078      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5079      // argument for which there is no corresponding parameter is
5080      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5081      Candidate.Conversions[ArgIdx].setEllipsis();
5082    }
5083  }
5084}
5085
5086/// \brief Add all of the function declarations in the given function set to
5087/// the overload canddiate set.
5088void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5089                                 Expr **Args, unsigned NumArgs,
5090                                 OverloadCandidateSet& CandidateSet,
5091                                 bool SuppressUserConversions) {
5092  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5093    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5094    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5095      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5096        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5097                           cast<CXXMethodDecl>(FD)->getParent(),
5098                           Args[0]->getType(), Args[0]->Classify(Context),
5099                           Args + 1, NumArgs - 1,
5100                           CandidateSet, SuppressUserConversions);
5101      else
5102        AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
5103                             SuppressUserConversions);
5104    } else {
5105      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5106      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5107          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5108        AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5109                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5110                                   /*FIXME: explicit args */ 0,
5111                                   Args[0]->getType(),
5112                                   Args[0]->Classify(Context),
5113                                   Args + 1, NumArgs - 1,
5114                                   CandidateSet,
5115                                   SuppressUserConversions);
5116      else
5117        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5118                                     /*FIXME: explicit args */ 0,
5119                                     Args, NumArgs, CandidateSet,
5120                                     SuppressUserConversions);
5121    }
5122  }
5123}
5124
5125/// AddMethodCandidate - Adds a named decl (which is some kind of
5126/// method) as a method candidate to the given overload set.
5127void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5128                              QualType ObjectType,
5129                              Expr::Classification ObjectClassification,
5130                              Expr **Args, unsigned NumArgs,
5131                              OverloadCandidateSet& CandidateSet,
5132                              bool SuppressUserConversions) {
5133  NamedDecl *Decl = FoundDecl.getDecl();
5134  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5135
5136  if (isa<UsingShadowDecl>(Decl))
5137    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5138
5139  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5140    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5141           "Expected a member function template");
5142    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5143                               /*ExplicitArgs*/ 0,
5144                               ObjectType, ObjectClassification, Args, NumArgs,
5145                               CandidateSet,
5146                               SuppressUserConversions);
5147  } else {
5148    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5149                       ObjectType, ObjectClassification, Args, NumArgs,
5150                       CandidateSet, SuppressUserConversions);
5151  }
5152}
5153
5154/// AddMethodCandidate - Adds the given C++ member function to the set
5155/// of candidate functions, using the given function call arguments
5156/// and the object argument (@c Object). For example, in a call
5157/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5158/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5159/// allow user-defined conversions via constructors or conversion
5160/// operators.
5161void
5162Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5163                         CXXRecordDecl *ActingContext, QualType ObjectType,
5164                         Expr::Classification ObjectClassification,
5165                         Expr **Args, unsigned NumArgs,
5166                         OverloadCandidateSet& CandidateSet,
5167                         bool SuppressUserConversions) {
5168  const FunctionProtoType* Proto
5169    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5170  assert(Proto && "Methods without a prototype cannot be overloaded");
5171  assert(!isa<CXXConstructorDecl>(Method) &&
5172         "Use AddOverloadCandidate for constructors");
5173
5174  if (!CandidateSet.isNewCandidate(Method))
5175    return;
5176
5177  // Overload resolution is always an unevaluated context.
5178  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5179
5180  // Add this candidate
5181  OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
5182  Candidate.FoundDecl = FoundDecl;
5183  Candidate.Function = Method;
5184  Candidate.IsSurrogate = false;
5185  Candidate.IgnoreObjectArgument = false;
5186  Candidate.ExplicitCallArguments = NumArgs;
5187
5188  unsigned NumArgsInProto = Proto->getNumArgs();
5189
5190  // (C++ 13.3.2p2): A candidate function having fewer than m
5191  // parameters is viable only if it has an ellipsis in its parameter
5192  // list (8.3.5).
5193  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5194    Candidate.Viable = false;
5195    Candidate.FailureKind = ovl_fail_too_many_arguments;
5196    return;
5197  }
5198
5199  // (C++ 13.3.2p2): A candidate function having more than m parameters
5200  // is viable only if the (m+1)st parameter has a default argument
5201  // (8.3.6). For the purposes of overload resolution, the
5202  // parameter list is truncated on the right, so that there are
5203  // exactly m parameters.
5204  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5205  if (NumArgs < MinRequiredArgs) {
5206    // Not enough arguments.
5207    Candidate.Viable = false;
5208    Candidate.FailureKind = ovl_fail_too_few_arguments;
5209    return;
5210  }
5211
5212  Candidate.Viable = true;
5213
5214  if (Method->isStatic() || ObjectType.isNull())
5215    // The implicit object argument is ignored.
5216    Candidate.IgnoreObjectArgument = true;
5217  else {
5218    // Determine the implicit conversion sequence for the object
5219    // parameter.
5220    Candidate.Conversions[0]
5221      = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5222                                        Method, ActingContext);
5223    if (Candidate.Conversions[0].isBad()) {
5224      Candidate.Viable = false;
5225      Candidate.FailureKind = ovl_fail_bad_conversion;
5226      return;
5227    }
5228  }
5229
5230  // Determine the implicit conversion sequences for each of the
5231  // arguments.
5232  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5233    if (ArgIdx < NumArgsInProto) {
5234      // (C++ 13.3.2p3): for F to be a viable function, there shall
5235      // exist for each argument an implicit conversion sequence
5236      // (13.3.3.1) that converts that argument to the corresponding
5237      // parameter of F.
5238      QualType ParamType = Proto->getArgType(ArgIdx);
5239      Candidate.Conversions[ArgIdx + 1]
5240        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5241                                SuppressUserConversions,
5242                                /*InOverloadResolution=*/true,
5243                                /*AllowObjCWritebackConversion=*/
5244                                  getLangOptions().ObjCAutoRefCount);
5245      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5246        Candidate.Viable = false;
5247        Candidate.FailureKind = ovl_fail_bad_conversion;
5248        break;
5249      }
5250    } else {
5251      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5252      // argument for which there is no corresponding parameter is
5253      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5254      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5255    }
5256  }
5257}
5258
5259/// \brief Add a C++ member function template as a candidate to the candidate
5260/// set, using template argument deduction to produce an appropriate member
5261/// function template specialization.
5262void
5263Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5264                                 DeclAccessPair FoundDecl,
5265                                 CXXRecordDecl *ActingContext,
5266                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5267                                 QualType ObjectType,
5268                                 Expr::Classification ObjectClassification,
5269                                 Expr **Args, unsigned NumArgs,
5270                                 OverloadCandidateSet& CandidateSet,
5271                                 bool SuppressUserConversions) {
5272  if (!CandidateSet.isNewCandidate(MethodTmpl))
5273    return;
5274
5275  // C++ [over.match.funcs]p7:
5276  //   In each case where a candidate is a function template, candidate
5277  //   function template specializations are generated using template argument
5278  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5279  //   candidate functions in the usual way.113) A given name can refer to one
5280  //   or more function templates and also to a set of overloaded non-template
5281  //   functions. In such a case, the candidate functions generated from each
5282  //   function template are combined with the set of non-template candidate
5283  //   functions.
5284  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5285  FunctionDecl *Specialization = 0;
5286  if (TemplateDeductionResult Result
5287      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
5288                                Args, NumArgs, Specialization, Info)) {
5289    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5290    Candidate.FoundDecl = FoundDecl;
5291    Candidate.Function = MethodTmpl->getTemplatedDecl();
5292    Candidate.Viable = false;
5293    Candidate.FailureKind = ovl_fail_bad_deduction;
5294    Candidate.IsSurrogate = false;
5295    Candidate.IgnoreObjectArgument = false;
5296    Candidate.ExplicitCallArguments = NumArgs;
5297    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5298                                                          Info);
5299    return;
5300  }
5301
5302  // Add the function template specialization produced by template argument
5303  // deduction as a candidate.
5304  assert(Specialization && "Missing member function template specialization?");
5305  assert(isa<CXXMethodDecl>(Specialization) &&
5306         "Specialization is not a member function?");
5307  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5308                     ActingContext, ObjectType, ObjectClassification,
5309                     Args, NumArgs, CandidateSet, SuppressUserConversions);
5310}
5311
5312/// \brief Add a C++ function template specialization as a candidate
5313/// in the candidate set, using template argument deduction to produce
5314/// an appropriate function template specialization.
5315void
5316Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5317                                   DeclAccessPair FoundDecl,
5318                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5319                                   Expr **Args, unsigned NumArgs,
5320                                   OverloadCandidateSet& CandidateSet,
5321                                   bool SuppressUserConversions) {
5322  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5323    return;
5324
5325  // C++ [over.match.funcs]p7:
5326  //   In each case where a candidate is a function template, candidate
5327  //   function template specializations are generated using template argument
5328  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5329  //   candidate functions in the usual way.113) A given name can refer to one
5330  //   or more function templates and also to a set of overloaded non-template
5331  //   functions. In such a case, the candidate functions generated from each
5332  //   function template are combined with the set of non-template candidate
5333  //   functions.
5334  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5335  FunctionDecl *Specialization = 0;
5336  if (TemplateDeductionResult Result
5337        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
5338                                  Args, NumArgs, Specialization, Info)) {
5339    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5340    Candidate.FoundDecl = FoundDecl;
5341    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5342    Candidate.Viable = false;
5343    Candidate.FailureKind = ovl_fail_bad_deduction;
5344    Candidate.IsSurrogate = false;
5345    Candidate.IgnoreObjectArgument = false;
5346    Candidate.ExplicitCallArguments = NumArgs;
5347    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5348                                                          Info);
5349    return;
5350  }
5351
5352  // Add the function template specialization produced by template argument
5353  // deduction as a candidate.
5354  assert(Specialization && "Missing function template specialization?");
5355  AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
5356                       SuppressUserConversions);
5357}
5358
5359/// AddConversionCandidate - Add a C++ conversion function as a
5360/// candidate in the candidate set (C++ [over.match.conv],
5361/// C++ [over.match.copy]). From is the expression we're converting from,
5362/// and ToType is the type that we're eventually trying to convert to
5363/// (which may or may not be the same type as the type that the
5364/// conversion function produces).
5365void
5366Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5367                             DeclAccessPair FoundDecl,
5368                             CXXRecordDecl *ActingContext,
5369                             Expr *From, QualType ToType,
5370                             OverloadCandidateSet& CandidateSet) {
5371  assert(!Conversion->getDescribedFunctionTemplate() &&
5372         "Conversion function templates use AddTemplateConversionCandidate");
5373  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5374  if (!CandidateSet.isNewCandidate(Conversion))
5375    return;
5376
5377  // Overload resolution is always an unevaluated context.
5378  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5379
5380  // Add this candidate
5381  OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5382  Candidate.FoundDecl = FoundDecl;
5383  Candidate.Function = Conversion;
5384  Candidate.IsSurrogate = false;
5385  Candidate.IgnoreObjectArgument = false;
5386  Candidate.FinalConversion.setAsIdentityConversion();
5387  Candidate.FinalConversion.setFromType(ConvType);
5388  Candidate.FinalConversion.setAllToTypes(ToType);
5389  Candidate.Viable = true;
5390  Candidate.ExplicitCallArguments = 1;
5391
5392  // C++ [over.match.funcs]p4:
5393  //   For conversion functions, the function is considered to be a member of
5394  //   the class of the implicit implied object argument for the purpose of
5395  //   defining the type of the implicit object parameter.
5396  //
5397  // Determine the implicit conversion sequence for the implicit
5398  // object parameter.
5399  QualType ImplicitParamType = From->getType();
5400  if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5401    ImplicitParamType = FromPtrType->getPointeeType();
5402  CXXRecordDecl *ConversionContext
5403    = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5404
5405  Candidate.Conversions[0]
5406    = TryObjectArgumentInitialization(*this, From->getType(),
5407                                      From->Classify(Context),
5408                                      Conversion, ConversionContext);
5409
5410  if (Candidate.Conversions[0].isBad()) {
5411    Candidate.Viable = false;
5412    Candidate.FailureKind = ovl_fail_bad_conversion;
5413    return;
5414  }
5415
5416  // We won't go through a user-define type conversion function to convert a
5417  // derived to base as such conversions are given Conversion Rank. They only
5418  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5419  QualType FromCanon
5420    = Context.getCanonicalType(From->getType().getUnqualifiedType());
5421  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5422  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5423    Candidate.Viable = false;
5424    Candidate.FailureKind = ovl_fail_trivial_conversion;
5425    return;
5426  }
5427
5428  // To determine what the conversion from the result of calling the
5429  // conversion function to the type we're eventually trying to
5430  // convert to (ToType), we need to synthesize a call to the
5431  // conversion function and attempt copy initialization from it. This
5432  // makes sure that we get the right semantics with respect to
5433  // lvalues/rvalues and the type. Fortunately, we can allocate this
5434  // call on the stack and we don't need its arguments to be
5435  // well-formed.
5436  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
5437                            VK_LValue, From->getLocStart());
5438  ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5439                                Context.getPointerType(Conversion->getType()),
5440                                CK_FunctionToPointerDecay,
5441                                &ConversionRef, VK_RValue);
5442
5443  QualType ConversionType = Conversion->getConversionType();
5444  if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5445    Candidate.Viable = false;
5446    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5447    return;
5448  }
5449
5450  ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5451
5452  // Note that it is safe to allocate CallExpr on the stack here because
5453  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5454  // allocator).
5455  QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5456  CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
5457                From->getLocStart());
5458  ImplicitConversionSequence ICS =
5459    TryCopyInitialization(*this, &Call, ToType,
5460                          /*SuppressUserConversions=*/true,
5461                          /*InOverloadResolution=*/false,
5462                          /*AllowObjCWritebackConversion=*/false);
5463
5464  switch (ICS.getKind()) {
5465  case ImplicitConversionSequence::StandardConversion:
5466    Candidate.FinalConversion = ICS.Standard;
5467
5468    // C++ [over.ics.user]p3:
5469    //   If the user-defined conversion is specified by a specialization of a
5470    //   conversion function template, the second standard conversion sequence
5471    //   shall have exact match rank.
5472    if (Conversion->getPrimaryTemplate() &&
5473        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5474      Candidate.Viable = false;
5475      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5476    }
5477
5478    // C++0x [dcl.init.ref]p5:
5479    //    In the second case, if the reference is an rvalue reference and
5480    //    the second standard conversion sequence of the user-defined
5481    //    conversion sequence includes an lvalue-to-rvalue conversion, the
5482    //    program is ill-formed.
5483    if (ToType->isRValueReferenceType() &&
5484        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5485      Candidate.Viable = false;
5486      Candidate.FailureKind = ovl_fail_bad_final_conversion;
5487    }
5488    break;
5489
5490  case ImplicitConversionSequence::BadConversion:
5491    Candidate.Viable = false;
5492    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5493    break;
5494
5495  default:
5496    llvm_unreachable(
5497           "Can only end up with a standard conversion sequence or failure");
5498  }
5499}
5500
5501/// \brief Adds a conversion function template specialization
5502/// candidate to the overload set, using template argument deduction
5503/// to deduce the template arguments of the conversion function
5504/// template from the type that we are converting to (C++
5505/// [temp.deduct.conv]).
5506void
5507Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
5508                                     DeclAccessPair FoundDecl,
5509                                     CXXRecordDecl *ActingDC,
5510                                     Expr *From, QualType ToType,
5511                                     OverloadCandidateSet &CandidateSet) {
5512  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5513         "Only conversion function templates permitted here");
5514
5515  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5516    return;
5517
5518  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5519  CXXConversionDecl *Specialization = 0;
5520  if (TemplateDeductionResult Result
5521        = DeduceTemplateArguments(FunctionTemplate, ToType,
5522                                  Specialization, Info)) {
5523    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5524    Candidate.FoundDecl = FoundDecl;
5525    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5526    Candidate.Viable = false;
5527    Candidate.FailureKind = ovl_fail_bad_deduction;
5528    Candidate.IsSurrogate = false;
5529    Candidate.IgnoreObjectArgument = false;
5530    Candidate.ExplicitCallArguments = 1;
5531    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5532                                                          Info);
5533    return;
5534  }
5535
5536  // Add the conversion function template specialization produced by
5537  // template argument deduction as a candidate.
5538  assert(Specialization && "Missing function template specialization?");
5539  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
5540                         CandidateSet);
5541}
5542
5543/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5544/// converts the given @c Object to a function pointer via the
5545/// conversion function @c Conversion, and then attempts to call it
5546/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5547/// the type of function that we'll eventually be calling.
5548void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
5549                                 DeclAccessPair FoundDecl,
5550                                 CXXRecordDecl *ActingContext,
5551                                 const FunctionProtoType *Proto,
5552                                 Expr *Object,
5553                                 Expr **Args, unsigned NumArgs,
5554                                 OverloadCandidateSet& CandidateSet) {
5555  if (!CandidateSet.isNewCandidate(Conversion))
5556    return;
5557
5558  // Overload resolution is always an unevaluated context.
5559  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5560
5561  OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
5562  Candidate.FoundDecl = FoundDecl;
5563  Candidate.Function = 0;
5564  Candidate.Surrogate = Conversion;
5565  Candidate.Viable = true;
5566  Candidate.IsSurrogate = true;
5567  Candidate.IgnoreObjectArgument = false;
5568  Candidate.ExplicitCallArguments = NumArgs;
5569
5570  // Determine the implicit conversion sequence for the implicit
5571  // object parameter.
5572  ImplicitConversionSequence ObjectInit
5573    = TryObjectArgumentInitialization(*this, Object->getType(),
5574                                      Object->Classify(Context),
5575                                      Conversion, ActingContext);
5576  if (ObjectInit.isBad()) {
5577    Candidate.Viable = false;
5578    Candidate.FailureKind = ovl_fail_bad_conversion;
5579    Candidate.Conversions[0] = ObjectInit;
5580    return;
5581  }
5582
5583  // The first conversion is actually a user-defined conversion whose
5584  // first conversion is ObjectInit's standard conversion (which is
5585  // effectively a reference binding). Record it as such.
5586  Candidate.Conversions[0].setUserDefined();
5587  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
5588  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
5589  Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
5590  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
5591  Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
5592  Candidate.Conversions[0].UserDefined.After
5593    = Candidate.Conversions[0].UserDefined.Before;
5594  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5595
5596  // Find the
5597  unsigned NumArgsInProto = Proto->getNumArgs();
5598
5599  // (C++ 13.3.2p2): A candidate function having fewer than m
5600  // parameters is viable only if it has an ellipsis in its parameter
5601  // list (8.3.5).
5602  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5603    Candidate.Viable = false;
5604    Candidate.FailureKind = ovl_fail_too_many_arguments;
5605    return;
5606  }
5607
5608  // Function types don't have any default arguments, so just check if
5609  // we have enough arguments.
5610  if (NumArgs < NumArgsInProto) {
5611    // Not enough arguments.
5612    Candidate.Viable = false;
5613    Candidate.FailureKind = ovl_fail_too_few_arguments;
5614    return;
5615  }
5616
5617  // Determine the implicit conversion sequences for each of the
5618  // arguments.
5619  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5620    if (ArgIdx < NumArgsInProto) {
5621      // (C++ 13.3.2p3): for F to be a viable function, there shall
5622      // exist for each argument an implicit conversion sequence
5623      // (13.3.3.1) that converts that argument to the corresponding
5624      // parameter of F.
5625      QualType ParamType = Proto->getArgType(ArgIdx);
5626      Candidate.Conversions[ArgIdx + 1]
5627        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5628                                /*SuppressUserConversions=*/false,
5629                                /*InOverloadResolution=*/false,
5630                                /*AllowObjCWritebackConversion=*/
5631                                  getLangOptions().ObjCAutoRefCount);
5632      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5633        Candidate.Viable = false;
5634        Candidate.FailureKind = ovl_fail_bad_conversion;
5635        break;
5636      }
5637    } else {
5638      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5639      // argument for which there is no corresponding parameter is
5640      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5641      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5642    }
5643  }
5644}
5645
5646/// \brief Add overload candidates for overloaded operators that are
5647/// member functions.
5648///
5649/// Add the overloaded operator candidates that are member functions
5650/// for the operator Op that was used in an operator expression such
5651/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5652/// CandidateSet will store the added overload candidates. (C++
5653/// [over.match.oper]).
5654void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5655                                       SourceLocation OpLoc,
5656                                       Expr **Args, unsigned NumArgs,
5657                                       OverloadCandidateSet& CandidateSet,
5658                                       SourceRange OpRange) {
5659  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5660
5661  // C++ [over.match.oper]p3:
5662  //   For a unary operator @ with an operand of a type whose
5663  //   cv-unqualified version is T1, and for a binary operator @ with
5664  //   a left operand of a type whose cv-unqualified version is T1 and
5665  //   a right operand of a type whose cv-unqualified version is T2,
5666  //   three sets of candidate functions, designated member
5667  //   candidates, non-member candidates and built-in candidates, are
5668  //   constructed as follows:
5669  QualType T1 = Args[0]->getType();
5670
5671  //     -- If T1 is a class type, the set of member candidates is the
5672  //        result of the qualified lookup of T1::operator@
5673  //        (13.3.1.1.1); otherwise, the set of member candidates is
5674  //        empty.
5675  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
5676    // Complete the type if it can be completed. Otherwise, we're done.
5677    if (RequireCompleteType(OpLoc, T1, PDiag()))
5678      return;
5679
5680    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5681    LookupQualifiedName(Operators, T1Rec->getDecl());
5682    Operators.suppressDiagnostics();
5683
5684    for (LookupResult::iterator Oper = Operators.begin(),
5685                             OperEnd = Operators.end();
5686         Oper != OperEnd;
5687         ++Oper)
5688      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
5689                         Args[0]->Classify(Context), Args + 1, NumArgs - 1,
5690                         CandidateSet,
5691                         /* SuppressUserConversions = */ false);
5692  }
5693}
5694
5695/// AddBuiltinCandidate - Add a candidate for a built-in
5696/// operator. ResultTy and ParamTys are the result and parameter types
5697/// of the built-in candidate, respectively. Args and NumArgs are the
5698/// arguments being passed to the candidate. IsAssignmentOperator
5699/// should be true when this built-in candidate is an assignment
5700/// operator. NumContextualBoolArguments is the number of arguments
5701/// (at the beginning of the argument list) that will be contextually
5702/// converted to bool.
5703void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
5704                               Expr **Args, unsigned NumArgs,
5705                               OverloadCandidateSet& CandidateSet,
5706                               bool IsAssignmentOperator,
5707                               unsigned NumContextualBoolArguments) {
5708  // Overload resolution is always an unevaluated context.
5709  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5710
5711  // Add this candidate
5712  OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
5713  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
5714  Candidate.Function = 0;
5715  Candidate.IsSurrogate = false;
5716  Candidate.IgnoreObjectArgument = false;
5717  Candidate.BuiltinTypes.ResultTy = ResultTy;
5718  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5719    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5720
5721  // Determine the implicit conversion sequences for each of the
5722  // arguments.
5723  Candidate.Viable = true;
5724  Candidate.ExplicitCallArguments = NumArgs;
5725  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5726    // C++ [over.match.oper]p4:
5727    //   For the built-in assignment operators, conversions of the
5728    //   left operand are restricted as follows:
5729    //     -- no temporaries are introduced to hold the left operand, and
5730    //     -- no user-defined conversions are applied to the left
5731    //        operand to achieve a type match with the left-most
5732    //        parameter of a built-in candidate.
5733    //
5734    // We block these conversions by turning off user-defined
5735    // conversions, since that is the only way that initialization of
5736    // a reference to a non-class type can occur from something that
5737    // is not of the same type.
5738    if (ArgIdx < NumContextualBoolArguments) {
5739      assert(ParamTys[ArgIdx] == Context.BoolTy &&
5740             "Contextual conversion to bool requires bool type");
5741      Candidate.Conversions[ArgIdx]
5742        = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
5743    } else {
5744      Candidate.Conversions[ArgIdx]
5745        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
5746                                ArgIdx == 0 && IsAssignmentOperator,
5747                                /*InOverloadResolution=*/false,
5748                                /*AllowObjCWritebackConversion=*/
5749                                  getLangOptions().ObjCAutoRefCount);
5750    }
5751    if (Candidate.Conversions[ArgIdx].isBad()) {
5752      Candidate.Viable = false;
5753      Candidate.FailureKind = ovl_fail_bad_conversion;
5754      break;
5755    }
5756  }
5757}
5758
5759/// BuiltinCandidateTypeSet - A set of types that will be used for the
5760/// candidate operator functions for built-in operators (C++
5761/// [over.built]). The types are separated into pointer types and
5762/// enumeration types.
5763class BuiltinCandidateTypeSet  {
5764  /// TypeSet - A set of types.
5765  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
5766
5767  /// PointerTypes - The set of pointer types that will be used in the
5768  /// built-in candidates.
5769  TypeSet PointerTypes;
5770
5771  /// MemberPointerTypes - The set of member pointer types that will be
5772  /// used in the built-in candidates.
5773  TypeSet MemberPointerTypes;
5774
5775  /// EnumerationTypes - The set of enumeration types that will be
5776  /// used in the built-in candidates.
5777  TypeSet EnumerationTypes;
5778
5779  /// \brief The set of vector types that will be used in the built-in
5780  /// candidates.
5781  TypeSet VectorTypes;
5782
5783  /// \brief A flag indicating non-record types are viable candidates
5784  bool HasNonRecordTypes;
5785
5786  /// \brief A flag indicating whether either arithmetic or enumeration types
5787  /// were present in the candidate set.
5788  bool HasArithmeticOrEnumeralTypes;
5789
5790  /// \brief A flag indicating whether the nullptr type was present in the
5791  /// candidate set.
5792  bool HasNullPtrType;
5793
5794  /// Sema - The semantic analysis instance where we are building the
5795  /// candidate type set.
5796  Sema &SemaRef;
5797
5798  /// Context - The AST context in which we will build the type sets.
5799  ASTContext &Context;
5800
5801  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5802                                               const Qualifiers &VisibleQuals);
5803  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
5804
5805public:
5806  /// iterator - Iterates through the types that are part of the set.
5807  typedef TypeSet::iterator iterator;
5808
5809  BuiltinCandidateTypeSet(Sema &SemaRef)
5810    : HasNonRecordTypes(false),
5811      HasArithmeticOrEnumeralTypes(false),
5812      HasNullPtrType(false),
5813      SemaRef(SemaRef),
5814      Context(SemaRef.Context) { }
5815
5816  void AddTypesConvertedFrom(QualType Ty,
5817                             SourceLocation Loc,
5818                             bool AllowUserConversions,
5819                             bool AllowExplicitConversions,
5820                             const Qualifiers &VisibleTypeConversionsQuals);
5821
5822  /// pointer_begin - First pointer type found;
5823  iterator pointer_begin() { return PointerTypes.begin(); }
5824
5825  /// pointer_end - Past the last pointer type found;
5826  iterator pointer_end() { return PointerTypes.end(); }
5827
5828  /// member_pointer_begin - First member pointer type found;
5829  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5830
5831  /// member_pointer_end - Past the last member pointer type found;
5832  iterator member_pointer_end() { return MemberPointerTypes.end(); }
5833
5834  /// enumeration_begin - First enumeration type found;
5835  iterator enumeration_begin() { return EnumerationTypes.begin(); }
5836
5837  /// enumeration_end - Past the last enumeration type found;
5838  iterator enumeration_end() { return EnumerationTypes.end(); }
5839
5840  iterator vector_begin() { return VectorTypes.begin(); }
5841  iterator vector_end() { return VectorTypes.end(); }
5842
5843  bool hasNonRecordTypes() { return HasNonRecordTypes; }
5844  bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
5845  bool hasNullPtrType() const { return HasNullPtrType; }
5846};
5847
5848/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
5849/// the set of pointer types along with any more-qualified variants of
5850/// that type. For example, if @p Ty is "int const *", this routine
5851/// will add "int const *", "int const volatile *", "int const
5852/// restrict *", and "int const volatile restrict *" to the set of
5853/// pointer types. Returns true if the add of @p Ty itself succeeded,
5854/// false otherwise.
5855///
5856/// FIXME: what to do about extended qualifiers?
5857bool
5858BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5859                                             const Qualifiers &VisibleQuals) {
5860
5861  // Insert this type.
5862  if (!PointerTypes.insert(Ty))
5863    return false;
5864
5865  QualType PointeeTy;
5866  const PointerType *PointerTy = Ty->getAs<PointerType>();
5867  bool buildObjCPtr = false;
5868  if (!PointerTy) {
5869    if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
5870      PointeeTy = PTy->getPointeeType();
5871      buildObjCPtr = true;
5872    }
5873    else
5874      llvm_unreachable("type was not a pointer type!");
5875  }
5876  else
5877    PointeeTy = PointerTy->getPointeeType();
5878
5879  // Don't add qualified variants of arrays. For one, they're not allowed
5880  // (the qualifier would sink to the element type), and for another, the
5881  // only overload situation where it matters is subscript or pointer +- int,
5882  // and those shouldn't have qualifier variants anyway.
5883  if (PointeeTy->isArrayType())
5884    return true;
5885  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5886  if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
5887    BaseCVR = Array->getElementType().getCVRQualifiers();
5888  bool hasVolatile = VisibleQuals.hasVolatile();
5889  bool hasRestrict = VisibleQuals.hasRestrict();
5890
5891  // Iterate through all strict supersets of BaseCVR.
5892  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5893    if ((CVR | BaseCVR) != CVR) continue;
5894    // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5895    // in the types.
5896    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5897    if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
5898    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
5899    if (!buildObjCPtr)
5900      PointerTypes.insert(Context.getPointerType(QPointeeTy));
5901    else
5902      PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
5903  }
5904
5905  return true;
5906}
5907
5908/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5909/// to the set of pointer types along with any more-qualified variants of
5910/// that type. For example, if @p Ty is "int const *", this routine
5911/// will add "int const *", "int const volatile *", "int const
5912/// restrict *", and "int const volatile restrict *" to the set of
5913/// pointer types. Returns true if the add of @p Ty itself succeeded,
5914/// false otherwise.
5915///
5916/// FIXME: what to do about extended qualifiers?
5917bool
5918BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5919    QualType Ty) {
5920  // Insert this type.
5921  if (!MemberPointerTypes.insert(Ty))
5922    return false;
5923
5924  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5925  assert(PointerTy && "type was not a member pointer type!");
5926
5927  QualType PointeeTy = PointerTy->getPointeeType();
5928  // Don't add qualified variants of arrays. For one, they're not allowed
5929  // (the qualifier would sink to the element type), and for another, the
5930  // only overload situation where it matters is subscript or pointer +- int,
5931  // and those shouldn't have qualifier variants anyway.
5932  if (PointeeTy->isArrayType())
5933    return true;
5934  const Type *ClassTy = PointerTy->getClass();
5935
5936  // Iterate through all strict supersets of the pointee type's CVR
5937  // qualifiers.
5938  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5939  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5940    if ((CVR | BaseCVR) != CVR) continue;
5941
5942    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
5943    MemberPointerTypes.insert(
5944      Context.getMemberPointerType(QPointeeTy, ClassTy));
5945  }
5946
5947  return true;
5948}
5949
5950/// AddTypesConvertedFrom - Add each of the types to which the type @p
5951/// Ty can be implicit converted to the given set of @p Types. We're
5952/// primarily interested in pointer types and enumeration types. We also
5953/// take member pointer types, for the conditional operator.
5954/// AllowUserConversions is true if we should look at the conversion
5955/// functions of a class type, and AllowExplicitConversions if we
5956/// should also include the explicit conversion functions of a class
5957/// type.
5958void
5959BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
5960                                               SourceLocation Loc,
5961                                               bool AllowUserConversions,
5962                                               bool AllowExplicitConversions,
5963                                               const Qualifiers &VisibleQuals) {
5964  // Only deal with canonical types.
5965  Ty = Context.getCanonicalType(Ty);
5966
5967  // Look through reference types; they aren't part of the type of an
5968  // expression for the purposes of conversions.
5969  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
5970    Ty = RefTy->getPointeeType();
5971
5972  // If we're dealing with an array type, decay to the pointer.
5973  if (Ty->isArrayType())
5974    Ty = SemaRef.Context.getArrayDecayedType(Ty);
5975
5976  // Otherwise, we don't care about qualifiers on the type.
5977  Ty = Ty.getLocalUnqualifiedType();
5978
5979  // Flag if we ever add a non-record type.
5980  const RecordType *TyRec = Ty->getAs<RecordType>();
5981  HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5982
5983  // Flag if we encounter an arithmetic type.
5984  HasArithmeticOrEnumeralTypes =
5985    HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5986
5987  if (Ty->isObjCIdType() || Ty->isObjCClassType())
5988    PointerTypes.insert(Ty);
5989  else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
5990    // Insert our type, and its more-qualified variants, into the set
5991    // of types.
5992    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
5993      return;
5994  } else if (Ty->isMemberPointerType()) {
5995    // Member pointers are far easier, since the pointee can't be converted.
5996    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5997      return;
5998  } else if (Ty->isEnumeralType()) {
5999    HasArithmeticOrEnumeralTypes = true;
6000    EnumerationTypes.insert(Ty);
6001  } else if (Ty->isVectorType()) {
6002    // We treat vector types as arithmetic types in many contexts as an
6003    // extension.
6004    HasArithmeticOrEnumeralTypes = true;
6005    VectorTypes.insert(Ty);
6006  } else if (Ty->isNullPtrType()) {
6007    HasNullPtrType = true;
6008  } else if (AllowUserConversions && TyRec) {
6009    // No conversion functions in incomplete types.
6010    if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6011      return;
6012
6013    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6014    const UnresolvedSetImpl *Conversions
6015      = ClassDecl->getVisibleConversionFunctions();
6016    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6017           E = Conversions->end(); I != E; ++I) {
6018      NamedDecl *D = I.getDecl();
6019      if (isa<UsingShadowDecl>(D))
6020        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6021
6022      // Skip conversion function templates; they don't tell us anything
6023      // about which builtin types we can convert to.
6024      if (isa<FunctionTemplateDecl>(D))
6025        continue;
6026
6027      CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6028      if (AllowExplicitConversions || !Conv->isExplicit()) {
6029        AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6030                              VisibleQuals);
6031      }
6032    }
6033  }
6034}
6035
6036/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6037/// the volatile- and non-volatile-qualified assignment operators for the
6038/// given type to the candidate set.
6039static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6040                                                   QualType T,
6041                                                   Expr **Args,
6042                                                   unsigned NumArgs,
6043                                    OverloadCandidateSet &CandidateSet) {
6044  QualType ParamTypes[2];
6045
6046  // T& operator=(T&, T)
6047  ParamTypes[0] = S.Context.getLValueReferenceType(T);
6048  ParamTypes[1] = T;
6049  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6050                        /*IsAssignmentOperator=*/true);
6051
6052  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6053    // volatile T& operator=(volatile T&, T)
6054    ParamTypes[0]
6055      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6056    ParamTypes[1] = T;
6057    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6058                          /*IsAssignmentOperator=*/true);
6059  }
6060}
6061
6062/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6063/// if any, found in visible type conversion functions found in ArgExpr's type.
6064static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6065    Qualifiers VRQuals;
6066    const RecordType *TyRec;
6067    if (const MemberPointerType *RHSMPType =
6068        ArgExpr->getType()->getAs<MemberPointerType>())
6069      TyRec = RHSMPType->getClass()->getAs<RecordType>();
6070    else
6071      TyRec = ArgExpr->getType()->getAs<RecordType>();
6072    if (!TyRec) {
6073      // Just to be safe, assume the worst case.
6074      VRQuals.addVolatile();
6075      VRQuals.addRestrict();
6076      return VRQuals;
6077    }
6078
6079    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6080    if (!ClassDecl->hasDefinition())
6081      return VRQuals;
6082
6083    const UnresolvedSetImpl *Conversions =
6084      ClassDecl->getVisibleConversionFunctions();
6085
6086    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6087           E = Conversions->end(); I != E; ++I) {
6088      NamedDecl *D = I.getDecl();
6089      if (isa<UsingShadowDecl>(D))
6090        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6091      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6092        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6093        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6094          CanTy = ResTypeRef->getPointeeType();
6095        // Need to go down the pointer/mempointer chain and add qualifiers
6096        // as see them.
6097        bool done = false;
6098        while (!done) {
6099          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6100            CanTy = ResTypePtr->getPointeeType();
6101          else if (const MemberPointerType *ResTypeMPtr =
6102                CanTy->getAs<MemberPointerType>())
6103            CanTy = ResTypeMPtr->getPointeeType();
6104          else
6105            done = true;
6106          if (CanTy.isVolatileQualified())
6107            VRQuals.addVolatile();
6108          if (CanTy.isRestrictQualified())
6109            VRQuals.addRestrict();
6110          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6111            return VRQuals;
6112        }
6113      }
6114    }
6115    return VRQuals;
6116}
6117
6118namespace {
6119
6120/// \brief Helper class to manage the addition of builtin operator overload
6121/// candidates. It provides shared state and utility methods used throughout
6122/// the process, as well as a helper method to add each group of builtin
6123/// operator overloads from the standard to a candidate set.
6124class BuiltinOperatorOverloadBuilder {
6125  // Common instance state available to all overload candidate addition methods.
6126  Sema &S;
6127  Expr **Args;
6128  unsigned NumArgs;
6129  Qualifiers VisibleTypeConversionsQuals;
6130  bool HasArithmeticOrEnumeralCandidateType;
6131  SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6132  OverloadCandidateSet &CandidateSet;
6133
6134  // Define some constants used to index and iterate over the arithemetic types
6135  // provided via the getArithmeticType() method below.
6136  // The "promoted arithmetic types" are the arithmetic
6137  // types are that preserved by promotion (C++ [over.built]p2).
6138  static const unsigned FirstIntegralType = 3;
6139  static const unsigned LastIntegralType = 18;
6140  static const unsigned FirstPromotedIntegralType = 3,
6141                        LastPromotedIntegralType = 9;
6142  static const unsigned FirstPromotedArithmeticType = 0,
6143                        LastPromotedArithmeticType = 9;
6144  static const unsigned NumArithmeticTypes = 18;
6145
6146  /// \brief Get the canonical type for a given arithmetic type index.
6147  CanQualType getArithmeticType(unsigned index) {
6148    assert(index < NumArithmeticTypes);
6149    static CanQualType ASTContext::* const
6150      ArithmeticTypes[NumArithmeticTypes] = {
6151      // Start of promoted types.
6152      &ASTContext::FloatTy,
6153      &ASTContext::DoubleTy,
6154      &ASTContext::LongDoubleTy,
6155
6156      // Start of integral types.
6157      &ASTContext::IntTy,
6158      &ASTContext::LongTy,
6159      &ASTContext::LongLongTy,
6160      &ASTContext::UnsignedIntTy,
6161      &ASTContext::UnsignedLongTy,
6162      &ASTContext::UnsignedLongLongTy,
6163      // End of promoted types.
6164
6165      &ASTContext::BoolTy,
6166      &ASTContext::CharTy,
6167      &ASTContext::WCharTy,
6168      &ASTContext::Char16Ty,
6169      &ASTContext::Char32Ty,
6170      &ASTContext::SignedCharTy,
6171      &ASTContext::ShortTy,
6172      &ASTContext::UnsignedCharTy,
6173      &ASTContext::UnsignedShortTy,
6174      // End of integral types.
6175      // FIXME: What about complex?
6176    };
6177    return S.Context.*ArithmeticTypes[index];
6178  }
6179
6180  /// \brief Gets the canonical type resulting from the usual arithemetic
6181  /// converions for the given arithmetic types.
6182  CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6183    // Accelerator table for performing the usual arithmetic conversions.
6184    // The rules are basically:
6185    //   - if either is floating-point, use the wider floating-point
6186    //   - if same signedness, use the higher rank
6187    //   - if same size, use unsigned of the higher rank
6188    //   - use the larger type
6189    // These rules, together with the axiom that higher ranks are
6190    // never smaller, are sufficient to precompute all of these results
6191    // *except* when dealing with signed types of higher rank.
6192    // (we could precompute SLL x UI for all known platforms, but it's
6193    // better not to make any assumptions).
6194    enum PromotedType {
6195                  Flt,  Dbl, LDbl,   SI,   SL,  SLL,   UI,   UL,  ULL, Dep=-1
6196    };
6197    static PromotedType ConversionsTable[LastPromotedArithmeticType]
6198                                        [LastPromotedArithmeticType] = {
6199      /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6200      /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6201      /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6202      /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL,   UI,   UL,  ULL },
6203      /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL,  Dep,   UL,  ULL },
6204      /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL,  Dep,  Dep,  ULL },
6205      /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep,   UI,   UL,  ULL },
6206      /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep,   UL,   UL,  ULL },
6207      /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL,  ULL,  ULL,  ULL },
6208    };
6209
6210    assert(L < LastPromotedArithmeticType);
6211    assert(R < LastPromotedArithmeticType);
6212    int Idx = ConversionsTable[L][R];
6213
6214    // Fast path: the table gives us a concrete answer.
6215    if (Idx != Dep) return getArithmeticType(Idx);
6216
6217    // Slow path: we need to compare widths.
6218    // An invariant is that the signed type has higher rank.
6219    CanQualType LT = getArithmeticType(L),
6220                RT = getArithmeticType(R);
6221    unsigned LW = S.Context.getIntWidth(LT),
6222             RW = S.Context.getIntWidth(RT);
6223
6224    // If they're different widths, use the signed type.
6225    if (LW > RW) return LT;
6226    else if (LW < RW) return RT;
6227
6228    // Otherwise, use the unsigned type of the signed type's rank.
6229    if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6230    assert(L == SLL || R == SLL);
6231    return S.Context.UnsignedLongLongTy;
6232  }
6233
6234  /// \brief Helper method to factor out the common pattern of adding overloads
6235  /// for '++' and '--' builtin operators.
6236  void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6237                                           bool HasVolatile) {
6238    QualType ParamTypes[2] = {
6239      S.Context.getLValueReferenceType(CandidateTy),
6240      S.Context.IntTy
6241    };
6242
6243    // Non-volatile version.
6244    if (NumArgs == 1)
6245      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6246    else
6247      S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6248
6249    // Use a heuristic to reduce number of builtin candidates in the set:
6250    // add volatile version only if there are conversions to a volatile type.
6251    if (HasVolatile) {
6252      ParamTypes[0] =
6253        S.Context.getLValueReferenceType(
6254          S.Context.getVolatileType(CandidateTy));
6255      if (NumArgs == 1)
6256        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6257      else
6258        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6259    }
6260  }
6261
6262public:
6263  BuiltinOperatorOverloadBuilder(
6264    Sema &S, Expr **Args, unsigned NumArgs,
6265    Qualifiers VisibleTypeConversionsQuals,
6266    bool HasArithmeticOrEnumeralCandidateType,
6267    SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6268    OverloadCandidateSet &CandidateSet)
6269    : S(S), Args(Args), NumArgs(NumArgs),
6270      VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6271      HasArithmeticOrEnumeralCandidateType(
6272        HasArithmeticOrEnumeralCandidateType),
6273      CandidateTypes(CandidateTypes),
6274      CandidateSet(CandidateSet) {
6275    // Validate some of our static helper constants in debug builds.
6276    assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6277           "Invalid first promoted integral type");
6278    assert(getArithmeticType(LastPromotedIntegralType - 1)
6279             == S.Context.UnsignedLongLongTy &&
6280           "Invalid last promoted integral type");
6281    assert(getArithmeticType(FirstPromotedArithmeticType)
6282             == S.Context.FloatTy &&
6283           "Invalid first promoted arithmetic type");
6284    assert(getArithmeticType(LastPromotedArithmeticType - 1)
6285             == S.Context.UnsignedLongLongTy &&
6286           "Invalid last promoted arithmetic type");
6287  }
6288
6289  // C++ [over.built]p3:
6290  //
6291  //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6292  //   is either volatile or empty, there exist candidate operator
6293  //   functions of the form
6294  //
6295  //       VQ T&      operator++(VQ T&);
6296  //       T          operator++(VQ T&, int);
6297  //
6298  // C++ [over.built]p4:
6299  //
6300  //   For every pair (T, VQ), where T is an arithmetic type other
6301  //   than bool, and VQ is either volatile or empty, there exist
6302  //   candidate operator functions of the form
6303  //
6304  //       VQ T&      operator--(VQ T&);
6305  //       T          operator--(VQ T&, int);
6306  void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6307    if (!HasArithmeticOrEnumeralCandidateType)
6308      return;
6309
6310    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6311         Arith < NumArithmeticTypes; ++Arith) {
6312      addPlusPlusMinusMinusStyleOverloads(
6313        getArithmeticType(Arith),
6314        VisibleTypeConversionsQuals.hasVolatile());
6315    }
6316  }
6317
6318  // C++ [over.built]p5:
6319  //
6320  //   For every pair (T, VQ), where T is a cv-qualified or
6321  //   cv-unqualified object type, and VQ is either volatile or
6322  //   empty, there exist candidate operator functions of the form
6323  //
6324  //       T*VQ&      operator++(T*VQ&);
6325  //       T*VQ&      operator--(T*VQ&);
6326  //       T*         operator++(T*VQ&, int);
6327  //       T*         operator--(T*VQ&, int);
6328  void addPlusPlusMinusMinusPointerOverloads() {
6329    for (BuiltinCandidateTypeSet::iterator
6330              Ptr = CandidateTypes[0].pointer_begin(),
6331           PtrEnd = CandidateTypes[0].pointer_end();
6332         Ptr != PtrEnd; ++Ptr) {
6333      // Skip pointer types that aren't pointers to object types.
6334      if (!(*Ptr)->getPointeeType()->isObjectType())
6335        continue;
6336
6337      addPlusPlusMinusMinusStyleOverloads(*Ptr,
6338        (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6339         VisibleTypeConversionsQuals.hasVolatile()));
6340    }
6341  }
6342
6343  // C++ [over.built]p6:
6344  //   For every cv-qualified or cv-unqualified object type T, there
6345  //   exist candidate operator functions of the form
6346  //
6347  //       T&         operator*(T*);
6348  //
6349  // C++ [over.built]p7:
6350  //   For every function type T that does not have cv-qualifiers or a
6351  //   ref-qualifier, there exist candidate operator functions of the form
6352  //       T&         operator*(T*);
6353  void addUnaryStarPointerOverloads() {
6354    for (BuiltinCandidateTypeSet::iterator
6355              Ptr = CandidateTypes[0].pointer_begin(),
6356           PtrEnd = CandidateTypes[0].pointer_end();
6357         Ptr != PtrEnd; ++Ptr) {
6358      QualType ParamTy = *Ptr;
6359      QualType PointeeTy = ParamTy->getPointeeType();
6360      if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6361        continue;
6362
6363      if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6364        if (Proto->getTypeQuals() || Proto->getRefQualifier())
6365          continue;
6366
6367      S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6368                            &ParamTy, Args, 1, CandidateSet);
6369    }
6370  }
6371
6372  // C++ [over.built]p9:
6373  //  For every promoted arithmetic type T, there exist candidate
6374  //  operator functions of the form
6375  //
6376  //       T         operator+(T);
6377  //       T         operator-(T);
6378  void addUnaryPlusOrMinusArithmeticOverloads() {
6379    if (!HasArithmeticOrEnumeralCandidateType)
6380      return;
6381
6382    for (unsigned Arith = FirstPromotedArithmeticType;
6383         Arith < LastPromotedArithmeticType; ++Arith) {
6384      QualType ArithTy = getArithmeticType(Arith);
6385      S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6386    }
6387
6388    // Extension: We also add these operators for vector types.
6389    for (BuiltinCandidateTypeSet::iterator
6390              Vec = CandidateTypes[0].vector_begin(),
6391           VecEnd = CandidateTypes[0].vector_end();
6392         Vec != VecEnd; ++Vec) {
6393      QualType VecTy = *Vec;
6394      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6395    }
6396  }
6397
6398  // C++ [over.built]p8:
6399  //   For every type T, there exist candidate operator functions of
6400  //   the form
6401  //
6402  //       T*         operator+(T*);
6403  void addUnaryPlusPointerOverloads() {
6404    for (BuiltinCandidateTypeSet::iterator
6405              Ptr = CandidateTypes[0].pointer_begin(),
6406           PtrEnd = CandidateTypes[0].pointer_end();
6407         Ptr != PtrEnd; ++Ptr) {
6408      QualType ParamTy = *Ptr;
6409      S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6410    }
6411  }
6412
6413  // C++ [over.built]p10:
6414  //   For every promoted integral type T, there exist candidate
6415  //   operator functions of the form
6416  //
6417  //        T         operator~(T);
6418  void addUnaryTildePromotedIntegralOverloads() {
6419    if (!HasArithmeticOrEnumeralCandidateType)
6420      return;
6421
6422    for (unsigned Int = FirstPromotedIntegralType;
6423         Int < LastPromotedIntegralType; ++Int) {
6424      QualType IntTy = getArithmeticType(Int);
6425      S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6426    }
6427
6428    // Extension: We also add this operator for vector types.
6429    for (BuiltinCandidateTypeSet::iterator
6430              Vec = CandidateTypes[0].vector_begin(),
6431           VecEnd = CandidateTypes[0].vector_end();
6432         Vec != VecEnd; ++Vec) {
6433      QualType VecTy = *Vec;
6434      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6435    }
6436  }
6437
6438  // C++ [over.match.oper]p16:
6439  //   For every pointer to member type T, there exist candidate operator
6440  //   functions of the form
6441  //
6442  //        bool operator==(T,T);
6443  //        bool operator!=(T,T);
6444  void addEqualEqualOrNotEqualMemberPointerOverloads() {
6445    /// Set of (canonical) types that we've already handled.
6446    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6447
6448    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6449      for (BuiltinCandidateTypeSet::iterator
6450                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6451             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6452           MemPtr != MemPtrEnd;
6453           ++MemPtr) {
6454        // Don't add the same builtin candidate twice.
6455        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6456          continue;
6457
6458        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6459        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6460                              CandidateSet);
6461      }
6462    }
6463  }
6464
6465  // C++ [over.built]p15:
6466  //
6467  //   For every T, where T is an enumeration type, a pointer type, or
6468  //   std::nullptr_t, there exist candidate operator functions of the form
6469  //
6470  //        bool       operator<(T, T);
6471  //        bool       operator>(T, T);
6472  //        bool       operator<=(T, T);
6473  //        bool       operator>=(T, T);
6474  //        bool       operator==(T, T);
6475  //        bool       operator!=(T, T);
6476  void addRelationalPointerOrEnumeralOverloads() {
6477    // C++ [over.built]p1:
6478    //   If there is a user-written candidate with the same name and parameter
6479    //   types as a built-in candidate operator function, the built-in operator
6480    //   function is hidden and is not included in the set of candidate
6481    //   functions.
6482    //
6483    // The text is actually in a note, but if we don't implement it then we end
6484    // up with ambiguities when the user provides an overloaded operator for
6485    // an enumeration type. Note that only enumeration types have this problem,
6486    // so we track which enumeration types we've seen operators for. Also, the
6487    // only other overloaded operator with enumeration argumenst, operator=,
6488    // cannot be overloaded for enumeration types, so this is the only place
6489    // where we must suppress candidates like this.
6490    llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6491      UserDefinedBinaryOperators;
6492
6493    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6494      if (CandidateTypes[ArgIdx].enumeration_begin() !=
6495          CandidateTypes[ArgIdx].enumeration_end()) {
6496        for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6497                                         CEnd = CandidateSet.end();
6498             C != CEnd; ++C) {
6499          if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6500            continue;
6501
6502          QualType FirstParamType =
6503            C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6504          QualType SecondParamType =
6505            C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6506
6507          // Skip if either parameter isn't of enumeral type.
6508          if (!FirstParamType->isEnumeralType() ||
6509              !SecondParamType->isEnumeralType())
6510            continue;
6511
6512          // Add this operator to the set of known user-defined operators.
6513          UserDefinedBinaryOperators.insert(
6514            std::make_pair(S.Context.getCanonicalType(FirstParamType),
6515                           S.Context.getCanonicalType(SecondParamType)));
6516        }
6517      }
6518    }
6519
6520    /// Set of (canonical) types that we've already handled.
6521    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6522
6523    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6524      for (BuiltinCandidateTypeSet::iterator
6525                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6526             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6527           Ptr != PtrEnd; ++Ptr) {
6528        // Don't add the same builtin candidate twice.
6529        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6530          continue;
6531
6532        QualType ParamTypes[2] = { *Ptr, *Ptr };
6533        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6534                              CandidateSet);
6535      }
6536      for (BuiltinCandidateTypeSet::iterator
6537                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6538             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6539           Enum != EnumEnd; ++Enum) {
6540        CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6541
6542        // Don't add the same builtin candidate twice, or if a user defined
6543        // candidate exists.
6544        if (!AddedTypes.insert(CanonType) ||
6545            UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6546                                                            CanonType)))
6547          continue;
6548
6549        QualType ParamTypes[2] = { *Enum, *Enum };
6550        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6551                              CandidateSet);
6552      }
6553
6554      if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6555        CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6556        if (AddedTypes.insert(NullPtrTy) &&
6557            !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6558                                                             NullPtrTy))) {
6559          QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6560          S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6561                                CandidateSet);
6562        }
6563      }
6564    }
6565  }
6566
6567  // C++ [over.built]p13:
6568  //
6569  //   For every cv-qualified or cv-unqualified object type T
6570  //   there exist candidate operator functions of the form
6571  //
6572  //      T*         operator+(T*, ptrdiff_t);
6573  //      T&         operator[](T*, ptrdiff_t);    [BELOW]
6574  //      T*         operator-(T*, ptrdiff_t);
6575  //      T*         operator+(ptrdiff_t, T*);
6576  //      T&         operator[](ptrdiff_t, T*);    [BELOW]
6577  //
6578  // C++ [over.built]p14:
6579  //
6580  //   For every T, where T is a pointer to object type, there
6581  //   exist candidate operator functions of the form
6582  //
6583  //      ptrdiff_t  operator-(T, T);
6584  void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6585    /// Set of (canonical) types that we've already handled.
6586    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6587
6588    for (int Arg = 0; Arg < 2; ++Arg) {
6589      QualType AsymetricParamTypes[2] = {
6590        S.Context.getPointerDiffType(),
6591        S.Context.getPointerDiffType(),
6592      };
6593      for (BuiltinCandidateTypeSet::iterator
6594                Ptr = CandidateTypes[Arg].pointer_begin(),
6595             PtrEnd = CandidateTypes[Arg].pointer_end();
6596           Ptr != PtrEnd; ++Ptr) {
6597        QualType PointeeTy = (*Ptr)->getPointeeType();
6598        if (!PointeeTy->isObjectType())
6599          continue;
6600
6601        AsymetricParamTypes[Arg] = *Ptr;
6602        if (Arg == 0 || Op == OO_Plus) {
6603          // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6604          // T* operator+(ptrdiff_t, T*);
6605          S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6606                                CandidateSet);
6607        }
6608        if (Op == OO_Minus) {
6609          // ptrdiff_t operator-(T, T);
6610          if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6611            continue;
6612
6613          QualType ParamTypes[2] = { *Ptr, *Ptr };
6614          S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6615                                Args, 2, CandidateSet);
6616        }
6617      }
6618    }
6619  }
6620
6621  // C++ [over.built]p12:
6622  //
6623  //   For every pair of promoted arithmetic types L and R, there
6624  //   exist candidate operator functions of the form
6625  //
6626  //        LR         operator*(L, R);
6627  //        LR         operator/(L, R);
6628  //        LR         operator+(L, R);
6629  //        LR         operator-(L, R);
6630  //        bool       operator<(L, R);
6631  //        bool       operator>(L, R);
6632  //        bool       operator<=(L, R);
6633  //        bool       operator>=(L, R);
6634  //        bool       operator==(L, R);
6635  //        bool       operator!=(L, R);
6636  //
6637  //   where LR is the result of the usual arithmetic conversions
6638  //   between types L and R.
6639  //
6640  // C++ [over.built]p24:
6641  //
6642  //   For every pair of promoted arithmetic types L and R, there exist
6643  //   candidate operator functions of the form
6644  //
6645  //        LR       operator?(bool, L, R);
6646  //
6647  //   where LR is the result of the usual arithmetic conversions
6648  //   between types L and R.
6649  // Our candidates ignore the first parameter.
6650  void addGenericBinaryArithmeticOverloads(bool isComparison) {
6651    if (!HasArithmeticOrEnumeralCandidateType)
6652      return;
6653
6654    for (unsigned Left = FirstPromotedArithmeticType;
6655         Left < LastPromotedArithmeticType; ++Left) {
6656      for (unsigned Right = FirstPromotedArithmeticType;
6657           Right < LastPromotedArithmeticType; ++Right) {
6658        QualType LandR[2] = { getArithmeticType(Left),
6659                              getArithmeticType(Right) };
6660        QualType Result =
6661          isComparison ? S.Context.BoolTy
6662                       : getUsualArithmeticConversions(Left, Right);
6663        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6664      }
6665    }
6666
6667    // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6668    // conditional operator for vector types.
6669    for (BuiltinCandidateTypeSet::iterator
6670              Vec1 = CandidateTypes[0].vector_begin(),
6671           Vec1End = CandidateTypes[0].vector_end();
6672         Vec1 != Vec1End; ++Vec1) {
6673      for (BuiltinCandidateTypeSet::iterator
6674                Vec2 = CandidateTypes[1].vector_begin(),
6675             Vec2End = CandidateTypes[1].vector_end();
6676           Vec2 != Vec2End; ++Vec2) {
6677        QualType LandR[2] = { *Vec1, *Vec2 };
6678        QualType Result = S.Context.BoolTy;
6679        if (!isComparison) {
6680          if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6681            Result = *Vec1;
6682          else
6683            Result = *Vec2;
6684        }
6685
6686        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6687      }
6688    }
6689  }
6690
6691  // C++ [over.built]p17:
6692  //
6693  //   For every pair of promoted integral types L and R, there
6694  //   exist candidate operator functions of the form
6695  //
6696  //      LR         operator%(L, R);
6697  //      LR         operator&(L, R);
6698  //      LR         operator^(L, R);
6699  //      LR         operator|(L, R);
6700  //      L          operator<<(L, R);
6701  //      L          operator>>(L, R);
6702  //
6703  //   where LR is the result of the usual arithmetic conversions
6704  //   between types L and R.
6705  void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
6706    if (!HasArithmeticOrEnumeralCandidateType)
6707      return;
6708
6709    for (unsigned Left = FirstPromotedIntegralType;
6710         Left < LastPromotedIntegralType; ++Left) {
6711      for (unsigned Right = FirstPromotedIntegralType;
6712           Right < LastPromotedIntegralType; ++Right) {
6713        QualType LandR[2] = { getArithmeticType(Left),
6714                              getArithmeticType(Right) };
6715        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6716            ? LandR[0]
6717            : getUsualArithmeticConversions(Left, Right);
6718        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6719      }
6720    }
6721  }
6722
6723  // C++ [over.built]p20:
6724  //
6725  //   For every pair (T, VQ), where T is an enumeration or
6726  //   pointer to member type and VQ is either volatile or
6727  //   empty, there exist candidate operator functions of the form
6728  //
6729  //        VQ T&      operator=(VQ T&, T);
6730  void addAssignmentMemberPointerOrEnumeralOverloads() {
6731    /// Set of (canonical) types that we've already handled.
6732    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6733
6734    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6735      for (BuiltinCandidateTypeSet::iterator
6736                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6737             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6738           Enum != EnumEnd; ++Enum) {
6739        if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6740          continue;
6741
6742        AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6743                                               CandidateSet);
6744      }
6745
6746      for (BuiltinCandidateTypeSet::iterator
6747                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6748             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6749           MemPtr != MemPtrEnd; ++MemPtr) {
6750        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6751          continue;
6752
6753        AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6754                                               CandidateSet);
6755      }
6756    }
6757  }
6758
6759  // C++ [over.built]p19:
6760  //
6761  //   For every pair (T, VQ), where T is any type and VQ is either
6762  //   volatile or empty, there exist candidate operator functions
6763  //   of the form
6764  //
6765  //        T*VQ&      operator=(T*VQ&, T*);
6766  //
6767  // C++ [over.built]p21:
6768  //
6769  //   For every pair (T, VQ), where T is a cv-qualified or
6770  //   cv-unqualified object type and VQ is either volatile or
6771  //   empty, there exist candidate operator functions of the form
6772  //
6773  //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
6774  //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
6775  void addAssignmentPointerOverloads(bool isEqualOp) {
6776    /// Set of (canonical) types that we've already handled.
6777    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6778
6779    for (BuiltinCandidateTypeSet::iterator
6780              Ptr = CandidateTypes[0].pointer_begin(),
6781           PtrEnd = CandidateTypes[0].pointer_end();
6782         Ptr != PtrEnd; ++Ptr) {
6783      // If this is operator=, keep track of the builtin candidates we added.
6784      if (isEqualOp)
6785        AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
6786      else if (!(*Ptr)->getPointeeType()->isObjectType())
6787        continue;
6788
6789      // non-volatile version
6790      QualType ParamTypes[2] = {
6791        S.Context.getLValueReferenceType(*Ptr),
6792        isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6793      };
6794      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6795                            /*IsAssigmentOperator=*/ isEqualOp);
6796
6797      if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6798          VisibleTypeConversionsQuals.hasVolatile()) {
6799        // volatile version
6800        ParamTypes[0] =
6801          S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6802        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6803                              /*IsAssigmentOperator=*/isEqualOp);
6804      }
6805    }
6806
6807    if (isEqualOp) {
6808      for (BuiltinCandidateTypeSet::iterator
6809                Ptr = CandidateTypes[1].pointer_begin(),
6810             PtrEnd = CandidateTypes[1].pointer_end();
6811           Ptr != PtrEnd; ++Ptr) {
6812        // Make sure we don't add the same candidate twice.
6813        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6814          continue;
6815
6816        QualType ParamTypes[2] = {
6817          S.Context.getLValueReferenceType(*Ptr),
6818          *Ptr,
6819        };
6820
6821        // non-volatile version
6822        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6823                              /*IsAssigmentOperator=*/true);
6824
6825        if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6826            VisibleTypeConversionsQuals.hasVolatile()) {
6827          // volatile version
6828          ParamTypes[0] =
6829            S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6830          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6831                                CandidateSet, /*IsAssigmentOperator=*/true);
6832        }
6833      }
6834    }
6835  }
6836
6837  // C++ [over.built]p18:
6838  //
6839  //   For every triple (L, VQ, R), where L is an arithmetic type,
6840  //   VQ is either volatile or empty, and R is a promoted
6841  //   arithmetic type, there exist candidate operator functions of
6842  //   the form
6843  //
6844  //        VQ L&      operator=(VQ L&, R);
6845  //        VQ L&      operator*=(VQ L&, R);
6846  //        VQ L&      operator/=(VQ L&, R);
6847  //        VQ L&      operator+=(VQ L&, R);
6848  //        VQ L&      operator-=(VQ L&, R);
6849  void addAssignmentArithmeticOverloads(bool isEqualOp) {
6850    if (!HasArithmeticOrEnumeralCandidateType)
6851      return;
6852
6853    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6854      for (unsigned Right = FirstPromotedArithmeticType;
6855           Right < LastPromotedArithmeticType; ++Right) {
6856        QualType ParamTypes[2];
6857        ParamTypes[1] = getArithmeticType(Right);
6858
6859        // Add this built-in operator as a candidate (VQ is empty).
6860        ParamTypes[0] =
6861          S.Context.getLValueReferenceType(getArithmeticType(Left));
6862        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6863                              /*IsAssigmentOperator=*/isEqualOp);
6864
6865        // Add this built-in operator as a candidate (VQ is 'volatile').
6866        if (VisibleTypeConversionsQuals.hasVolatile()) {
6867          ParamTypes[0] =
6868            S.Context.getVolatileType(getArithmeticType(Left));
6869          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6870          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6871                                CandidateSet,
6872                                /*IsAssigmentOperator=*/isEqualOp);
6873        }
6874      }
6875    }
6876
6877    // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6878    for (BuiltinCandidateTypeSet::iterator
6879              Vec1 = CandidateTypes[0].vector_begin(),
6880           Vec1End = CandidateTypes[0].vector_end();
6881         Vec1 != Vec1End; ++Vec1) {
6882      for (BuiltinCandidateTypeSet::iterator
6883                Vec2 = CandidateTypes[1].vector_begin(),
6884             Vec2End = CandidateTypes[1].vector_end();
6885           Vec2 != Vec2End; ++Vec2) {
6886        QualType ParamTypes[2];
6887        ParamTypes[1] = *Vec2;
6888        // Add this built-in operator as a candidate (VQ is empty).
6889        ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6890        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6891                              /*IsAssigmentOperator=*/isEqualOp);
6892
6893        // Add this built-in operator as a candidate (VQ is 'volatile').
6894        if (VisibleTypeConversionsQuals.hasVolatile()) {
6895          ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6896          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6897          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6898                                CandidateSet,
6899                                /*IsAssigmentOperator=*/isEqualOp);
6900        }
6901      }
6902    }
6903  }
6904
6905  // C++ [over.built]p22:
6906  //
6907  //   For every triple (L, VQ, R), where L is an integral type, VQ
6908  //   is either volatile or empty, and R is a promoted integral
6909  //   type, there exist candidate operator functions of the form
6910  //
6911  //        VQ L&       operator%=(VQ L&, R);
6912  //        VQ L&       operator<<=(VQ L&, R);
6913  //        VQ L&       operator>>=(VQ L&, R);
6914  //        VQ L&       operator&=(VQ L&, R);
6915  //        VQ L&       operator^=(VQ L&, R);
6916  //        VQ L&       operator|=(VQ L&, R);
6917  void addAssignmentIntegralOverloads() {
6918    if (!HasArithmeticOrEnumeralCandidateType)
6919      return;
6920
6921    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6922      for (unsigned Right = FirstPromotedIntegralType;
6923           Right < LastPromotedIntegralType; ++Right) {
6924        QualType ParamTypes[2];
6925        ParamTypes[1] = getArithmeticType(Right);
6926
6927        // Add this built-in operator as a candidate (VQ is empty).
6928        ParamTypes[0] =
6929          S.Context.getLValueReferenceType(getArithmeticType(Left));
6930        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6931        if (VisibleTypeConversionsQuals.hasVolatile()) {
6932          // Add this built-in operator as a candidate (VQ is 'volatile').
6933          ParamTypes[0] = getArithmeticType(Left);
6934          ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6935          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6936          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6937                                CandidateSet);
6938        }
6939      }
6940    }
6941  }
6942
6943  // C++ [over.operator]p23:
6944  //
6945  //   There also exist candidate operator functions of the form
6946  //
6947  //        bool        operator!(bool);
6948  //        bool        operator&&(bool, bool);
6949  //        bool        operator||(bool, bool);
6950  void addExclaimOverload() {
6951    QualType ParamTy = S.Context.BoolTy;
6952    S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6953                          /*IsAssignmentOperator=*/false,
6954                          /*NumContextualBoolArguments=*/1);
6955  }
6956  void addAmpAmpOrPipePipeOverload() {
6957    QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6958    S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6959                          /*IsAssignmentOperator=*/false,
6960                          /*NumContextualBoolArguments=*/2);
6961  }
6962
6963  // C++ [over.built]p13:
6964  //
6965  //   For every cv-qualified or cv-unqualified object type T there
6966  //   exist candidate operator functions of the form
6967  //
6968  //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
6969  //        T&         operator[](T*, ptrdiff_t);
6970  //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
6971  //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
6972  //        T&         operator[](ptrdiff_t, T*);
6973  void addSubscriptOverloads() {
6974    for (BuiltinCandidateTypeSet::iterator
6975              Ptr = CandidateTypes[0].pointer_begin(),
6976           PtrEnd = CandidateTypes[0].pointer_end();
6977         Ptr != PtrEnd; ++Ptr) {
6978      QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6979      QualType PointeeType = (*Ptr)->getPointeeType();
6980      if (!PointeeType->isObjectType())
6981        continue;
6982
6983      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6984
6985      // T& operator[](T*, ptrdiff_t)
6986      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6987    }
6988
6989    for (BuiltinCandidateTypeSet::iterator
6990              Ptr = CandidateTypes[1].pointer_begin(),
6991           PtrEnd = CandidateTypes[1].pointer_end();
6992         Ptr != PtrEnd; ++Ptr) {
6993      QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6994      QualType PointeeType = (*Ptr)->getPointeeType();
6995      if (!PointeeType->isObjectType())
6996        continue;
6997
6998      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6999
7000      // T& operator[](ptrdiff_t, T*)
7001      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7002    }
7003  }
7004
7005  // C++ [over.built]p11:
7006  //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7007  //    C1 is the same type as C2 or is a derived class of C2, T is an object
7008  //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7009  //    there exist candidate operator functions of the form
7010  //
7011  //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7012  //
7013  //    where CV12 is the union of CV1 and CV2.
7014  void addArrowStarOverloads() {
7015    for (BuiltinCandidateTypeSet::iterator
7016             Ptr = CandidateTypes[0].pointer_begin(),
7017           PtrEnd = CandidateTypes[0].pointer_end();
7018         Ptr != PtrEnd; ++Ptr) {
7019      QualType C1Ty = (*Ptr);
7020      QualType C1;
7021      QualifierCollector Q1;
7022      C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7023      if (!isa<RecordType>(C1))
7024        continue;
7025      // heuristic to reduce number of builtin candidates in the set.
7026      // Add volatile/restrict version only if there are conversions to a
7027      // volatile/restrict type.
7028      if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7029        continue;
7030      if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7031        continue;
7032      for (BuiltinCandidateTypeSet::iterator
7033                MemPtr = CandidateTypes[1].member_pointer_begin(),
7034             MemPtrEnd = CandidateTypes[1].member_pointer_end();
7035           MemPtr != MemPtrEnd; ++MemPtr) {
7036        const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7037        QualType C2 = QualType(mptr->getClass(), 0);
7038        C2 = C2.getUnqualifiedType();
7039        if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7040          break;
7041        QualType ParamTypes[2] = { *Ptr, *MemPtr };
7042        // build CV12 T&
7043        QualType T = mptr->getPointeeType();
7044        if (!VisibleTypeConversionsQuals.hasVolatile() &&
7045            T.isVolatileQualified())
7046          continue;
7047        if (!VisibleTypeConversionsQuals.hasRestrict() &&
7048            T.isRestrictQualified())
7049          continue;
7050        T = Q1.apply(S.Context, T);
7051        QualType ResultTy = S.Context.getLValueReferenceType(T);
7052        S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7053      }
7054    }
7055  }
7056
7057  // Note that we don't consider the first argument, since it has been
7058  // contextually converted to bool long ago. The candidates below are
7059  // therefore added as binary.
7060  //
7061  // C++ [over.built]p25:
7062  //   For every type T, where T is a pointer, pointer-to-member, or scoped
7063  //   enumeration type, there exist candidate operator functions of the form
7064  //
7065  //        T        operator?(bool, T, T);
7066  //
7067  void addConditionalOperatorOverloads() {
7068    /// Set of (canonical) types that we've already handled.
7069    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7070
7071    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7072      for (BuiltinCandidateTypeSet::iterator
7073                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7074             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7075           Ptr != PtrEnd; ++Ptr) {
7076        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7077          continue;
7078
7079        QualType ParamTypes[2] = { *Ptr, *Ptr };
7080        S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7081      }
7082
7083      for (BuiltinCandidateTypeSet::iterator
7084                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7085             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7086           MemPtr != MemPtrEnd; ++MemPtr) {
7087        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7088          continue;
7089
7090        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7091        S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7092      }
7093
7094      if (S.getLangOptions().CPlusPlus0x) {
7095        for (BuiltinCandidateTypeSet::iterator
7096                  Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7097               EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7098             Enum != EnumEnd; ++Enum) {
7099          if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7100            continue;
7101
7102          if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7103            continue;
7104
7105          QualType ParamTypes[2] = { *Enum, *Enum };
7106          S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7107        }
7108      }
7109    }
7110  }
7111};
7112
7113} // end anonymous namespace
7114
7115/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7116/// operator overloads to the candidate set (C++ [over.built]), based
7117/// on the operator @p Op and the arguments given. For example, if the
7118/// operator is a binary '+', this routine might add "int
7119/// operator+(int, int)" to cover integer addition.
7120void
7121Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7122                                   SourceLocation OpLoc,
7123                                   Expr **Args, unsigned NumArgs,
7124                                   OverloadCandidateSet& CandidateSet) {
7125  // Find all of the types that the arguments can convert to, but only
7126  // if the operator we're looking at has built-in operator candidates
7127  // that make use of these types. Also record whether we encounter non-record
7128  // candidate types or either arithmetic or enumeral candidate types.
7129  Qualifiers VisibleTypeConversionsQuals;
7130  VisibleTypeConversionsQuals.addConst();
7131  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7132    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7133
7134  bool HasNonRecordCandidateType = false;
7135  bool HasArithmeticOrEnumeralCandidateType = false;
7136  SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7137  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7138    CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7139    CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7140                                                 OpLoc,
7141                                                 true,
7142                                                 (Op == OO_Exclaim ||
7143                                                  Op == OO_AmpAmp ||
7144                                                  Op == OO_PipePipe),
7145                                                 VisibleTypeConversionsQuals);
7146    HasNonRecordCandidateType = HasNonRecordCandidateType ||
7147        CandidateTypes[ArgIdx].hasNonRecordTypes();
7148    HasArithmeticOrEnumeralCandidateType =
7149        HasArithmeticOrEnumeralCandidateType ||
7150        CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7151  }
7152
7153  // Exit early when no non-record types have been added to the candidate set
7154  // for any of the arguments to the operator.
7155  //
7156  // We can't exit early for !, ||, or &&, since there we have always have
7157  // 'bool' overloads.
7158  if (!HasNonRecordCandidateType &&
7159      !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7160    return;
7161
7162  // Setup an object to manage the common state for building overloads.
7163  BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7164                                           VisibleTypeConversionsQuals,
7165                                           HasArithmeticOrEnumeralCandidateType,
7166                                           CandidateTypes, CandidateSet);
7167
7168  // Dispatch over the operation to add in only those overloads which apply.
7169  switch (Op) {
7170  case OO_None:
7171  case NUM_OVERLOADED_OPERATORS:
7172    llvm_unreachable("Expected an overloaded operator");
7173
7174  case OO_New:
7175  case OO_Delete:
7176  case OO_Array_New:
7177  case OO_Array_Delete:
7178  case OO_Call:
7179    llvm_unreachable(
7180                    "Special operators don't use AddBuiltinOperatorCandidates");
7181
7182  case OO_Comma:
7183  case OO_Arrow:
7184    // C++ [over.match.oper]p3:
7185    //   -- For the operator ',', the unary operator '&', or the
7186    //      operator '->', the built-in candidates set is empty.
7187    break;
7188
7189  case OO_Plus: // '+' is either unary or binary
7190    if (NumArgs == 1)
7191      OpBuilder.addUnaryPlusPointerOverloads();
7192    // Fall through.
7193
7194  case OO_Minus: // '-' is either unary or binary
7195    if (NumArgs == 1) {
7196      OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7197    } else {
7198      OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7199      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7200    }
7201    break;
7202
7203  case OO_Star: // '*' is either unary or binary
7204    if (NumArgs == 1)
7205      OpBuilder.addUnaryStarPointerOverloads();
7206    else
7207      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7208    break;
7209
7210  case OO_Slash:
7211    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7212    break;
7213
7214  case OO_PlusPlus:
7215  case OO_MinusMinus:
7216    OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7217    OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7218    break;
7219
7220  case OO_EqualEqual:
7221  case OO_ExclaimEqual:
7222    OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7223    // Fall through.
7224
7225  case OO_Less:
7226  case OO_Greater:
7227  case OO_LessEqual:
7228  case OO_GreaterEqual:
7229    OpBuilder.addRelationalPointerOrEnumeralOverloads();
7230    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7231    break;
7232
7233  case OO_Percent:
7234  case OO_Caret:
7235  case OO_Pipe:
7236  case OO_LessLess:
7237  case OO_GreaterGreater:
7238    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7239    break;
7240
7241  case OO_Amp: // '&' is either unary or binary
7242    if (NumArgs == 1)
7243      // C++ [over.match.oper]p3:
7244      //   -- For the operator ',', the unary operator '&', or the
7245      //      operator '->', the built-in candidates set is empty.
7246      break;
7247
7248    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7249    break;
7250
7251  case OO_Tilde:
7252    OpBuilder.addUnaryTildePromotedIntegralOverloads();
7253    break;
7254
7255  case OO_Equal:
7256    OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7257    // Fall through.
7258
7259  case OO_PlusEqual:
7260  case OO_MinusEqual:
7261    OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7262    // Fall through.
7263
7264  case OO_StarEqual:
7265  case OO_SlashEqual:
7266    OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7267    break;
7268
7269  case OO_PercentEqual:
7270  case OO_LessLessEqual:
7271  case OO_GreaterGreaterEqual:
7272  case OO_AmpEqual:
7273  case OO_CaretEqual:
7274  case OO_PipeEqual:
7275    OpBuilder.addAssignmentIntegralOverloads();
7276    break;
7277
7278  case OO_Exclaim:
7279    OpBuilder.addExclaimOverload();
7280    break;
7281
7282  case OO_AmpAmp:
7283  case OO_PipePipe:
7284    OpBuilder.addAmpAmpOrPipePipeOverload();
7285    break;
7286
7287  case OO_Subscript:
7288    OpBuilder.addSubscriptOverloads();
7289    break;
7290
7291  case OO_ArrowStar:
7292    OpBuilder.addArrowStarOverloads();
7293    break;
7294
7295  case OO_Conditional:
7296    OpBuilder.addConditionalOperatorOverloads();
7297    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7298    break;
7299  }
7300}
7301
7302/// \brief Add function candidates found via argument-dependent lookup
7303/// to the set of overloading candidates.
7304///
7305/// This routine performs argument-dependent name lookup based on the
7306/// given function name (which may also be an operator name) and adds
7307/// all of the overload candidates found by ADL to the overload
7308/// candidate set (C++ [basic.lookup.argdep]).
7309void
7310Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7311                                           bool Operator,
7312                                           Expr **Args, unsigned NumArgs,
7313                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
7314                                           OverloadCandidateSet& CandidateSet,
7315                                           bool PartialOverloading,
7316                                           bool StdNamespaceIsAssociated) {
7317  ADLResult Fns;
7318
7319  // FIXME: This approach for uniquing ADL results (and removing
7320  // redundant candidates from the set) relies on pointer-equality,
7321  // which means we need to key off the canonical decl.  However,
7322  // always going back to the canonical decl might not get us the
7323  // right set of default arguments.  What default arguments are
7324  // we supposed to consider on ADL candidates, anyway?
7325
7326  // FIXME: Pass in the explicit template arguments?
7327  ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
7328                          StdNamespaceIsAssociated);
7329
7330  // Erase all of the candidates we already knew about.
7331  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7332                                   CandEnd = CandidateSet.end();
7333       Cand != CandEnd; ++Cand)
7334    if (Cand->Function) {
7335      Fns.erase(Cand->Function);
7336      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7337        Fns.erase(FunTmpl);
7338    }
7339
7340  // For each of the ADL candidates we found, add it to the overload
7341  // set.
7342  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7343    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7344    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7345      if (ExplicitTemplateArgs)
7346        continue;
7347
7348      AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
7349                           false, PartialOverloading);
7350    } else
7351      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7352                                   FoundDecl, ExplicitTemplateArgs,
7353                                   Args, NumArgs, CandidateSet);
7354  }
7355}
7356
7357/// isBetterOverloadCandidate - Determines whether the first overload
7358/// candidate is a better candidate than the second (C++ 13.3.3p1).
7359bool
7360isBetterOverloadCandidate(Sema &S,
7361                          const OverloadCandidate &Cand1,
7362                          const OverloadCandidate &Cand2,
7363                          SourceLocation Loc,
7364                          bool UserDefinedConversion) {
7365  // Define viable functions to be better candidates than non-viable
7366  // functions.
7367  if (!Cand2.Viable)
7368    return Cand1.Viable;
7369  else if (!Cand1.Viable)
7370    return false;
7371
7372  // C++ [over.match.best]p1:
7373  //
7374  //   -- if F is a static member function, ICS1(F) is defined such
7375  //      that ICS1(F) is neither better nor worse than ICS1(G) for
7376  //      any function G, and, symmetrically, ICS1(G) is neither
7377  //      better nor worse than ICS1(F).
7378  unsigned StartArg = 0;
7379  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7380    StartArg = 1;
7381
7382  // C++ [over.match.best]p1:
7383  //   A viable function F1 is defined to be a better function than another
7384  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
7385  //   conversion sequence than ICSi(F2), and then...
7386  unsigned NumArgs = Cand1.NumConversions;
7387  assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7388  bool HasBetterConversion = false;
7389  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7390    switch (CompareImplicitConversionSequences(S,
7391                                               Cand1.Conversions[ArgIdx],
7392                                               Cand2.Conversions[ArgIdx])) {
7393    case ImplicitConversionSequence::Better:
7394      // Cand1 has a better conversion sequence.
7395      HasBetterConversion = true;
7396      break;
7397
7398    case ImplicitConversionSequence::Worse:
7399      // Cand1 can't be better than Cand2.
7400      return false;
7401
7402    case ImplicitConversionSequence::Indistinguishable:
7403      // Do nothing.
7404      break;
7405    }
7406  }
7407
7408  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
7409  //       ICSj(F2), or, if not that,
7410  if (HasBetterConversion)
7411    return true;
7412
7413  //     - F1 is a non-template function and F2 is a function template
7414  //       specialization, or, if not that,
7415  if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
7416      Cand2.Function && Cand2.Function->getPrimaryTemplate())
7417    return true;
7418
7419  //   -- F1 and F2 are function template specializations, and the function
7420  //      template for F1 is more specialized than the template for F2
7421  //      according to the partial ordering rules described in 14.5.5.2, or,
7422  //      if not that,
7423  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
7424      Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
7425    if (FunctionTemplateDecl *BetterTemplate
7426          = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7427                                         Cand2.Function->getPrimaryTemplate(),
7428                                         Loc,
7429                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
7430                                                             : TPOC_Call,
7431                                         Cand1.ExplicitCallArguments))
7432      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
7433  }
7434
7435  //   -- the context is an initialization by user-defined conversion
7436  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
7437  //      from the return type of F1 to the destination type (i.e.,
7438  //      the type of the entity being initialized) is a better
7439  //      conversion sequence than the standard conversion sequence
7440  //      from the return type of F2 to the destination type.
7441  if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
7442      isa<CXXConversionDecl>(Cand1.Function) &&
7443      isa<CXXConversionDecl>(Cand2.Function)) {
7444    switch (CompareStandardConversionSequences(S,
7445                                               Cand1.FinalConversion,
7446                                               Cand2.FinalConversion)) {
7447    case ImplicitConversionSequence::Better:
7448      // Cand1 has a better conversion sequence.
7449      return true;
7450
7451    case ImplicitConversionSequence::Worse:
7452      // Cand1 can't be better than Cand2.
7453      return false;
7454
7455    case ImplicitConversionSequence::Indistinguishable:
7456      // Do nothing
7457      break;
7458    }
7459  }
7460
7461  return false;
7462}
7463
7464/// \brief Computes the best viable function (C++ 13.3.3)
7465/// within an overload candidate set.
7466///
7467/// \param CandidateSet the set of candidate functions.
7468///
7469/// \param Loc the location of the function name (or operator symbol) for
7470/// which overload resolution occurs.
7471///
7472/// \param Best f overload resolution was successful or found a deleted
7473/// function, Best points to the candidate function found.
7474///
7475/// \returns The result of overload resolution.
7476OverloadingResult
7477OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
7478                                         iterator &Best,
7479                                         bool UserDefinedConversion) {
7480  // Find the best viable function.
7481  Best = end();
7482  for (iterator Cand = begin(); Cand != end(); ++Cand) {
7483    if (Cand->Viable)
7484      if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
7485                                                     UserDefinedConversion))
7486        Best = Cand;
7487  }
7488
7489  // If we didn't find any viable functions, abort.
7490  if (Best == end())
7491    return OR_No_Viable_Function;
7492
7493  // Make sure that this function is better than every other viable
7494  // function. If not, we have an ambiguity.
7495  for (iterator Cand = begin(); Cand != end(); ++Cand) {
7496    if (Cand->Viable &&
7497        Cand != Best &&
7498        !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
7499                                   UserDefinedConversion)) {
7500      Best = end();
7501      return OR_Ambiguous;
7502    }
7503  }
7504
7505  // Best is the best viable function.
7506  if (Best->Function &&
7507      (Best->Function->isDeleted() ||
7508       S.isFunctionConsideredUnavailable(Best->Function)))
7509    return OR_Deleted;
7510
7511  return OR_Success;
7512}
7513
7514namespace {
7515
7516enum OverloadCandidateKind {
7517  oc_function,
7518  oc_method,
7519  oc_constructor,
7520  oc_function_template,
7521  oc_method_template,
7522  oc_constructor_template,
7523  oc_implicit_default_constructor,
7524  oc_implicit_copy_constructor,
7525  oc_implicit_move_constructor,
7526  oc_implicit_copy_assignment,
7527  oc_implicit_move_assignment,
7528  oc_implicit_inherited_constructor
7529};
7530
7531OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7532                                                FunctionDecl *Fn,
7533                                                std::string &Description) {
7534  bool isTemplate = false;
7535
7536  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7537    isTemplate = true;
7538    Description = S.getTemplateArgumentBindingsText(
7539      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7540  }
7541
7542  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
7543    if (!Ctor->isImplicit())
7544      return isTemplate ? oc_constructor_template : oc_constructor;
7545
7546    if (Ctor->getInheritedConstructor())
7547      return oc_implicit_inherited_constructor;
7548
7549    if (Ctor->isDefaultConstructor())
7550      return oc_implicit_default_constructor;
7551
7552    if (Ctor->isMoveConstructor())
7553      return oc_implicit_move_constructor;
7554
7555    assert(Ctor->isCopyConstructor() &&
7556           "unexpected sort of implicit constructor");
7557    return oc_implicit_copy_constructor;
7558  }
7559
7560  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7561    // This actually gets spelled 'candidate function' for now, but
7562    // it doesn't hurt to split it out.
7563    if (!Meth->isImplicit())
7564      return isTemplate ? oc_method_template : oc_method;
7565
7566    if (Meth->isMoveAssignmentOperator())
7567      return oc_implicit_move_assignment;
7568
7569    assert(Meth->isCopyAssignmentOperator()
7570           && "implicit method is not copy assignment operator?");
7571    return oc_implicit_copy_assignment;
7572  }
7573
7574  return isTemplate ? oc_function_template : oc_function;
7575}
7576
7577void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7578  const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7579  if (!Ctor) return;
7580
7581  Ctor = Ctor->getInheritedConstructor();
7582  if (!Ctor) return;
7583
7584  S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7585}
7586
7587} // end anonymous namespace
7588
7589// Notes the location of an overload candidate.
7590void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
7591  std::string FnDesc;
7592  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
7593  PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7594                             << (unsigned) K << FnDesc;
7595  HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7596  Diag(Fn->getLocation(), PD);
7597  MaybeEmitInheritedConstructorNote(*this, Fn);
7598}
7599
7600//Notes the location of all overload candidates designated through
7601// OverloadedExpr
7602void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
7603  assert(OverloadedExpr->getType() == Context.OverloadTy);
7604
7605  OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7606  OverloadExpr *OvlExpr = Ovl.Expression;
7607
7608  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7609                            IEnd = OvlExpr->decls_end();
7610       I != IEnd; ++I) {
7611    if (FunctionTemplateDecl *FunTmpl =
7612                dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
7613      NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
7614    } else if (FunctionDecl *Fun
7615                      = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
7616      NoteOverloadCandidate(Fun, DestType);
7617    }
7618  }
7619}
7620
7621/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
7622/// "lead" diagnostic; it will be given two arguments, the source and
7623/// target types of the conversion.
7624void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7625                                 Sema &S,
7626                                 SourceLocation CaretLoc,
7627                                 const PartialDiagnostic &PDiag) const {
7628  S.Diag(CaretLoc, PDiag)
7629    << Ambiguous.getFromType() << Ambiguous.getToType();
7630  for (AmbiguousConversionSequence::const_iterator
7631         I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7632    S.NoteOverloadCandidate(*I);
7633  }
7634}
7635
7636namespace {
7637
7638void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7639  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7640  assert(Conv.isBad());
7641  assert(Cand->Function && "for now, candidate must be a function");
7642  FunctionDecl *Fn = Cand->Function;
7643
7644  // There's a conversion slot for the object argument if this is a
7645  // non-constructor method.  Note that 'I' corresponds the
7646  // conversion-slot index.
7647  bool isObjectArgument = false;
7648  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
7649    if (I == 0)
7650      isObjectArgument = true;
7651    else
7652      I--;
7653  }
7654
7655  std::string FnDesc;
7656  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7657
7658  Expr *FromExpr = Conv.Bad.FromExpr;
7659  QualType FromTy = Conv.Bad.getFromType();
7660  QualType ToTy = Conv.Bad.getToType();
7661
7662  if (FromTy == S.Context.OverloadTy) {
7663    assert(FromExpr && "overload set argument came from implicit argument?");
7664    Expr *E = FromExpr->IgnoreParens();
7665    if (isa<UnaryOperator>(E))
7666      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
7667    DeclarationName Name = cast<OverloadExpr>(E)->getName();
7668
7669    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7670      << (unsigned) FnKind << FnDesc
7671      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7672      << ToTy << Name << I+1;
7673    MaybeEmitInheritedConstructorNote(S, Fn);
7674    return;
7675  }
7676
7677  // Do some hand-waving analysis to see if the non-viability is due
7678  // to a qualifier mismatch.
7679  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7680  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7681  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7682    CToTy = RT->getPointeeType();
7683  else {
7684    // TODO: detect and diagnose the full richness of const mismatches.
7685    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7686      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7687        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7688  }
7689
7690  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7691      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7692    // It is dumb that we have to do this here.
7693    while (isa<ArrayType>(CFromTy))
7694      CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7695    while (isa<ArrayType>(CToTy))
7696      CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7697
7698    Qualifiers FromQs = CFromTy.getQualifiers();
7699    Qualifiers ToQs = CToTy.getQualifiers();
7700
7701    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7702      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7703        << (unsigned) FnKind << FnDesc
7704        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7705        << FromTy
7706        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7707        << (unsigned) isObjectArgument << I+1;
7708      MaybeEmitInheritedConstructorNote(S, Fn);
7709      return;
7710    }
7711
7712    if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7713      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
7714        << (unsigned) FnKind << FnDesc
7715        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7716        << FromTy
7717        << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7718        << (unsigned) isObjectArgument << I+1;
7719      MaybeEmitInheritedConstructorNote(S, Fn);
7720      return;
7721    }
7722
7723    if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7724      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7725      << (unsigned) FnKind << FnDesc
7726      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7727      << FromTy
7728      << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7729      << (unsigned) isObjectArgument << I+1;
7730      MaybeEmitInheritedConstructorNote(S, Fn);
7731      return;
7732    }
7733
7734    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7735    assert(CVR && "unexpected qualifiers mismatch");
7736
7737    if (isObjectArgument) {
7738      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7739        << (unsigned) FnKind << FnDesc
7740        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7741        << FromTy << (CVR - 1);
7742    } else {
7743      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7744        << (unsigned) FnKind << FnDesc
7745        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7746        << FromTy << (CVR - 1) << I+1;
7747    }
7748    MaybeEmitInheritedConstructorNote(S, Fn);
7749    return;
7750  }
7751
7752  // Special diagnostic for failure to convert an initializer list, since
7753  // telling the user that it has type void is not useful.
7754  if (FromExpr && isa<InitListExpr>(FromExpr)) {
7755    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7756      << (unsigned) FnKind << FnDesc
7757      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7758      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7759    MaybeEmitInheritedConstructorNote(S, Fn);
7760    return;
7761  }
7762
7763  // Diagnose references or pointers to incomplete types differently,
7764  // since it's far from impossible that the incompleteness triggered
7765  // the failure.
7766  QualType TempFromTy = FromTy.getNonReferenceType();
7767  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7768    TempFromTy = PTy->getPointeeType();
7769  if (TempFromTy->isIncompleteType()) {
7770    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7771      << (unsigned) FnKind << FnDesc
7772      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7773      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7774    MaybeEmitInheritedConstructorNote(S, Fn);
7775    return;
7776  }
7777
7778  // Diagnose base -> derived pointer conversions.
7779  unsigned BaseToDerivedConversion = 0;
7780  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7781    if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7782      if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7783                                               FromPtrTy->getPointeeType()) &&
7784          !FromPtrTy->getPointeeType()->isIncompleteType() &&
7785          !ToPtrTy->getPointeeType()->isIncompleteType() &&
7786          S.IsDerivedFrom(ToPtrTy->getPointeeType(),
7787                          FromPtrTy->getPointeeType()))
7788        BaseToDerivedConversion = 1;
7789    }
7790  } else if (const ObjCObjectPointerType *FromPtrTy
7791                                    = FromTy->getAs<ObjCObjectPointerType>()) {
7792    if (const ObjCObjectPointerType *ToPtrTy
7793                                        = ToTy->getAs<ObjCObjectPointerType>())
7794      if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7795        if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7796          if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7797                                                FromPtrTy->getPointeeType()) &&
7798              FromIface->isSuperClassOf(ToIface))
7799            BaseToDerivedConversion = 2;
7800  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7801      if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7802          !FromTy->isIncompleteType() &&
7803          !ToRefTy->getPointeeType()->isIncompleteType() &&
7804          S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7805        BaseToDerivedConversion = 3;
7806    }
7807
7808  if (BaseToDerivedConversion) {
7809    S.Diag(Fn->getLocation(),
7810           diag::note_ovl_candidate_bad_base_to_derived_conv)
7811      << (unsigned) FnKind << FnDesc
7812      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7813      << (BaseToDerivedConversion - 1)
7814      << FromTy << ToTy << I+1;
7815    MaybeEmitInheritedConstructorNote(S, Fn);
7816    return;
7817  }
7818
7819  if (isa<ObjCObjectPointerType>(CFromTy) &&
7820      isa<PointerType>(CToTy)) {
7821      Qualifiers FromQs = CFromTy.getQualifiers();
7822      Qualifiers ToQs = CToTy.getQualifiers();
7823      if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7824        S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7825        << (unsigned) FnKind << FnDesc
7826        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7827        << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7828        MaybeEmitInheritedConstructorNote(S, Fn);
7829        return;
7830      }
7831  }
7832
7833  // Emit the generic diagnostic and, optionally, add the hints to it.
7834  PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7835  FDiag << (unsigned) FnKind << FnDesc
7836    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7837    << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7838    << (unsigned) (Cand->Fix.Kind);
7839
7840  // If we can fix the conversion, suggest the FixIts.
7841  for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
7842       HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
7843    FDiag << *HI;
7844  S.Diag(Fn->getLocation(), FDiag);
7845
7846  MaybeEmitInheritedConstructorNote(S, Fn);
7847}
7848
7849void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7850                           unsigned NumFormalArgs) {
7851  // TODO: treat calls to a missing default constructor as a special case
7852
7853  FunctionDecl *Fn = Cand->Function;
7854  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7855
7856  unsigned MinParams = Fn->getMinRequiredArguments();
7857
7858  // With invalid overloaded operators, it's possible that we think we
7859  // have an arity mismatch when it fact it looks like we have the
7860  // right number of arguments, because only overloaded operators have
7861  // the weird behavior of overloading member and non-member functions.
7862  // Just don't report anything.
7863  if (Fn->isInvalidDecl() &&
7864      Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7865    return;
7866
7867  // at least / at most / exactly
7868  unsigned mode, modeCount;
7869  if (NumFormalArgs < MinParams) {
7870    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7871           (Cand->FailureKind == ovl_fail_bad_deduction &&
7872            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
7873    if (MinParams != FnTy->getNumArgs() ||
7874        FnTy->isVariadic() || FnTy->isTemplateVariadic())
7875      mode = 0; // "at least"
7876    else
7877      mode = 2; // "exactly"
7878    modeCount = MinParams;
7879  } else {
7880    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7881           (Cand->FailureKind == ovl_fail_bad_deduction &&
7882            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
7883    if (MinParams != FnTy->getNumArgs())
7884      mode = 1; // "at most"
7885    else
7886      mode = 2; // "exactly"
7887    modeCount = FnTy->getNumArgs();
7888  }
7889
7890  std::string Description;
7891  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7892
7893  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
7894    << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
7895    << modeCount << NumFormalArgs;
7896  MaybeEmitInheritedConstructorNote(S, Fn);
7897}
7898
7899/// Diagnose a failed template-argument deduction.
7900void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7901                          Expr **Args, unsigned NumArgs) {
7902  FunctionDecl *Fn = Cand->Function; // pattern
7903
7904  TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
7905  NamedDecl *ParamD;
7906  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7907  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7908  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
7909  switch (Cand->DeductionFailure.Result) {
7910  case Sema::TDK_Success:
7911    llvm_unreachable("TDK_success while diagnosing bad deduction");
7912
7913  case Sema::TDK_Incomplete: {
7914    assert(ParamD && "no parameter found for incomplete deduction result");
7915    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7916      << ParamD->getDeclName();
7917    MaybeEmitInheritedConstructorNote(S, Fn);
7918    return;
7919  }
7920
7921  case Sema::TDK_Underqualified: {
7922    assert(ParamD && "no parameter found for bad qualifiers deduction result");
7923    TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7924
7925    QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7926
7927    // Param will have been canonicalized, but it should just be a
7928    // qualified version of ParamD, so move the qualifiers to that.
7929    QualifierCollector Qs;
7930    Qs.strip(Param);
7931    QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
7932    assert(S.Context.hasSameType(Param, NonCanonParam));
7933
7934    // Arg has also been canonicalized, but there's nothing we can do
7935    // about that.  It also doesn't matter as much, because it won't
7936    // have any template parameters in it (because deduction isn't
7937    // done on dependent types).
7938    QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7939
7940    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7941      << ParamD->getDeclName() << Arg << NonCanonParam;
7942    MaybeEmitInheritedConstructorNote(S, Fn);
7943    return;
7944  }
7945
7946  case Sema::TDK_Inconsistent: {
7947    assert(ParamD && "no parameter found for inconsistent deduction result");
7948    int which = 0;
7949    if (isa<TemplateTypeParmDecl>(ParamD))
7950      which = 0;
7951    else if (isa<NonTypeTemplateParmDecl>(ParamD))
7952      which = 1;
7953    else {
7954      which = 2;
7955    }
7956
7957    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
7958      << which << ParamD->getDeclName()
7959      << *Cand->DeductionFailure.getFirstArg()
7960      << *Cand->DeductionFailure.getSecondArg();
7961    MaybeEmitInheritedConstructorNote(S, Fn);
7962    return;
7963  }
7964
7965  case Sema::TDK_InvalidExplicitArguments:
7966    assert(ParamD && "no parameter found for invalid explicit arguments");
7967    if (ParamD->getDeclName())
7968      S.Diag(Fn->getLocation(),
7969             diag::note_ovl_candidate_explicit_arg_mismatch_named)
7970        << ParamD->getDeclName();
7971    else {
7972      int index = 0;
7973      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7974        index = TTP->getIndex();
7975      else if (NonTypeTemplateParmDecl *NTTP
7976                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7977        index = NTTP->getIndex();
7978      else
7979        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
7980      S.Diag(Fn->getLocation(),
7981             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7982        << (index + 1);
7983    }
7984    MaybeEmitInheritedConstructorNote(S, Fn);
7985    return;
7986
7987  case Sema::TDK_TooManyArguments:
7988  case Sema::TDK_TooFewArguments:
7989    DiagnoseArityMismatch(S, Cand, NumArgs);
7990    return;
7991
7992  case Sema::TDK_InstantiationDepth:
7993    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
7994    MaybeEmitInheritedConstructorNote(S, Fn);
7995    return;
7996
7997  case Sema::TDK_SubstitutionFailure: {
7998    std::string ArgString;
7999    if (TemplateArgumentList *Args
8000                            = Cand->DeductionFailure.getTemplateArgumentList())
8001      ArgString = S.getTemplateArgumentBindingsText(
8002                    Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8003                                                    *Args);
8004    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8005      << ArgString;
8006    MaybeEmitInheritedConstructorNote(S, Fn);
8007    return;
8008  }
8009
8010  // TODO: diagnose these individually, then kill off
8011  // note_ovl_candidate_bad_deduction, which is uselessly vague.
8012  case Sema::TDK_NonDeducedMismatch:
8013  case Sema::TDK_FailedOverloadResolution:
8014    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
8015    MaybeEmitInheritedConstructorNote(S, Fn);
8016    return;
8017  }
8018}
8019
8020/// CUDA: diagnose an invalid call across targets.
8021void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8022  FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8023  FunctionDecl *Callee = Cand->Function;
8024
8025  Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8026                           CalleeTarget = S.IdentifyCUDATarget(Callee);
8027
8028  std::string FnDesc;
8029  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8030
8031  S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8032      << (unsigned) FnKind << CalleeTarget << CallerTarget;
8033}
8034
8035/// Generates a 'note' diagnostic for an overload candidate.  We've
8036/// already generated a primary error at the call site.
8037///
8038/// It really does need to be a single diagnostic with its caret
8039/// pointed at the candidate declaration.  Yes, this creates some
8040/// major challenges of technical writing.  Yes, this makes pointing
8041/// out problems with specific arguments quite awkward.  It's still
8042/// better than generating twenty screens of text for every failed
8043/// overload.
8044///
8045/// It would be great to be able to express per-candidate problems
8046/// more richly for those diagnostic clients that cared, but we'd
8047/// still have to be just as careful with the default diagnostics.
8048void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8049                           Expr **Args, unsigned NumArgs) {
8050  FunctionDecl *Fn = Cand->Function;
8051
8052  // Note deleted candidates, but only if they're viable.
8053  if (Cand->Viable && (Fn->isDeleted() ||
8054      S.isFunctionConsideredUnavailable(Fn))) {
8055    std::string FnDesc;
8056    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8057
8058    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8059      << FnKind << FnDesc << Fn->isDeleted();
8060    MaybeEmitInheritedConstructorNote(S, Fn);
8061    return;
8062  }
8063
8064  // We don't really have anything else to say about viable candidates.
8065  if (Cand->Viable) {
8066    S.NoteOverloadCandidate(Fn);
8067    return;
8068  }
8069
8070  switch (Cand->FailureKind) {
8071  case ovl_fail_too_many_arguments:
8072  case ovl_fail_too_few_arguments:
8073    return DiagnoseArityMismatch(S, Cand, NumArgs);
8074
8075  case ovl_fail_bad_deduction:
8076    return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
8077
8078  case ovl_fail_trivial_conversion:
8079  case ovl_fail_bad_final_conversion:
8080  case ovl_fail_final_conversion_not_exact:
8081    return S.NoteOverloadCandidate(Fn);
8082
8083  case ovl_fail_bad_conversion: {
8084    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8085    for (unsigned N = Cand->NumConversions; I != N; ++I)
8086      if (Cand->Conversions[I].isBad())
8087        return DiagnoseBadConversion(S, Cand, I);
8088
8089    // FIXME: this currently happens when we're called from SemaInit
8090    // when user-conversion overload fails.  Figure out how to handle
8091    // those conditions and diagnose them well.
8092    return S.NoteOverloadCandidate(Fn);
8093  }
8094
8095  case ovl_fail_bad_target:
8096    return DiagnoseBadTarget(S, Cand);
8097  }
8098}
8099
8100void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8101  // Desugar the type of the surrogate down to a function type,
8102  // retaining as many typedefs as possible while still showing
8103  // the function type (and, therefore, its parameter types).
8104  QualType FnType = Cand->Surrogate->getConversionType();
8105  bool isLValueReference = false;
8106  bool isRValueReference = false;
8107  bool isPointer = false;
8108  if (const LValueReferenceType *FnTypeRef =
8109        FnType->getAs<LValueReferenceType>()) {
8110    FnType = FnTypeRef->getPointeeType();
8111    isLValueReference = true;
8112  } else if (const RValueReferenceType *FnTypeRef =
8113               FnType->getAs<RValueReferenceType>()) {
8114    FnType = FnTypeRef->getPointeeType();
8115    isRValueReference = true;
8116  }
8117  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8118    FnType = FnTypePtr->getPointeeType();
8119    isPointer = true;
8120  }
8121  // Desugar down to a function type.
8122  FnType = QualType(FnType->getAs<FunctionType>(), 0);
8123  // Reconstruct the pointer/reference as appropriate.
8124  if (isPointer) FnType = S.Context.getPointerType(FnType);
8125  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8126  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8127
8128  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8129    << FnType;
8130  MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8131}
8132
8133void NoteBuiltinOperatorCandidate(Sema &S,
8134                                  const char *Opc,
8135                                  SourceLocation OpLoc,
8136                                  OverloadCandidate *Cand) {
8137  assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8138  std::string TypeStr("operator");
8139  TypeStr += Opc;
8140  TypeStr += "(";
8141  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8142  if (Cand->NumConversions == 1) {
8143    TypeStr += ")";
8144    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8145  } else {
8146    TypeStr += ", ";
8147    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8148    TypeStr += ")";
8149    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8150  }
8151}
8152
8153void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8154                                  OverloadCandidate *Cand) {
8155  unsigned NoOperands = Cand->NumConversions;
8156  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8157    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8158    if (ICS.isBad()) break; // all meaningless after first invalid
8159    if (!ICS.isAmbiguous()) continue;
8160
8161    ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8162                              S.PDiag(diag::note_ambiguous_type_conversion));
8163  }
8164}
8165
8166SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8167  if (Cand->Function)
8168    return Cand->Function->getLocation();
8169  if (Cand->IsSurrogate)
8170    return Cand->Surrogate->getLocation();
8171  return SourceLocation();
8172}
8173
8174static unsigned
8175RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
8176  switch ((Sema::TemplateDeductionResult)DFI.Result) {
8177  case Sema::TDK_Success:
8178    llvm_unreachable("TDK_success while diagnosing bad deduction");
8179
8180  case Sema::TDK_Incomplete:
8181    return 1;
8182
8183  case Sema::TDK_Underqualified:
8184  case Sema::TDK_Inconsistent:
8185    return 2;
8186
8187  case Sema::TDK_SubstitutionFailure:
8188  case Sema::TDK_NonDeducedMismatch:
8189    return 3;
8190
8191  case Sema::TDK_InstantiationDepth:
8192  case Sema::TDK_FailedOverloadResolution:
8193    return 4;
8194
8195  case Sema::TDK_InvalidExplicitArguments:
8196    return 5;
8197
8198  case Sema::TDK_TooManyArguments:
8199  case Sema::TDK_TooFewArguments:
8200    return 6;
8201  }
8202  llvm_unreachable("Unhandled deduction result");
8203}
8204
8205struct CompareOverloadCandidatesForDisplay {
8206  Sema &S;
8207  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8208
8209  bool operator()(const OverloadCandidate *L,
8210                  const OverloadCandidate *R) {
8211    // Fast-path this check.
8212    if (L == R) return false;
8213
8214    // Order first by viability.
8215    if (L->Viable) {
8216      if (!R->Viable) return true;
8217
8218      // TODO: introduce a tri-valued comparison for overload
8219      // candidates.  Would be more worthwhile if we had a sort
8220      // that could exploit it.
8221      if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8222      if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8223    } else if (R->Viable)
8224      return false;
8225
8226    assert(L->Viable == R->Viable);
8227
8228    // Criteria by which we can sort non-viable candidates:
8229    if (!L->Viable) {
8230      // 1. Arity mismatches come after other candidates.
8231      if (L->FailureKind == ovl_fail_too_many_arguments ||
8232          L->FailureKind == ovl_fail_too_few_arguments)
8233        return false;
8234      if (R->FailureKind == ovl_fail_too_many_arguments ||
8235          R->FailureKind == ovl_fail_too_few_arguments)
8236        return true;
8237
8238      // 2. Bad conversions come first and are ordered by the number
8239      // of bad conversions and quality of good conversions.
8240      if (L->FailureKind == ovl_fail_bad_conversion) {
8241        if (R->FailureKind != ovl_fail_bad_conversion)
8242          return true;
8243
8244        // The conversion that can be fixed with a smaller number of changes,
8245        // comes first.
8246        unsigned numLFixes = L->Fix.NumConversionsFixed;
8247        unsigned numRFixes = R->Fix.NumConversionsFixed;
8248        numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8249        numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8250        if (numLFixes != numRFixes) {
8251          if (numLFixes < numRFixes)
8252            return true;
8253          else
8254            return false;
8255        }
8256
8257        // If there's any ordering between the defined conversions...
8258        // FIXME: this might not be transitive.
8259        assert(L->NumConversions == R->NumConversions);
8260
8261        int leftBetter = 0;
8262        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8263        for (unsigned E = L->NumConversions; I != E; ++I) {
8264          switch (CompareImplicitConversionSequences(S,
8265                                                     L->Conversions[I],
8266                                                     R->Conversions[I])) {
8267          case ImplicitConversionSequence::Better:
8268            leftBetter++;
8269            break;
8270
8271          case ImplicitConversionSequence::Worse:
8272            leftBetter--;
8273            break;
8274
8275          case ImplicitConversionSequence::Indistinguishable:
8276            break;
8277          }
8278        }
8279        if (leftBetter > 0) return true;
8280        if (leftBetter < 0) return false;
8281
8282      } else if (R->FailureKind == ovl_fail_bad_conversion)
8283        return false;
8284
8285      if (L->FailureKind == ovl_fail_bad_deduction) {
8286        if (R->FailureKind != ovl_fail_bad_deduction)
8287          return true;
8288
8289        if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8290          return RankDeductionFailure(L->DeductionFailure)
8291               < RankDeductionFailure(R->DeductionFailure);
8292      } else if (R->FailureKind == ovl_fail_bad_deduction)
8293        return false;
8294
8295      // TODO: others?
8296    }
8297
8298    // Sort everything else by location.
8299    SourceLocation LLoc = GetLocationForCandidate(L);
8300    SourceLocation RLoc = GetLocationForCandidate(R);
8301
8302    // Put candidates without locations (e.g. builtins) at the end.
8303    if (LLoc.isInvalid()) return false;
8304    if (RLoc.isInvalid()) return true;
8305
8306    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8307  }
8308};
8309
8310/// CompleteNonViableCandidate - Normally, overload resolution only
8311/// computes up to the first. Produces the FixIt set if possible.
8312void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8313                                Expr **Args, unsigned NumArgs) {
8314  assert(!Cand->Viable);
8315
8316  // Don't do anything on failures other than bad conversion.
8317  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8318
8319  // We only want the FixIts if all the arguments can be corrected.
8320  bool Unfixable = false;
8321  // Use a implicit copy initialization to check conversion fixes.
8322  Cand->Fix.setConversionChecker(TryCopyInitialization);
8323
8324  // Skip forward to the first bad conversion.
8325  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
8326  unsigned ConvCount = Cand->NumConversions;
8327  while (true) {
8328    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8329    ConvIdx++;
8330    if (Cand->Conversions[ConvIdx - 1].isBad()) {
8331      Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
8332      break;
8333    }
8334  }
8335
8336  if (ConvIdx == ConvCount)
8337    return;
8338
8339  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8340         "remaining conversion is initialized?");
8341
8342  // FIXME: this should probably be preserved from the overload
8343  // operation somehow.
8344  bool SuppressUserConversions = false;
8345
8346  const FunctionProtoType* Proto;
8347  unsigned ArgIdx = ConvIdx;
8348
8349  if (Cand->IsSurrogate) {
8350    QualType ConvType
8351      = Cand->Surrogate->getConversionType().getNonReferenceType();
8352    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8353      ConvType = ConvPtrType->getPointeeType();
8354    Proto = ConvType->getAs<FunctionProtoType>();
8355    ArgIdx--;
8356  } else if (Cand->Function) {
8357    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8358    if (isa<CXXMethodDecl>(Cand->Function) &&
8359        !isa<CXXConstructorDecl>(Cand->Function))
8360      ArgIdx--;
8361  } else {
8362    // Builtin binary operator with a bad first conversion.
8363    assert(ConvCount <= 3);
8364    for (; ConvIdx != ConvCount; ++ConvIdx)
8365      Cand->Conversions[ConvIdx]
8366        = TryCopyInitialization(S, Args[ConvIdx],
8367                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
8368                                SuppressUserConversions,
8369                                /*InOverloadResolution*/ true,
8370                                /*AllowObjCWritebackConversion=*/
8371                                  S.getLangOptions().ObjCAutoRefCount);
8372    return;
8373  }
8374
8375  // Fill in the rest of the conversions.
8376  unsigned NumArgsInProto = Proto->getNumArgs();
8377  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
8378    if (ArgIdx < NumArgsInProto) {
8379      Cand->Conversions[ConvIdx]
8380        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
8381                                SuppressUserConversions,
8382                                /*InOverloadResolution=*/true,
8383                                /*AllowObjCWritebackConversion=*/
8384                                  S.getLangOptions().ObjCAutoRefCount);
8385      // Store the FixIt in the candidate if it exists.
8386      if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
8387        Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
8388    }
8389    else
8390      Cand->Conversions[ConvIdx].setEllipsis();
8391  }
8392}
8393
8394} // end anonymous namespace
8395
8396/// PrintOverloadCandidates - When overload resolution fails, prints
8397/// diagnostic messages containing the candidates in the candidate
8398/// set.
8399void OverloadCandidateSet::NoteCandidates(Sema &S,
8400                                          OverloadCandidateDisplayKind OCD,
8401                                          Expr **Args, unsigned NumArgs,
8402                                          const char *Opc,
8403                                          SourceLocation OpLoc) {
8404  // Sort the candidates by viability and position.  Sorting directly would
8405  // be prohibitive, so we make a set of pointers and sort those.
8406  SmallVector<OverloadCandidate*, 32> Cands;
8407  if (OCD == OCD_AllCandidates) Cands.reserve(size());
8408  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
8409    if (Cand->Viable)
8410      Cands.push_back(Cand);
8411    else if (OCD == OCD_AllCandidates) {
8412      CompleteNonViableCandidate(S, Cand, Args, NumArgs);
8413      if (Cand->Function || Cand->IsSurrogate)
8414        Cands.push_back(Cand);
8415      // Otherwise, this a non-viable builtin candidate.  We do not, in general,
8416      // want to list every possible builtin candidate.
8417    }
8418  }
8419
8420  std::sort(Cands.begin(), Cands.end(),
8421            CompareOverloadCandidatesForDisplay(S));
8422
8423  bool ReportedAmbiguousConversions = false;
8424
8425  SmallVectorImpl<OverloadCandidate*>::iterator I, E;
8426  const DiagnosticsEngine::OverloadsShown ShowOverloads =
8427      S.Diags.getShowOverloads();
8428  unsigned CandsShown = 0;
8429  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8430    OverloadCandidate *Cand = *I;
8431
8432    // Set an arbitrary limit on the number of candidate functions we'll spam
8433    // the user with.  FIXME: This limit should depend on details of the
8434    // candidate list.
8435    if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
8436      break;
8437    }
8438    ++CandsShown;
8439
8440    if (Cand->Function)
8441      NoteFunctionCandidate(S, Cand, Args, NumArgs);
8442    else if (Cand->IsSurrogate)
8443      NoteSurrogateCandidate(S, Cand);
8444    else {
8445      assert(Cand->Viable &&
8446             "Non-viable built-in candidates are not added to Cands.");
8447      // Generally we only see ambiguities including viable builtin
8448      // operators if overload resolution got screwed up by an
8449      // ambiguous user-defined conversion.
8450      //
8451      // FIXME: It's quite possible for different conversions to see
8452      // different ambiguities, though.
8453      if (!ReportedAmbiguousConversions) {
8454        NoteAmbiguousUserConversions(S, OpLoc, Cand);
8455        ReportedAmbiguousConversions = true;
8456      }
8457
8458      // If this is a viable builtin, print it.
8459      NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
8460    }
8461  }
8462
8463  if (I != E)
8464    S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
8465}
8466
8467// [PossiblyAFunctionType]  -->   [Return]
8468// NonFunctionType --> NonFunctionType
8469// R (A) --> R(A)
8470// R (*)(A) --> R (A)
8471// R (&)(A) --> R (A)
8472// R (S::*)(A) --> R (A)
8473QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8474  QualType Ret = PossiblyAFunctionType;
8475  if (const PointerType *ToTypePtr =
8476    PossiblyAFunctionType->getAs<PointerType>())
8477    Ret = ToTypePtr->getPointeeType();
8478  else if (const ReferenceType *ToTypeRef =
8479    PossiblyAFunctionType->getAs<ReferenceType>())
8480    Ret = ToTypeRef->getPointeeType();
8481  else if (const MemberPointerType *MemTypePtr =
8482    PossiblyAFunctionType->getAs<MemberPointerType>())
8483    Ret = MemTypePtr->getPointeeType();
8484  Ret =
8485    Context.getCanonicalType(Ret).getUnqualifiedType();
8486  return Ret;
8487}
8488
8489// A helper class to help with address of function resolution
8490// - allows us to avoid passing around all those ugly parameters
8491class AddressOfFunctionResolver
8492{
8493  Sema& S;
8494  Expr* SourceExpr;
8495  const QualType& TargetType;
8496  QualType TargetFunctionType; // Extracted function type from target type
8497
8498  bool Complain;
8499  //DeclAccessPair& ResultFunctionAccessPair;
8500  ASTContext& Context;
8501
8502  bool TargetTypeIsNonStaticMemberFunction;
8503  bool FoundNonTemplateFunction;
8504
8505  OverloadExpr::FindResult OvlExprInfo;
8506  OverloadExpr *OvlExpr;
8507  TemplateArgumentListInfo OvlExplicitTemplateArgs;
8508  SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
8509
8510public:
8511  AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8512                            const QualType& TargetType, bool Complain)
8513    : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8514      Complain(Complain), Context(S.getASTContext()),
8515      TargetTypeIsNonStaticMemberFunction(
8516                                    !!TargetType->getAs<MemberPointerType>()),
8517      FoundNonTemplateFunction(false),
8518      OvlExprInfo(OverloadExpr::find(SourceExpr)),
8519      OvlExpr(OvlExprInfo.Expression)
8520  {
8521    ExtractUnqualifiedFunctionTypeFromTargetType();
8522
8523    if (!TargetFunctionType->isFunctionType()) {
8524      if (OvlExpr->hasExplicitTemplateArgs()) {
8525        DeclAccessPair dap;
8526        if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
8527                                            OvlExpr, false, &dap) ) {
8528
8529          if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8530            if (!Method->isStatic()) {
8531              // If the target type is a non-function type and the function
8532              // found is a non-static member function, pretend as if that was
8533              // the target, it's the only possible type to end up with.
8534              TargetTypeIsNonStaticMemberFunction = true;
8535
8536              // And skip adding the function if its not in the proper form.
8537              // We'll diagnose this due to an empty set of functions.
8538              if (!OvlExprInfo.HasFormOfMemberPointer)
8539                return;
8540            }
8541          }
8542
8543          Matches.push_back(std::make_pair(dap,Fn));
8544        }
8545      }
8546      return;
8547    }
8548
8549    if (OvlExpr->hasExplicitTemplateArgs())
8550      OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
8551
8552    if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8553      // C++ [over.over]p4:
8554      //   If more than one function is selected, [...]
8555      if (Matches.size() > 1) {
8556        if (FoundNonTemplateFunction)
8557          EliminateAllTemplateMatches();
8558        else
8559          EliminateAllExceptMostSpecializedTemplate();
8560      }
8561    }
8562  }
8563
8564private:
8565  bool isTargetTypeAFunction() const {
8566    return TargetFunctionType->isFunctionType();
8567  }
8568
8569  // [ToType]     [Return]
8570
8571  // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8572  // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8573  // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8574  void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8575    TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8576  }
8577
8578  // return true if any matching specializations were found
8579  bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8580                                   const DeclAccessPair& CurAccessFunPair) {
8581    if (CXXMethodDecl *Method
8582              = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8583      // Skip non-static function templates when converting to pointer, and
8584      // static when converting to member pointer.
8585      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8586        return false;
8587    }
8588    else if (TargetTypeIsNonStaticMemberFunction)
8589      return false;
8590
8591    // C++ [over.over]p2:
8592    //   If the name is a function template, template argument deduction is
8593    //   done (14.8.2.2), and if the argument deduction succeeds, the
8594    //   resulting template argument list is used to generate a single
8595    //   function template specialization, which is added to the set of
8596    //   overloaded functions considered.
8597    FunctionDecl *Specialization = 0;
8598    TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8599    if (Sema::TemplateDeductionResult Result
8600          = S.DeduceTemplateArguments(FunctionTemplate,
8601                                      &OvlExplicitTemplateArgs,
8602                                      TargetFunctionType, Specialization,
8603                                      Info)) {
8604      // FIXME: make a note of the failed deduction for diagnostics.
8605      (void)Result;
8606      return false;
8607    }
8608
8609    // Template argument deduction ensures that we have an exact match.
8610    // This function template specicalization works.
8611    Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8612    assert(TargetFunctionType
8613                      == Context.getCanonicalType(Specialization->getType()));
8614    Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8615    return true;
8616  }
8617
8618  bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8619                                      const DeclAccessPair& CurAccessFunPair) {
8620    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8621      // Skip non-static functions when converting to pointer, and static
8622      // when converting to member pointer.
8623      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8624        return false;
8625    }
8626    else if (TargetTypeIsNonStaticMemberFunction)
8627      return false;
8628
8629    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
8630      if (S.getLangOptions().CUDA)
8631        if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8632          if (S.CheckCUDATarget(Caller, FunDecl))
8633            return false;
8634
8635      QualType ResultTy;
8636      if (Context.hasSameUnqualifiedType(TargetFunctionType,
8637                                         FunDecl->getType()) ||
8638          S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8639                                 ResultTy)) {
8640        Matches.push_back(std::make_pair(CurAccessFunPair,
8641          cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
8642        FoundNonTemplateFunction = true;
8643        return true;
8644      }
8645    }
8646
8647    return false;
8648  }
8649
8650  bool FindAllFunctionsThatMatchTargetTypeExactly() {
8651    bool Ret = false;
8652
8653    // If the overload expression doesn't have the form of a pointer to
8654    // member, don't try to convert it to a pointer-to-member type.
8655    if (IsInvalidFormOfPointerToMemberFunction())
8656      return false;
8657
8658    for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8659                               E = OvlExpr->decls_end();
8660         I != E; ++I) {
8661      // Look through any using declarations to find the underlying function.
8662      NamedDecl *Fn = (*I)->getUnderlyingDecl();
8663
8664      // C++ [over.over]p3:
8665      //   Non-member functions and static member functions match
8666      //   targets of type "pointer-to-function" or "reference-to-function."
8667      //   Nonstatic member functions match targets of
8668      //   type "pointer-to-member-function."
8669      // Note that according to DR 247, the containing class does not matter.
8670      if (FunctionTemplateDecl *FunctionTemplate
8671                                        = dyn_cast<FunctionTemplateDecl>(Fn)) {
8672        if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8673          Ret = true;
8674      }
8675      // If we have explicit template arguments supplied, skip non-templates.
8676      else if (!OvlExpr->hasExplicitTemplateArgs() &&
8677               AddMatchingNonTemplateFunction(Fn, I.getPair()))
8678        Ret = true;
8679    }
8680    assert(Ret || Matches.empty());
8681    return Ret;
8682  }
8683
8684  void EliminateAllExceptMostSpecializedTemplate() {
8685    //   [...] and any given function template specialization F1 is
8686    //   eliminated if the set contains a second function template
8687    //   specialization whose function template is more specialized
8688    //   than the function template of F1 according to the partial
8689    //   ordering rules of 14.5.5.2.
8690
8691    // The algorithm specified above is quadratic. We instead use a
8692    // two-pass algorithm (similar to the one used to identify the
8693    // best viable function in an overload set) that identifies the
8694    // best function template (if it exists).
8695
8696    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8697    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8698      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
8699
8700    UnresolvedSetIterator Result =
8701      S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8702                           TPOC_Other, 0, SourceExpr->getLocStart(),
8703                           S.PDiag(),
8704                           S.PDiag(diag::err_addr_ovl_ambiguous)
8705                             << Matches[0].second->getDeclName(),
8706                           S.PDiag(diag::note_ovl_candidate)
8707                             << (unsigned) oc_function_template,
8708                           Complain, TargetFunctionType);
8709
8710    if (Result != MatchesCopy.end()) {
8711      // Make it the first and only element
8712      Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8713      Matches[0].second = cast<FunctionDecl>(*Result);
8714      Matches.resize(1);
8715    }
8716  }
8717
8718  void EliminateAllTemplateMatches() {
8719    //   [...] any function template specializations in the set are
8720    //   eliminated if the set also contains a non-template function, [...]
8721    for (unsigned I = 0, N = Matches.size(); I != N; ) {
8722      if (Matches[I].second->getPrimaryTemplate() == 0)
8723        ++I;
8724      else {
8725        Matches[I] = Matches[--N];
8726        Matches.set_size(N);
8727      }
8728    }
8729  }
8730
8731public:
8732  void ComplainNoMatchesFound() const {
8733    assert(Matches.empty());
8734    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8735        << OvlExpr->getName() << TargetFunctionType
8736        << OvlExpr->getSourceRange();
8737    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
8738  }
8739
8740  bool IsInvalidFormOfPointerToMemberFunction() const {
8741    return TargetTypeIsNonStaticMemberFunction &&
8742      !OvlExprInfo.HasFormOfMemberPointer;
8743  }
8744
8745  void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8746      // TODO: Should we condition this on whether any functions might
8747      // have matched, or is it more appropriate to do that in callers?
8748      // TODO: a fixit wouldn't hurt.
8749      S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8750        << TargetType << OvlExpr->getSourceRange();
8751  }
8752
8753  void ComplainOfInvalidConversion() const {
8754    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8755      << OvlExpr->getName() << TargetType;
8756  }
8757
8758  void ComplainMultipleMatchesFound() const {
8759    assert(Matches.size() > 1);
8760    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8761      << OvlExpr->getName()
8762      << OvlExpr->getSourceRange();
8763    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
8764  }
8765
8766  bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8767
8768  int getNumMatches() const { return Matches.size(); }
8769
8770  FunctionDecl* getMatchingFunctionDecl() const {
8771    if (Matches.size() != 1) return 0;
8772    return Matches[0].second;
8773  }
8774
8775  const DeclAccessPair* getMatchingFunctionAccessPair() const {
8776    if (Matches.size() != 1) return 0;
8777    return &Matches[0].first;
8778  }
8779};
8780
8781/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8782/// an overloaded function (C++ [over.over]), where @p From is an
8783/// expression with overloaded function type and @p ToType is the type
8784/// we're trying to resolve to. For example:
8785///
8786/// @code
8787/// int f(double);
8788/// int f(int);
8789///
8790/// int (*pfd)(double) = f; // selects f(double)
8791/// @endcode
8792///
8793/// This routine returns the resulting FunctionDecl if it could be
8794/// resolved, and NULL otherwise. When @p Complain is true, this
8795/// routine will emit diagnostics if there is an error.
8796FunctionDecl *
8797Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8798                                         QualType TargetType,
8799                                         bool Complain,
8800                                         DeclAccessPair &FoundResult,
8801                                         bool *pHadMultipleCandidates) {
8802  assert(AddressOfExpr->getType() == Context.OverloadTy);
8803
8804  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8805                                     Complain);
8806  int NumMatches = Resolver.getNumMatches();
8807  FunctionDecl* Fn = 0;
8808  if (NumMatches == 0 && Complain) {
8809    if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8810      Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8811    else
8812      Resolver.ComplainNoMatchesFound();
8813  }
8814  else if (NumMatches > 1 && Complain)
8815    Resolver.ComplainMultipleMatchesFound();
8816  else if (NumMatches == 1) {
8817    Fn = Resolver.getMatchingFunctionDecl();
8818    assert(Fn);
8819    FoundResult = *Resolver.getMatchingFunctionAccessPair();
8820    MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
8821    if (Complain)
8822      CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
8823  }
8824
8825  if (pHadMultipleCandidates)
8826    *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
8827  return Fn;
8828}
8829
8830/// \brief Given an expression that refers to an overloaded function, try to
8831/// resolve that overloaded function expression down to a single function.
8832///
8833/// This routine can only resolve template-ids that refer to a single function
8834/// template, where that template-id refers to a single template whose template
8835/// arguments are either provided by the template-id or have defaults,
8836/// as described in C++0x [temp.arg.explicit]p3.
8837FunctionDecl *
8838Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8839                                                  bool Complain,
8840                                                  DeclAccessPair *FoundResult) {
8841  // C++ [over.over]p1:
8842  //   [...] [Note: any redundant set of parentheses surrounding the
8843  //   overloaded function name is ignored (5.1). ]
8844  // C++ [over.over]p1:
8845  //   [...] The overloaded function name can be preceded by the &
8846  //   operator.
8847
8848  // If we didn't actually find any template-ids, we're done.
8849  if (!ovl->hasExplicitTemplateArgs())
8850    return 0;
8851
8852  TemplateArgumentListInfo ExplicitTemplateArgs;
8853  ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
8854
8855  // Look through all of the overloaded functions, searching for one
8856  // whose type matches exactly.
8857  FunctionDecl *Matched = 0;
8858  for (UnresolvedSetIterator I = ovl->decls_begin(),
8859         E = ovl->decls_end(); I != E; ++I) {
8860    // C++0x [temp.arg.explicit]p3:
8861    //   [...] In contexts where deduction is done and fails, or in contexts
8862    //   where deduction is not done, if a template argument list is
8863    //   specified and it, along with any default template arguments,
8864    //   identifies a single function template specialization, then the
8865    //   template-id is an lvalue for the function template specialization.
8866    FunctionTemplateDecl *FunctionTemplate
8867      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
8868
8869    // C++ [over.over]p2:
8870    //   If the name is a function template, template argument deduction is
8871    //   done (14.8.2.2), and if the argument deduction succeeds, the
8872    //   resulting template argument list is used to generate a single
8873    //   function template specialization, which is added to the set of
8874    //   overloaded functions considered.
8875    FunctionDecl *Specialization = 0;
8876    TemplateDeductionInfo Info(Context, ovl->getNameLoc());
8877    if (TemplateDeductionResult Result
8878          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8879                                    Specialization, Info)) {
8880      // FIXME: make a note of the failed deduction for diagnostics.
8881      (void)Result;
8882      continue;
8883    }
8884
8885    assert(Specialization && "no specialization and no error?");
8886
8887    // Multiple matches; we can't resolve to a single declaration.
8888    if (Matched) {
8889      if (Complain) {
8890        Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8891          << ovl->getName();
8892        NoteAllOverloadCandidates(ovl);
8893      }
8894      return 0;
8895    }
8896
8897    Matched = Specialization;
8898    if (FoundResult) *FoundResult = I.getPair();
8899  }
8900
8901  return Matched;
8902}
8903
8904
8905
8906
8907// Resolve and fix an overloaded expression that can be resolved
8908// because it identifies a single function template specialization.
8909//
8910// Last three arguments should only be supplied if Complain = true
8911//
8912// Return true if it was logically possible to so resolve the
8913// expression, regardless of whether or not it succeeded.  Always
8914// returns true if 'complain' is set.
8915bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8916                      ExprResult &SrcExpr, bool doFunctionPointerConverion,
8917                   bool complain, const SourceRange& OpRangeForComplaining,
8918                                           QualType DestTypeForComplaining,
8919                                            unsigned DiagIDForComplaining) {
8920  assert(SrcExpr.get()->getType() == Context.OverloadTy);
8921
8922  OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
8923
8924  DeclAccessPair found;
8925  ExprResult SingleFunctionExpression;
8926  if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8927                           ovl.Expression, /*complain*/ false, &found)) {
8928    if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8929      SrcExpr = ExprError();
8930      return true;
8931    }
8932
8933    // It is only correct to resolve to an instance method if we're
8934    // resolving a form that's permitted to be a pointer to member.
8935    // Otherwise we'll end up making a bound member expression, which
8936    // is illegal in all the contexts we resolve like this.
8937    if (!ovl.HasFormOfMemberPointer &&
8938        isa<CXXMethodDecl>(fn) &&
8939        cast<CXXMethodDecl>(fn)->isInstance()) {
8940      if (!complain) return false;
8941
8942      Diag(ovl.Expression->getExprLoc(),
8943           diag::err_bound_member_function)
8944        << 0 << ovl.Expression->getSourceRange();
8945
8946      // TODO: I believe we only end up here if there's a mix of
8947      // static and non-static candidates (otherwise the expression
8948      // would have 'bound member' type, not 'overload' type).
8949      // Ideally we would note which candidate was chosen and why
8950      // the static candidates were rejected.
8951      SrcExpr = ExprError();
8952      return true;
8953    }
8954
8955    // Fix the expresion to refer to 'fn'.
8956    SingleFunctionExpression =
8957      Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
8958
8959    // If desired, do function-to-pointer decay.
8960    if (doFunctionPointerConverion) {
8961      SingleFunctionExpression =
8962        DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
8963      if (SingleFunctionExpression.isInvalid()) {
8964        SrcExpr = ExprError();
8965        return true;
8966      }
8967    }
8968  }
8969
8970  if (!SingleFunctionExpression.isUsable()) {
8971    if (complain) {
8972      Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8973        << ovl.Expression->getName()
8974        << DestTypeForComplaining
8975        << OpRangeForComplaining
8976        << ovl.Expression->getQualifierLoc().getSourceRange();
8977      NoteAllOverloadCandidates(SrcExpr.get());
8978
8979      SrcExpr = ExprError();
8980      return true;
8981    }
8982
8983    return false;
8984  }
8985
8986  SrcExpr = SingleFunctionExpression;
8987  return true;
8988}
8989
8990/// \brief Add a single candidate to the overload set.
8991static void AddOverloadedCallCandidate(Sema &S,
8992                                       DeclAccessPair FoundDecl,
8993                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
8994                                       Expr **Args, unsigned NumArgs,
8995                                       OverloadCandidateSet &CandidateSet,
8996                                       bool PartialOverloading,
8997                                       bool KnownValid) {
8998  NamedDecl *Callee = FoundDecl.getDecl();
8999  if (isa<UsingShadowDecl>(Callee))
9000    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9001
9002  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9003    if (ExplicitTemplateArgs) {
9004      assert(!KnownValid && "Explicit template arguments?");
9005      return;
9006    }
9007    S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
9008                           false, PartialOverloading);
9009    return;
9010  }
9011
9012  if (FunctionTemplateDecl *FuncTemplate
9013      = dyn_cast<FunctionTemplateDecl>(Callee)) {
9014    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9015                                   ExplicitTemplateArgs,
9016                                   Args, NumArgs, CandidateSet);
9017    return;
9018  }
9019
9020  assert(!KnownValid && "unhandled case in overloaded call candidate");
9021}
9022
9023/// \brief Add the overload candidates named by callee and/or found by argument
9024/// dependent lookup to the given overload set.
9025void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9026                                       Expr **Args, unsigned NumArgs,
9027                                       OverloadCandidateSet &CandidateSet,
9028                                       bool PartialOverloading) {
9029
9030#ifndef NDEBUG
9031  // Verify that ArgumentDependentLookup is consistent with the rules
9032  // in C++0x [basic.lookup.argdep]p3:
9033  //
9034  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9035  //   and let Y be the lookup set produced by argument dependent
9036  //   lookup (defined as follows). If X contains
9037  //
9038  //     -- a declaration of a class member, or
9039  //
9040  //     -- a block-scope function declaration that is not a
9041  //        using-declaration, or
9042  //
9043  //     -- a declaration that is neither a function or a function
9044  //        template
9045  //
9046  //   then Y is empty.
9047
9048  if (ULE->requiresADL()) {
9049    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9050           E = ULE->decls_end(); I != E; ++I) {
9051      assert(!(*I)->getDeclContext()->isRecord());
9052      assert(isa<UsingShadowDecl>(*I) ||
9053             !(*I)->getDeclContext()->isFunctionOrMethod());
9054      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9055    }
9056  }
9057#endif
9058
9059  // It would be nice to avoid this copy.
9060  TemplateArgumentListInfo TABuffer;
9061  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9062  if (ULE->hasExplicitTemplateArgs()) {
9063    ULE->copyTemplateArgumentsInto(TABuffer);
9064    ExplicitTemplateArgs = &TABuffer;
9065  }
9066
9067  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9068         E = ULE->decls_end(); I != E; ++I)
9069    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
9070                               Args, NumArgs, CandidateSet,
9071                               PartialOverloading, /*KnownValid*/ true);
9072
9073  if (ULE->requiresADL())
9074    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9075                                         Args, NumArgs,
9076                                         ExplicitTemplateArgs,
9077                                         CandidateSet,
9078                                         PartialOverloading,
9079                                         ULE->isStdAssociatedNamespace());
9080}
9081
9082/// Attempt to recover from an ill-formed use of a non-dependent name in a
9083/// template, where the non-dependent name was declared after the template
9084/// was defined. This is common in code written for a compilers which do not
9085/// correctly implement two-stage name lookup.
9086///
9087/// Returns true if a viable candidate was found and a diagnostic was issued.
9088static bool
9089DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9090                       const CXXScopeSpec &SS, LookupResult &R,
9091                       TemplateArgumentListInfo *ExplicitTemplateArgs,
9092                       Expr **Args, unsigned NumArgs) {
9093  if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9094    return false;
9095
9096  for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9097    SemaRef.LookupQualifiedName(R, DC);
9098
9099    if (!R.empty()) {
9100      R.suppressDiagnostics();
9101
9102      if (isa<CXXRecordDecl>(DC)) {
9103        // Don't diagnose names we find in classes; we get much better
9104        // diagnostics for these from DiagnoseEmptyLookup.
9105        R.clear();
9106        return false;
9107      }
9108
9109      OverloadCandidateSet Candidates(FnLoc);
9110      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9111        AddOverloadedCallCandidate(SemaRef, I.getPair(),
9112                                   ExplicitTemplateArgs, Args, NumArgs,
9113                                   Candidates, false, /*KnownValid*/ false);
9114
9115      OverloadCandidateSet::iterator Best;
9116      if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9117        // No viable functions. Don't bother the user with notes for functions
9118        // which don't work and shouldn't be found anyway.
9119        R.clear();
9120        return false;
9121      }
9122
9123      // Find the namespaces where ADL would have looked, and suggest
9124      // declaring the function there instead.
9125      Sema::AssociatedNamespaceSet AssociatedNamespaces;
9126      Sema::AssociatedClassSet AssociatedClasses;
9127      SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
9128                                                 AssociatedNamespaces,
9129                                                 AssociatedClasses);
9130      // Never suggest declaring a function within namespace 'std'.
9131      Sema::AssociatedNamespaceSet SuggestedNamespaces;
9132      if (DeclContext *Std = SemaRef.getStdNamespace()) {
9133        for (Sema::AssociatedNamespaceSet::iterator
9134               it = AssociatedNamespaces.begin(),
9135               end = AssociatedNamespaces.end(); it != end; ++it) {
9136          if (!Std->Encloses(*it))
9137            SuggestedNamespaces.insert(*it);
9138        }
9139      } else {
9140        // Lacking the 'std::' namespace, use all of the associated namespaces.
9141        SuggestedNamespaces = AssociatedNamespaces;
9142      }
9143
9144      SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9145        << R.getLookupName();
9146      if (SuggestedNamespaces.empty()) {
9147        SemaRef.Diag(Best->Function->getLocation(),
9148                     diag::note_not_found_by_two_phase_lookup)
9149          << R.getLookupName() << 0;
9150      } else if (SuggestedNamespaces.size() == 1) {
9151        SemaRef.Diag(Best->Function->getLocation(),
9152                     diag::note_not_found_by_two_phase_lookup)
9153          << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
9154      } else {
9155        // FIXME: It would be useful to list the associated namespaces here,
9156        // but the diagnostics infrastructure doesn't provide a way to produce
9157        // a localized representation of a list of items.
9158        SemaRef.Diag(Best->Function->getLocation(),
9159                     diag::note_not_found_by_two_phase_lookup)
9160          << R.getLookupName() << 2;
9161      }
9162
9163      // Try to recover by calling this function.
9164      return true;
9165    }
9166
9167    R.clear();
9168  }
9169
9170  return false;
9171}
9172
9173/// Attempt to recover from ill-formed use of a non-dependent operator in a
9174/// template, where the non-dependent operator was declared after the template
9175/// was defined.
9176///
9177/// Returns true if a viable candidate was found and a diagnostic was issued.
9178static bool
9179DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9180                               SourceLocation OpLoc,
9181                               Expr **Args, unsigned NumArgs) {
9182  DeclarationName OpName =
9183    SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9184  LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9185  return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9186                                /*ExplicitTemplateArgs=*/0, Args, NumArgs);
9187}
9188
9189namespace {
9190// Callback to limit the allowed keywords and to only accept typo corrections
9191// that are keywords or whose decls refer to functions (or template functions)
9192// that accept the given number of arguments.
9193class RecoveryCallCCC : public CorrectionCandidateCallback {
9194 public:
9195  RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9196      : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9197    WantTypeSpecifiers = SemaRef.getLangOptions().CPlusPlus;
9198    WantRemainingKeywords = false;
9199  }
9200
9201  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9202    if (!candidate.getCorrectionDecl())
9203      return candidate.isKeyword();
9204
9205    for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9206           DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9207      FunctionDecl *FD = 0;
9208      NamedDecl *ND = (*DI)->getUnderlyingDecl();
9209      if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9210        FD = FTD->getTemplatedDecl();
9211      if (!HasExplicitTemplateArgs && !FD) {
9212        if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9213          // If the Decl is neither a function nor a template function,
9214          // determine if it is a pointer or reference to a function. If so,
9215          // check against the number of arguments expected for the pointee.
9216          QualType ValType = cast<ValueDecl>(ND)->getType();
9217          if (ValType->isAnyPointerType() || ValType->isReferenceType())
9218            ValType = ValType->getPointeeType();
9219          if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9220            if (FPT->getNumArgs() == NumArgs)
9221              return true;
9222        }
9223      }
9224      if (FD && FD->getNumParams() >= NumArgs &&
9225          FD->getMinRequiredArguments() <= NumArgs)
9226        return true;
9227    }
9228    return false;
9229  }
9230
9231 private:
9232  unsigned NumArgs;
9233  bool HasExplicitTemplateArgs;
9234};
9235
9236// Callback that effectively disabled typo correction
9237class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9238 public:
9239  NoTypoCorrectionCCC() {
9240    WantTypeSpecifiers = false;
9241    WantExpressionKeywords = false;
9242    WantCXXNamedCasts = false;
9243    WantRemainingKeywords = false;
9244  }
9245
9246  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9247    return false;
9248  }
9249};
9250}
9251
9252/// Attempts to recover from a call where no functions were found.
9253///
9254/// Returns true if new candidates were found.
9255static ExprResult
9256BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9257                      UnresolvedLookupExpr *ULE,
9258                      SourceLocation LParenLoc,
9259                      Expr **Args, unsigned NumArgs,
9260                      SourceLocation RParenLoc,
9261                      bool EmptyLookup, bool AllowTypoCorrection) {
9262
9263  CXXScopeSpec SS;
9264  SS.Adopt(ULE->getQualifierLoc());
9265  SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
9266
9267  TemplateArgumentListInfo TABuffer;
9268  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9269  if (ULE->hasExplicitTemplateArgs()) {
9270    ULE->copyTemplateArgumentsInto(TABuffer);
9271    ExplicitTemplateArgs = &TABuffer;
9272  }
9273
9274  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9275                 Sema::LookupOrdinaryName);
9276  RecoveryCallCCC Validator(SemaRef, NumArgs, ExplicitTemplateArgs != 0);
9277  NoTypoCorrectionCCC RejectAll;
9278  CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9279      (CorrectionCandidateCallback*)&Validator :
9280      (CorrectionCandidateCallback*)&RejectAll;
9281  if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9282                              ExplicitTemplateArgs, Args, NumArgs) &&
9283      (!EmptyLookup ||
9284       SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
9285                                   ExplicitTemplateArgs, Args, NumArgs)))
9286    return ExprError();
9287
9288  assert(!R.empty() && "lookup results empty despite recovery");
9289
9290  // Build an implicit member call if appropriate.  Just drop the
9291  // casts and such from the call, we don't really care.
9292  ExprResult NewFn = ExprError();
9293  if ((*R.begin())->isCXXClassMember())
9294    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9295                                                    R, ExplicitTemplateArgs);
9296  else if (ExplicitTemplateArgs)
9297    NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
9298                                        *ExplicitTemplateArgs);
9299  else
9300    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9301
9302  if (NewFn.isInvalid())
9303    return ExprError();
9304
9305  // This shouldn't cause an infinite loop because we're giving it
9306  // an expression with viable lookup results, which should never
9307  // end up here.
9308  return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
9309                               MultiExprArg(Args, NumArgs), RParenLoc);
9310}
9311
9312/// ResolveOverloadedCallFn - Given the call expression that calls Fn
9313/// (which eventually refers to the declaration Func) and the call
9314/// arguments Args/NumArgs, attempt to resolve the function call down
9315/// to a specific function. If overload resolution succeeds, returns
9316/// the function declaration produced by overload
9317/// resolution. Otherwise, emits diagnostics, deletes all of the
9318/// arguments and Fn, and returns NULL.
9319ExprResult
9320Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
9321                              SourceLocation LParenLoc,
9322                              Expr **Args, unsigned NumArgs,
9323                              SourceLocation RParenLoc,
9324                              Expr *ExecConfig,
9325                              bool AllowTypoCorrection) {
9326#ifndef NDEBUG
9327  if (ULE->requiresADL()) {
9328    // To do ADL, we must have found an unqualified name.
9329    assert(!ULE->getQualifier() && "qualified name with ADL");
9330
9331    // We don't perform ADL for implicit declarations of builtins.
9332    // Verify that this was correctly set up.
9333    FunctionDecl *F;
9334    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9335        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9336        F->getBuiltinID() && F->isImplicit())
9337      llvm_unreachable("performing ADL for builtin");
9338
9339    // We don't perform ADL in C.
9340    assert(getLangOptions().CPlusPlus && "ADL enabled in C");
9341  } else
9342    assert(!ULE->isStdAssociatedNamespace() &&
9343           "std is associated namespace but not doing ADL");
9344#endif
9345
9346  UnbridgedCastsSet UnbridgedCasts;
9347  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9348    return ExprError();
9349
9350  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9351
9352  // Add the functions denoted by the callee to the set of candidate
9353  // functions, including those from argument-dependent lookup.
9354  AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
9355
9356  // If we found nothing, try to recover.
9357  // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9358  // out if it fails.
9359  if (CandidateSet.empty()) {
9360    // In Microsoft mode, if we are inside a template class member function then
9361    // create a type dependent CallExpr. The goal is to postpone name lookup
9362    // to instantiation time to be able to search into type dependent base
9363    // classes.
9364    if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
9365        (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
9366      CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9367                                          Context.DependentTy, VK_RValue,
9368                                          RParenLoc);
9369      CE->setTypeDependent(true);
9370      return Owned(CE);
9371    }
9372    return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9373                                 RParenLoc, /*EmptyLookup=*/true,
9374                                 AllowTypoCorrection);
9375  }
9376
9377  UnbridgedCasts.restore();
9378
9379  OverloadCandidateSet::iterator Best;
9380  switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
9381  case OR_Success: {
9382    FunctionDecl *FDecl = Best->Function;
9383    MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9384    CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
9385    DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9386    Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9387    return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9388                                 ExecConfig);
9389  }
9390
9391  case OR_No_Viable_Function: {
9392    // Try to recover by looking for viable functions which the user might
9393    // have meant to call.
9394    ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9395                                                Args, NumArgs, RParenLoc,
9396                                                /*EmptyLookup=*/false,
9397                                                AllowTypoCorrection);
9398    if (!Recovery.isInvalid())
9399      return Recovery;
9400
9401    Diag(Fn->getSourceRange().getBegin(),
9402         diag::err_ovl_no_viable_function_in_call)
9403      << ULE->getName() << Fn->getSourceRange();
9404    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
9405    break;
9406  }
9407
9408  case OR_Ambiguous:
9409    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
9410      << ULE->getName() << Fn->getSourceRange();
9411    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
9412    break;
9413
9414  case OR_Deleted:
9415    {
9416      Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
9417        << Best->Function->isDeleted()
9418        << ULE->getName()
9419        << getDeletedOrUnavailableSuffix(Best->Function)
9420        << Fn->getSourceRange();
9421      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
9422
9423      // We emitted an error for the unvailable/deleted function call but keep
9424      // the call in the AST.
9425      FunctionDecl *FDecl = Best->Function;
9426      Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9427      return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9428                                   RParenLoc, ExecConfig);
9429    }
9430  }
9431
9432  // Overload resolution failed.
9433  return ExprError();
9434}
9435
9436static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
9437  return Functions.size() > 1 ||
9438    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9439}
9440
9441/// \brief Create a unary operation that may resolve to an overloaded
9442/// operator.
9443///
9444/// \param OpLoc The location of the operator itself (e.g., '*').
9445///
9446/// \param OpcIn The UnaryOperator::Opcode that describes this
9447/// operator.
9448///
9449/// \param Functions The set of non-member functions that will be
9450/// considered by overload resolution. The caller needs to build this
9451/// set based on the context using, e.g.,
9452/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9453/// set should not contain any member functions; those will be added
9454/// by CreateOverloadedUnaryOp().
9455///
9456/// \param input The input argument.
9457ExprResult
9458Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9459                              const UnresolvedSetImpl &Fns,
9460                              Expr *Input) {
9461  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
9462
9463  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9464  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9465  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9466  // TODO: provide better source location info.
9467  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
9468
9469  if (checkPlaceholderForOverload(*this, Input))
9470    return ExprError();
9471
9472  Expr *Args[2] = { Input, 0 };
9473  unsigned NumArgs = 1;
9474
9475  // For post-increment and post-decrement, add the implicit '0' as
9476  // the second argument, so that we know this is a post-increment or
9477  // post-decrement.
9478  if (Opc == UO_PostInc || Opc == UO_PostDec) {
9479    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
9480    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9481                                     SourceLocation());
9482    NumArgs = 2;
9483  }
9484
9485  if (Input->isTypeDependent()) {
9486    if (Fns.empty())
9487      return Owned(new (Context) UnaryOperator(Input,
9488                                               Opc,
9489                                               Context.DependentTy,
9490                                               VK_RValue, OK_Ordinary,
9491                                               OpLoc));
9492
9493    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
9494    UnresolvedLookupExpr *Fn
9495      = UnresolvedLookupExpr::Create(Context, NamingClass,
9496                                     NestedNameSpecifierLoc(), OpNameInfo,
9497                                     /*ADL*/ true, IsOverloaded(Fns),
9498                                     Fns.begin(), Fns.end());
9499    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
9500                                                  &Args[0], NumArgs,
9501                                                   Context.DependentTy,
9502                                                   VK_RValue,
9503                                                   OpLoc));
9504  }
9505
9506  // Build an empty overload set.
9507  OverloadCandidateSet CandidateSet(OpLoc);
9508
9509  // Add the candidates from the given function set.
9510  AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
9511
9512  // Add operator candidates that are member functions.
9513  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9514
9515  // Add candidates from ADL.
9516  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9517                                       Args, NumArgs,
9518                                       /*ExplicitTemplateArgs*/ 0,
9519                                       CandidateSet);
9520
9521  // Add builtin operator candidates.
9522  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9523
9524  bool HadMultipleCandidates = (CandidateSet.size() > 1);
9525
9526  // Perform overload resolution.
9527  OverloadCandidateSet::iterator Best;
9528  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
9529  case OR_Success: {
9530    // We found a built-in operator or an overloaded operator.
9531    FunctionDecl *FnDecl = Best->Function;
9532
9533    if (FnDecl) {
9534      // We matched an overloaded operator. Build a call to that
9535      // operator.
9536
9537      MarkFunctionReferenced(OpLoc, FnDecl);
9538
9539      // Convert the arguments.
9540      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
9541        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
9542
9543        ExprResult InputRes =
9544          PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9545                                              Best->FoundDecl, Method);
9546        if (InputRes.isInvalid())
9547          return ExprError();
9548        Input = InputRes.take();
9549      } else {
9550        // Convert the arguments.
9551        ExprResult InputInit
9552          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
9553                                                      Context,
9554                                                      FnDecl->getParamDecl(0)),
9555                                      SourceLocation(),
9556                                      Input);
9557        if (InputInit.isInvalid())
9558          return ExprError();
9559        Input = InputInit.take();
9560      }
9561
9562      DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9563
9564      // Determine the result type.
9565      QualType ResultTy = FnDecl->getResultType();
9566      ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9567      ResultTy = ResultTy.getNonLValueExprType(Context);
9568
9569      // Build the actual expression node.
9570      ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9571                                                HadMultipleCandidates);
9572      if (FnExpr.isInvalid())
9573        return ExprError();
9574
9575      Args[0] = Input;
9576      CallExpr *TheCall =
9577        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
9578                                          Args, NumArgs, ResultTy, VK, OpLoc);
9579
9580      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
9581                              FnDecl))
9582        return ExprError();
9583
9584      return MaybeBindToTemporary(TheCall);
9585    } else {
9586      // We matched a built-in operator. Convert the arguments, then
9587      // break out so that we will build the appropriate built-in
9588      // operator node.
9589      ExprResult InputRes =
9590        PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9591                                  Best->Conversions[0], AA_Passing);
9592      if (InputRes.isInvalid())
9593        return ExprError();
9594      Input = InputRes.take();
9595      break;
9596    }
9597  }
9598
9599  case OR_No_Viable_Function:
9600    // This is an erroneous use of an operator which can be overloaded by
9601    // a non-member function. Check for non-member operators which were
9602    // defined too late to be candidates.
9603    if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9604      // FIXME: Recover by calling the found function.
9605      return ExprError();
9606
9607    // No viable function; fall through to handling this as a
9608    // built-in operator, which will produce an error message for us.
9609    break;
9610
9611  case OR_Ambiguous:
9612    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
9613        << UnaryOperator::getOpcodeStr(Opc)
9614        << Input->getType()
9615        << Input->getSourceRange();
9616    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
9617                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
9618    return ExprError();
9619
9620  case OR_Deleted:
9621    Diag(OpLoc, diag::err_ovl_deleted_oper)
9622      << Best->Function->isDeleted()
9623      << UnaryOperator::getOpcodeStr(Opc)
9624      << getDeletedOrUnavailableSuffix(Best->Function)
9625      << Input->getSourceRange();
9626    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9627                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
9628    return ExprError();
9629  }
9630
9631  // Either we found no viable overloaded operator or we matched a
9632  // built-in operator. In either case, fall through to trying to
9633  // build a built-in operation.
9634  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9635}
9636
9637/// \brief Create a binary operation that may resolve to an overloaded
9638/// operator.
9639///
9640/// \param OpLoc The location of the operator itself (e.g., '+').
9641///
9642/// \param OpcIn The BinaryOperator::Opcode that describes this
9643/// operator.
9644///
9645/// \param Functions The set of non-member functions that will be
9646/// considered by overload resolution. The caller needs to build this
9647/// set based on the context using, e.g.,
9648/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9649/// set should not contain any member functions; those will be added
9650/// by CreateOverloadedBinOp().
9651///
9652/// \param LHS Left-hand argument.
9653/// \param RHS Right-hand argument.
9654ExprResult
9655Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
9656                            unsigned OpcIn,
9657                            const UnresolvedSetImpl &Fns,
9658                            Expr *LHS, Expr *RHS) {
9659  Expr *Args[2] = { LHS, RHS };
9660  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
9661
9662  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9663  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9664  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9665
9666  // If either side is type-dependent, create an appropriate dependent
9667  // expression.
9668  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9669    if (Fns.empty()) {
9670      // If there are no functions to store, just build a dependent
9671      // BinaryOperator or CompoundAssignment.
9672      if (Opc <= BO_Assign || Opc > BO_OrAssign)
9673        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
9674                                                  Context.DependentTy,
9675                                                  VK_RValue, OK_Ordinary,
9676                                                  OpLoc));
9677
9678      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9679                                                        Context.DependentTy,
9680                                                        VK_LValue,
9681                                                        OK_Ordinary,
9682                                                        Context.DependentTy,
9683                                                        Context.DependentTy,
9684                                                        OpLoc));
9685    }
9686
9687    // FIXME: save results of ADL from here?
9688    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
9689    // TODO: provide better source location info in DNLoc component.
9690    DeclarationNameInfo OpNameInfo(OpName, OpLoc);
9691    UnresolvedLookupExpr *Fn
9692      = UnresolvedLookupExpr::Create(Context, NamingClass,
9693                                     NestedNameSpecifierLoc(), OpNameInfo,
9694                                     /*ADL*/ true, IsOverloaded(Fns),
9695                                     Fns.begin(), Fns.end());
9696    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
9697                                                   Args, 2,
9698                                                   Context.DependentTy,
9699                                                   VK_RValue,
9700                                                   OpLoc));
9701  }
9702
9703  // Always do placeholder-like conversions on the RHS.
9704  if (checkPlaceholderForOverload(*this, Args[1]))
9705    return ExprError();
9706
9707  // Do placeholder-like conversion on the LHS; note that we should
9708  // not get here with a PseudoObject LHS.
9709  assert(Args[0]->getObjectKind() != OK_ObjCProperty);
9710  if (checkPlaceholderForOverload(*this, Args[0]))
9711    return ExprError();
9712
9713  // If this is the assignment operator, we only perform overload resolution
9714  // if the left-hand side is a class or enumeration type. This is actually
9715  // a hack. The standard requires that we do overload resolution between the
9716  // various built-in candidates, but as DR507 points out, this can lead to
9717  // problems. So we do it this way, which pretty much follows what GCC does.
9718  // Note that we go the traditional code path for compound assignment forms.
9719  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
9720    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9721
9722  // If this is the .* operator, which is not overloadable, just
9723  // create a built-in binary operator.
9724  if (Opc == BO_PtrMemD)
9725    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9726
9727  // Build an empty overload set.
9728  OverloadCandidateSet CandidateSet(OpLoc);
9729
9730  // Add the candidates from the given function set.
9731  AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
9732
9733  // Add operator candidates that are member functions.
9734  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9735
9736  // Add candidates from ADL.
9737  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9738                                       Args, 2,
9739                                       /*ExplicitTemplateArgs*/ 0,
9740                                       CandidateSet);
9741
9742  // Add builtin operator candidates.
9743  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9744
9745  bool HadMultipleCandidates = (CandidateSet.size() > 1);
9746
9747  // Perform overload resolution.
9748  OverloadCandidateSet::iterator Best;
9749  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
9750    case OR_Success: {
9751      // We found a built-in operator or an overloaded operator.
9752      FunctionDecl *FnDecl = Best->Function;
9753
9754      if (FnDecl) {
9755        // We matched an overloaded operator. Build a call to that
9756        // operator.
9757
9758        MarkFunctionReferenced(OpLoc, FnDecl);
9759
9760        // Convert the arguments.
9761        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
9762          // Best->Access is only meaningful for class members.
9763          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
9764
9765          ExprResult Arg1 =
9766            PerformCopyInitialization(
9767              InitializedEntity::InitializeParameter(Context,
9768                                                     FnDecl->getParamDecl(0)),
9769              SourceLocation(), Owned(Args[1]));
9770          if (Arg1.isInvalid())
9771            return ExprError();
9772
9773          ExprResult Arg0 =
9774            PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9775                                                Best->FoundDecl, Method);
9776          if (Arg0.isInvalid())
9777            return ExprError();
9778          Args[0] = Arg0.takeAs<Expr>();
9779          Args[1] = RHS = Arg1.takeAs<Expr>();
9780        } else {
9781          // Convert the arguments.
9782          ExprResult Arg0 = PerformCopyInitialization(
9783            InitializedEntity::InitializeParameter(Context,
9784                                                   FnDecl->getParamDecl(0)),
9785            SourceLocation(), Owned(Args[0]));
9786          if (Arg0.isInvalid())
9787            return ExprError();
9788
9789          ExprResult Arg1 =
9790            PerformCopyInitialization(
9791              InitializedEntity::InitializeParameter(Context,
9792                                                     FnDecl->getParamDecl(1)),
9793              SourceLocation(), Owned(Args[1]));
9794          if (Arg1.isInvalid())
9795            return ExprError();
9796          Args[0] = LHS = Arg0.takeAs<Expr>();
9797          Args[1] = RHS = Arg1.takeAs<Expr>();
9798        }
9799
9800        DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9801
9802        // Determine the result type.
9803        QualType ResultTy = FnDecl->getResultType();
9804        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9805        ResultTy = ResultTy.getNonLValueExprType(Context);
9806
9807        // Build the actual expression node.
9808        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9809                                                  HadMultipleCandidates, OpLoc);
9810        if (FnExpr.isInvalid())
9811          return ExprError();
9812
9813        CXXOperatorCallExpr *TheCall =
9814          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
9815                                            Args, 2, ResultTy, VK, OpLoc);
9816
9817        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
9818                                FnDecl))
9819          return ExprError();
9820
9821        return MaybeBindToTemporary(TheCall);
9822      } else {
9823        // We matched a built-in operator. Convert the arguments, then
9824        // break out so that we will build the appropriate built-in
9825        // operator node.
9826        ExprResult ArgsRes0 =
9827          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9828                                    Best->Conversions[0], AA_Passing);
9829        if (ArgsRes0.isInvalid())
9830          return ExprError();
9831        Args[0] = ArgsRes0.take();
9832
9833        ExprResult ArgsRes1 =
9834          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9835                                    Best->Conversions[1], AA_Passing);
9836        if (ArgsRes1.isInvalid())
9837          return ExprError();
9838        Args[1] = ArgsRes1.take();
9839        break;
9840      }
9841    }
9842
9843    case OR_No_Viable_Function: {
9844      // C++ [over.match.oper]p9:
9845      //   If the operator is the operator , [...] and there are no
9846      //   viable functions, then the operator is assumed to be the
9847      //   built-in operator and interpreted according to clause 5.
9848      if (Opc == BO_Comma)
9849        break;
9850
9851      // For class as left operand for assignment or compound assigment
9852      // operator do not fall through to handling in built-in, but report that
9853      // no overloaded assignment operator found
9854      ExprResult Result = ExprError();
9855      if (Args[0]->getType()->isRecordType() &&
9856          Opc >= BO_Assign && Opc <= BO_OrAssign) {
9857        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
9858             << BinaryOperator::getOpcodeStr(Opc)
9859             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9860      } else {
9861        // This is an erroneous use of an operator which can be overloaded by
9862        // a non-member function. Check for non-member operators which were
9863        // defined too late to be candidates.
9864        if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9865          // FIXME: Recover by calling the found function.
9866          return ExprError();
9867
9868        // No viable function; try to create a built-in operation, which will
9869        // produce an error. Then, show the non-viable candidates.
9870        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9871      }
9872      assert(Result.isInvalid() &&
9873             "C++ binary operator overloading is missing candidates!");
9874      if (Result.isInvalid())
9875        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9876                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
9877      return move(Result);
9878    }
9879
9880    case OR_Ambiguous:
9881      Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
9882          << BinaryOperator::getOpcodeStr(Opc)
9883          << Args[0]->getType() << Args[1]->getType()
9884          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9885      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9886                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
9887      return ExprError();
9888
9889    case OR_Deleted:
9890      Diag(OpLoc, diag::err_ovl_deleted_oper)
9891        << Best->Function->isDeleted()
9892        << BinaryOperator::getOpcodeStr(Opc)
9893        << getDeletedOrUnavailableSuffix(Best->Function)
9894        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9895      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9896                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
9897      return ExprError();
9898  }
9899
9900  // We matched a built-in operator; build it.
9901  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9902}
9903
9904ExprResult
9905Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9906                                         SourceLocation RLoc,
9907                                         Expr *Base, Expr *Idx) {
9908  Expr *Args[2] = { Base, Idx };
9909  DeclarationName OpName =
9910      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9911
9912  // If either side is type-dependent, create an appropriate dependent
9913  // expression.
9914  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9915
9916    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
9917    // CHECKME: no 'operator' keyword?
9918    DeclarationNameInfo OpNameInfo(OpName, LLoc);
9919    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
9920    UnresolvedLookupExpr *Fn
9921      = UnresolvedLookupExpr::Create(Context, NamingClass,
9922                                     NestedNameSpecifierLoc(), OpNameInfo,
9923                                     /*ADL*/ true, /*Overloaded*/ false,
9924                                     UnresolvedSetIterator(),
9925                                     UnresolvedSetIterator());
9926    // Can't add any actual overloads yet
9927
9928    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9929                                                   Args, 2,
9930                                                   Context.DependentTy,
9931                                                   VK_RValue,
9932                                                   RLoc));
9933  }
9934
9935  // Handle placeholders on both operands.
9936  if (checkPlaceholderForOverload(*this, Args[0]))
9937    return ExprError();
9938  if (checkPlaceholderForOverload(*this, Args[1]))
9939    return ExprError();
9940
9941  // Build an empty overload set.
9942  OverloadCandidateSet CandidateSet(LLoc);
9943
9944  // Subscript can only be overloaded as a member function.
9945
9946  // Add operator candidates that are member functions.
9947  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9948
9949  // Add builtin operator candidates.
9950  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9951
9952  bool HadMultipleCandidates = (CandidateSet.size() > 1);
9953
9954  // Perform overload resolution.
9955  OverloadCandidateSet::iterator Best;
9956  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
9957    case OR_Success: {
9958      // We found a built-in operator or an overloaded operator.
9959      FunctionDecl *FnDecl = Best->Function;
9960
9961      if (FnDecl) {
9962        // We matched an overloaded operator. Build a call to that
9963        // operator.
9964
9965        MarkFunctionReferenced(LLoc, FnDecl);
9966
9967        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
9968        DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
9969
9970        // Convert the arguments.
9971        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
9972        ExprResult Arg0 =
9973          PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9974                                              Best->FoundDecl, Method);
9975        if (Arg0.isInvalid())
9976          return ExprError();
9977        Args[0] = Arg0.take();
9978
9979        // Convert the arguments.
9980        ExprResult InputInit
9981          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
9982                                                      Context,
9983                                                      FnDecl->getParamDecl(0)),
9984                                      SourceLocation(),
9985                                      Owned(Args[1]));
9986        if (InputInit.isInvalid())
9987          return ExprError();
9988
9989        Args[1] = InputInit.takeAs<Expr>();
9990
9991        // Determine the result type
9992        QualType ResultTy = FnDecl->getResultType();
9993        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9994        ResultTy = ResultTy.getNonLValueExprType(Context);
9995
9996        // Build the actual expression node.
9997        DeclarationNameLoc LocInfo;
9998        LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9999        LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
10000        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10001                                                  HadMultipleCandidates,
10002                                                  LLoc, LocInfo);
10003        if (FnExpr.isInvalid())
10004          return ExprError();
10005
10006        CXXOperatorCallExpr *TheCall =
10007          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10008                                            FnExpr.take(), Args, 2,
10009                                            ResultTy, VK, RLoc);
10010
10011        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10012                                FnDecl))
10013          return ExprError();
10014
10015        return MaybeBindToTemporary(TheCall);
10016      } else {
10017        // We matched a built-in operator. Convert the arguments, then
10018        // break out so that we will build the appropriate built-in
10019        // operator node.
10020        ExprResult ArgsRes0 =
10021          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10022                                    Best->Conversions[0], AA_Passing);
10023        if (ArgsRes0.isInvalid())
10024          return ExprError();
10025        Args[0] = ArgsRes0.take();
10026
10027        ExprResult ArgsRes1 =
10028          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10029                                    Best->Conversions[1], AA_Passing);
10030        if (ArgsRes1.isInvalid())
10031          return ExprError();
10032        Args[1] = ArgsRes1.take();
10033
10034        break;
10035      }
10036    }
10037
10038    case OR_No_Viable_Function: {
10039      if (CandidateSet.empty())
10040        Diag(LLoc, diag::err_ovl_no_oper)
10041          << Args[0]->getType() << /*subscript*/ 0
10042          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10043      else
10044        Diag(LLoc, diag::err_ovl_no_viable_subscript)
10045          << Args[0]->getType()
10046          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10047      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10048                                  "[]", LLoc);
10049      return ExprError();
10050    }
10051
10052    case OR_Ambiguous:
10053      Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10054          << "[]"
10055          << Args[0]->getType() << Args[1]->getType()
10056          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10057      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
10058                                  "[]", LLoc);
10059      return ExprError();
10060
10061    case OR_Deleted:
10062      Diag(LLoc, diag::err_ovl_deleted_oper)
10063        << Best->Function->isDeleted() << "[]"
10064        << getDeletedOrUnavailableSuffix(Best->Function)
10065        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10066      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10067                                  "[]", LLoc);
10068      return ExprError();
10069    }
10070
10071  // We matched a built-in operator; build it.
10072  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10073}
10074
10075/// BuildCallToMemberFunction - Build a call to a member
10076/// function. MemExpr is the expression that refers to the member
10077/// function (and includes the object parameter), Args/NumArgs are the
10078/// arguments to the function call (not including the object
10079/// parameter). The caller needs to validate that the member
10080/// expression refers to a non-static member function or an overloaded
10081/// member function.
10082ExprResult
10083Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10084                                SourceLocation LParenLoc, Expr **Args,
10085                                unsigned NumArgs, SourceLocation RParenLoc) {
10086  assert(MemExprE->getType() == Context.BoundMemberTy ||
10087         MemExprE->getType() == Context.OverloadTy);
10088
10089  // Dig out the member expression. This holds both the object
10090  // argument and the member function we're referring to.
10091  Expr *NakedMemExpr = MemExprE->IgnoreParens();
10092
10093  // Determine whether this is a call to a pointer-to-member function.
10094  if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10095    assert(op->getType() == Context.BoundMemberTy);
10096    assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10097
10098    QualType fnType =
10099      op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10100
10101    const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10102    QualType resultType = proto->getCallResultType(Context);
10103    ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10104
10105    // Check that the object type isn't more qualified than the
10106    // member function we're calling.
10107    Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10108
10109    QualType objectType = op->getLHS()->getType();
10110    if (op->getOpcode() == BO_PtrMemI)
10111      objectType = objectType->castAs<PointerType>()->getPointeeType();
10112    Qualifiers objectQuals = objectType.getQualifiers();
10113
10114    Qualifiers difference = objectQuals - funcQuals;
10115    difference.removeObjCGCAttr();
10116    difference.removeAddressSpace();
10117    if (difference) {
10118      std::string qualsString = difference.getAsString();
10119      Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10120        << fnType.getUnqualifiedType()
10121        << qualsString
10122        << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10123    }
10124
10125    CXXMemberCallExpr *call
10126      = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10127                                        resultType, valueKind, RParenLoc);
10128
10129    if (CheckCallReturnType(proto->getResultType(),
10130                            op->getRHS()->getSourceRange().getBegin(),
10131                            call, 0))
10132      return ExprError();
10133
10134    if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10135      return ExprError();
10136
10137    return MaybeBindToTemporary(call);
10138  }
10139
10140  UnbridgedCastsSet UnbridgedCasts;
10141  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10142    return ExprError();
10143
10144  MemberExpr *MemExpr;
10145  CXXMethodDecl *Method = 0;
10146  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
10147  NestedNameSpecifier *Qualifier = 0;
10148  if (isa<MemberExpr>(NakedMemExpr)) {
10149    MemExpr = cast<MemberExpr>(NakedMemExpr);
10150    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
10151    FoundDecl = MemExpr->getFoundDecl();
10152    Qualifier = MemExpr->getQualifier();
10153    UnbridgedCasts.restore();
10154  } else {
10155    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
10156    Qualifier = UnresExpr->getQualifier();
10157
10158    QualType ObjectType = UnresExpr->getBaseType();
10159    Expr::Classification ObjectClassification
10160      = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10161                            : UnresExpr->getBase()->Classify(Context);
10162
10163    // Add overload candidates
10164    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
10165
10166    // FIXME: avoid copy.
10167    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10168    if (UnresExpr->hasExplicitTemplateArgs()) {
10169      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10170      TemplateArgs = &TemplateArgsBuffer;
10171    }
10172
10173    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10174           E = UnresExpr->decls_end(); I != E; ++I) {
10175
10176      NamedDecl *Func = *I;
10177      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10178      if (isa<UsingShadowDecl>(Func))
10179        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10180
10181
10182      // Microsoft supports direct constructor calls.
10183      if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
10184        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
10185                             CandidateSet);
10186      } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
10187        // If explicit template arguments were provided, we can't call a
10188        // non-template member function.
10189        if (TemplateArgs)
10190          continue;
10191
10192        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
10193                           ObjectClassification,
10194                           Args, NumArgs, CandidateSet,
10195                           /*SuppressUserConversions=*/false);
10196      } else {
10197        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
10198                                   I.getPair(), ActingDC, TemplateArgs,
10199                                   ObjectType,  ObjectClassification,
10200                                   Args, NumArgs, CandidateSet,
10201                                   /*SuppressUsedConversions=*/false);
10202      }
10203    }
10204
10205    DeclarationName DeclName = UnresExpr->getMemberName();
10206
10207    UnbridgedCasts.restore();
10208
10209    OverloadCandidateSet::iterator Best;
10210    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
10211                                            Best)) {
10212    case OR_Success:
10213      Method = cast<CXXMethodDecl>(Best->Function);
10214      MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
10215      FoundDecl = Best->FoundDecl;
10216      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
10217      DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
10218      break;
10219
10220    case OR_No_Viable_Function:
10221      Diag(UnresExpr->getMemberLoc(),
10222           diag::err_ovl_no_viable_member_function_in_call)
10223        << DeclName << MemExprE->getSourceRange();
10224      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
10225      // FIXME: Leaking incoming expressions!
10226      return ExprError();
10227
10228    case OR_Ambiguous:
10229      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
10230        << DeclName << MemExprE->getSourceRange();
10231      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
10232      // FIXME: Leaking incoming expressions!
10233      return ExprError();
10234
10235    case OR_Deleted:
10236      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
10237        << Best->Function->isDeleted()
10238        << DeclName
10239        << getDeletedOrUnavailableSuffix(Best->Function)
10240        << MemExprE->getSourceRange();
10241      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
10242      // FIXME: Leaking incoming expressions!
10243      return ExprError();
10244    }
10245
10246    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
10247
10248    // If overload resolution picked a static member, build a
10249    // non-member call based on that function.
10250    if (Method->isStatic()) {
10251      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10252                                   Args, NumArgs, RParenLoc);
10253    }
10254
10255    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
10256  }
10257
10258  QualType ResultType = Method->getResultType();
10259  ExprValueKind VK = Expr::getValueKindForType(ResultType);
10260  ResultType = ResultType.getNonLValueExprType(Context);
10261
10262  assert(Method && "Member call to something that isn't a method?");
10263  CXXMemberCallExpr *TheCall =
10264    new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10265                                    ResultType, VK, RParenLoc);
10266
10267  // Check for a valid return type.
10268  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
10269                          TheCall, Method))
10270    return ExprError();
10271
10272  // Convert the object argument (for a non-static member function call).
10273  // We only need to do this if there was actually an overload; otherwise
10274  // it was done at lookup.
10275  if (!Method->isStatic()) {
10276    ExprResult ObjectArg =
10277      PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10278                                          FoundDecl, Method);
10279    if (ObjectArg.isInvalid())
10280      return ExprError();
10281    MemExpr->setBase(ObjectArg.take());
10282  }
10283
10284  // Convert the rest of the arguments
10285  const FunctionProtoType *Proto =
10286    Method->getType()->getAs<FunctionProtoType>();
10287  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
10288                              RParenLoc))
10289    return ExprError();
10290
10291  if (CheckFunctionCall(Method, TheCall))
10292    return ExprError();
10293
10294  if ((isa<CXXConstructorDecl>(CurContext) ||
10295       isa<CXXDestructorDecl>(CurContext)) &&
10296      TheCall->getMethodDecl()->isPure()) {
10297    const CXXMethodDecl *MD = TheCall->getMethodDecl();
10298
10299    if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
10300      Diag(MemExpr->getLocStart(),
10301           diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10302        << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10303        << MD->getParent()->getDeclName();
10304
10305      Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
10306    }
10307  }
10308  return MaybeBindToTemporary(TheCall);
10309}
10310
10311/// BuildCallToObjectOfClassType - Build a call to an object of class
10312/// type (C++ [over.call.object]), which can end up invoking an
10313/// overloaded function call operator (@c operator()) or performing a
10314/// user-defined conversion on the object argument.
10315ExprResult
10316Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
10317                                   SourceLocation LParenLoc,
10318                                   Expr **Args, unsigned NumArgs,
10319                                   SourceLocation RParenLoc) {
10320  if (checkPlaceholderForOverload(*this, Obj))
10321    return ExprError();
10322  ExprResult Object = Owned(Obj);
10323
10324  UnbridgedCastsSet UnbridgedCasts;
10325  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10326    return ExprError();
10327
10328  assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10329  const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
10330
10331  // C++ [over.call.object]p1:
10332  //  If the primary-expression E in the function call syntax
10333  //  evaluates to a class object of type "cv T", then the set of
10334  //  candidate functions includes at least the function call
10335  //  operators of T. The function call operators of T are obtained by
10336  //  ordinary lookup of the name operator() in the context of
10337  //  (E).operator().
10338  OverloadCandidateSet CandidateSet(LParenLoc);
10339  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
10340
10341  if (RequireCompleteType(LParenLoc, Object.get()->getType(),
10342                          PDiag(diag::err_incomplete_object_call)
10343                          << Object.get()->getSourceRange()))
10344    return true;
10345
10346  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10347  LookupQualifiedName(R, Record->getDecl());
10348  R.suppressDiagnostics();
10349
10350  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10351       Oper != OperEnd; ++Oper) {
10352    AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10353                       Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
10354                       /*SuppressUserConversions=*/ false);
10355  }
10356
10357  // C++ [over.call.object]p2:
10358  //   In addition, for each (non-explicit in C++0x) conversion function
10359  //   declared in T of the form
10360  //
10361  //        operator conversion-type-id () cv-qualifier;
10362  //
10363  //   where cv-qualifier is the same cv-qualification as, or a
10364  //   greater cv-qualification than, cv, and where conversion-type-id
10365  //   denotes the type "pointer to function of (P1,...,Pn) returning
10366  //   R", or the type "reference to pointer to function of
10367  //   (P1,...,Pn) returning R", or the type "reference to function
10368  //   of (P1,...,Pn) returning R", a surrogate call function [...]
10369  //   is also considered as a candidate function. Similarly,
10370  //   surrogate call functions are added to the set of candidate
10371  //   functions for each conversion function declared in an
10372  //   accessible base class provided the function is not hidden
10373  //   within T by another intervening declaration.
10374  const UnresolvedSetImpl *Conversions
10375    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
10376  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
10377         E = Conversions->end(); I != E; ++I) {
10378    NamedDecl *D = *I;
10379    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10380    if (isa<UsingShadowDecl>(D))
10381      D = cast<UsingShadowDecl>(D)->getTargetDecl();
10382
10383    // Skip over templated conversion functions; they aren't
10384    // surrogates.
10385    if (isa<FunctionTemplateDecl>(D))
10386      continue;
10387
10388    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
10389    if (!Conv->isExplicit()) {
10390      // Strip the reference type (if any) and then the pointer type (if
10391      // any) to get down to what might be a function type.
10392      QualType ConvType = Conv->getConversionType().getNonReferenceType();
10393      if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10394        ConvType = ConvPtrType->getPointeeType();
10395
10396      if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10397      {
10398        AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10399                              Object.get(), Args, NumArgs, CandidateSet);
10400      }
10401    }
10402  }
10403
10404  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10405
10406  // Perform overload resolution.
10407  OverloadCandidateSet::iterator Best;
10408  switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
10409                             Best)) {
10410  case OR_Success:
10411    // Overload resolution succeeded; we'll build the appropriate call
10412    // below.
10413    break;
10414
10415  case OR_No_Viable_Function:
10416    if (CandidateSet.empty())
10417      Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
10418        << Object.get()->getType() << /*call*/ 1
10419        << Object.get()->getSourceRange();
10420    else
10421      Diag(Object.get()->getSourceRange().getBegin(),
10422           diag::err_ovl_no_viable_object_call)
10423        << Object.get()->getType() << Object.get()->getSourceRange();
10424    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
10425    break;
10426
10427  case OR_Ambiguous:
10428    Diag(Object.get()->getSourceRange().getBegin(),
10429         diag::err_ovl_ambiguous_object_call)
10430      << Object.get()->getType() << Object.get()->getSourceRange();
10431    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
10432    break;
10433
10434  case OR_Deleted:
10435    Diag(Object.get()->getSourceRange().getBegin(),
10436         diag::err_ovl_deleted_object_call)
10437      << Best->Function->isDeleted()
10438      << Object.get()->getType()
10439      << getDeletedOrUnavailableSuffix(Best->Function)
10440      << Object.get()->getSourceRange();
10441    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
10442    break;
10443  }
10444
10445  if (Best == CandidateSet.end())
10446    return true;
10447
10448  UnbridgedCasts.restore();
10449
10450  if (Best->Function == 0) {
10451    // Since there is no function declaration, this is one of the
10452    // surrogate candidates. Dig out the conversion function.
10453    CXXConversionDecl *Conv
10454      = cast<CXXConversionDecl>(
10455                         Best->Conversions[0].UserDefined.ConversionFunction);
10456
10457    CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
10458    DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
10459
10460    // We selected one of the surrogate functions that converts the
10461    // object parameter to a function pointer. Perform the conversion
10462    // on the object argument, then let ActOnCallExpr finish the job.
10463
10464    // Create an implicit member expr to refer to the conversion operator.
10465    // and then call it.
10466    ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10467                                             Conv, HadMultipleCandidates);
10468    if (Call.isInvalid())
10469      return ExprError();
10470    // Record usage of conversion in an implicit cast.
10471    Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10472                                          CK_UserDefinedConversion,
10473                                          Call.get(), 0, VK_RValue));
10474
10475    return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
10476                         RParenLoc);
10477  }
10478
10479  MarkFunctionReferenced(LParenLoc, Best->Function);
10480  CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
10481  DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
10482
10483  // We found an overloaded operator(). Build a CXXOperatorCallExpr
10484  // that calls this method, using Object for the implicit object
10485  // parameter and passing along the remaining arguments.
10486  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10487  const FunctionProtoType *Proto =
10488    Method->getType()->getAs<FunctionProtoType>();
10489
10490  unsigned NumArgsInProto = Proto->getNumArgs();
10491  unsigned NumArgsToCheck = NumArgs;
10492
10493  // Build the full argument list for the method call (the
10494  // implicit object parameter is placed at the beginning of the
10495  // list).
10496  Expr **MethodArgs;
10497  if (NumArgs < NumArgsInProto) {
10498    NumArgsToCheck = NumArgsInProto;
10499    MethodArgs = new Expr*[NumArgsInProto + 1];
10500  } else {
10501    MethodArgs = new Expr*[NumArgs + 1];
10502  }
10503  MethodArgs[0] = Object.get();
10504  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10505    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
10506
10507  ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10508                                           HadMultipleCandidates);
10509  if (NewFn.isInvalid())
10510    return true;
10511
10512  // Once we've built TheCall, all of the expressions are properly
10513  // owned.
10514  QualType ResultTy = Method->getResultType();
10515  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10516  ResultTy = ResultTy.getNonLValueExprType(Context);
10517
10518  CXXOperatorCallExpr *TheCall =
10519    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
10520                                      MethodArgs, NumArgs + 1,
10521                                      ResultTy, VK, RParenLoc);
10522  delete [] MethodArgs;
10523
10524  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
10525                          Method))
10526    return true;
10527
10528  // We may have default arguments. If so, we need to allocate more
10529  // slots in the call for them.
10530  if (NumArgs < NumArgsInProto)
10531    TheCall->setNumArgs(Context, NumArgsInProto + 1);
10532  else if (NumArgs > NumArgsInProto)
10533    NumArgsToCheck = NumArgsInProto;
10534
10535  bool IsError = false;
10536
10537  // Initialize the implicit object parameter.
10538  ExprResult ObjRes =
10539    PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10540                                        Best->FoundDecl, Method);
10541  if (ObjRes.isInvalid())
10542    IsError = true;
10543  else
10544    Object = move(ObjRes);
10545  TheCall->setArg(0, Object.take());
10546
10547  // Check the argument types.
10548  for (unsigned i = 0; i != NumArgsToCheck; i++) {
10549    Expr *Arg;
10550    if (i < NumArgs) {
10551      Arg = Args[i];
10552
10553      // Pass the argument.
10554
10555      ExprResult InputInit
10556        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10557                                                    Context,
10558                                                    Method->getParamDecl(i)),
10559                                    SourceLocation(), Arg);
10560
10561      IsError |= InputInit.isInvalid();
10562      Arg = InputInit.takeAs<Expr>();
10563    } else {
10564      ExprResult DefArg
10565        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10566      if (DefArg.isInvalid()) {
10567        IsError = true;
10568        break;
10569      }
10570
10571      Arg = DefArg.takeAs<Expr>();
10572    }
10573
10574    TheCall->setArg(i + 1, Arg);
10575  }
10576
10577  // If this is a variadic call, handle args passed through "...".
10578  if (Proto->isVariadic()) {
10579    // Promote the arguments (C99 6.5.2.2p7).
10580    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
10581      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10582      IsError |= Arg.isInvalid();
10583      TheCall->setArg(i + 1, Arg.take());
10584    }
10585  }
10586
10587  if (IsError) return true;
10588
10589  if (CheckFunctionCall(Method, TheCall))
10590    return true;
10591
10592  return MaybeBindToTemporary(TheCall);
10593}
10594
10595/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
10596///  (if one exists), where @c Base is an expression of class type and
10597/// @c Member is the name of the member we're trying to find.
10598ExprResult
10599Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
10600  assert(Base->getType()->isRecordType() &&
10601         "left-hand side must have class type");
10602
10603  if (checkPlaceholderForOverload(*this, Base))
10604    return ExprError();
10605
10606  SourceLocation Loc = Base->getExprLoc();
10607
10608  // C++ [over.ref]p1:
10609  //
10610  //   [...] An expression x->m is interpreted as (x.operator->())->m
10611  //   for a class object x of type T if T::operator->() exists and if
10612  //   the operator is selected as the best match function by the
10613  //   overload resolution mechanism (13.3).
10614  DeclarationName OpName =
10615    Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
10616  OverloadCandidateSet CandidateSet(Loc);
10617  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
10618
10619  if (RequireCompleteType(Loc, Base->getType(),
10620                          PDiag(diag::err_typecheck_incomplete_tag)
10621                            << Base->getSourceRange()))
10622    return ExprError();
10623
10624  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10625  LookupQualifiedName(R, BaseRecord->getDecl());
10626  R.suppressDiagnostics();
10627
10628  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10629       Oper != OperEnd; ++Oper) {
10630    AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10631                       0, 0, CandidateSet, /*SuppressUserConversions=*/false);
10632  }
10633
10634  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10635
10636  // Perform overload resolution.
10637  OverloadCandidateSet::iterator Best;
10638  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10639  case OR_Success:
10640    // Overload resolution succeeded; we'll build the call below.
10641    break;
10642
10643  case OR_No_Viable_Function:
10644    if (CandidateSet.empty())
10645      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
10646        << Base->getType() << Base->getSourceRange();
10647    else
10648      Diag(OpLoc, diag::err_ovl_no_viable_oper)
10649        << "operator->" << Base->getSourceRange();
10650    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
10651    return ExprError();
10652
10653  case OR_Ambiguous:
10654    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10655      << "->" << Base->getType() << Base->getSourceRange();
10656    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
10657    return ExprError();
10658
10659  case OR_Deleted:
10660    Diag(OpLoc,  diag::err_ovl_deleted_oper)
10661      << Best->Function->isDeleted()
10662      << "->"
10663      << getDeletedOrUnavailableSuffix(Best->Function)
10664      << Base->getSourceRange();
10665    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
10666    return ExprError();
10667  }
10668
10669  MarkFunctionReferenced(OpLoc, Best->Function);
10670  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
10671  DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10672
10673  // Convert the object parameter.
10674  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10675  ExprResult BaseResult =
10676    PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10677                                        Best->FoundDecl, Method);
10678  if (BaseResult.isInvalid())
10679    return ExprError();
10680  Base = BaseResult.take();
10681
10682  // Build the operator call.
10683  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10684                                            HadMultipleCandidates);
10685  if (FnExpr.isInvalid())
10686    return ExprError();
10687
10688  QualType ResultTy = Method->getResultType();
10689  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10690  ResultTy = ResultTy.getNonLValueExprType(Context);
10691  CXXOperatorCallExpr *TheCall =
10692    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
10693                                      &Base, 1, ResultTy, VK, OpLoc);
10694
10695  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
10696                          Method))
10697          return ExprError();
10698
10699  return MaybeBindToTemporary(TheCall);
10700}
10701
10702/// FixOverloadedFunctionReference - E is an expression that refers to
10703/// a C++ overloaded function (possibly with some parentheses and
10704/// perhaps a '&' around it). We have resolved the overloaded function
10705/// to the function declaration Fn, so patch up the expression E to
10706/// refer (possibly indirectly) to Fn. Returns the new expr.
10707Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
10708                                           FunctionDecl *Fn) {
10709  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
10710    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10711                                                   Found, Fn);
10712    if (SubExpr == PE->getSubExpr())
10713      return PE;
10714
10715    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
10716  }
10717
10718  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10719    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10720                                                   Found, Fn);
10721    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
10722                               SubExpr->getType()) &&
10723           "Implicit cast type cannot be determined from overload");
10724    assert(ICE->path_empty() && "fixing up hierarchy conversion?");
10725    if (SubExpr == ICE->getSubExpr())
10726      return ICE;
10727
10728    return ImplicitCastExpr::Create(Context, ICE->getType(),
10729                                    ICE->getCastKind(),
10730                                    SubExpr, 0,
10731                                    ICE->getValueKind());
10732  }
10733
10734  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
10735    assert(UnOp->getOpcode() == UO_AddrOf &&
10736           "Can only take the address of an overloaded function");
10737    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10738      if (Method->isStatic()) {
10739        // Do nothing: static member functions aren't any different
10740        // from non-member functions.
10741      } else {
10742        // Fix the sub expression, which really has to be an
10743        // UnresolvedLookupExpr holding an overloaded member function
10744        // or template.
10745        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10746                                                       Found, Fn);
10747        if (SubExpr == UnOp->getSubExpr())
10748          return UnOp;
10749
10750        assert(isa<DeclRefExpr>(SubExpr)
10751               && "fixed to something other than a decl ref");
10752        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10753               && "fixed to a member ref with no nested name qualifier");
10754
10755        // We have taken the address of a pointer to member
10756        // function. Perform the computation here so that we get the
10757        // appropriate pointer to member type.
10758        QualType ClassType
10759          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10760        QualType MemPtrType
10761          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10762
10763        return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10764                                           VK_RValue, OK_Ordinary,
10765                                           UnOp->getOperatorLoc());
10766      }
10767    }
10768    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10769                                                   Found, Fn);
10770    if (SubExpr == UnOp->getSubExpr())
10771      return UnOp;
10772
10773    return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
10774                                     Context.getPointerType(SubExpr->getType()),
10775                                       VK_RValue, OK_Ordinary,
10776                                       UnOp->getOperatorLoc());
10777  }
10778
10779  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
10780    // FIXME: avoid copy.
10781    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10782    if (ULE->hasExplicitTemplateArgs()) {
10783      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10784      TemplateArgs = &TemplateArgsBuffer;
10785    }
10786
10787    DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10788                                           ULE->getQualifierLoc(),
10789                                           ULE->getTemplateKeywordLoc(),
10790                                           Fn,
10791                                           ULE->getNameLoc(),
10792                                           Fn->getType(),
10793                                           VK_LValue,
10794                                           Found.getDecl(),
10795                                           TemplateArgs);
10796    DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10797    return DRE;
10798  }
10799
10800  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
10801    // FIXME: avoid copy.
10802    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10803    if (MemExpr->hasExplicitTemplateArgs()) {
10804      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10805      TemplateArgs = &TemplateArgsBuffer;
10806    }
10807
10808    Expr *Base;
10809
10810    // If we're filling in a static method where we used to have an
10811    // implicit member access, rewrite to a simple decl ref.
10812    if (MemExpr->isImplicitAccess()) {
10813      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10814        DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10815                                               MemExpr->getQualifierLoc(),
10816                                               MemExpr->getTemplateKeywordLoc(),
10817                                               Fn,
10818                                               MemExpr->getMemberLoc(),
10819                                               Fn->getType(),
10820                                               VK_LValue,
10821                                               Found.getDecl(),
10822                                               TemplateArgs);
10823        DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10824        return DRE;
10825      } else {
10826        SourceLocation Loc = MemExpr->getMemberLoc();
10827        if (MemExpr->getQualifier())
10828          Loc = MemExpr->getQualifierLoc().getBeginLoc();
10829        CheckCXXThisCapture(Loc);
10830        Base = new (Context) CXXThisExpr(Loc,
10831                                         MemExpr->getBaseType(),
10832                                         /*isImplicit=*/true);
10833      }
10834    } else
10835      Base = MemExpr->getBase();
10836
10837    ExprValueKind valueKind;
10838    QualType type;
10839    if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10840      valueKind = VK_LValue;
10841      type = Fn->getType();
10842    } else {
10843      valueKind = VK_RValue;
10844      type = Context.BoundMemberTy;
10845    }
10846
10847    MemberExpr *ME = MemberExpr::Create(Context, Base,
10848                                        MemExpr->isArrow(),
10849                                        MemExpr->getQualifierLoc(),
10850                                        MemExpr->getTemplateKeywordLoc(),
10851                                        Fn,
10852                                        Found,
10853                                        MemExpr->getMemberNameInfo(),
10854                                        TemplateArgs,
10855                                        type, valueKind, OK_Ordinary);
10856    ME->setHadMultipleCandidates(true);
10857    return ME;
10858  }
10859
10860  llvm_unreachable("Invalid reference to overloaded function");
10861}
10862
10863ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
10864                                                DeclAccessPair Found,
10865                                                FunctionDecl *Fn) {
10866  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
10867}
10868
10869} // end namespace clang
10870