SemaOverload.cpp revision 831421f24057b93ea28bc92d8bd6290631a43caf
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/SmallString.h"
32#include "llvm/ADT/STLExtras.h"
33#include <algorithm>
34
35namespace clang {
36using namespace sema;
37
38/// A convenience routine for creating a decayed reference to a
39/// function.
40static ExprResult
41CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
42                      SourceLocation Loc = SourceLocation(),
43                      const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
44  DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
45                                                 VK_LValue, Loc, LocInfo);
46  if (HadMultipleCandidates)
47    DRE->setHadMultipleCandidates(true);
48  ExprResult E = S.Owned(DRE);
49  E = S.DefaultFunctionArrayConversion(E.take());
50  if (E.isInvalid())
51    return ExprError();
52  return move(E);
53}
54
55static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
56                                 bool InOverloadResolution,
57                                 StandardConversionSequence &SCS,
58                                 bool CStyle,
59                                 bool AllowObjCWritebackConversion);
60
61static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
62                                                 QualType &ToType,
63                                                 bool InOverloadResolution,
64                                                 StandardConversionSequence &SCS,
65                                                 bool CStyle);
66static OverloadingResult
67IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
68                        UserDefinedConversionSequence& User,
69                        OverloadCandidateSet& Conversions,
70                        bool AllowExplicit);
71
72
73static ImplicitConversionSequence::CompareKind
74CompareStandardConversionSequences(Sema &S,
75                                   const StandardConversionSequence& SCS1,
76                                   const StandardConversionSequence& SCS2);
77
78static ImplicitConversionSequence::CompareKind
79CompareQualificationConversions(Sema &S,
80                                const StandardConversionSequence& SCS1,
81                                const StandardConversionSequence& SCS2);
82
83static ImplicitConversionSequence::CompareKind
84CompareDerivedToBaseConversions(Sema &S,
85                                const StandardConversionSequence& SCS1,
86                                const StandardConversionSequence& SCS2);
87
88
89
90/// GetConversionCategory - Retrieve the implicit conversion
91/// category corresponding to the given implicit conversion kind.
92ImplicitConversionCategory
93GetConversionCategory(ImplicitConversionKind Kind) {
94  static const ImplicitConversionCategory
95    Category[(int)ICK_Num_Conversion_Kinds] = {
96    ICC_Identity,
97    ICC_Lvalue_Transformation,
98    ICC_Lvalue_Transformation,
99    ICC_Lvalue_Transformation,
100    ICC_Identity,
101    ICC_Qualification_Adjustment,
102    ICC_Promotion,
103    ICC_Promotion,
104    ICC_Promotion,
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    ICC_Conversion
118  };
119  return Category[(int)Kind];
120}
121
122/// GetConversionRank - Retrieve the implicit conversion rank
123/// corresponding to the given implicit conversion kind.
124ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
125  static const ImplicitConversionRank
126    Rank[(int)ICK_Num_Conversion_Kinds] = {
127    ICR_Exact_Match,
128    ICR_Exact_Match,
129    ICR_Exact_Match,
130    ICR_Exact_Match,
131    ICR_Exact_Match,
132    ICR_Exact_Match,
133    ICR_Promotion,
134    ICR_Promotion,
135    ICR_Promotion,
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_Conversion,
147    ICR_Complex_Real_Conversion,
148    ICR_Conversion,
149    ICR_Conversion,
150    ICR_Writeback_Conversion
151  };
152  return Rank[(int)Kind];
153}
154
155/// GetImplicitConversionName - Return the name of this kind of
156/// implicit conversion.
157const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
158  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
159    "No conversion",
160    "Lvalue-to-rvalue",
161    "Array-to-pointer",
162    "Function-to-pointer",
163    "Noreturn adjustment",
164    "Qualification",
165    "Integral promotion",
166    "Floating point promotion",
167    "Complex promotion",
168    "Integral conversion",
169    "Floating conversion",
170    "Complex conversion",
171    "Floating-integral conversion",
172    "Pointer conversion",
173    "Pointer-to-member conversion",
174    "Boolean conversion",
175    "Compatible-types conversion",
176    "Derived-to-base conversion",
177    "Vector conversion",
178    "Vector splat",
179    "Complex-real conversion",
180    "Block Pointer conversion",
181    "Transparent Union Conversion"
182    "Writeback conversion"
183  };
184  return Name[Kind];
185}
186
187/// StandardConversionSequence - Set the standard conversion
188/// sequence to the identity conversion.
189void StandardConversionSequence::setAsIdentityConversion() {
190  First = ICK_Identity;
191  Second = ICK_Identity;
192  Third = ICK_Identity;
193  DeprecatedStringLiteralToCharPtr = false;
194  QualificationIncludesObjCLifetime = false;
195  ReferenceBinding = false;
196  DirectBinding = false;
197  IsLvalueReference = true;
198  BindsToFunctionLvalue = false;
199  BindsToRvalue = false;
200  BindsImplicitObjectArgumentWithoutRefQualifier = false;
201  ObjCLifetimeConversionBinding = false;
202  CopyConstructor = 0;
203}
204
205/// getRank - Retrieve the rank of this standard conversion sequence
206/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
207/// implicit conversions.
208ImplicitConversionRank StandardConversionSequence::getRank() const {
209  ImplicitConversionRank Rank = ICR_Exact_Match;
210  if  (GetConversionRank(First) > Rank)
211    Rank = GetConversionRank(First);
212  if  (GetConversionRank(Second) > Rank)
213    Rank = GetConversionRank(Second);
214  if  (GetConversionRank(Third) > Rank)
215    Rank = GetConversionRank(Third);
216  return Rank;
217}
218
219/// isPointerConversionToBool - Determines whether this conversion is
220/// a conversion of a pointer or pointer-to-member to bool. This is
221/// used as part of the ranking of standard conversion sequences
222/// (C++ 13.3.3.2p4).
223bool StandardConversionSequence::isPointerConversionToBool() const {
224  // Note that FromType has not necessarily been transformed by the
225  // array-to-pointer or function-to-pointer implicit conversions, so
226  // check for their presence as well as checking whether FromType is
227  // a pointer.
228  if (getToType(1)->isBooleanType() &&
229      (getFromType()->isPointerType() ||
230       getFromType()->isObjCObjectPointerType() ||
231       getFromType()->isBlockPointerType() ||
232       getFromType()->isNullPtrType() ||
233       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
234    return true;
235
236  return false;
237}
238
239/// isPointerConversionToVoidPointer - Determines whether this
240/// conversion is a conversion of a pointer to a void pointer. This is
241/// used as part of the ranking of standard conversion sequences (C++
242/// 13.3.3.2p4).
243bool
244StandardConversionSequence::
245isPointerConversionToVoidPointer(ASTContext& Context) const {
246  QualType FromType = getFromType();
247  QualType ToType = getToType(1);
248
249  // Note that FromType has not necessarily been transformed by the
250  // array-to-pointer implicit conversion, so check for its presence
251  // and redo the conversion to get a pointer.
252  if (First == ICK_Array_To_Pointer)
253    FromType = Context.getArrayDecayedType(FromType);
254
255  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
256    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
257      return ToPtrType->getPointeeType()->isVoidType();
258
259  return false;
260}
261
262/// Skip any implicit casts which could be either part of a narrowing conversion
263/// or after one in an implicit conversion.
264static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
265  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
266    switch (ICE->getCastKind()) {
267    case CK_NoOp:
268    case CK_IntegralCast:
269    case CK_IntegralToBoolean:
270    case CK_IntegralToFloating:
271    case CK_FloatingToIntegral:
272    case CK_FloatingToBoolean:
273    case CK_FloatingCast:
274      Converted = ICE->getSubExpr();
275      continue;
276
277    default:
278      return Converted;
279    }
280  }
281
282  return Converted;
283}
284
285/// Check if this standard conversion sequence represents a narrowing
286/// conversion, according to C++11 [dcl.init.list]p7.
287///
288/// \param Ctx  The AST context.
289/// \param Converted  The result of applying this standard conversion sequence.
290/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
291///        value of the expression prior to the narrowing conversion.
292/// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
293///        type of the expression prior to the narrowing conversion.
294NarrowingKind
295StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
296                                             const Expr *Converted,
297                                             APValue &ConstantValue,
298                                             QualType &ConstantType) const {
299  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
300
301  // C++11 [dcl.init.list]p7:
302  //   A narrowing conversion is an implicit conversion ...
303  QualType FromType = getToType(0);
304  QualType ToType = getToType(1);
305  switch (Second) {
306  // -- from a floating-point type to an integer type, or
307  //
308  // -- from an integer type or unscoped enumeration type to a floating-point
309  //    type, except where the source is a constant expression and the actual
310  //    value after conversion will fit into the target type and will produce
311  //    the original value when converted back to the original type, or
312  case ICK_Floating_Integral:
313    if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
314      return NK_Type_Narrowing;
315    } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
316      llvm::APSInt IntConstantValue;
317      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
318      if (Initializer &&
319          Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
320        // Convert the integer to the floating type.
321        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
322        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
323                                llvm::APFloat::rmNearestTiesToEven);
324        // And back.
325        llvm::APSInt ConvertedValue = IntConstantValue;
326        bool ignored;
327        Result.convertToInteger(ConvertedValue,
328                                llvm::APFloat::rmTowardZero, &ignored);
329        // If the resulting value is different, this was a narrowing conversion.
330        if (IntConstantValue != ConvertedValue) {
331          ConstantValue = APValue(IntConstantValue);
332          ConstantType = Initializer->getType();
333          return NK_Constant_Narrowing;
334        }
335      } else {
336        // Variables are always narrowings.
337        return NK_Variable_Narrowing;
338      }
339    }
340    return NK_Not_Narrowing;
341
342  // -- from long double to double or float, or from double to float, except
343  //    where the source is a constant expression and the actual value after
344  //    conversion is within the range of values that can be represented (even
345  //    if it cannot be represented exactly), or
346  case ICK_Floating_Conversion:
347    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
348        Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
349      // FromType is larger than ToType.
350      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
351      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
352        // Constant!
353        assert(ConstantValue.isFloat());
354        llvm::APFloat FloatVal = ConstantValue.getFloat();
355        // Convert the source value into the target type.
356        bool ignored;
357        llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
358          Ctx.getFloatTypeSemantics(ToType),
359          llvm::APFloat::rmNearestTiesToEven, &ignored);
360        // If there was no overflow, the source value is within the range of
361        // values that can be represented.
362        if (ConvertStatus & llvm::APFloat::opOverflow) {
363          ConstantType = Initializer->getType();
364          return NK_Constant_Narrowing;
365        }
366      } else {
367        return NK_Variable_Narrowing;
368      }
369    }
370    return NK_Not_Narrowing;
371
372  // -- from an integer type or unscoped enumeration type to an integer type
373  //    that cannot represent all the values of the original type, except where
374  //    the source is a constant expression and the actual value after
375  //    conversion will fit into the target type and will produce the original
376  //    value when converted back to the original type.
377  case ICK_Boolean_Conversion:  // Bools are integers too.
378    if (!FromType->isIntegralOrUnscopedEnumerationType()) {
379      // Boolean conversions can be from pointers and pointers to members
380      // [conv.bool], and those aren't considered narrowing conversions.
381      return NK_Not_Narrowing;
382    }  // Otherwise, fall through to the integral case.
383  case ICK_Integral_Conversion: {
384    assert(FromType->isIntegralOrUnscopedEnumerationType());
385    assert(ToType->isIntegralOrUnscopedEnumerationType());
386    const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
387    const unsigned FromWidth = Ctx.getIntWidth(FromType);
388    const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
389    const unsigned ToWidth = Ctx.getIntWidth(ToType);
390
391    if (FromWidth > ToWidth ||
392        (FromWidth == ToWidth && FromSigned != ToSigned) ||
393        (FromSigned && !ToSigned)) {
394      // Not all values of FromType can be represented in ToType.
395      llvm::APSInt InitializerValue;
396      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
397      if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
398        // Such conversions on variables are always narrowing.
399        return NK_Variable_Narrowing;
400      }
401      bool Narrowing = false;
402      if (FromWidth < ToWidth) {
403        // Negative -> unsigned is narrowing. Otherwise, more bits is never
404        // narrowing.
405        if (InitializerValue.isSigned() && InitializerValue.isNegative())
406          Narrowing = true;
407      } else {
408        // Add a bit to the InitializerValue so we don't have to worry about
409        // signed vs. unsigned comparisons.
410        InitializerValue = InitializerValue.extend(
411          InitializerValue.getBitWidth() + 1);
412        // Convert the initializer to and from the target width and signed-ness.
413        llvm::APSInt ConvertedValue = InitializerValue;
414        ConvertedValue = ConvertedValue.trunc(ToWidth);
415        ConvertedValue.setIsSigned(ToSigned);
416        ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
417        ConvertedValue.setIsSigned(InitializerValue.isSigned());
418        // If the result is different, this was a narrowing conversion.
419        if (ConvertedValue != InitializerValue)
420          Narrowing = true;
421      }
422      if (Narrowing) {
423        ConstantType = Initializer->getType();
424        ConstantValue = APValue(InitializerValue);
425        return NK_Constant_Narrowing;
426      }
427    }
428    return NK_Not_Narrowing;
429  }
430
431  default:
432    // Other kinds of conversions are not narrowings.
433    return NK_Not_Narrowing;
434  }
435}
436
437/// DebugPrint - Print this standard conversion sequence to standard
438/// error. Useful for debugging overloading issues.
439void StandardConversionSequence::DebugPrint() const {
440  raw_ostream &OS = llvm::errs();
441  bool PrintedSomething = false;
442  if (First != ICK_Identity) {
443    OS << GetImplicitConversionName(First);
444    PrintedSomething = true;
445  }
446
447  if (Second != ICK_Identity) {
448    if (PrintedSomething) {
449      OS << " -> ";
450    }
451    OS << GetImplicitConversionName(Second);
452
453    if (CopyConstructor) {
454      OS << " (by copy constructor)";
455    } else if (DirectBinding) {
456      OS << " (direct reference binding)";
457    } else if (ReferenceBinding) {
458      OS << " (reference binding)";
459    }
460    PrintedSomething = true;
461  }
462
463  if (Third != ICK_Identity) {
464    if (PrintedSomething) {
465      OS << " -> ";
466    }
467    OS << GetImplicitConversionName(Third);
468    PrintedSomething = true;
469  }
470
471  if (!PrintedSomething) {
472    OS << "No conversions required";
473  }
474}
475
476/// DebugPrint - Print this user-defined conversion sequence to standard
477/// error. Useful for debugging overloading issues.
478void UserDefinedConversionSequence::DebugPrint() const {
479  raw_ostream &OS = llvm::errs();
480  if (Before.First || Before.Second || Before.Third) {
481    Before.DebugPrint();
482    OS << " -> ";
483  }
484  if (ConversionFunction)
485    OS << '\'' << *ConversionFunction << '\'';
486  else
487    OS << "aggregate initialization";
488  if (After.First || After.Second || After.Third) {
489    OS << " -> ";
490    After.DebugPrint();
491  }
492}
493
494/// DebugPrint - Print this implicit conversion sequence to standard
495/// error. Useful for debugging overloading issues.
496void ImplicitConversionSequence::DebugPrint() const {
497  raw_ostream &OS = llvm::errs();
498  switch (ConversionKind) {
499  case StandardConversion:
500    OS << "Standard conversion: ";
501    Standard.DebugPrint();
502    break;
503  case UserDefinedConversion:
504    OS << "User-defined conversion: ";
505    UserDefined.DebugPrint();
506    break;
507  case EllipsisConversion:
508    OS << "Ellipsis conversion";
509    break;
510  case AmbiguousConversion:
511    OS << "Ambiguous conversion";
512    break;
513  case BadConversion:
514    OS << "Bad conversion";
515    break;
516  }
517
518  OS << "\n";
519}
520
521void AmbiguousConversionSequence::construct() {
522  new (&conversions()) ConversionSet();
523}
524
525void AmbiguousConversionSequence::destruct() {
526  conversions().~ConversionSet();
527}
528
529void
530AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
531  FromTypePtr = O.FromTypePtr;
532  ToTypePtr = O.ToTypePtr;
533  new (&conversions()) ConversionSet(O.conversions());
534}
535
536namespace {
537  // Structure used by OverloadCandidate::DeductionFailureInfo to store
538  // template parameter and template argument information.
539  struct DFIParamWithArguments {
540    TemplateParameter Param;
541    TemplateArgument FirstArg;
542    TemplateArgument SecondArg;
543  };
544}
545
546/// \brief Convert from Sema's representation of template deduction information
547/// to the form used in overload-candidate information.
548OverloadCandidate::DeductionFailureInfo
549static MakeDeductionFailureInfo(ASTContext &Context,
550                                Sema::TemplateDeductionResult TDK,
551                                TemplateDeductionInfo &Info) {
552  OverloadCandidate::DeductionFailureInfo Result;
553  Result.Result = static_cast<unsigned>(TDK);
554  Result.HasDiagnostic = false;
555  Result.Data = 0;
556  switch (TDK) {
557  case Sema::TDK_Success:
558  case Sema::TDK_InstantiationDepth:
559  case Sema::TDK_TooManyArguments:
560  case Sema::TDK_TooFewArguments:
561    break;
562
563  case Sema::TDK_Incomplete:
564  case Sema::TDK_InvalidExplicitArguments:
565    Result.Data = Info.Param.getOpaqueValue();
566    break;
567
568  case Sema::TDK_Inconsistent:
569  case Sema::TDK_Underqualified: {
570    // FIXME: Should allocate from normal heap so that we can free this later.
571    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
572    Saved->Param = Info.Param;
573    Saved->FirstArg = Info.FirstArg;
574    Saved->SecondArg = Info.SecondArg;
575    Result.Data = Saved;
576    break;
577  }
578
579  case Sema::TDK_SubstitutionFailure:
580    Result.Data = Info.take();
581    if (Info.hasSFINAEDiagnostic()) {
582      PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
583          SourceLocation(), PartialDiagnostic::NullDiagnostic());
584      Info.takeSFINAEDiagnostic(*Diag);
585      Result.HasDiagnostic = true;
586    }
587    break;
588
589  case Sema::TDK_NonDeducedMismatch:
590  case Sema::TDK_FailedOverloadResolution:
591    break;
592  }
593
594  return Result;
595}
596
597void OverloadCandidate::DeductionFailureInfo::Destroy() {
598  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
599  case Sema::TDK_Success:
600  case Sema::TDK_InstantiationDepth:
601  case Sema::TDK_Incomplete:
602  case Sema::TDK_TooManyArguments:
603  case Sema::TDK_TooFewArguments:
604  case Sema::TDK_InvalidExplicitArguments:
605    break;
606
607  case Sema::TDK_Inconsistent:
608  case Sema::TDK_Underqualified:
609    // FIXME: Destroy the data?
610    Data = 0;
611    break;
612
613  case Sema::TDK_SubstitutionFailure:
614    // FIXME: Destroy the template argument list?
615    Data = 0;
616    if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
617      Diag->~PartialDiagnosticAt();
618      HasDiagnostic = false;
619    }
620    break;
621
622  // Unhandled
623  case Sema::TDK_NonDeducedMismatch:
624  case Sema::TDK_FailedOverloadResolution:
625    break;
626  }
627}
628
629PartialDiagnosticAt *
630OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
631  if (HasDiagnostic)
632    return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
633  return 0;
634}
635
636TemplateParameter
637OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
638  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
639  case Sema::TDK_Success:
640  case Sema::TDK_InstantiationDepth:
641  case Sema::TDK_TooManyArguments:
642  case Sema::TDK_TooFewArguments:
643  case Sema::TDK_SubstitutionFailure:
644    return TemplateParameter();
645
646  case Sema::TDK_Incomplete:
647  case Sema::TDK_InvalidExplicitArguments:
648    return TemplateParameter::getFromOpaqueValue(Data);
649
650  case Sema::TDK_Inconsistent:
651  case Sema::TDK_Underqualified:
652    return static_cast<DFIParamWithArguments*>(Data)->Param;
653
654  // Unhandled
655  case Sema::TDK_NonDeducedMismatch:
656  case Sema::TDK_FailedOverloadResolution:
657    break;
658  }
659
660  return TemplateParameter();
661}
662
663TemplateArgumentList *
664OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
665  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
666    case Sema::TDK_Success:
667    case Sema::TDK_InstantiationDepth:
668    case Sema::TDK_TooManyArguments:
669    case Sema::TDK_TooFewArguments:
670    case Sema::TDK_Incomplete:
671    case Sema::TDK_InvalidExplicitArguments:
672    case Sema::TDK_Inconsistent:
673    case Sema::TDK_Underqualified:
674      return 0;
675
676    case Sema::TDK_SubstitutionFailure:
677      return static_cast<TemplateArgumentList*>(Data);
678
679    // Unhandled
680    case Sema::TDK_NonDeducedMismatch:
681    case Sema::TDK_FailedOverloadResolution:
682      break;
683  }
684
685  return 0;
686}
687
688const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
689  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
690  case Sema::TDK_Success:
691  case Sema::TDK_InstantiationDepth:
692  case Sema::TDK_Incomplete:
693  case Sema::TDK_TooManyArguments:
694  case Sema::TDK_TooFewArguments:
695  case Sema::TDK_InvalidExplicitArguments:
696  case Sema::TDK_SubstitutionFailure:
697    return 0;
698
699  case Sema::TDK_Inconsistent:
700  case Sema::TDK_Underqualified:
701    return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
702
703  // Unhandled
704  case Sema::TDK_NonDeducedMismatch:
705  case Sema::TDK_FailedOverloadResolution:
706    break;
707  }
708
709  return 0;
710}
711
712const TemplateArgument *
713OverloadCandidate::DeductionFailureInfo::getSecondArg() {
714  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
715  case Sema::TDK_Success:
716  case Sema::TDK_InstantiationDepth:
717  case Sema::TDK_Incomplete:
718  case Sema::TDK_TooManyArguments:
719  case Sema::TDK_TooFewArguments:
720  case Sema::TDK_InvalidExplicitArguments:
721  case Sema::TDK_SubstitutionFailure:
722    return 0;
723
724  case Sema::TDK_Inconsistent:
725  case Sema::TDK_Underqualified:
726    return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
727
728  // Unhandled
729  case Sema::TDK_NonDeducedMismatch:
730  case Sema::TDK_FailedOverloadResolution:
731    break;
732  }
733
734  return 0;
735}
736
737void OverloadCandidateSet::clear() {
738  for (iterator i = begin(), e = end(); i != e; ++i)
739    for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
740      i->Conversions[ii].~ImplicitConversionSequence();
741  NumInlineSequences = 0;
742  Candidates.clear();
743  Functions.clear();
744}
745
746namespace {
747  class UnbridgedCastsSet {
748    struct Entry {
749      Expr **Addr;
750      Expr *Saved;
751    };
752    SmallVector<Entry, 2> Entries;
753
754  public:
755    void save(Sema &S, Expr *&E) {
756      assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
757      Entry entry = { &E, E };
758      Entries.push_back(entry);
759      E = S.stripARCUnbridgedCast(E);
760    }
761
762    void restore() {
763      for (SmallVectorImpl<Entry>::iterator
764             i = Entries.begin(), e = Entries.end(); i != e; ++i)
765        *i->Addr = i->Saved;
766    }
767  };
768}
769
770/// checkPlaceholderForOverload - Do any interesting placeholder-like
771/// preprocessing on the given expression.
772///
773/// \param unbridgedCasts a collection to which to add unbridged casts;
774///   without this, they will be immediately diagnosed as errors
775///
776/// Return true on unrecoverable error.
777static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
778                                        UnbridgedCastsSet *unbridgedCasts = 0) {
779  if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
780    // We can't handle overloaded expressions here because overload
781    // resolution might reasonably tweak them.
782    if (placeholder->getKind() == BuiltinType::Overload) return false;
783
784    // If the context potentially accepts unbridged ARC casts, strip
785    // the unbridged cast and add it to the collection for later restoration.
786    if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
787        unbridgedCasts) {
788      unbridgedCasts->save(S, E);
789      return false;
790    }
791
792    // Go ahead and check everything else.
793    ExprResult result = S.CheckPlaceholderExpr(E);
794    if (result.isInvalid())
795      return true;
796
797    E = result.take();
798    return false;
799  }
800
801  // Nothing to do.
802  return false;
803}
804
805/// checkArgPlaceholdersForOverload - Check a set of call operands for
806/// placeholders.
807static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
808                                            unsigned numArgs,
809                                            UnbridgedCastsSet &unbridged) {
810  for (unsigned i = 0; i != numArgs; ++i)
811    if (checkPlaceholderForOverload(S, args[i], &unbridged))
812      return true;
813
814  return false;
815}
816
817// IsOverload - Determine whether the given New declaration is an
818// overload of the declarations in Old. This routine returns false if
819// New and Old cannot be overloaded, e.g., if New has the same
820// signature as some function in Old (C++ 1.3.10) or if the Old
821// declarations aren't functions (or function templates) at all. When
822// it does return false, MatchedDecl will point to the decl that New
823// cannot be overloaded with.  This decl may be a UsingShadowDecl on
824// top of the underlying declaration.
825//
826// Example: Given the following input:
827//
828//   void f(int, float); // #1
829//   void f(int, int); // #2
830//   int f(int, int); // #3
831//
832// When we process #1, there is no previous declaration of "f",
833// so IsOverload will not be used.
834//
835// When we process #2, Old contains only the FunctionDecl for #1.  By
836// comparing the parameter types, we see that #1 and #2 are overloaded
837// (since they have different signatures), so this routine returns
838// false; MatchedDecl is unchanged.
839//
840// When we process #3, Old is an overload set containing #1 and #2. We
841// compare the signatures of #3 to #1 (they're overloaded, so we do
842// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
843// identical (return types of functions are not part of the
844// signature), IsOverload returns false and MatchedDecl will be set to
845// point to the FunctionDecl for #2.
846//
847// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
848// into a class by a using declaration.  The rules for whether to hide
849// shadow declarations ignore some properties which otherwise figure
850// into a function template's signature.
851Sema::OverloadKind
852Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
853                    NamedDecl *&Match, bool NewIsUsingDecl) {
854  for (LookupResult::iterator I = Old.begin(), E = Old.end();
855         I != E; ++I) {
856    NamedDecl *OldD = *I;
857
858    bool OldIsUsingDecl = false;
859    if (isa<UsingShadowDecl>(OldD)) {
860      OldIsUsingDecl = true;
861
862      // We can always introduce two using declarations into the same
863      // context, even if they have identical signatures.
864      if (NewIsUsingDecl) continue;
865
866      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
867    }
868
869    // If either declaration was introduced by a using declaration,
870    // we'll need to use slightly different rules for matching.
871    // Essentially, these rules are the normal rules, except that
872    // function templates hide function templates with different
873    // return types or template parameter lists.
874    bool UseMemberUsingDeclRules =
875      (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
876
877    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
878      if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
879        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
880          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
881          continue;
882        }
883
884        Match = *I;
885        return Ovl_Match;
886      }
887    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
888      if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
889        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
890          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
891          continue;
892        }
893
894        Match = *I;
895        return Ovl_Match;
896      }
897    } else if (isa<UsingDecl>(OldD)) {
898      // We can overload with these, which can show up when doing
899      // redeclaration checks for UsingDecls.
900      assert(Old.getLookupKind() == LookupUsingDeclName);
901    } else if (isa<TagDecl>(OldD)) {
902      // We can always overload with tags by hiding them.
903    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
904      // Optimistically assume that an unresolved using decl will
905      // overload; if it doesn't, we'll have to diagnose during
906      // template instantiation.
907    } else {
908      // (C++ 13p1):
909      //   Only function declarations can be overloaded; object and type
910      //   declarations cannot be overloaded.
911      Match = *I;
912      return Ovl_NonFunction;
913    }
914  }
915
916  return Ovl_Overload;
917}
918
919bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
920                      bool UseUsingDeclRules) {
921  // If both of the functions are extern "C", then they are not
922  // overloads.
923  if (Old->isExternC() && New->isExternC())
924    return false;
925
926  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
927  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
928
929  // C++ [temp.fct]p2:
930  //   A function template can be overloaded with other function templates
931  //   and with normal (non-template) functions.
932  if ((OldTemplate == 0) != (NewTemplate == 0))
933    return true;
934
935  // Is the function New an overload of the function Old?
936  QualType OldQType = Context.getCanonicalType(Old->getType());
937  QualType NewQType = Context.getCanonicalType(New->getType());
938
939  // Compare the signatures (C++ 1.3.10) of the two functions to
940  // determine whether they are overloads. If we find any mismatch
941  // in the signature, they are overloads.
942
943  // If either of these functions is a K&R-style function (no
944  // prototype), then we consider them to have matching signatures.
945  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
946      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
947    return false;
948
949  const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
950  const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
951
952  // The signature of a function includes the types of its
953  // parameters (C++ 1.3.10), which includes the presence or absence
954  // of the ellipsis; see C++ DR 357).
955  if (OldQType != NewQType &&
956      (OldType->getNumArgs() != NewType->getNumArgs() ||
957       OldType->isVariadic() != NewType->isVariadic() ||
958       !FunctionArgTypesAreEqual(OldType, NewType)))
959    return true;
960
961  // C++ [temp.over.link]p4:
962  //   The signature of a function template consists of its function
963  //   signature, its return type and its template parameter list. The names
964  //   of the template parameters are significant only for establishing the
965  //   relationship between the template parameters and the rest of the
966  //   signature.
967  //
968  // We check the return type and template parameter lists for function
969  // templates first; the remaining checks follow.
970  //
971  // However, we don't consider either of these when deciding whether
972  // a member introduced by a shadow declaration is hidden.
973  if (!UseUsingDeclRules && NewTemplate &&
974      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
975                                       OldTemplate->getTemplateParameters(),
976                                       false, TPL_TemplateMatch) ||
977       OldType->getResultType() != NewType->getResultType()))
978    return true;
979
980  // If the function is a class member, its signature includes the
981  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
982  //
983  // As part of this, also check whether one of the member functions
984  // is static, in which case they are not overloads (C++
985  // 13.1p2). While not part of the definition of the signature,
986  // this check is important to determine whether these functions
987  // can be overloaded.
988  CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
989  CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
990  if (OldMethod && NewMethod &&
991      !OldMethod->isStatic() && !NewMethod->isStatic() &&
992      (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
993       OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
994    if (!UseUsingDeclRules &&
995        OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
996        (OldMethod->getRefQualifier() == RQ_None ||
997         NewMethod->getRefQualifier() == RQ_None)) {
998      // C++0x [over.load]p2:
999      //   - Member function declarations with the same name and the same
1000      //     parameter-type-list as well as member function template
1001      //     declarations with the same name, the same parameter-type-list, and
1002      //     the same template parameter lists cannot be overloaded if any of
1003      //     them, but not all, have a ref-qualifier (8.3.5).
1004      Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1005        << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1006      Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1007    }
1008
1009    return true;
1010  }
1011
1012  // The signatures match; this is not an overload.
1013  return false;
1014}
1015
1016/// \brief Checks availability of the function depending on the current
1017/// function context. Inside an unavailable function, unavailability is ignored.
1018///
1019/// \returns true if \arg FD is unavailable and current context is inside
1020/// an available function, false otherwise.
1021bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1022  return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1023}
1024
1025/// \brief Tries a user-defined conversion from From to ToType.
1026///
1027/// Produces an implicit conversion sequence for when a standard conversion
1028/// is not an option. See TryImplicitConversion for more information.
1029static ImplicitConversionSequence
1030TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1031                         bool SuppressUserConversions,
1032                         bool AllowExplicit,
1033                         bool InOverloadResolution,
1034                         bool CStyle,
1035                         bool AllowObjCWritebackConversion) {
1036  ImplicitConversionSequence ICS;
1037
1038  if (SuppressUserConversions) {
1039    // We're not in the case above, so there is no conversion that
1040    // we can perform.
1041    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1042    return ICS;
1043  }
1044
1045  // Attempt user-defined conversion.
1046  OverloadCandidateSet Conversions(From->getExprLoc());
1047  OverloadingResult UserDefResult
1048    = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1049                              AllowExplicit);
1050
1051  if (UserDefResult == OR_Success) {
1052    ICS.setUserDefined();
1053    // C++ [over.ics.user]p4:
1054    //   A conversion of an expression of class type to the same class
1055    //   type is given Exact Match rank, and a conversion of an
1056    //   expression of class type to a base class of that type is
1057    //   given Conversion rank, in spite of the fact that a copy
1058    //   constructor (i.e., a user-defined conversion function) is
1059    //   called for those cases.
1060    if (CXXConstructorDecl *Constructor
1061          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1062      QualType FromCanon
1063        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1064      QualType ToCanon
1065        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1066      if (Constructor->isCopyConstructor() &&
1067          (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1068        // Turn this into a "standard" conversion sequence, so that it
1069        // gets ranked with standard conversion sequences.
1070        ICS.setStandard();
1071        ICS.Standard.setAsIdentityConversion();
1072        ICS.Standard.setFromType(From->getType());
1073        ICS.Standard.setAllToTypes(ToType);
1074        ICS.Standard.CopyConstructor = Constructor;
1075        if (ToCanon != FromCanon)
1076          ICS.Standard.Second = ICK_Derived_To_Base;
1077      }
1078    }
1079
1080    // C++ [over.best.ics]p4:
1081    //   However, when considering the argument of a user-defined
1082    //   conversion function that is a candidate by 13.3.1.3 when
1083    //   invoked for the copying of the temporary in the second step
1084    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1085    //   13.3.1.6 in all cases, only standard conversion sequences and
1086    //   ellipsis conversion sequences are allowed.
1087    if (SuppressUserConversions && ICS.isUserDefined()) {
1088      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1089    }
1090  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1091    ICS.setAmbiguous();
1092    ICS.Ambiguous.setFromType(From->getType());
1093    ICS.Ambiguous.setToType(ToType);
1094    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1095         Cand != Conversions.end(); ++Cand)
1096      if (Cand->Viable)
1097        ICS.Ambiguous.addConversion(Cand->Function);
1098  } else {
1099    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1100  }
1101
1102  return ICS;
1103}
1104
1105/// TryImplicitConversion - Attempt to perform an implicit conversion
1106/// from the given expression (Expr) to the given type (ToType). This
1107/// function returns an implicit conversion sequence that can be used
1108/// to perform the initialization. Given
1109///
1110///   void f(float f);
1111///   void g(int i) { f(i); }
1112///
1113/// this routine would produce an implicit conversion sequence to
1114/// describe the initialization of f from i, which will be a standard
1115/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1116/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1117//
1118/// Note that this routine only determines how the conversion can be
1119/// performed; it does not actually perform the conversion. As such,
1120/// it will not produce any diagnostics if no conversion is available,
1121/// but will instead return an implicit conversion sequence of kind
1122/// "BadConversion".
1123///
1124/// If @p SuppressUserConversions, then user-defined conversions are
1125/// not permitted.
1126/// If @p AllowExplicit, then explicit user-defined conversions are
1127/// permitted.
1128///
1129/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1130/// writeback conversion, which allows __autoreleasing id* parameters to
1131/// be initialized with __strong id* or __weak id* arguments.
1132static ImplicitConversionSequence
1133TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1134                      bool SuppressUserConversions,
1135                      bool AllowExplicit,
1136                      bool InOverloadResolution,
1137                      bool CStyle,
1138                      bool AllowObjCWritebackConversion) {
1139  ImplicitConversionSequence ICS;
1140  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1141                           ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1142    ICS.setStandard();
1143    return ICS;
1144  }
1145
1146  if (!S.getLangOpts().CPlusPlus) {
1147    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1148    return ICS;
1149  }
1150
1151  // C++ [over.ics.user]p4:
1152  //   A conversion of an expression of class type to the same class
1153  //   type is given Exact Match rank, and a conversion of an
1154  //   expression of class type to a base class of that type is
1155  //   given Conversion rank, in spite of the fact that a copy/move
1156  //   constructor (i.e., a user-defined conversion function) is
1157  //   called for those cases.
1158  QualType FromType = From->getType();
1159  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1160      (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1161       S.IsDerivedFrom(FromType, ToType))) {
1162    ICS.setStandard();
1163    ICS.Standard.setAsIdentityConversion();
1164    ICS.Standard.setFromType(FromType);
1165    ICS.Standard.setAllToTypes(ToType);
1166
1167    // We don't actually check at this point whether there is a valid
1168    // copy/move constructor, since overloading just assumes that it
1169    // exists. When we actually perform initialization, we'll find the
1170    // appropriate constructor to copy the returned object, if needed.
1171    ICS.Standard.CopyConstructor = 0;
1172
1173    // Determine whether this is considered a derived-to-base conversion.
1174    if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1175      ICS.Standard.Second = ICK_Derived_To_Base;
1176
1177    return ICS;
1178  }
1179
1180  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1181                                  AllowExplicit, InOverloadResolution, CStyle,
1182                                  AllowObjCWritebackConversion);
1183}
1184
1185ImplicitConversionSequence
1186Sema::TryImplicitConversion(Expr *From, QualType ToType,
1187                            bool SuppressUserConversions,
1188                            bool AllowExplicit,
1189                            bool InOverloadResolution,
1190                            bool CStyle,
1191                            bool AllowObjCWritebackConversion) {
1192  return clang::TryImplicitConversion(*this, From, ToType,
1193                                      SuppressUserConversions, AllowExplicit,
1194                                      InOverloadResolution, CStyle,
1195                                      AllowObjCWritebackConversion);
1196}
1197
1198/// PerformImplicitConversion - Perform an implicit conversion of the
1199/// expression From to the type ToType. Returns the
1200/// converted expression. Flavor is the kind of conversion we're
1201/// performing, used in the error message. If @p AllowExplicit,
1202/// explicit user-defined conversions are permitted.
1203ExprResult
1204Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1205                                AssignmentAction Action, bool AllowExplicit) {
1206  ImplicitConversionSequence ICS;
1207  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1208}
1209
1210ExprResult
1211Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1212                                AssignmentAction Action, bool AllowExplicit,
1213                                ImplicitConversionSequence& ICS) {
1214  if (checkPlaceholderForOverload(*this, From))
1215    return ExprError();
1216
1217  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1218  bool AllowObjCWritebackConversion
1219    = getLangOpts().ObjCAutoRefCount &&
1220      (Action == AA_Passing || Action == AA_Sending);
1221
1222  ICS = clang::TryImplicitConversion(*this, From, ToType,
1223                                     /*SuppressUserConversions=*/false,
1224                                     AllowExplicit,
1225                                     /*InOverloadResolution=*/false,
1226                                     /*CStyle=*/false,
1227                                     AllowObjCWritebackConversion);
1228  return PerformImplicitConversion(From, ToType, ICS, Action);
1229}
1230
1231/// \brief Determine whether the conversion from FromType to ToType is a valid
1232/// conversion that strips "noreturn" off the nested function type.
1233bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1234                                QualType &ResultTy) {
1235  if (Context.hasSameUnqualifiedType(FromType, ToType))
1236    return false;
1237
1238  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1239  // where F adds one of the following at most once:
1240  //   - a pointer
1241  //   - a member pointer
1242  //   - a block pointer
1243  CanQualType CanTo = Context.getCanonicalType(ToType);
1244  CanQualType CanFrom = Context.getCanonicalType(FromType);
1245  Type::TypeClass TyClass = CanTo->getTypeClass();
1246  if (TyClass != CanFrom->getTypeClass()) return false;
1247  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1248    if (TyClass == Type::Pointer) {
1249      CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1250      CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1251    } else if (TyClass == Type::BlockPointer) {
1252      CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1253      CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1254    } else if (TyClass == Type::MemberPointer) {
1255      CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1256      CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1257    } else {
1258      return false;
1259    }
1260
1261    TyClass = CanTo->getTypeClass();
1262    if (TyClass != CanFrom->getTypeClass()) return false;
1263    if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1264      return false;
1265  }
1266
1267  const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1268  FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1269  if (!EInfo.getNoReturn()) return false;
1270
1271  FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1272  assert(QualType(FromFn, 0).isCanonical());
1273  if (QualType(FromFn, 0) != CanTo) return false;
1274
1275  ResultTy = ToType;
1276  return true;
1277}
1278
1279/// \brief Determine whether the conversion from FromType to ToType is a valid
1280/// vector conversion.
1281///
1282/// \param ICK Will be set to the vector conversion kind, if this is a vector
1283/// conversion.
1284static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1285                               QualType ToType, ImplicitConversionKind &ICK) {
1286  // We need at least one of these types to be a vector type to have a vector
1287  // conversion.
1288  if (!ToType->isVectorType() && !FromType->isVectorType())
1289    return false;
1290
1291  // Identical types require no conversions.
1292  if (Context.hasSameUnqualifiedType(FromType, ToType))
1293    return false;
1294
1295  // There are no conversions between extended vector types, only identity.
1296  if (ToType->isExtVectorType()) {
1297    // There are no conversions between extended vector types other than the
1298    // identity conversion.
1299    if (FromType->isExtVectorType())
1300      return false;
1301
1302    // Vector splat from any arithmetic type to a vector.
1303    if (FromType->isArithmeticType()) {
1304      ICK = ICK_Vector_Splat;
1305      return true;
1306    }
1307  }
1308
1309  // We can perform the conversion between vector types in the following cases:
1310  // 1)vector types are equivalent AltiVec and GCC vector types
1311  // 2)lax vector conversions are permitted and the vector types are of the
1312  //   same size
1313  if (ToType->isVectorType() && FromType->isVectorType()) {
1314    if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1315        (Context.getLangOpts().LaxVectorConversions &&
1316         (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1317      ICK = ICK_Vector_Conversion;
1318      return true;
1319    }
1320  }
1321
1322  return false;
1323}
1324
1325static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1326                                bool InOverloadResolution,
1327                                StandardConversionSequence &SCS,
1328                                bool CStyle);
1329
1330/// IsStandardConversion - Determines whether there is a standard
1331/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1332/// expression From to the type ToType. Standard conversion sequences
1333/// only consider non-class types; for conversions that involve class
1334/// types, use TryImplicitConversion. If a conversion exists, SCS will
1335/// contain the standard conversion sequence required to perform this
1336/// conversion and this routine will return true. Otherwise, this
1337/// routine will return false and the value of SCS is unspecified.
1338static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1339                                 bool InOverloadResolution,
1340                                 StandardConversionSequence &SCS,
1341                                 bool CStyle,
1342                                 bool AllowObjCWritebackConversion) {
1343  QualType FromType = From->getType();
1344
1345  // Standard conversions (C++ [conv])
1346  SCS.setAsIdentityConversion();
1347  SCS.DeprecatedStringLiteralToCharPtr = false;
1348  SCS.IncompatibleObjC = false;
1349  SCS.setFromType(FromType);
1350  SCS.CopyConstructor = 0;
1351
1352  // There are no standard conversions for class types in C++, so
1353  // abort early. When overloading in C, however, we do permit
1354  if (FromType->isRecordType() || ToType->isRecordType()) {
1355    if (S.getLangOpts().CPlusPlus)
1356      return false;
1357
1358    // When we're overloading in C, we allow, as standard conversions,
1359  }
1360
1361  // The first conversion can be an lvalue-to-rvalue conversion,
1362  // array-to-pointer conversion, or function-to-pointer conversion
1363  // (C++ 4p1).
1364
1365  if (FromType == S.Context.OverloadTy) {
1366    DeclAccessPair AccessPair;
1367    if (FunctionDecl *Fn
1368          = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1369                                                 AccessPair)) {
1370      // We were able to resolve the address of the overloaded function,
1371      // so we can convert to the type of that function.
1372      FromType = Fn->getType();
1373
1374      // we can sometimes resolve &foo<int> regardless of ToType, so check
1375      // if the type matches (identity) or we are converting to bool
1376      if (!S.Context.hasSameUnqualifiedType(
1377                      S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1378        QualType resultTy;
1379        // if the function type matches except for [[noreturn]], it's ok
1380        if (!S.IsNoReturnConversion(FromType,
1381              S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1382          // otherwise, only a boolean conversion is standard
1383          if (!ToType->isBooleanType())
1384            return false;
1385      }
1386
1387      // Check if the "from" expression is taking the address of an overloaded
1388      // function and recompute the FromType accordingly. Take advantage of the
1389      // fact that non-static member functions *must* have such an address-of
1390      // expression.
1391      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1392      if (Method && !Method->isStatic()) {
1393        assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1394               "Non-unary operator on non-static member address");
1395        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1396               == UO_AddrOf &&
1397               "Non-address-of operator on non-static member address");
1398        const Type *ClassType
1399          = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1400        FromType = S.Context.getMemberPointerType(FromType, ClassType);
1401      } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1402        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1403               UO_AddrOf &&
1404               "Non-address-of operator for overloaded function expression");
1405        FromType = S.Context.getPointerType(FromType);
1406      }
1407
1408      // Check that we've computed the proper type after overload resolution.
1409      assert(S.Context.hasSameType(
1410        FromType,
1411        S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1412    } else {
1413      return false;
1414    }
1415  }
1416  // Lvalue-to-rvalue conversion (C++11 4.1):
1417  //   A glvalue (3.10) of a non-function, non-array type T can
1418  //   be converted to a prvalue.
1419  bool argIsLValue = From->isGLValue();
1420  if (argIsLValue &&
1421      !FromType->isFunctionType() && !FromType->isArrayType() &&
1422      S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1423    SCS.First = ICK_Lvalue_To_Rvalue;
1424
1425    // C11 6.3.2.1p2:
1426    //   ... if the lvalue has atomic type, the value has the non-atomic version
1427    //   of the type of the lvalue ...
1428    if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1429      FromType = Atomic->getValueType();
1430
1431    // If T is a non-class type, the type of the rvalue is the
1432    // cv-unqualified version of T. Otherwise, the type of the rvalue
1433    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1434    // just strip the qualifiers because they don't matter.
1435    FromType = FromType.getUnqualifiedType();
1436  } else if (FromType->isArrayType()) {
1437    // Array-to-pointer conversion (C++ 4.2)
1438    SCS.First = ICK_Array_To_Pointer;
1439
1440    // An lvalue or rvalue of type "array of N T" or "array of unknown
1441    // bound of T" can be converted to an rvalue of type "pointer to
1442    // T" (C++ 4.2p1).
1443    FromType = S.Context.getArrayDecayedType(FromType);
1444
1445    if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1446      // This conversion is deprecated. (C++ D.4).
1447      SCS.DeprecatedStringLiteralToCharPtr = true;
1448
1449      // For the purpose of ranking in overload resolution
1450      // (13.3.3.1.1), this conversion is considered an
1451      // array-to-pointer conversion followed by a qualification
1452      // conversion (4.4). (C++ 4.2p2)
1453      SCS.Second = ICK_Identity;
1454      SCS.Third = ICK_Qualification;
1455      SCS.QualificationIncludesObjCLifetime = false;
1456      SCS.setAllToTypes(FromType);
1457      return true;
1458    }
1459  } else if (FromType->isFunctionType() && argIsLValue) {
1460    // Function-to-pointer conversion (C++ 4.3).
1461    SCS.First = ICK_Function_To_Pointer;
1462
1463    // An lvalue of function type T can be converted to an rvalue of
1464    // type "pointer to T." The result is a pointer to the
1465    // function. (C++ 4.3p1).
1466    FromType = S.Context.getPointerType(FromType);
1467  } else {
1468    // We don't require any conversions for the first step.
1469    SCS.First = ICK_Identity;
1470  }
1471  SCS.setToType(0, FromType);
1472
1473  // The second conversion can be an integral promotion, floating
1474  // point promotion, integral conversion, floating point conversion,
1475  // floating-integral conversion, pointer conversion,
1476  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1477  // For overloading in C, this can also be a "compatible-type"
1478  // conversion.
1479  bool IncompatibleObjC = false;
1480  ImplicitConversionKind SecondICK = ICK_Identity;
1481  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1482    // The unqualified versions of the types are the same: there's no
1483    // conversion to do.
1484    SCS.Second = ICK_Identity;
1485  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1486    // Integral promotion (C++ 4.5).
1487    SCS.Second = ICK_Integral_Promotion;
1488    FromType = ToType.getUnqualifiedType();
1489  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1490    // Floating point promotion (C++ 4.6).
1491    SCS.Second = ICK_Floating_Promotion;
1492    FromType = ToType.getUnqualifiedType();
1493  } else if (S.IsComplexPromotion(FromType, ToType)) {
1494    // Complex promotion (Clang extension)
1495    SCS.Second = ICK_Complex_Promotion;
1496    FromType = ToType.getUnqualifiedType();
1497  } else if (ToType->isBooleanType() &&
1498             (FromType->isArithmeticType() ||
1499              FromType->isAnyPointerType() ||
1500              FromType->isBlockPointerType() ||
1501              FromType->isMemberPointerType() ||
1502              FromType->isNullPtrType())) {
1503    // Boolean conversions (C++ 4.12).
1504    SCS.Second = ICK_Boolean_Conversion;
1505    FromType = S.Context.BoolTy;
1506  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1507             ToType->isIntegralType(S.Context)) {
1508    // Integral conversions (C++ 4.7).
1509    SCS.Second = ICK_Integral_Conversion;
1510    FromType = ToType.getUnqualifiedType();
1511  } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1512    // Complex conversions (C99 6.3.1.6)
1513    SCS.Second = ICK_Complex_Conversion;
1514    FromType = ToType.getUnqualifiedType();
1515  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1516             (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1517    // Complex-real conversions (C99 6.3.1.7)
1518    SCS.Second = ICK_Complex_Real;
1519    FromType = ToType.getUnqualifiedType();
1520  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1521    // Floating point conversions (C++ 4.8).
1522    SCS.Second = ICK_Floating_Conversion;
1523    FromType = ToType.getUnqualifiedType();
1524  } else if ((FromType->isRealFloatingType() &&
1525              ToType->isIntegralType(S.Context)) ||
1526             (FromType->isIntegralOrUnscopedEnumerationType() &&
1527              ToType->isRealFloatingType())) {
1528    // Floating-integral conversions (C++ 4.9).
1529    SCS.Second = ICK_Floating_Integral;
1530    FromType = ToType.getUnqualifiedType();
1531  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1532    SCS.Second = ICK_Block_Pointer_Conversion;
1533  } else if (AllowObjCWritebackConversion &&
1534             S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1535    SCS.Second = ICK_Writeback_Conversion;
1536  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1537                                   FromType, IncompatibleObjC)) {
1538    // Pointer conversions (C++ 4.10).
1539    SCS.Second = ICK_Pointer_Conversion;
1540    SCS.IncompatibleObjC = IncompatibleObjC;
1541    FromType = FromType.getUnqualifiedType();
1542  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1543                                         InOverloadResolution, FromType)) {
1544    // Pointer to member conversions (4.11).
1545    SCS.Second = ICK_Pointer_Member;
1546  } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1547    SCS.Second = SecondICK;
1548    FromType = ToType.getUnqualifiedType();
1549  } else if (!S.getLangOpts().CPlusPlus &&
1550             S.Context.typesAreCompatible(ToType, FromType)) {
1551    // Compatible conversions (Clang extension for C function overloading)
1552    SCS.Second = ICK_Compatible_Conversion;
1553    FromType = ToType.getUnqualifiedType();
1554  } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1555    // Treat a conversion that strips "noreturn" as an identity conversion.
1556    SCS.Second = ICK_NoReturn_Adjustment;
1557  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1558                                             InOverloadResolution,
1559                                             SCS, CStyle)) {
1560    SCS.Second = ICK_TransparentUnionConversion;
1561    FromType = ToType;
1562  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1563                                 CStyle)) {
1564    // tryAtomicConversion has updated the standard conversion sequence
1565    // appropriately.
1566    return true;
1567  } else {
1568    // No second conversion required.
1569    SCS.Second = ICK_Identity;
1570  }
1571  SCS.setToType(1, FromType);
1572
1573  QualType CanonFrom;
1574  QualType CanonTo;
1575  // The third conversion can be a qualification conversion (C++ 4p1).
1576  bool ObjCLifetimeConversion;
1577  if (S.IsQualificationConversion(FromType, ToType, CStyle,
1578                                  ObjCLifetimeConversion)) {
1579    SCS.Third = ICK_Qualification;
1580    SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1581    FromType = ToType;
1582    CanonFrom = S.Context.getCanonicalType(FromType);
1583    CanonTo = S.Context.getCanonicalType(ToType);
1584  } else {
1585    // No conversion required
1586    SCS.Third = ICK_Identity;
1587
1588    // C++ [over.best.ics]p6:
1589    //   [...] Any difference in top-level cv-qualification is
1590    //   subsumed by the initialization itself and does not constitute
1591    //   a conversion. [...]
1592    CanonFrom = S.Context.getCanonicalType(FromType);
1593    CanonTo = S.Context.getCanonicalType(ToType);
1594    if (CanonFrom.getLocalUnqualifiedType()
1595                                       == CanonTo.getLocalUnqualifiedType() &&
1596        (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1597         || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1598         || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
1599      FromType = ToType;
1600      CanonFrom = CanonTo;
1601    }
1602  }
1603  SCS.setToType(2, FromType);
1604
1605  // If we have not converted the argument type to the parameter type,
1606  // this is a bad conversion sequence.
1607  if (CanonFrom != CanonTo)
1608    return false;
1609
1610  return true;
1611}
1612
1613static bool
1614IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1615                                     QualType &ToType,
1616                                     bool InOverloadResolution,
1617                                     StandardConversionSequence &SCS,
1618                                     bool CStyle) {
1619
1620  const RecordType *UT = ToType->getAsUnionType();
1621  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1622    return false;
1623  // The field to initialize within the transparent union.
1624  RecordDecl *UD = UT->getDecl();
1625  // It's compatible if the expression matches any of the fields.
1626  for (RecordDecl::field_iterator it = UD->field_begin(),
1627       itend = UD->field_end();
1628       it != itend; ++it) {
1629    if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1630                             CStyle, /*ObjCWritebackConversion=*/false)) {
1631      ToType = it->getType();
1632      return true;
1633    }
1634  }
1635  return false;
1636}
1637
1638/// IsIntegralPromotion - Determines whether the conversion from the
1639/// expression From (whose potentially-adjusted type is FromType) to
1640/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1641/// sets PromotedType to the promoted type.
1642bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1643  const BuiltinType *To = ToType->getAs<BuiltinType>();
1644  // All integers are built-in.
1645  if (!To) {
1646    return false;
1647  }
1648
1649  // An rvalue of type char, signed char, unsigned char, short int, or
1650  // unsigned short int can be converted to an rvalue of type int if
1651  // int can represent all the values of the source type; otherwise,
1652  // the source rvalue can be converted to an rvalue of type unsigned
1653  // int (C++ 4.5p1).
1654  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1655      !FromType->isEnumeralType()) {
1656    if (// We can promote any signed, promotable integer type to an int
1657        (FromType->isSignedIntegerType() ||
1658         // We can promote any unsigned integer type whose size is
1659         // less than int to an int.
1660         (!FromType->isSignedIntegerType() &&
1661          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1662      return To->getKind() == BuiltinType::Int;
1663    }
1664
1665    return To->getKind() == BuiltinType::UInt;
1666  }
1667
1668  // C++0x [conv.prom]p3:
1669  //   A prvalue of an unscoped enumeration type whose underlying type is not
1670  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1671  //   following types that can represent all the values of the enumeration
1672  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1673  //   unsigned int, long int, unsigned long int, long long int, or unsigned
1674  //   long long int. If none of the types in that list can represent all the
1675  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1676  //   type can be converted to an rvalue a prvalue of the extended integer type
1677  //   with lowest integer conversion rank (4.13) greater than the rank of long
1678  //   long in which all the values of the enumeration can be represented. If
1679  //   there are two such extended types, the signed one is chosen.
1680  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1681    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1682    // provided for a scoped enumeration.
1683    if (FromEnumType->getDecl()->isScoped())
1684      return false;
1685
1686    // We have already pre-calculated the promotion type, so this is trivial.
1687    if (ToType->isIntegerType() &&
1688        !RequireCompleteType(From->getLocStart(), FromType, 0))
1689      return Context.hasSameUnqualifiedType(ToType,
1690                                FromEnumType->getDecl()->getPromotionType());
1691  }
1692
1693  // C++0x [conv.prom]p2:
1694  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1695  //   to an rvalue a prvalue of the first of the following types that can
1696  //   represent all the values of its underlying type: int, unsigned int,
1697  //   long int, unsigned long int, long long int, or unsigned long long int.
1698  //   If none of the types in that list can represent all the values of its
1699  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1700  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1701  //   type.
1702  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1703      ToType->isIntegerType()) {
1704    // Determine whether the type we're converting from is signed or
1705    // unsigned.
1706    bool FromIsSigned = FromType->isSignedIntegerType();
1707    uint64_t FromSize = Context.getTypeSize(FromType);
1708
1709    // The types we'll try to promote to, in the appropriate
1710    // order. Try each of these types.
1711    QualType PromoteTypes[6] = {
1712      Context.IntTy, Context.UnsignedIntTy,
1713      Context.LongTy, Context.UnsignedLongTy ,
1714      Context.LongLongTy, Context.UnsignedLongLongTy
1715    };
1716    for (int Idx = 0; Idx < 6; ++Idx) {
1717      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1718      if (FromSize < ToSize ||
1719          (FromSize == ToSize &&
1720           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1721        // We found the type that we can promote to. If this is the
1722        // type we wanted, we have a promotion. Otherwise, no
1723        // promotion.
1724        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1725      }
1726    }
1727  }
1728
1729  // An rvalue for an integral bit-field (9.6) can be converted to an
1730  // rvalue of type int if int can represent all the values of the
1731  // bit-field; otherwise, it can be converted to unsigned int if
1732  // unsigned int can represent all the values of the bit-field. If
1733  // the bit-field is larger yet, no integral promotion applies to
1734  // it. If the bit-field has an enumerated type, it is treated as any
1735  // other value of that type for promotion purposes (C++ 4.5p3).
1736  // FIXME: We should delay checking of bit-fields until we actually perform the
1737  // conversion.
1738  using llvm::APSInt;
1739  if (From)
1740    if (FieldDecl *MemberDecl = From->getBitField()) {
1741      APSInt BitWidth;
1742      if (FromType->isIntegralType(Context) &&
1743          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1744        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1745        ToSize = Context.getTypeSize(ToType);
1746
1747        // Are we promoting to an int from a bitfield that fits in an int?
1748        if (BitWidth < ToSize ||
1749            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1750          return To->getKind() == BuiltinType::Int;
1751        }
1752
1753        // Are we promoting to an unsigned int from an unsigned bitfield
1754        // that fits into an unsigned int?
1755        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1756          return To->getKind() == BuiltinType::UInt;
1757        }
1758
1759        return false;
1760      }
1761    }
1762
1763  // An rvalue of type bool can be converted to an rvalue of type int,
1764  // with false becoming zero and true becoming one (C++ 4.5p4).
1765  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1766    return true;
1767  }
1768
1769  return false;
1770}
1771
1772/// IsFloatingPointPromotion - Determines whether the conversion from
1773/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1774/// returns true and sets PromotedType to the promoted type.
1775bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1776  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1777    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1778      /// An rvalue of type float can be converted to an rvalue of type
1779      /// double. (C++ 4.6p1).
1780      if (FromBuiltin->getKind() == BuiltinType::Float &&
1781          ToBuiltin->getKind() == BuiltinType::Double)
1782        return true;
1783
1784      // C99 6.3.1.5p1:
1785      //   When a float is promoted to double or long double, or a
1786      //   double is promoted to long double [...].
1787      if (!getLangOpts().CPlusPlus &&
1788          (FromBuiltin->getKind() == BuiltinType::Float ||
1789           FromBuiltin->getKind() == BuiltinType::Double) &&
1790          (ToBuiltin->getKind() == BuiltinType::LongDouble))
1791        return true;
1792
1793      // Half can be promoted to float.
1794      if (FromBuiltin->getKind() == BuiltinType::Half &&
1795          ToBuiltin->getKind() == BuiltinType::Float)
1796        return true;
1797    }
1798
1799  return false;
1800}
1801
1802/// \brief Determine if a conversion is a complex promotion.
1803///
1804/// A complex promotion is defined as a complex -> complex conversion
1805/// where the conversion between the underlying real types is a
1806/// floating-point or integral promotion.
1807bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1808  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1809  if (!FromComplex)
1810    return false;
1811
1812  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1813  if (!ToComplex)
1814    return false;
1815
1816  return IsFloatingPointPromotion(FromComplex->getElementType(),
1817                                  ToComplex->getElementType()) ||
1818    IsIntegralPromotion(0, FromComplex->getElementType(),
1819                        ToComplex->getElementType());
1820}
1821
1822/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1823/// the pointer type FromPtr to a pointer to type ToPointee, with the
1824/// same type qualifiers as FromPtr has on its pointee type. ToType,
1825/// if non-empty, will be a pointer to ToType that may or may not have
1826/// the right set of qualifiers on its pointee.
1827///
1828static QualType
1829BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1830                                   QualType ToPointee, QualType ToType,
1831                                   ASTContext &Context,
1832                                   bool StripObjCLifetime = false) {
1833  assert((FromPtr->getTypeClass() == Type::Pointer ||
1834          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1835         "Invalid similarly-qualified pointer type");
1836
1837  /// Conversions to 'id' subsume cv-qualifier conversions.
1838  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1839    return ToType.getUnqualifiedType();
1840
1841  QualType CanonFromPointee
1842    = Context.getCanonicalType(FromPtr->getPointeeType());
1843  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1844  Qualifiers Quals = CanonFromPointee.getQualifiers();
1845
1846  if (StripObjCLifetime)
1847    Quals.removeObjCLifetime();
1848
1849  // Exact qualifier match -> return the pointer type we're converting to.
1850  if (CanonToPointee.getLocalQualifiers() == Quals) {
1851    // ToType is exactly what we need. Return it.
1852    if (!ToType.isNull())
1853      return ToType.getUnqualifiedType();
1854
1855    // Build a pointer to ToPointee. It has the right qualifiers
1856    // already.
1857    if (isa<ObjCObjectPointerType>(ToType))
1858      return Context.getObjCObjectPointerType(ToPointee);
1859    return Context.getPointerType(ToPointee);
1860  }
1861
1862  // Just build a canonical type that has the right qualifiers.
1863  QualType QualifiedCanonToPointee
1864    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1865
1866  if (isa<ObjCObjectPointerType>(ToType))
1867    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1868  return Context.getPointerType(QualifiedCanonToPointee);
1869}
1870
1871static bool isNullPointerConstantForConversion(Expr *Expr,
1872                                               bool InOverloadResolution,
1873                                               ASTContext &Context) {
1874  // Handle value-dependent integral null pointer constants correctly.
1875  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1876  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1877      Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1878    return !InOverloadResolution;
1879
1880  return Expr->isNullPointerConstant(Context,
1881                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1882                                        : Expr::NPC_ValueDependentIsNull);
1883}
1884
1885/// IsPointerConversion - Determines whether the conversion of the
1886/// expression From, which has the (possibly adjusted) type FromType,
1887/// can be converted to the type ToType via a pointer conversion (C++
1888/// 4.10). If so, returns true and places the converted type (that
1889/// might differ from ToType in its cv-qualifiers at some level) into
1890/// ConvertedType.
1891///
1892/// This routine also supports conversions to and from block pointers
1893/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1894/// pointers to interfaces. FIXME: Once we've determined the
1895/// appropriate overloading rules for Objective-C, we may want to
1896/// split the Objective-C checks into a different routine; however,
1897/// GCC seems to consider all of these conversions to be pointer
1898/// conversions, so for now they live here. IncompatibleObjC will be
1899/// set if the conversion is an allowed Objective-C conversion that
1900/// should result in a warning.
1901bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1902                               bool InOverloadResolution,
1903                               QualType& ConvertedType,
1904                               bool &IncompatibleObjC) {
1905  IncompatibleObjC = false;
1906  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1907                              IncompatibleObjC))
1908    return true;
1909
1910  // Conversion from a null pointer constant to any Objective-C pointer type.
1911  if (ToType->isObjCObjectPointerType() &&
1912      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1913    ConvertedType = ToType;
1914    return true;
1915  }
1916
1917  // Blocks: Block pointers can be converted to void*.
1918  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1919      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1920    ConvertedType = ToType;
1921    return true;
1922  }
1923  // Blocks: A null pointer constant can be converted to a block
1924  // pointer type.
1925  if (ToType->isBlockPointerType() &&
1926      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1927    ConvertedType = ToType;
1928    return true;
1929  }
1930
1931  // If the left-hand-side is nullptr_t, the right side can be a null
1932  // pointer constant.
1933  if (ToType->isNullPtrType() &&
1934      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1935    ConvertedType = ToType;
1936    return true;
1937  }
1938
1939  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
1940  if (!ToTypePtr)
1941    return false;
1942
1943  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
1944  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1945    ConvertedType = ToType;
1946    return true;
1947  }
1948
1949  // Beyond this point, both types need to be pointers
1950  // , including objective-c pointers.
1951  QualType ToPointeeType = ToTypePtr->getPointeeType();
1952  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1953      !getLangOpts().ObjCAutoRefCount) {
1954    ConvertedType = BuildSimilarlyQualifiedPointerType(
1955                                      FromType->getAs<ObjCObjectPointerType>(),
1956                                                       ToPointeeType,
1957                                                       ToType, Context);
1958    return true;
1959  }
1960  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
1961  if (!FromTypePtr)
1962    return false;
1963
1964  QualType FromPointeeType = FromTypePtr->getPointeeType();
1965
1966  // If the unqualified pointee types are the same, this can't be a
1967  // pointer conversion, so don't do all of the work below.
1968  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1969    return false;
1970
1971  // An rvalue of type "pointer to cv T," where T is an object type,
1972  // can be converted to an rvalue of type "pointer to cv void" (C++
1973  // 4.10p2).
1974  if (FromPointeeType->isIncompleteOrObjectType() &&
1975      ToPointeeType->isVoidType()) {
1976    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1977                                                       ToPointeeType,
1978                                                       ToType, Context,
1979                                                   /*StripObjCLifetime=*/true);
1980    return true;
1981  }
1982
1983  // MSVC allows implicit function to void* type conversion.
1984  if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
1985      ToPointeeType->isVoidType()) {
1986    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1987                                                       ToPointeeType,
1988                                                       ToType, Context);
1989    return true;
1990  }
1991
1992  // When we're overloading in C, we allow a special kind of pointer
1993  // conversion for compatible-but-not-identical pointee types.
1994  if (!getLangOpts().CPlusPlus &&
1995      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
1996    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1997                                                       ToPointeeType,
1998                                                       ToType, Context);
1999    return true;
2000  }
2001
2002  // C++ [conv.ptr]p3:
2003  //
2004  //   An rvalue of type "pointer to cv D," where D is a class type,
2005  //   can be converted to an rvalue of type "pointer to cv B," where
2006  //   B is a base class (clause 10) of D. If B is an inaccessible
2007  //   (clause 11) or ambiguous (10.2) base class of D, a program that
2008  //   necessitates this conversion is ill-formed. The result of the
2009  //   conversion is a pointer to the base class sub-object of the
2010  //   derived class object. The null pointer value is converted to
2011  //   the null pointer value of the destination type.
2012  //
2013  // Note that we do not check for ambiguity or inaccessibility
2014  // here. That is handled by CheckPointerConversion.
2015  if (getLangOpts().CPlusPlus &&
2016      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2017      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2018      !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2019      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2020    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2021                                                       ToPointeeType,
2022                                                       ToType, Context);
2023    return true;
2024  }
2025
2026  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2027      Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2028    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2029                                                       ToPointeeType,
2030                                                       ToType, Context);
2031    return true;
2032  }
2033
2034  return false;
2035}
2036
2037/// \brief Adopt the given qualifiers for the given type.
2038static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2039  Qualifiers TQs = T.getQualifiers();
2040
2041  // Check whether qualifiers already match.
2042  if (TQs == Qs)
2043    return T;
2044
2045  if (Qs.compatiblyIncludes(TQs))
2046    return Context.getQualifiedType(T, Qs);
2047
2048  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2049}
2050
2051/// isObjCPointerConversion - Determines whether this is an
2052/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2053/// with the same arguments and return values.
2054bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2055                                   QualType& ConvertedType,
2056                                   bool &IncompatibleObjC) {
2057  if (!getLangOpts().ObjC1)
2058    return false;
2059
2060  // The set of qualifiers on the type we're converting from.
2061  Qualifiers FromQualifiers = FromType.getQualifiers();
2062
2063  // First, we handle all conversions on ObjC object pointer types.
2064  const ObjCObjectPointerType* ToObjCPtr =
2065    ToType->getAs<ObjCObjectPointerType>();
2066  const ObjCObjectPointerType *FromObjCPtr =
2067    FromType->getAs<ObjCObjectPointerType>();
2068
2069  if (ToObjCPtr && FromObjCPtr) {
2070    // If the pointee types are the same (ignoring qualifications),
2071    // then this is not a pointer conversion.
2072    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2073                                       FromObjCPtr->getPointeeType()))
2074      return false;
2075
2076    // Check for compatible
2077    // Objective C++: We're able to convert between "id" or "Class" and a
2078    // pointer to any interface (in both directions).
2079    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2080      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2081      return true;
2082    }
2083    // Conversions with Objective-C's id<...>.
2084    if ((FromObjCPtr->isObjCQualifiedIdType() ||
2085         ToObjCPtr->isObjCQualifiedIdType()) &&
2086        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2087                                                  /*compare=*/false)) {
2088      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2089      return true;
2090    }
2091    // Objective C++: We're able to convert from a pointer to an
2092    // interface to a pointer to a different interface.
2093    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2094      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2095      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2096      if (getLangOpts().CPlusPlus && LHS && RHS &&
2097          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2098                                                FromObjCPtr->getPointeeType()))
2099        return false;
2100      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2101                                                   ToObjCPtr->getPointeeType(),
2102                                                         ToType, Context);
2103      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2104      return true;
2105    }
2106
2107    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2108      // Okay: this is some kind of implicit downcast of Objective-C
2109      // interfaces, which is permitted. However, we're going to
2110      // complain about it.
2111      IncompatibleObjC = true;
2112      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2113                                                   ToObjCPtr->getPointeeType(),
2114                                                         ToType, Context);
2115      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2116      return true;
2117    }
2118  }
2119  // Beyond this point, both types need to be C pointers or block pointers.
2120  QualType ToPointeeType;
2121  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2122    ToPointeeType = ToCPtr->getPointeeType();
2123  else if (const BlockPointerType *ToBlockPtr =
2124            ToType->getAs<BlockPointerType>()) {
2125    // Objective C++: We're able to convert from a pointer to any object
2126    // to a block pointer type.
2127    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2128      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2129      return true;
2130    }
2131    ToPointeeType = ToBlockPtr->getPointeeType();
2132  }
2133  else if (FromType->getAs<BlockPointerType>() &&
2134           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2135    // Objective C++: We're able to convert from a block pointer type to a
2136    // pointer to any object.
2137    ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2138    return true;
2139  }
2140  else
2141    return false;
2142
2143  QualType FromPointeeType;
2144  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2145    FromPointeeType = FromCPtr->getPointeeType();
2146  else if (const BlockPointerType *FromBlockPtr =
2147           FromType->getAs<BlockPointerType>())
2148    FromPointeeType = FromBlockPtr->getPointeeType();
2149  else
2150    return false;
2151
2152  // If we have pointers to pointers, recursively check whether this
2153  // is an Objective-C conversion.
2154  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2155      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2156                              IncompatibleObjC)) {
2157    // We always complain about this conversion.
2158    IncompatibleObjC = true;
2159    ConvertedType = Context.getPointerType(ConvertedType);
2160    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2161    return true;
2162  }
2163  // Allow conversion of pointee being objective-c pointer to another one;
2164  // as in I* to id.
2165  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2166      ToPointeeType->getAs<ObjCObjectPointerType>() &&
2167      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2168                              IncompatibleObjC)) {
2169
2170    ConvertedType = Context.getPointerType(ConvertedType);
2171    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2172    return true;
2173  }
2174
2175  // If we have pointers to functions or blocks, check whether the only
2176  // differences in the argument and result types are in Objective-C
2177  // pointer conversions. If so, we permit the conversion (but
2178  // complain about it).
2179  const FunctionProtoType *FromFunctionType
2180    = FromPointeeType->getAs<FunctionProtoType>();
2181  const FunctionProtoType *ToFunctionType
2182    = ToPointeeType->getAs<FunctionProtoType>();
2183  if (FromFunctionType && ToFunctionType) {
2184    // If the function types are exactly the same, this isn't an
2185    // Objective-C pointer conversion.
2186    if (Context.getCanonicalType(FromPointeeType)
2187          == Context.getCanonicalType(ToPointeeType))
2188      return false;
2189
2190    // Perform the quick checks that will tell us whether these
2191    // function types are obviously different.
2192    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2193        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2194        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2195      return false;
2196
2197    bool HasObjCConversion = false;
2198    if (Context.getCanonicalType(FromFunctionType->getResultType())
2199          == Context.getCanonicalType(ToFunctionType->getResultType())) {
2200      // Okay, the types match exactly. Nothing to do.
2201    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2202                                       ToFunctionType->getResultType(),
2203                                       ConvertedType, IncompatibleObjC)) {
2204      // Okay, we have an Objective-C pointer conversion.
2205      HasObjCConversion = true;
2206    } else {
2207      // Function types are too different. Abort.
2208      return false;
2209    }
2210
2211    // Check argument types.
2212    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2213         ArgIdx != NumArgs; ++ArgIdx) {
2214      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2215      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2216      if (Context.getCanonicalType(FromArgType)
2217            == Context.getCanonicalType(ToArgType)) {
2218        // Okay, the types match exactly. Nothing to do.
2219      } else if (isObjCPointerConversion(FromArgType, ToArgType,
2220                                         ConvertedType, IncompatibleObjC)) {
2221        // Okay, we have an Objective-C pointer conversion.
2222        HasObjCConversion = true;
2223      } else {
2224        // Argument types are too different. Abort.
2225        return false;
2226      }
2227    }
2228
2229    if (HasObjCConversion) {
2230      // We had an Objective-C conversion. Allow this pointer
2231      // conversion, but complain about it.
2232      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2233      IncompatibleObjC = true;
2234      return true;
2235    }
2236  }
2237
2238  return false;
2239}
2240
2241/// \brief Determine whether this is an Objective-C writeback conversion,
2242/// used for parameter passing when performing automatic reference counting.
2243///
2244/// \param FromType The type we're converting form.
2245///
2246/// \param ToType The type we're converting to.
2247///
2248/// \param ConvertedType The type that will be produced after applying
2249/// this conversion.
2250bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2251                                     QualType &ConvertedType) {
2252  if (!getLangOpts().ObjCAutoRefCount ||
2253      Context.hasSameUnqualifiedType(FromType, ToType))
2254    return false;
2255
2256  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2257  QualType ToPointee;
2258  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2259    ToPointee = ToPointer->getPointeeType();
2260  else
2261    return false;
2262
2263  Qualifiers ToQuals = ToPointee.getQualifiers();
2264  if (!ToPointee->isObjCLifetimeType() ||
2265      ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2266      !ToQuals.withoutObjCLifetime().empty())
2267    return false;
2268
2269  // Argument must be a pointer to __strong to __weak.
2270  QualType FromPointee;
2271  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2272    FromPointee = FromPointer->getPointeeType();
2273  else
2274    return false;
2275
2276  Qualifiers FromQuals = FromPointee.getQualifiers();
2277  if (!FromPointee->isObjCLifetimeType() ||
2278      (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2279       FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2280    return false;
2281
2282  // Make sure that we have compatible qualifiers.
2283  FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2284  if (!ToQuals.compatiblyIncludes(FromQuals))
2285    return false;
2286
2287  // Remove qualifiers from the pointee type we're converting from; they
2288  // aren't used in the compatibility check belong, and we'll be adding back
2289  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2290  FromPointee = FromPointee.getUnqualifiedType();
2291
2292  // The unqualified form of the pointee types must be compatible.
2293  ToPointee = ToPointee.getUnqualifiedType();
2294  bool IncompatibleObjC;
2295  if (Context.typesAreCompatible(FromPointee, ToPointee))
2296    FromPointee = ToPointee;
2297  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2298                                    IncompatibleObjC))
2299    return false;
2300
2301  /// \brief Construct the type we're converting to, which is a pointer to
2302  /// __autoreleasing pointee.
2303  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2304  ConvertedType = Context.getPointerType(FromPointee);
2305  return true;
2306}
2307
2308bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2309                                    QualType& ConvertedType) {
2310  QualType ToPointeeType;
2311  if (const BlockPointerType *ToBlockPtr =
2312        ToType->getAs<BlockPointerType>())
2313    ToPointeeType = ToBlockPtr->getPointeeType();
2314  else
2315    return false;
2316
2317  QualType FromPointeeType;
2318  if (const BlockPointerType *FromBlockPtr =
2319      FromType->getAs<BlockPointerType>())
2320    FromPointeeType = FromBlockPtr->getPointeeType();
2321  else
2322    return false;
2323  // We have pointer to blocks, check whether the only
2324  // differences in the argument and result types are in Objective-C
2325  // pointer conversions. If so, we permit the conversion.
2326
2327  const FunctionProtoType *FromFunctionType
2328    = FromPointeeType->getAs<FunctionProtoType>();
2329  const FunctionProtoType *ToFunctionType
2330    = ToPointeeType->getAs<FunctionProtoType>();
2331
2332  if (!FromFunctionType || !ToFunctionType)
2333    return false;
2334
2335  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2336    return true;
2337
2338  // Perform the quick checks that will tell us whether these
2339  // function types are obviously different.
2340  if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2341      FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2342    return false;
2343
2344  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2345  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2346  if (FromEInfo != ToEInfo)
2347    return false;
2348
2349  bool IncompatibleObjC = false;
2350  if (Context.hasSameType(FromFunctionType->getResultType(),
2351                          ToFunctionType->getResultType())) {
2352    // Okay, the types match exactly. Nothing to do.
2353  } else {
2354    QualType RHS = FromFunctionType->getResultType();
2355    QualType LHS = ToFunctionType->getResultType();
2356    if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2357        !RHS.hasQualifiers() && LHS.hasQualifiers())
2358       LHS = LHS.getUnqualifiedType();
2359
2360     if (Context.hasSameType(RHS,LHS)) {
2361       // OK exact match.
2362     } else if (isObjCPointerConversion(RHS, LHS,
2363                                        ConvertedType, IncompatibleObjC)) {
2364     if (IncompatibleObjC)
2365       return false;
2366     // Okay, we have an Objective-C pointer conversion.
2367     }
2368     else
2369       return false;
2370   }
2371
2372   // Check argument types.
2373   for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2374        ArgIdx != NumArgs; ++ArgIdx) {
2375     IncompatibleObjC = false;
2376     QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2377     QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2378     if (Context.hasSameType(FromArgType, ToArgType)) {
2379       // Okay, the types match exactly. Nothing to do.
2380     } else if (isObjCPointerConversion(ToArgType, FromArgType,
2381                                        ConvertedType, IncompatibleObjC)) {
2382       if (IncompatibleObjC)
2383         return false;
2384       // Okay, we have an Objective-C pointer conversion.
2385     } else
2386       // Argument types are too different. Abort.
2387       return false;
2388   }
2389   if (LangOpts.ObjCAutoRefCount &&
2390       !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2391                                                    ToFunctionType))
2392     return false;
2393
2394   ConvertedType = ToType;
2395   return true;
2396}
2397
2398enum {
2399  ft_default,
2400  ft_different_class,
2401  ft_parameter_arity,
2402  ft_parameter_mismatch,
2403  ft_return_type,
2404  ft_qualifer_mismatch
2405};
2406
2407/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2408/// function types.  Catches different number of parameter, mismatch in
2409/// parameter types, and different return types.
2410void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2411                                      QualType FromType, QualType ToType) {
2412  // If either type is not valid, include no extra info.
2413  if (FromType.isNull() || ToType.isNull()) {
2414    PDiag << ft_default;
2415    return;
2416  }
2417
2418  // Get the function type from the pointers.
2419  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2420    const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2421                            *ToMember = ToType->getAs<MemberPointerType>();
2422    if (FromMember->getClass() != ToMember->getClass()) {
2423      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2424            << QualType(FromMember->getClass(), 0);
2425      return;
2426    }
2427    FromType = FromMember->getPointeeType();
2428    ToType = ToMember->getPointeeType();
2429  }
2430
2431  if (FromType->isPointerType())
2432    FromType = FromType->getPointeeType();
2433  if (ToType->isPointerType())
2434    ToType = ToType->getPointeeType();
2435
2436  // Remove references.
2437  FromType = FromType.getNonReferenceType();
2438  ToType = ToType.getNonReferenceType();
2439
2440  // Don't print extra info for non-specialized template functions.
2441  if (FromType->isInstantiationDependentType() &&
2442      !FromType->getAs<TemplateSpecializationType>()) {
2443    PDiag << ft_default;
2444    return;
2445  }
2446
2447  // No extra info for same types.
2448  if (Context.hasSameType(FromType, ToType)) {
2449    PDiag << ft_default;
2450    return;
2451  }
2452
2453  const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2454                          *ToFunction = ToType->getAs<FunctionProtoType>();
2455
2456  // Both types need to be function types.
2457  if (!FromFunction || !ToFunction) {
2458    PDiag << ft_default;
2459    return;
2460  }
2461
2462  if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2463    PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2464          << FromFunction->getNumArgs();
2465    return;
2466  }
2467
2468  // Handle different parameter types.
2469  unsigned ArgPos;
2470  if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2471    PDiag << ft_parameter_mismatch << ArgPos + 1
2472          << ToFunction->getArgType(ArgPos)
2473          << FromFunction->getArgType(ArgPos);
2474    return;
2475  }
2476
2477  // Handle different return type.
2478  if (!Context.hasSameType(FromFunction->getResultType(),
2479                           ToFunction->getResultType())) {
2480    PDiag << ft_return_type << ToFunction->getResultType()
2481          << FromFunction->getResultType();
2482    return;
2483  }
2484
2485  unsigned FromQuals = FromFunction->getTypeQuals(),
2486           ToQuals = ToFunction->getTypeQuals();
2487  if (FromQuals != ToQuals) {
2488    PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2489    return;
2490  }
2491
2492  // Unable to find a difference, so add no extra info.
2493  PDiag << ft_default;
2494}
2495
2496/// FunctionArgTypesAreEqual - This routine checks two function proto types
2497/// for equality of their argument types. Caller has already checked that
2498/// they have same number of arguments. This routine assumes that Objective-C
2499/// pointer types which only differ in their protocol qualifiers are equal.
2500/// If the parameters are different, ArgPos will have the the parameter index
2501/// of the first different parameter.
2502bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2503                                    const FunctionProtoType *NewType,
2504                                    unsigned *ArgPos) {
2505  if (!getLangOpts().ObjC1) {
2506    for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2507         N = NewType->arg_type_begin(),
2508         E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2509      if (!Context.hasSameType(*O, *N)) {
2510        if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2511        return false;
2512      }
2513    }
2514    return true;
2515  }
2516
2517  for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2518       N = NewType->arg_type_begin(),
2519       E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2520    QualType ToType = (*O);
2521    QualType FromType = (*N);
2522    if (!Context.hasSameType(ToType, FromType)) {
2523      if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2524        if (const PointerType *PTFr = FromType->getAs<PointerType>())
2525          if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2526               PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2527              (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2528               PTFr->getPointeeType()->isObjCQualifiedClassType()))
2529            continue;
2530      }
2531      else if (const ObjCObjectPointerType *PTTo =
2532                 ToType->getAs<ObjCObjectPointerType>()) {
2533        if (const ObjCObjectPointerType *PTFr =
2534              FromType->getAs<ObjCObjectPointerType>())
2535          if (Context.hasSameUnqualifiedType(
2536                PTTo->getObjectType()->getBaseType(),
2537                PTFr->getObjectType()->getBaseType()))
2538            continue;
2539      }
2540      if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2541      return false;
2542    }
2543  }
2544  return true;
2545}
2546
2547/// CheckPointerConversion - Check the pointer conversion from the
2548/// expression From to the type ToType. This routine checks for
2549/// ambiguous or inaccessible derived-to-base pointer
2550/// conversions for which IsPointerConversion has already returned
2551/// true. It returns true and produces a diagnostic if there was an
2552/// error, or returns false otherwise.
2553bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2554                                  CastKind &Kind,
2555                                  CXXCastPath& BasePath,
2556                                  bool IgnoreBaseAccess) {
2557  QualType FromType = From->getType();
2558  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2559
2560  Kind = CK_BitCast;
2561
2562  if (!IsCStyleOrFunctionalCast &&
2563      Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2564      From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2565    DiagRuntimeBehavior(From->getExprLoc(), From,
2566                        PDiag(diag::warn_impcast_bool_to_null_pointer)
2567                          << ToType << From->getSourceRange());
2568
2569  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2570    if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2571      QualType FromPointeeType = FromPtrType->getPointeeType(),
2572               ToPointeeType   = ToPtrType->getPointeeType();
2573
2574      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2575          !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2576        // We must have a derived-to-base conversion. Check an
2577        // ambiguous or inaccessible conversion.
2578        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2579                                         From->getExprLoc(),
2580                                         From->getSourceRange(), &BasePath,
2581                                         IgnoreBaseAccess))
2582          return true;
2583
2584        // The conversion was successful.
2585        Kind = CK_DerivedToBase;
2586      }
2587    }
2588  } else if (const ObjCObjectPointerType *ToPtrType =
2589               ToType->getAs<ObjCObjectPointerType>()) {
2590    if (const ObjCObjectPointerType *FromPtrType =
2591          FromType->getAs<ObjCObjectPointerType>()) {
2592      // Objective-C++ conversions are always okay.
2593      // FIXME: We should have a different class of conversions for the
2594      // Objective-C++ implicit conversions.
2595      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2596        return false;
2597    } else if (FromType->isBlockPointerType()) {
2598      Kind = CK_BlockPointerToObjCPointerCast;
2599    } else {
2600      Kind = CK_CPointerToObjCPointerCast;
2601    }
2602  } else if (ToType->isBlockPointerType()) {
2603    if (!FromType->isBlockPointerType())
2604      Kind = CK_AnyPointerToBlockPointerCast;
2605  }
2606
2607  // We shouldn't fall into this case unless it's valid for other
2608  // reasons.
2609  if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2610    Kind = CK_NullToPointer;
2611
2612  return false;
2613}
2614
2615/// IsMemberPointerConversion - Determines whether the conversion of the
2616/// expression From, which has the (possibly adjusted) type FromType, can be
2617/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2618/// If so, returns true and places the converted type (that might differ from
2619/// ToType in its cv-qualifiers at some level) into ConvertedType.
2620bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2621                                     QualType ToType,
2622                                     bool InOverloadResolution,
2623                                     QualType &ConvertedType) {
2624  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2625  if (!ToTypePtr)
2626    return false;
2627
2628  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2629  if (From->isNullPointerConstant(Context,
2630                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2631                                        : Expr::NPC_ValueDependentIsNull)) {
2632    ConvertedType = ToType;
2633    return true;
2634  }
2635
2636  // Otherwise, both types have to be member pointers.
2637  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2638  if (!FromTypePtr)
2639    return false;
2640
2641  // A pointer to member of B can be converted to a pointer to member of D,
2642  // where D is derived from B (C++ 4.11p2).
2643  QualType FromClass(FromTypePtr->getClass(), 0);
2644  QualType ToClass(ToTypePtr->getClass(), 0);
2645
2646  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2647      !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2648      IsDerivedFrom(ToClass, FromClass)) {
2649    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2650                                                 ToClass.getTypePtr());
2651    return true;
2652  }
2653
2654  return false;
2655}
2656
2657/// CheckMemberPointerConversion - Check the member pointer conversion from the
2658/// expression From to the type ToType. This routine checks for ambiguous or
2659/// virtual or inaccessible base-to-derived member pointer conversions
2660/// for which IsMemberPointerConversion has already returned true. It returns
2661/// true and produces a diagnostic if there was an error, or returns false
2662/// otherwise.
2663bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2664                                        CastKind &Kind,
2665                                        CXXCastPath &BasePath,
2666                                        bool IgnoreBaseAccess) {
2667  QualType FromType = From->getType();
2668  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2669  if (!FromPtrType) {
2670    // This must be a null pointer to member pointer conversion
2671    assert(From->isNullPointerConstant(Context,
2672                                       Expr::NPC_ValueDependentIsNull) &&
2673           "Expr must be null pointer constant!");
2674    Kind = CK_NullToMemberPointer;
2675    return false;
2676  }
2677
2678  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2679  assert(ToPtrType && "No member pointer cast has a target type "
2680                      "that is not a member pointer.");
2681
2682  QualType FromClass = QualType(FromPtrType->getClass(), 0);
2683  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2684
2685  // FIXME: What about dependent types?
2686  assert(FromClass->isRecordType() && "Pointer into non-class.");
2687  assert(ToClass->isRecordType() && "Pointer into non-class.");
2688
2689  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2690                     /*DetectVirtual=*/true);
2691  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2692  assert(DerivationOkay &&
2693         "Should not have been called if derivation isn't OK.");
2694  (void)DerivationOkay;
2695
2696  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2697                                  getUnqualifiedType())) {
2698    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2699    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2700      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2701    return true;
2702  }
2703
2704  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2705    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2706      << FromClass << ToClass << QualType(VBase, 0)
2707      << From->getSourceRange();
2708    return true;
2709  }
2710
2711  if (!IgnoreBaseAccess)
2712    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2713                         Paths.front(),
2714                         diag::err_downcast_from_inaccessible_base);
2715
2716  // Must be a base to derived member conversion.
2717  BuildBasePathArray(Paths, BasePath);
2718  Kind = CK_BaseToDerivedMemberPointer;
2719  return false;
2720}
2721
2722/// IsQualificationConversion - Determines whether the conversion from
2723/// an rvalue of type FromType to ToType is a qualification conversion
2724/// (C++ 4.4).
2725///
2726/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2727/// when the qualification conversion involves a change in the Objective-C
2728/// object lifetime.
2729bool
2730Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2731                                bool CStyle, bool &ObjCLifetimeConversion) {
2732  FromType = Context.getCanonicalType(FromType);
2733  ToType = Context.getCanonicalType(ToType);
2734  ObjCLifetimeConversion = false;
2735
2736  // If FromType and ToType are the same type, this is not a
2737  // qualification conversion.
2738  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2739    return false;
2740
2741  // (C++ 4.4p4):
2742  //   A conversion can add cv-qualifiers at levels other than the first
2743  //   in multi-level pointers, subject to the following rules: [...]
2744  bool PreviousToQualsIncludeConst = true;
2745  bool UnwrappedAnyPointer = false;
2746  while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2747    // Within each iteration of the loop, we check the qualifiers to
2748    // determine if this still looks like a qualification
2749    // conversion. Then, if all is well, we unwrap one more level of
2750    // pointers or pointers-to-members and do it all again
2751    // until there are no more pointers or pointers-to-members left to
2752    // unwrap.
2753    UnwrappedAnyPointer = true;
2754
2755    Qualifiers FromQuals = FromType.getQualifiers();
2756    Qualifiers ToQuals = ToType.getQualifiers();
2757
2758    // Objective-C ARC:
2759    //   Check Objective-C lifetime conversions.
2760    if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2761        UnwrappedAnyPointer) {
2762      if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2763        ObjCLifetimeConversion = true;
2764        FromQuals.removeObjCLifetime();
2765        ToQuals.removeObjCLifetime();
2766      } else {
2767        // Qualification conversions cannot cast between different
2768        // Objective-C lifetime qualifiers.
2769        return false;
2770      }
2771    }
2772
2773    // Allow addition/removal of GC attributes but not changing GC attributes.
2774    if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2775        (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2776      FromQuals.removeObjCGCAttr();
2777      ToQuals.removeObjCGCAttr();
2778    }
2779
2780    //   -- for every j > 0, if const is in cv 1,j then const is in cv
2781    //      2,j, and similarly for volatile.
2782    if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2783      return false;
2784
2785    //   -- if the cv 1,j and cv 2,j are different, then const is in
2786    //      every cv for 0 < k < j.
2787    if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2788        && !PreviousToQualsIncludeConst)
2789      return false;
2790
2791    // Keep track of whether all prior cv-qualifiers in the "to" type
2792    // include const.
2793    PreviousToQualsIncludeConst
2794      = PreviousToQualsIncludeConst && ToQuals.hasConst();
2795  }
2796
2797  // We are left with FromType and ToType being the pointee types
2798  // after unwrapping the original FromType and ToType the same number
2799  // of types. If we unwrapped any pointers, and if FromType and
2800  // ToType have the same unqualified type (since we checked
2801  // qualifiers above), then this is a qualification conversion.
2802  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2803}
2804
2805/// \brief - Determine whether this is a conversion from a scalar type to an
2806/// atomic type.
2807///
2808/// If successful, updates \c SCS's second and third steps in the conversion
2809/// sequence to finish the conversion.
2810static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2811                                bool InOverloadResolution,
2812                                StandardConversionSequence &SCS,
2813                                bool CStyle) {
2814  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2815  if (!ToAtomic)
2816    return false;
2817
2818  StandardConversionSequence InnerSCS;
2819  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2820                            InOverloadResolution, InnerSCS,
2821                            CStyle, /*AllowObjCWritebackConversion=*/false))
2822    return false;
2823
2824  SCS.Second = InnerSCS.Second;
2825  SCS.setToType(1, InnerSCS.getToType(1));
2826  SCS.Third = InnerSCS.Third;
2827  SCS.QualificationIncludesObjCLifetime
2828    = InnerSCS.QualificationIncludesObjCLifetime;
2829  SCS.setToType(2, InnerSCS.getToType(2));
2830  return true;
2831}
2832
2833static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2834                                              CXXConstructorDecl *Constructor,
2835                                              QualType Type) {
2836  const FunctionProtoType *CtorType =
2837      Constructor->getType()->getAs<FunctionProtoType>();
2838  if (CtorType->getNumArgs() > 0) {
2839    QualType FirstArg = CtorType->getArgType(0);
2840    if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2841      return true;
2842  }
2843  return false;
2844}
2845
2846static OverloadingResult
2847IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2848                                       CXXRecordDecl *To,
2849                                       UserDefinedConversionSequence &User,
2850                                       OverloadCandidateSet &CandidateSet,
2851                                       bool AllowExplicit) {
2852  DeclContext::lookup_iterator Con, ConEnd;
2853  for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2854       Con != ConEnd; ++Con) {
2855    NamedDecl *D = *Con;
2856    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2857
2858    // Find the constructor (which may be a template).
2859    CXXConstructorDecl *Constructor = 0;
2860    FunctionTemplateDecl *ConstructorTmpl
2861      = dyn_cast<FunctionTemplateDecl>(D);
2862    if (ConstructorTmpl)
2863      Constructor
2864        = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2865    else
2866      Constructor = cast<CXXConstructorDecl>(D);
2867
2868    bool Usable = !Constructor->isInvalidDecl() &&
2869                  S.isInitListConstructor(Constructor) &&
2870                  (AllowExplicit || !Constructor->isExplicit());
2871    if (Usable) {
2872      // If the first argument is (a reference to) the target type,
2873      // suppress conversions.
2874      bool SuppressUserConversions =
2875          isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2876      if (ConstructorTmpl)
2877        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2878                                       /*ExplicitArgs*/ 0,
2879                                       From, CandidateSet,
2880                                       SuppressUserConversions);
2881      else
2882        S.AddOverloadCandidate(Constructor, FoundDecl,
2883                               From, CandidateSet,
2884                               SuppressUserConversions);
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    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2895    S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2896
2897    QualType ThisType = Constructor->getThisType(S.Context);
2898    // Initializer lists don't have conversions as such.
2899    User.Before.setAsIdentityConversion();
2900    User.HadMultipleCandidates = HadMultipleCandidates;
2901    User.ConversionFunction = Constructor;
2902    User.FoundConversionFunction = Best->FoundDecl;
2903    User.After.setAsIdentityConversion();
2904    User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2905    User.After.setAllToTypes(ToType);
2906    return OR_Success;
2907  }
2908
2909  case OR_No_Viable_Function:
2910    return OR_No_Viable_Function;
2911  case OR_Deleted:
2912    return OR_Deleted;
2913  case OR_Ambiguous:
2914    return OR_Ambiguous;
2915  }
2916
2917  llvm_unreachable("Invalid OverloadResult!");
2918}
2919
2920/// Determines whether there is a user-defined conversion sequence
2921/// (C++ [over.ics.user]) that converts expression From to the type
2922/// ToType. If such a conversion exists, User will contain the
2923/// user-defined conversion sequence that performs such a conversion
2924/// and this routine will return true. Otherwise, this routine returns
2925/// false and User is unspecified.
2926///
2927/// \param AllowExplicit  true if the conversion should consider C++0x
2928/// "explicit" conversion functions as well as non-explicit conversion
2929/// functions (C++0x [class.conv.fct]p2).
2930static OverloadingResult
2931IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2932                        UserDefinedConversionSequence &User,
2933                        OverloadCandidateSet &CandidateSet,
2934                        bool AllowExplicit) {
2935  // Whether we will only visit constructors.
2936  bool ConstructorsOnly = false;
2937
2938  // If the type we are conversion to is a class type, enumerate its
2939  // constructors.
2940  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2941    // C++ [over.match.ctor]p1:
2942    //   When objects of class type are direct-initialized (8.5), or
2943    //   copy-initialized from an expression of the same or a
2944    //   derived class type (8.5), overload resolution selects the
2945    //   constructor. [...] For copy-initialization, the candidate
2946    //   functions are all the converting constructors (12.3.1) of
2947    //   that class. The argument list is the expression-list within
2948    //   the parentheses of the initializer.
2949    if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
2950        (From->getType()->getAs<RecordType>() &&
2951         S.IsDerivedFrom(From->getType(), ToType)))
2952      ConstructorsOnly = true;
2953
2954    S.RequireCompleteType(From->getLocStart(), ToType, 0);
2955    // RequireCompleteType may have returned true due to some invalid decl
2956    // during template instantiation, but ToType may be complete enough now
2957    // to try to recover.
2958    if (ToType->isIncompleteType()) {
2959      // We're not going to find any constructors.
2960    } else if (CXXRecordDecl *ToRecordDecl
2961                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
2962
2963      Expr **Args = &From;
2964      unsigned NumArgs = 1;
2965      bool ListInitializing = false;
2966      if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
2967        // But first, see if there is an init-list-contructor that will work.
2968        OverloadingResult Result = IsInitializerListConstructorConversion(
2969            S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2970        if (Result != OR_No_Viable_Function)
2971          return Result;
2972        // Never mind.
2973        CandidateSet.clear();
2974
2975        // If we're list-initializing, we pass the individual elements as
2976        // arguments, not the entire list.
2977        Args = InitList->getInits();
2978        NumArgs = InitList->getNumInits();
2979        ListInitializing = true;
2980      }
2981
2982      DeclContext::lookup_iterator Con, ConEnd;
2983      for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
2984           Con != ConEnd; ++Con) {
2985        NamedDecl *D = *Con;
2986        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2987
2988        // Find the constructor (which may be a template).
2989        CXXConstructorDecl *Constructor = 0;
2990        FunctionTemplateDecl *ConstructorTmpl
2991          = dyn_cast<FunctionTemplateDecl>(D);
2992        if (ConstructorTmpl)
2993          Constructor
2994            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2995        else
2996          Constructor = cast<CXXConstructorDecl>(D);
2997
2998        bool Usable = !Constructor->isInvalidDecl();
2999        if (ListInitializing)
3000          Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3001        else
3002          Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3003        if (Usable) {
3004          bool SuppressUserConversions = !ConstructorsOnly;
3005          if (SuppressUserConversions && ListInitializing) {
3006            SuppressUserConversions = false;
3007            if (NumArgs == 1) {
3008              // If the first argument is (a reference to) the target type,
3009              // suppress conversions.
3010              SuppressUserConversions = isFirstArgumentCompatibleWithType(
3011                                                S.Context, Constructor, ToType);
3012            }
3013          }
3014          if (ConstructorTmpl)
3015            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3016                                           /*ExplicitArgs*/ 0,
3017                                           llvm::makeArrayRef(Args, NumArgs),
3018                                           CandidateSet, SuppressUserConversions);
3019          else
3020            // Allow one user-defined conversion when user specifies a
3021            // From->ToType conversion via an static cast (c-style, etc).
3022            S.AddOverloadCandidate(Constructor, FoundDecl,
3023                                   llvm::makeArrayRef(Args, NumArgs),
3024                                   CandidateSet, SuppressUserConversions);
3025        }
3026      }
3027    }
3028  }
3029
3030  // Enumerate conversion functions, if we're allowed to.
3031  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3032  } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3033    // No conversion functions from incomplete types.
3034  } else if (const RecordType *FromRecordType
3035                                   = From->getType()->getAs<RecordType>()) {
3036    if (CXXRecordDecl *FromRecordDecl
3037         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3038      // Add all of the conversion functions as candidates.
3039      const UnresolvedSetImpl *Conversions
3040        = FromRecordDecl->getVisibleConversionFunctions();
3041      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3042             E = Conversions->end(); I != E; ++I) {
3043        DeclAccessPair FoundDecl = I.getPair();
3044        NamedDecl *D = FoundDecl.getDecl();
3045        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3046        if (isa<UsingShadowDecl>(D))
3047          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3048
3049        CXXConversionDecl *Conv;
3050        FunctionTemplateDecl *ConvTemplate;
3051        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3052          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3053        else
3054          Conv = cast<CXXConversionDecl>(D);
3055
3056        if (AllowExplicit || !Conv->isExplicit()) {
3057          if (ConvTemplate)
3058            S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3059                                             ActingContext, From, ToType,
3060                                             CandidateSet);
3061          else
3062            S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3063                                     From, ToType, CandidateSet);
3064        }
3065      }
3066    }
3067  }
3068
3069  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3070
3071  OverloadCandidateSet::iterator Best;
3072  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3073  case OR_Success:
3074    // Record the standard conversion we used and the conversion function.
3075    if (CXXConstructorDecl *Constructor
3076          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3077      S.MarkFunctionReferenced(From->getLocStart(), Constructor);
3078
3079      // C++ [over.ics.user]p1:
3080      //   If the user-defined conversion is specified by a
3081      //   constructor (12.3.1), the initial standard conversion
3082      //   sequence converts the source type to the type required by
3083      //   the argument of the constructor.
3084      //
3085      QualType ThisType = Constructor->getThisType(S.Context);
3086      if (isa<InitListExpr>(From)) {
3087        // Initializer lists don't have conversions as such.
3088        User.Before.setAsIdentityConversion();
3089      } else {
3090        if (Best->Conversions[0].isEllipsis())
3091          User.EllipsisConversion = true;
3092        else {
3093          User.Before = Best->Conversions[0].Standard;
3094          User.EllipsisConversion = false;
3095        }
3096      }
3097      User.HadMultipleCandidates = HadMultipleCandidates;
3098      User.ConversionFunction = Constructor;
3099      User.FoundConversionFunction = Best->FoundDecl;
3100      User.After.setAsIdentityConversion();
3101      User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3102      User.After.setAllToTypes(ToType);
3103      return OR_Success;
3104    }
3105    if (CXXConversionDecl *Conversion
3106                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3107      S.MarkFunctionReferenced(From->getLocStart(), Conversion);
3108
3109      // C++ [over.ics.user]p1:
3110      //
3111      //   [...] If the user-defined conversion is specified by a
3112      //   conversion function (12.3.2), the initial standard
3113      //   conversion sequence converts the source type to the
3114      //   implicit object parameter of the conversion function.
3115      User.Before = Best->Conversions[0].Standard;
3116      User.HadMultipleCandidates = HadMultipleCandidates;
3117      User.ConversionFunction = Conversion;
3118      User.FoundConversionFunction = Best->FoundDecl;
3119      User.EllipsisConversion = false;
3120
3121      // C++ [over.ics.user]p2:
3122      //   The second standard conversion sequence converts the
3123      //   result of the user-defined conversion to the target type
3124      //   for the sequence. Since an implicit conversion sequence
3125      //   is an initialization, the special rules for
3126      //   initialization by user-defined conversion apply when
3127      //   selecting the best user-defined conversion for a
3128      //   user-defined conversion sequence (see 13.3.3 and
3129      //   13.3.3.1).
3130      User.After = Best->FinalConversion;
3131      return OR_Success;
3132    }
3133    llvm_unreachable("Not a constructor or conversion function?");
3134
3135  case OR_No_Viable_Function:
3136    return OR_No_Viable_Function;
3137  case OR_Deleted:
3138    // No conversion here! We're done.
3139    return OR_Deleted;
3140
3141  case OR_Ambiguous:
3142    return OR_Ambiguous;
3143  }
3144
3145  llvm_unreachable("Invalid OverloadResult!");
3146}
3147
3148bool
3149Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3150  ImplicitConversionSequence ICS;
3151  OverloadCandidateSet CandidateSet(From->getExprLoc());
3152  OverloadingResult OvResult =
3153    IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3154                            CandidateSet, false);
3155  if (OvResult == OR_Ambiguous)
3156    Diag(From->getLocStart(),
3157         diag::err_typecheck_ambiguous_condition)
3158          << From->getType() << ToType << From->getSourceRange();
3159  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3160    Diag(From->getLocStart(),
3161         diag::err_typecheck_nonviable_condition)
3162    << From->getType() << ToType << From->getSourceRange();
3163  else
3164    return false;
3165  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3166  return true;
3167}
3168
3169/// \brief Compare the user-defined conversion functions or constructors
3170/// of two user-defined conversion sequences to determine whether any ordering
3171/// is possible.
3172static ImplicitConversionSequence::CompareKind
3173compareConversionFunctions(Sema &S,
3174                           FunctionDecl *Function1,
3175                           FunctionDecl *Function2) {
3176  if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
3177    return ImplicitConversionSequence::Indistinguishable;
3178
3179  // Objective-C++:
3180  //   If both conversion functions are implicitly-declared conversions from
3181  //   a lambda closure type to a function pointer and a block pointer,
3182  //   respectively, always prefer the conversion to a function pointer,
3183  //   because the function pointer is more lightweight and is more likely
3184  //   to keep code working.
3185  CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3186  if (!Conv1)
3187    return ImplicitConversionSequence::Indistinguishable;
3188
3189  CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3190  if (!Conv2)
3191    return ImplicitConversionSequence::Indistinguishable;
3192
3193  if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3194    bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3195    bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3196    if (Block1 != Block2)
3197      return Block1? ImplicitConversionSequence::Worse
3198                   : ImplicitConversionSequence::Better;
3199  }
3200
3201  return ImplicitConversionSequence::Indistinguishable;
3202}
3203
3204/// CompareImplicitConversionSequences - Compare two implicit
3205/// conversion sequences to determine whether one is better than the
3206/// other or if they are indistinguishable (C++ 13.3.3.2).
3207static ImplicitConversionSequence::CompareKind
3208CompareImplicitConversionSequences(Sema &S,
3209                                   const ImplicitConversionSequence& ICS1,
3210                                   const ImplicitConversionSequence& ICS2)
3211{
3212  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3213  // conversion sequences (as defined in 13.3.3.1)
3214  //   -- a standard conversion sequence (13.3.3.1.1) is a better
3215  //      conversion sequence than a user-defined conversion sequence or
3216  //      an ellipsis conversion sequence, and
3217  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3218  //      conversion sequence than an ellipsis conversion sequence
3219  //      (13.3.3.1.3).
3220  //
3221  // C++0x [over.best.ics]p10:
3222  //   For the purpose of ranking implicit conversion sequences as
3223  //   described in 13.3.3.2, the ambiguous conversion sequence is
3224  //   treated as a user-defined sequence that is indistinguishable
3225  //   from any other user-defined conversion sequence.
3226  if (ICS1.getKindRank() < ICS2.getKindRank())
3227    return ImplicitConversionSequence::Better;
3228  if (ICS2.getKindRank() < ICS1.getKindRank())
3229    return ImplicitConversionSequence::Worse;
3230
3231  // The following checks require both conversion sequences to be of
3232  // the same kind.
3233  if (ICS1.getKind() != ICS2.getKind())
3234    return ImplicitConversionSequence::Indistinguishable;
3235
3236  ImplicitConversionSequence::CompareKind Result =
3237      ImplicitConversionSequence::Indistinguishable;
3238
3239  // Two implicit conversion sequences of the same form are
3240  // indistinguishable conversion sequences unless one of the
3241  // following rules apply: (C++ 13.3.3.2p3):
3242  if (ICS1.isStandard())
3243    Result = CompareStandardConversionSequences(S,
3244                                                ICS1.Standard, ICS2.Standard);
3245  else if (ICS1.isUserDefined()) {
3246    // User-defined conversion sequence U1 is a better conversion
3247    // sequence than another user-defined conversion sequence U2 if
3248    // they contain the same user-defined conversion function or
3249    // constructor and if the second standard conversion sequence of
3250    // U1 is better than the second standard conversion sequence of
3251    // U2 (C++ 13.3.3.2p3).
3252    if (ICS1.UserDefined.ConversionFunction ==
3253          ICS2.UserDefined.ConversionFunction)
3254      Result = CompareStandardConversionSequences(S,
3255                                                  ICS1.UserDefined.After,
3256                                                  ICS2.UserDefined.After);
3257    else
3258      Result = compareConversionFunctions(S,
3259                                          ICS1.UserDefined.ConversionFunction,
3260                                          ICS2.UserDefined.ConversionFunction);
3261  }
3262
3263  // List-initialization sequence L1 is a better conversion sequence than
3264  // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3265  // for some X and L2 does not.
3266  if (Result == ImplicitConversionSequence::Indistinguishable &&
3267      !ICS1.isBad() &&
3268      ICS1.isListInitializationSequence() &&
3269      ICS2.isListInitializationSequence()) {
3270    if (ICS1.isStdInitializerListElement() &&
3271        !ICS2.isStdInitializerListElement())
3272      return ImplicitConversionSequence::Better;
3273    if (!ICS1.isStdInitializerListElement() &&
3274        ICS2.isStdInitializerListElement())
3275      return ImplicitConversionSequence::Worse;
3276  }
3277
3278  return Result;
3279}
3280
3281static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3282  while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3283    Qualifiers Quals;
3284    T1 = Context.getUnqualifiedArrayType(T1, Quals);
3285    T2 = Context.getUnqualifiedArrayType(T2, Quals);
3286  }
3287
3288  return Context.hasSameUnqualifiedType(T1, T2);
3289}
3290
3291// Per 13.3.3.2p3, compare the given standard conversion sequences to
3292// determine if one is a proper subset of the other.
3293static ImplicitConversionSequence::CompareKind
3294compareStandardConversionSubsets(ASTContext &Context,
3295                                 const StandardConversionSequence& SCS1,
3296                                 const StandardConversionSequence& SCS2) {
3297  ImplicitConversionSequence::CompareKind Result
3298    = ImplicitConversionSequence::Indistinguishable;
3299
3300  // the identity conversion sequence is considered to be a subsequence of
3301  // any non-identity conversion sequence
3302  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3303    return ImplicitConversionSequence::Better;
3304  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3305    return ImplicitConversionSequence::Worse;
3306
3307  if (SCS1.Second != SCS2.Second) {
3308    if (SCS1.Second == ICK_Identity)
3309      Result = ImplicitConversionSequence::Better;
3310    else if (SCS2.Second == ICK_Identity)
3311      Result = ImplicitConversionSequence::Worse;
3312    else
3313      return ImplicitConversionSequence::Indistinguishable;
3314  } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3315    return ImplicitConversionSequence::Indistinguishable;
3316
3317  if (SCS1.Third == SCS2.Third) {
3318    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3319                             : ImplicitConversionSequence::Indistinguishable;
3320  }
3321
3322  if (SCS1.Third == ICK_Identity)
3323    return Result == ImplicitConversionSequence::Worse
3324             ? ImplicitConversionSequence::Indistinguishable
3325             : ImplicitConversionSequence::Better;
3326
3327  if (SCS2.Third == ICK_Identity)
3328    return Result == ImplicitConversionSequence::Better
3329             ? ImplicitConversionSequence::Indistinguishable
3330             : ImplicitConversionSequence::Worse;
3331
3332  return ImplicitConversionSequence::Indistinguishable;
3333}
3334
3335/// \brief Determine whether one of the given reference bindings is better
3336/// than the other based on what kind of bindings they are.
3337static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3338                                       const StandardConversionSequence &SCS2) {
3339  // C++0x [over.ics.rank]p3b4:
3340  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3341  //      implicit object parameter of a non-static member function declared
3342  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3343  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3344  //      lvalue reference to a function lvalue and S2 binds an rvalue
3345  //      reference*.
3346  //
3347  // FIXME: Rvalue references. We're going rogue with the above edits,
3348  // because the semantics in the current C++0x working paper (N3225 at the
3349  // time of this writing) break the standard definition of std::forward
3350  // and std::reference_wrapper when dealing with references to functions.
3351  // Proposed wording changes submitted to CWG for consideration.
3352  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3353      SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3354    return false;
3355
3356  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3357          SCS2.IsLvalueReference) ||
3358         (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3359          !SCS2.IsLvalueReference);
3360}
3361
3362/// CompareStandardConversionSequences - Compare two standard
3363/// conversion sequences to determine whether one is better than the
3364/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3365static ImplicitConversionSequence::CompareKind
3366CompareStandardConversionSequences(Sema &S,
3367                                   const StandardConversionSequence& SCS1,
3368                                   const StandardConversionSequence& SCS2)
3369{
3370  // Standard conversion sequence S1 is a better conversion sequence
3371  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3372
3373  //  -- S1 is a proper subsequence of S2 (comparing the conversion
3374  //     sequences in the canonical form defined by 13.3.3.1.1,
3375  //     excluding any Lvalue Transformation; the identity conversion
3376  //     sequence is considered to be a subsequence of any
3377  //     non-identity conversion sequence) or, if not that,
3378  if (ImplicitConversionSequence::CompareKind CK
3379        = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3380    return CK;
3381
3382  //  -- the rank of S1 is better than the rank of S2 (by the rules
3383  //     defined below), or, if not that,
3384  ImplicitConversionRank Rank1 = SCS1.getRank();
3385  ImplicitConversionRank Rank2 = SCS2.getRank();
3386  if (Rank1 < Rank2)
3387    return ImplicitConversionSequence::Better;
3388  else if (Rank2 < Rank1)
3389    return ImplicitConversionSequence::Worse;
3390
3391  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3392  // are indistinguishable unless one of the following rules
3393  // applies:
3394
3395  //   A conversion that is not a conversion of a pointer, or
3396  //   pointer to member, to bool is better than another conversion
3397  //   that is such a conversion.
3398  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3399    return SCS2.isPointerConversionToBool()
3400             ? ImplicitConversionSequence::Better
3401             : ImplicitConversionSequence::Worse;
3402
3403  // C++ [over.ics.rank]p4b2:
3404  //
3405  //   If class B is derived directly or indirectly from class A,
3406  //   conversion of B* to A* is better than conversion of B* to
3407  //   void*, and conversion of A* to void* is better than conversion
3408  //   of B* to void*.
3409  bool SCS1ConvertsToVoid
3410    = SCS1.isPointerConversionToVoidPointer(S.Context);
3411  bool SCS2ConvertsToVoid
3412    = SCS2.isPointerConversionToVoidPointer(S.Context);
3413  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3414    // Exactly one of the conversion sequences is a conversion to
3415    // a void pointer; it's the worse conversion.
3416    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3417                              : ImplicitConversionSequence::Worse;
3418  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3419    // Neither conversion sequence converts to a void pointer; compare
3420    // their derived-to-base conversions.
3421    if (ImplicitConversionSequence::CompareKind DerivedCK
3422          = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3423      return DerivedCK;
3424  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3425             !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3426    // Both conversion sequences are conversions to void
3427    // pointers. Compare the source types to determine if there's an
3428    // inheritance relationship in their sources.
3429    QualType FromType1 = SCS1.getFromType();
3430    QualType FromType2 = SCS2.getFromType();
3431
3432    // Adjust the types we're converting from via the array-to-pointer
3433    // conversion, if we need to.
3434    if (SCS1.First == ICK_Array_To_Pointer)
3435      FromType1 = S.Context.getArrayDecayedType(FromType1);
3436    if (SCS2.First == ICK_Array_To_Pointer)
3437      FromType2 = S.Context.getArrayDecayedType(FromType2);
3438
3439    QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3440    QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3441
3442    if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3443      return ImplicitConversionSequence::Better;
3444    else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3445      return ImplicitConversionSequence::Worse;
3446
3447    // Objective-C++: If one interface is more specific than the
3448    // other, it is the better one.
3449    const ObjCObjectPointerType* FromObjCPtr1
3450      = FromType1->getAs<ObjCObjectPointerType>();
3451    const ObjCObjectPointerType* FromObjCPtr2
3452      = FromType2->getAs<ObjCObjectPointerType>();
3453    if (FromObjCPtr1 && FromObjCPtr2) {
3454      bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3455                                                          FromObjCPtr2);
3456      bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3457                                                           FromObjCPtr1);
3458      if (AssignLeft != AssignRight) {
3459        return AssignLeft? ImplicitConversionSequence::Better
3460                         : ImplicitConversionSequence::Worse;
3461      }
3462    }
3463  }
3464
3465  // Compare based on qualification conversions (C++ 13.3.3.2p3,
3466  // bullet 3).
3467  if (ImplicitConversionSequence::CompareKind QualCK
3468        = CompareQualificationConversions(S, SCS1, SCS2))
3469    return QualCK;
3470
3471  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3472    // Check for a better reference binding based on the kind of bindings.
3473    if (isBetterReferenceBindingKind(SCS1, SCS2))
3474      return ImplicitConversionSequence::Better;
3475    else if (isBetterReferenceBindingKind(SCS2, SCS1))
3476      return ImplicitConversionSequence::Worse;
3477
3478    // C++ [over.ics.rank]p3b4:
3479    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3480    //      which the references refer are the same type except for
3481    //      top-level cv-qualifiers, and the type to which the reference
3482    //      initialized by S2 refers is more cv-qualified than the type
3483    //      to which the reference initialized by S1 refers.
3484    QualType T1 = SCS1.getToType(2);
3485    QualType T2 = SCS2.getToType(2);
3486    T1 = S.Context.getCanonicalType(T1);
3487    T2 = S.Context.getCanonicalType(T2);
3488    Qualifiers T1Quals, T2Quals;
3489    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3490    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3491    if (UnqualT1 == UnqualT2) {
3492      // Objective-C++ ARC: If the references refer to objects with different
3493      // lifetimes, prefer bindings that don't change lifetime.
3494      if (SCS1.ObjCLifetimeConversionBinding !=
3495                                          SCS2.ObjCLifetimeConversionBinding) {
3496        return SCS1.ObjCLifetimeConversionBinding
3497                                           ? ImplicitConversionSequence::Worse
3498                                           : ImplicitConversionSequence::Better;
3499      }
3500
3501      // If the type is an array type, promote the element qualifiers to the
3502      // type for comparison.
3503      if (isa<ArrayType>(T1) && T1Quals)
3504        T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3505      if (isa<ArrayType>(T2) && T2Quals)
3506        T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3507      if (T2.isMoreQualifiedThan(T1))
3508        return ImplicitConversionSequence::Better;
3509      else if (T1.isMoreQualifiedThan(T2))
3510        return ImplicitConversionSequence::Worse;
3511    }
3512  }
3513
3514  // In Microsoft mode, prefer an integral conversion to a
3515  // floating-to-integral conversion if the integral conversion
3516  // is between types of the same size.
3517  // For example:
3518  // void f(float);
3519  // void f(int);
3520  // int main {
3521  //    long a;
3522  //    f(a);
3523  // }
3524  // Here, MSVC will call f(int) instead of generating a compile error
3525  // as clang will do in standard mode.
3526  if (S.getLangOpts().MicrosoftMode &&
3527      SCS1.Second == ICK_Integral_Conversion &&
3528      SCS2.Second == ICK_Floating_Integral &&
3529      S.Context.getTypeSize(SCS1.getFromType()) ==
3530      S.Context.getTypeSize(SCS1.getToType(2)))
3531    return ImplicitConversionSequence::Better;
3532
3533  return ImplicitConversionSequence::Indistinguishable;
3534}
3535
3536/// CompareQualificationConversions - Compares two standard conversion
3537/// sequences to determine whether they can be ranked based on their
3538/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3539ImplicitConversionSequence::CompareKind
3540CompareQualificationConversions(Sema &S,
3541                                const StandardConversionSequence& SCS1,
3542                                const StandardConversionSequence& SCS2) {
3543  // C++ 13.3.3.2p3:
3544  //  -- S1 and S2 differ only in their qualification conversion and
3545  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3546  //     cv-qualification signature of type T1 is a proper subset of
3547  //     the cv-qualification signature of type T2, and S1 is not the
3548  //     deprecated string literal array-to-pointer conversion (4.2).
3549  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3550      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3551    return ImplicitConversionSequence::Indistinguishable;
3552
3553  // FIXME: the example in the standard doesn't use a qualification
3554  // conversion (!)
3555  QualType T1 = SCS1.getToType(2);
3556  QualType T2 = SCS2.getToType(2);
3557  T1 = S.Context.getCanonicalType(T1);
3558  T2 = S.Context.getCanonicalType(T2);
3559  Qualifiers T1Quals, T2Quals;
3560  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3561  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3562
3563  // If the types are the same, we won't learn anything by unwrapped
3564  // them.
3565  if (UnqualT1 == UnqualT2)
3566    return ImplicitConversionSequence::Indistinguishable;
3567
3568  // If the type is an array type, promote the element qualifiers to the type
3569  // for comparison.
3570  if (isa<ArrayType>(T1) && T1Quals)
3571    T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3572  if (isa<ArrayType>(T2) && T2Quals)
3573    T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3574
3575  ImplicitConversionSequence::CompareKind Result
3576    = ImplicitConversionSequence::Indistinguishable;
3577
3578  // Objective-C++ ARC:
3579  //   Prefer qualification conversions not involving a change in lifetime
3580  //   to qualification conversions that do not change lifetime.
3581  if (SCS1.QualificationIncludesObjCLifetime !=
3582                                      SCS2.QualificationIncludesObjCLifetime) {
3583    Result = SCS1.QualificationIncludesObjCLifetime
3584               ? ImplicitConversionSequence::Worse
3585               : ImplicitConversionSequence::Better;
3586  }
3587
3588  while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3589    // Within each iteration of the loop, we check the qualifiers to
3590    // determine if this still looks like a qualification
3591    // conversion. Then, if all is well, we unwrap one more level of
3592    // pointers or pointers-to-members and do it all again
3593    // until there are no more pointers or pointers-to-members left
3594    // to unwrap. This essentially mimics what
3595    // IsQualificationConversion does, but here we're checking for a
3596    // strict subset of qualifiers.
3597    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3598      // The qualifiers are the same, so this doesn't tell us anything
3599      // about how the sequences rank.
3600      ;
3601    else if (T2.isMoreQualifiedThan(T1)) {
3602      // T1 has fewer qualifiers, so it could be the better sequence.
3603      if (Result == ImplicitConversionSequence::Worse)
3604        // Neither has qualifiers that are a subset of the other's
3605        // qualifiers.
3606        return ImplicitConversionSequence::Indistinguishable;
3607
3608      Result = ImplicitConversionSequence::Better;
3609    } else if (T1.isMoreQualifiedThan(T2)) {
3610      // T2 has fewer qualifiers, so it could be the better sequence.
3611      if (Result == ImplicitConversionSequence::Better)
3612        // Neither has qualifiers that are a subset of the other's
3613        // qualifiers.
3614        return ImplicitConversionSequence::Indistinguishable;
3615
3616      Result = ImplicitConversionSequence::Worse;
3617    } else {
3618      // Qualifiers are disjoint.
3619      return ImplicitConversionSequence::Indistinguishable;
3620    }
3621
3622    // If the types after this point are equivalent, we're done.
3623    if (S.Context.hasSameUnqualifiedType(T1, T2))
3624      break;
3625  }
3626
3627  // Check that the winning standard conversion sequence isn't using
3628  // the deprecated string literal array to pointer conversion.
3629  switch (Result) {
3630  case ImplicitConversionSequence::Better:
3631    if (SCS1.DeprecatedStringLiteralToCharPtr)
3632      Result = ImplicitConversionSequence::Indistinguishable;
3633    break;
3634
3635  case ImplicitConversionSequence::Indistinguishable:
3636    break;
3637
3638  case ImplicitConversionSequence::Worse:
3639    if (SCS2.DeprecatedStringLiteralToCharPtr)
3640      Result = ImplicitConversionSequence::Indistinguishable;
3641    break;
3642  }
3643
3644  return Result;
3645}
3646
3647/// CompareDerivedToBaseConversions - Compares two standard conversion
3648/// sequences to determine whether they can be ranked based on their
3649/// various kinds of derived-to-base conversions (C++
3650/// [over.ics.rank]p4b3).  As part of these checks, we also look at
3651/// conversions between Objective-C interface types.
3652ImplicitConversionSequence::CompareKind
3653CompareDerivedToBaseConversions(Sema &S,
3654                                const StandardConversionSequence& SCS1,
3655                                const StandardConversionSequence& SCS2) {
3656  QualType FromType1 = SCS1.getFromType();
3657  QualType ToType1 = SCS1.getToType(1);
3658  QualType FromType2 = SCS2.getFromType();
3659  QualType ToType2 = SCS2.getToType(1);
3660
3661  // Adjust the types we're converting from via the array-to-pointer
3662  // conversion, if we need to.
3663  if (SCS1.First == ICK_Array_To_Pointer)
3664    FromType1 = S.Context.getArrayDecayedType(FromType1);
3665  if (SCS2.First == ICK_Array_To_Pointer)
3666    FromType2 = S.Context.getArrayDecayedType(FromType2);
3667
3668  // Canonicalize all of the types.
3669  FromType1 = S.Context.getCanonicalType(FromType1);
3670  ToType1 = S.Context.getCanonicalType(ToType1);
3671  FromType2 = S.Context.getCanonicalType(FromType2);
3672  ToType2 = S.Context.getCanonicalType(ToType2);
3673
3674  // C++ [over.ics.rank]p4b3:
3675  //
3676  //   If class B is derived directly or indirectly from class A and
3677  //   class C is derived directly or indirectly from B,
3678  //
3679  // Compare based on pointer conversions.
3680  if (SCS1.Second == ICK_Pointer_Conversion &&
3681      SCS2.Second == ICK_Pointer_Conversion &&
3682      /*FIXME: Remove if Objective-C id conversions get their own rank*/
3683      FromType1->isPointerType() && FromType2->isPointerType() &&
3684      ToType1->isPointerType() && ToType2->isPointerType()) {
3685    QualType FromPointee1
3686      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3687    QualType ToPointee1
3688      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3689    QualType FromPointee2
3690      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3691    QualType ToPointee2
3692      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3693
3694    //   -- conversion of C* to B* is better than conversion of C* to A*,
3695    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3696      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3697        return ImplicitConversionSequence::Better;
3698      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3699        return ImplicitConversionSequence::Worse;
3700    }
3701
3702    //   -- conversion of B* to A* is better than conversion of C* to A*,
3703    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3704      if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3705        return ImplicitConversionSequence::Better;
3706      else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3707        return ImplicitConversionSequence::Worse;
3708    }
3709  } else if (SCS1.Second == ICK_Pointer_Conversion &&
3710             SCS2.Second == ICK_Pointer_Conversion) {
3711    const ObjCObjectPointerType *FromPtr1
3712      = FromType1->getAs<ObjCObjectPointerType>();
3713    const ObjCObjectPointerType *FromPtr2
3714      = FromType2->getAs<ObjCObjectPointerType>();
3715    const ObjCObjectPointerType *ToPtr1
3716      = ToType1->getAs<ObjCObjectPointerType>();
3717    const ObjCObjectPointerType *ToPtr2
3718      = ToType2->getAs<ObjCObjectPointerType>();
3719
3720    if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3721      // Apply the same conversion ranking rules for Objective-C pointer types
3722      // that we do for C++ pointers to class types. However, we employ the
3723      // Objective-C pseudo-subtyping relationship used for assignment of
3724      // Objective-C pointer types.
3725      bool FromAssignLeft
3726        = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3727      bool FromAssignRight
3728        = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3729      bool ToAssignLeft
3730        = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3731      bool ToAssignRight
3732        = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3733
3734      // A conversion to an a non-id object pointer type or qualified 'id'
3735      // type is better than a conversion to 'id'.
3736      if (ToPtr1->isObjCIdType() &&
3737          (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3738        return ImplicitConversionSequence::Worse;
3739      if (ToPtr2->isObjCIdType() &&
3740          (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3741        return ImplicitConversionSequence::Better;
3742
3743      // A conversion to a non-id object pointer type is better than a
3744      // conversion to a qualified 'id' type
3745      if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3746        return ImplicitConversionSequence::Worse;
3747      if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3748        return ImplicitConversionSequence::Better;
3749
3750      // A conversion to an a non-Class object pointer type or qualified 'Class'
3751      // type is better than a conversion to 'Class'.
3752      if (ToPtr1->isObjCClassType() &&
3753          (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3754        return ImplicitConversionSequence::Worse;
3755      if (ToPtr2->isObjCClassType() &&
3756          (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3757        return ImplicitConversionSequence::Better;
3758
3759      // A conversion to a non-Class object pointer type is better than a
3760      // conversion to a qualified 'Class' type.
3761      if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3762        return ImplicitConversionSequence::Worse;
3763      if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3764        return ImplicitConversionSequence::Better;
3765
3766      //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3767      if (S.Context.hasSameType(FromType1, FromType2) &&
3768          !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3769          (ToAssignLeft != ToAssignRight))
3770        return ToAssignLeft? ImplicitConversionSequence::Worse
3771                           : ImplicitConversionSequence::Better;
3772
3773      //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3774      if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3775          (FromAssignLeft != FromAssignRight))
3776        return FromAssignLeft? ImplicitConversionSequence::Better
3777        : ImplicitConversionSequence::Worse;
3778    }
3779  }
3780
3781  // Ranking of member-pointer types.
3782  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3783      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3784      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3785    const MemberPointerType * FromMemPointer1 =
3786                                        FromType1->getAs<MemberPointerType>();
3787    const MemberPointerType * ToMemPointer1 =
3788                                          ToType1->getAs<MemberPointerType>();
3789    const MemberPointerType * FromMemPointer2 =
3790                                          FromType2->getAs<MemberPointerType>();
3791    const MemberPointerType * ToMemPointer2 =
3792                                          ToType2->getAs<MemberPointerType>();
3793    const Type *FromPointeeType1 = FromMemPointer1->getClass();
3794    const Type *ToPointeeType1 = ToMemPointer1->getClass();
3795    const Type *FromPointeeType2 = FromMemPointer2->getClass();
3796    const Type *ToPointeeType2 = ToMemPointer2->getClass();
3797    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3798    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3799    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3800    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3801    // conversion of A::* to B::* is better than conversion of A::* to C::*,
3802    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3803      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3804        return ImplicitConversionSequence::Worse;
3805      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3806        return ImplicitConversionSequence::Better;
3807    }
3808    // conversion of B::* to C::* is better than conversion of A::* to C::*
3809    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3810      if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3811        return ImplicitConversionSequence::Better;
3812      else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3813        return ImplicitConversionSequence::Worse;
3814    }
3815  }
3816
3817  if (SCS1.Second == ICK_Derived_To_Base) {
3818    //   -- conversion of C to B is better than conversion of C to A,
3819    //   -- binding of an expression of type C to a reference of type
3820    //      B& is better than binding an expression of type C to a
3821    //      reference of type A&,
3822    if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3823        !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3824      if (S.IsDerivedFrom(ToType1, ToType2))
3825        return ImplicitConversionSequence::Better;
3826      else if (S.IsDerivedFrom(ToType2, ToType1))
3827        return ImplicitConversionSequence::Worse;
3828    }
3829
3830    //   -- conversion of B to A is better than conversion of C to A.
3831    //   -- binding of an expression of type B to a reference of type
3832    //      A& is better than binding an expression of type C to a
3833    //      reference of type A&,
3834    if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3835        S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3836      if (S.IsDerivedFrom(FromType2, FromType1))
3837        return ImplicitConversionSequence::Better;
3838      else if (S.IsDerivedFrom(FromType1, FromType2))
3839        return ImplicitConversionSequence::Worse;
3840    }
3841  }
3842
3843  return ImplicitConversionSequence::Indistinguishable;
3844}
3845
3846/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3847/// determine whether they are reference-related,
3848/// reference-compatible, reference-compatible with added
3849/// qualification, or incompatible, for use in C++ initialization by
3850/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3851/// type, and the first type (T1) is the pointee type of the reference
3852/// type being initialized.
3853Sema::ReferenceCompareResult
3854Sema::CompareReferenceRelationship(SourceLocation Loc,
3855                                   QualType OrigT1, QualType OrigT2,
3856                                   bool &DerivedToBase,
3857                                   bool &ObjCConversion,
3858                                   bool &ObjCLifetimeConversion) {
3859  assert(!OrigT1->isReferenceType() &&
3860    "T1 must be the pointee type of the reference type");
3861  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3862
3863  QualType T1 = Context.getCanonicalType(OrigT1);
3864  QualType T2 = Context.getCanonicalType(OrigT2);
3865  Qualifiers T1Quals, T2Quals;
3866  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3867  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3868
3869  // C++ [dcl.init.ref]p4:
3870  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3871  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3872  //   T1 is a base class of T2.
3873  DerivedToBase = false;
3874  ObjCConversion = false;
3875  ObjCLifetimeConversion = false;
3876  if (UnqualT1 == UnqualT2) {
3877    // Nothing to do.
3878  } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3879           IsDerivedFrom(UnqualT2, UnqualT1))
3880    DerivedToBase = true;
3881  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3882           UnqualT2->isObjCObjectOrInterfaceType() &&
3883           Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3884    ObjCConversion = true;
3885  else
3886    return Ref_Incompatible;
3887
3888  // At this point, we know that T1 and T2 are reference-related (at
3889  // least).
3890
3891  // If the type is an array type, promote the element qualifiers to the type
3892  // for comparison.
3893  if (isa<ArrayType>(T1) && T1Quals)
3894    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3895  if (isa<ArrayType>(T2) && T2Quals)
3896    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3897
3898  // C++ [dcl.init.ref]p4:
3899  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3900  //   reference-related to T2 and cv1 is the same cv-qualification
3901  //   as, or greater cv-qualification than, cv2. For purposes of
3902  //   overload resolution, cases for which cv1 is greater
3903  //   cv-qualification than cv2 are identified as
3904  //   reference-compatible with added qualification (see 13.3.3.2).
3905  //
3906  // Note that we also require equivalence of Objective-C GC and address-space
3907  // qualifiers when performing these computations, so that e.g., an int in
3908  // address space 1 is not reference-compatible with an int in address
3909  // space 2.
3910  if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3911      T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3912    T1Quals.removeObjCLifetime();
3913    T2Quals.removeObjCLifetime();
3914    ObjCLifetimeConversion = true;
3915  }
3916
3917  if (T1Quals == T2Quals)
3918    return Ref_Compatible;
3919  else if (T1Quals.compatiblyIncludes(T2Quals))
3920    return Ref_Compatible_With_Added_Qualification;
3921  else
3922    return Ref_Related;
3923}
3924
3925/// \brief Look for a user-defined conversion to an value reference-compatible
3926///        with DeclType. Return true if something definite is found.
3927static bool
3928FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3929                         QualType DeclType, SourceLocation DeclLoc,
3930                         Expr *Init, QualType T2, bool AllowRvalues,
3931                         bool AllowExplicit) {
3932  assert(T2->isRecordType() && "Can only find conversions of record types.");
3933  CXXRecordDecl *T2RecordDecl
3934    = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3935
3936  OverloadCandidateSet CandidateSet(DeclLoc);
3937  const UnresolvedSetImpl *Conversions
3938    = T2RecordDecl->getVisibleConversionFunctions();
3939  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3940         E = Conversions->end(); I != E; ++I) {
3941    NamedDecl *D = *I;
3942    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3943    if (isa<UsingShadowDecl>(D))
3944      D = cast<UsingShadowDecl>(D)->getTargetDecl();
3945
3946    FunctionTemplateDecl *ConvTemplate
3947      = dyn_cast<FunctionTemplateDecl>(D);
3948    CXXConversionDecl *Conv;
3949    if (ConvTemplate)
3950      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3951    else
3952      Conv = cast<CXXConversionDecl>(D);
3953
3954    // If this is an explicit conversion, and we're not allowed to consider
3955    // explicit conversions, skip it.
3956    if (!AllowExplicit && Conv->isExplicit())
3957      continue;
3958
3959    if (AllowRvalues) {
3960      bool DerivedToBase = false;
3961      bool ObjCConversion = false;
3962      bool ObjCLifetimeConversion = false;
3963
3964      // If we are initializing an rvalue reference, don't permit conversion
3965      // functions that return lvalues.
3966      if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3967        const ReferenceType *RefType
3968          = Conv->getConversionType()->getAs<LValueReferenceType>();
3969        if (RefType && !RefType->getPointeeType()->isFunctionType())
3970          continue;
3971      }
3972
3973      if (!ConvTemplate &&
3974          S.CompareReferenceRelationship(
3975            DeclLoc,
3976            Conv->getConversionType().getNonReferenceType()
3977              .getUnqualifiedType(),
3978            DeclType.getNonReferenceType().getUnqualifiedType(),
3979            DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
3980          Sema::Ref_Incompatible)
3981        continue;
3982    } else {
3983      // If the conversion function doesn't return a reference type,
3984      // it can't be considered for this conversion. An rvalue reference
3985      // is only acceptable if its referencee is a function type.
3986
3987      const ReferenceType *RefType =
3988        Conv->getConversionType()->getAs<ReferenceType>();
3989      if (!RefType ||
3990          (!RefType->isLValueReferenceType() &&
3991           !RefType->getPointeeType()->isFunctionType()))
3992        continue;
3993    }
3994
3995    if (ConvTemplate)
3996      S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
3997                                       Init, DeclType, CandidateSet);
3998    else
3999      S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4000                               DeclType, CandidateSet);
4001  }
4002
4003  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4004
4005  OverloadCandidateSet::iterator Best;
4006  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4007  case OR_Success:
4008    // C++ [over.ics.ref]p1:
4009    //
4010    //   [...] If the parameter binds directly to the result of
4011    //   applying a conversion function to the argument
4012    //   expression, the implicit conversion sequence is a
4013    //   user-defined conversion sequence (13.3.3.1.2), with the
4014    //   second standard conversion sequence either an identity
4015    //   conversion or, if the conversion function returns an
4016    //   entity of a type that is a derived class of the parameter
4017    //   type, a derived-to-base Conversion.
4018    if (!Best->FinalConversion.DirectBinding)
4019      return false;
4020
4021    if (Best->Function)
4022      S.MarkFunctionReferenced(DeclLoc, Best->Function);
4023    ICS.setUserDefined();
4024    ICS.UserDefined.Before = Best->Conversions[0].Standard;
4025    ICS.UserDefined.After = Best->FinalConversion;
4026    ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4027    ICS.UserDefined.ConversionFunction = Best->Function;
4028    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4029    ICS.UserDefined.EllipsisConversion = false;
4030    assert(ICS.UserDefined.After.ReferenceBinding &&
4031           ICS.UserDefined.After.DirectBinding &&
4032           "Expected a direct reference binding!");
4033    return true;
4034
4035  case OR_Ambiguous:
4036    ICS.setAmbiguous();
4037    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4038         Cand != CandidateSet.end(); ++Cand)
4039      if (Cand->Viable)
4040        ICS.Ambiguous.addConversion(Cand->Function);
4041    return true;
4042
4043  case OR_No_Viable_Function:
4044  case OR_Deleted:
4045    // There was no suitable conversion, or we found a deleted
4046    // conversion; continue with other checks.
4047    return false;
4048  }
4049
4050  llvm_unreachable("Invalid OverloadResult!");
4051}
4052
4053/// \brief Compute an implicit conversion sequence for reference
4054/// initialization.
4055static ImplicitConversionSequence
4056TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4057                 SourceLocation DeclLoc,
4058                 bool SuppressUserConversions,
4059                 bool AllowExplicit) {
4060  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4061
4062  // Most paths end in a failed conversion.
4063  ImplicitConversionSequence ICS;
4064  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4065
4066  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4067  QualType T2 = Init->getType();
4068
4069  // If the initializer is the address of an overloaded function, try
4070  // to resolve the overloaded function. If all goes well, T2 is the
4071  // type of the resulting function.
4072  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4073    DeclAccessPair Found;
4074    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4075                                                                false, Found))
4076      T2 = Fn->getType();
4077  }
4078
4079  // Compute some basic properties of the types and the initializer.
4080  bool isRValRef = DeclType->isRValueReferenceType();
4081  bool DerivedToBase = false;
4082  bool ObjCConversion = false;
4083  bool ObjCLifetimeConversion = false;
4084  Expr::Classification InitCategory = Init->Classify(S.Context);
4085  Sema::ReferenceCompareResult RefRelationship
4086    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4087                                     ObjCConversion, ObjCLifetimeConversion);
4088
4089
4090  // C++0x [dcl.init.ref]p5:
4091  //   A reference to type "cv1 T1" is initialized by an expression
4092  //   of type "cv2 T2" as follows:
4093
4094  //     -- If reference is an lvalue reference and the initializer expression
4095  if (!isRValRef) {
4096    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4097    //        reference-compatible with "cv2 T2," or
4098    //
4099    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4100    if (InitCategory.isLValue() &&
4101        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4102      // C++ [over.ics.ref]p1:
4103      //   When a parameter of reference type binds directly (8.5.3)
4104      //   to an argument expression, the implicit conversion sequence
4105      //   is the identity conversion, unless the argument expression
4106      //   has a type that is a derived class of the parameter type,
4107      //   in which case the implicit conversion sequence is a
4108      //   derived-to-base Conversion (13.3.3.1).
4109      ICS.setStandard();
4110      ICS.Standard.First = ICK_Identity;
4111      ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4112                         : ObjCConversion? ICK_Compatible_Conversion
4113                         : ICK_Identity;
4114      ICS.Standard.Third = ICK_Identity;
4115      ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4116      ICS.Standard.setToType(0, T2);
4117      ICS.Standard.setToType(1, T1);
4118      ICS.Standard.setToType(2, T1);
4119      ICS.Standard.ReferenceBinding = true;
4120      ICS.Standard.DirectBinding = true;
4121      ICS.Standard.IsLvalueReference = !isRValRef;
4122      ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4123      ICS.Standard.BindsToRvalue = false;
4124      ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4125      ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4126      ICS.Standard.CopyConstructor = 0;
4127
4128      // Nothing more to do: the inaccessibility/ambiguity check for
4129      // derived-to-base conversions is suppressed when we're
4130      // computing the implicit conversion sequence (C++
4131      // [over.best.ics]p2).
4132      return ICS;
4133    }
4134
4135    //       -- has a class type (i.e., T2 is a class type), where T1 is
4136    //          not reference-related to T2, and can be implicitly
4137    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4138    //          is reference-compatible with "cv3 T3" 92) (this
4139    //          conversion is selected by enumerating the applicable
4140    //          conversion functions (13.3.1.6) and choosing the best
4141    //          one through overload resolution (13.3)),
4142    if (!SuppressUserConversions && T2->isRecordType() &&
4143        !S.RequireCompleteType(DeclLoc, T2, 0) &&
4144        RefRelationship == Sema::Ref_Incompatible) {
4145      if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4146                                   Init, T2, /*AllowRvalues=*/false,
4147                                   AllowExplicit))
4148        return ICS;
4149    }
4150  }
4151
4152  //     -- Otherwise, the reference shall be an lvalue reference to a
4153  //        non-volatile const type (i.e., cv1 shall be const), or the reference
4154  //        shall be an rvalue reference.
4155  //
4156  // We actually handle one oddity of C++ [over.ics.ref] at this
4157  // point, which is that, due to p2 (which short-circuits reference
4158  // binding by only attempting a simple conversion for non-direct
4159  // bindings) and p3's strange wording, we allow a const volatile
4160  // reference to bind to an rvalue. Hence the check for the presence
4161  // of "const" rather than checking for "const" being the only
4162  // qualifier.
4163  // This is also the point where rvalue references and lvalue inits no longer
4164  // go together.
4165  if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4166    return ICS;
4167
4168  //       -- If the initializer expression
4169  //
4170  //            -- is an xvalue, class prvalue, array prvalue or function
4171  //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4172  if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4173      (InitCategory.isXValue() ||
4174      (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4175      (InitCategory.isLValue() && T2->isFunctionType()))) {
4176    ICS.setStandard();
4177    ICS.Standard.First = ICK_Identity;
4178    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4179                      : ObjCConversion? ICK_Compatible_Conversion
4180                      : ICK_Identity;
4181    ICS.Standard.Third = ICK_Identity;
4182    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4183    ICS.Standard.setToType(0, T2);
4184    ICS.Standard.setToType(1, T1);
4185    ICS.Standard.setToType(2, T1);
4186    ICS.Standard.ReferenceBinding = true;
4187    // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4188    // binding unless we're binding to a class prvalue.
4189    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4190    // allow the use of rvalue references in C++98/03 for the benefit of
4191    // standard library implementors; therefore, we need the xvalue check here.
4192    ICS.Standard.DirectBinding =
4193      S.getLangOpts().CPlusPlus0x ||
4194      (InitCategory.isPRValue() && !T2->isRecordType());
4195    ICS.Standard.IsLvalueReference = !isRValRef;
4196    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4197    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4198    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4199    ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4200    ICS.Standard.CopyConstructor = 0;
4201    return ICS;
4202  }
4203
4204  //            -- has a class type (i.e., T2 is a class type), where T1 is not
4205  //               reference-related to T2, and can be implicitly converted to
4206  //               an xvalue, class prvalue, or function lvalue of type
4207  //               "cv3 T3", where "cv1 T1" is reference-compatible with
4208  //               "cv3 T3",
4209  //
4210  //          then the reference is bound to the value of the initializer
4211  //          expression in the first case and to the result of the conversion
4212  //          in the second case (or, in either case, to an appropriate base
4213  //          class subobject).
4214  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4215      T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4216      FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4217                               Init, T2, /*AllowRvalues=*/true,
4218                               AllowExplicit)) {
4219    // In the second case, if the reference is an rvalue reference
4220    // and the second standard conversion sequence of the
4221    // user-defined conversion sequence includes an lvalue-to-rvalue
4222    // conversion, the program is ill-formed.
4223    if (ICS.isUserDefined() && isRValRef &&
4224        ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4225      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4226
4227    return ICS;
4228  }
4229
4230  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4231  //          initialized from the initializer expression using the
4232  //          rules for a non-reference copy initialization (8.5). The
4233  //          reference is then bound to the temporary. If T1 is
4234  //          reference-related to T2, cv1 must be the same
4235  //          cv-qualification as, or greater cv-qualification than,
4236  //          cv2; otherwise, the program is ill-formed.
4237  if (RefRelationship == Sema::Ref_Related) {
4238    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4239    // we would be reference-compatible or reference-compatible with
4240    // added qualification. But that wasn't the case, so the reference
4241    // initialization fails.
4242    //
4243    // Note that we only want to check address spaces and cvr-qualifiers here.
4244    // ObjC GC and lifetime qualifiers aren't important.
4245    Qualifiers T1Quals = T1.getQualifiers();
4246    Qualifiers T2Quals = T2.getQualifiers();
4247    T1Quals.removeObjCGCAttr();
4248    T1Quals.removeObjCLifetime();
4249    T2Quals.removeObjCGCAttr();
4250    T2Quals.removeObjCLifetime();
4251    if (!T1Quals.compatiblyIncludes(T2Quals))
4252      return ICS;
4253  }
4254
4255  // If at least one of the types is a class type, the types are not
4256  // related, and we aren't allowed any user conversions, the
4257  // reference binding fails. This case is important for breaking
4258  // recursion, since TryImplicitConversion below will attempt to
4259  // create a temporary through the use of a copy constructor.
4260  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4261      (T1->isRecordType() || T2->isRecordType()))
4262    return ICS;
4263
4264  // If T1 is reference-related to T2 and the reference is an rvalue
4265  // reference, the initializer expression shall not be an lvalue.
4266  if (RefRelationship >= Sema::Ref_Related &&
4267      isRValRef && Init->Classify(S.Context).isLValue())
4268    return ICS;
4269
4270  // C++ [over.ics.ref]p2:
4271  //   When a parameter of reference type is not bound directly to
4272  //   an argument expression, the conversion sequence is the one
4273  //   required to convert the argument expression to the
4274  //   underlying type of the reference according to
4275  //   13.3.3.1. Conceptually, this conversion sequence corresponds
4276  //   to copy-initializing a temporary of the underlying type with
4277  //   the argument expression. Any difference in top-level
4278  //   cv-qualification is subsumed by the initialization itself
4279  //   and does not constitute a conversion.
4280  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4281                              /*AllowExplicit=*/false,
4282                              /*InOverloadResolution=*/false,
4283                              /*CStyle=*/false,
4284                              /*AllowObjCWritebackConversion=*/false);
4285
4286  // Of course, that's still a reference binding.
4287  if (ICS.isStandard()) {
4288    ICS.Standard.ReferenceBinding = true;
4289    ICS.Standard.IsLvalueReference = !isRValRef;
4290    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4291    ICS.Standard.BindsToRvalue = true;
4292    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4293    ICS.Standard.ObjCLifetimeConversionBinding = false;
4294  } else if (ICS.isUserDefined()) {
4295    // Don't allow rvalue references to bind to lvalues.
4296    if (DeclType->isRValueReferenceType()) {
4297      if (const ReferenceType *RefType
4298            = ICS.UserDefined.ConversionFunction->getResultType()
4299                ->getAs<LValueReferenceType>()) {
4300        if (!RefType->getPointeeType()->isFunctionType()) {
4301          ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4302                     DeclType);
4303          return ICS;
4304        }
4305      }
4306    }
4307
4308    ICS.UserDefined.After.ReferenceBinding = true;
4309    ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4310    ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4311    ICS.UserDefined.After.BindsToRvalue = true;
4312    ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4313    ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4314  }
4315
4316  return ICS;
4317}
4318
4319static ImplicitConversionSequence
4320TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4321                      bool SuppressUserConversions,
4322                      bool InOverloadResolution,
4323                      bool AllowObjCWritebackConversion,
4324                      bool AllowExplicit = false);
4325
4326/// TryListConversion - Try to copy-initialize a value of type ToType from the
4327/// initializer list From.
4328static ImplicitConversionSequence
4329TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4330                  bool SuppressUserConversions,
4331                  bool InOverloadResolution,
4332                  bool AllowObjCWritebackConversion) {
4333  // C++11 [over.ics.list]p1:
4334  //   When an argument is an initializer list, it is not an expression and
4335  //   special rules apply for converting it to a parameter type.
4336
4337  ImplicitConversionSequence Result;
4338  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4339  Result.setListInitializationSequence();
4340
4341  // We need a complete type for what follows. Incomplete types can never be
4342  // initialized from init lists.
4343  if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4344    return Result;
4345
4346  // C++11 [over.ics.list]p2:
4347  //   If the parameter type is std::initializer_list<X> or "array of X" and
4348  //   all the elements can be implicitly converted to X, the implicit
4349  //   conversion sequence is the worst conversion necessary to convert an
4350  //   element of the list to X.
4351  bool toStdInitializerList = false;
4352  QualType X;
4353  if (ToType->isArrayType())
4354    X = S.Context.getBaseElementType(ToType);
4355  else
4356    toStdInitializerList = S.isStdInitializerList(ToType, &X);
4357  if (!X.isNull()) {
4358    for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4359      Expr *Init = From->getInit(i);
4360      ImplicitConversionSequence ICS =
4361          TryCopyInitialization(S, Init, X, SuppressUserConversions,
4362                                InOverloadResolution,
4363                                AllowObjCWritebackConversion);
4364      // If a single element isn't convertible, fail.
4365      if (ICS.isBad()) {
4366        Result = ICS;
4367        break;
4368      }
4369      // Otherwise, look for the worst conversion.
4370      if (Result.isBad() ||
4371          CompareImplicitConversionSequences(S, ICS, Result) ==
4372              ImplicitConversionSequence::Worse)
4373        Result = ICS;
4374    }
4375
4376    // For an empty list, we won't have computed any conversion sequence.
4377    // Introduce the identity conversion sequence.
4378    if (From->getNumInits() == 0) {
4379      Result.setStandard();
4380      Result.Standard.setAsIdentityConversion();
4381      Result.Standard.setFromType(ToType);
4382      Result.Standard.setAllToTypes(ToType);
4383    }
4384
4385    Result.setListInitializationSequence();
4386    Result.setStdInitializerListElement(toStdInitializerList);
4387    return Result;
4388  }
4389
4390  // C++11 [over.ics.list]p3:
4391  //   Otherwise, if the parameter is a non-aggregate class X and overload
4392  //   resolution chooses a single best constructor [...] the implicit
4393  //   conversion sequence is a user-defined conversion sequence. If multiple
4394  //   constructors are viable but none is better than the others, the
4395  //   implicit conversion sequence is a user-defined conversion sequence.
4396  if (ToType->isRecordType() && !ToType->isAggregateType()) {
4397    // This function can deal with initializer lists.
4398    Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4399                                      /*AllowExplicit=*/false,
4400                                      InOverloadResolution, /*CStyle=*/false,
4401                                      AllowObjCWritebackConversion);
4402    Result.setListInitializationSequence();
4403    return Result;
4404  }
4405
4406  // C++11 [over.ics.list]p4:
4407  //   Otherwise, if the parameter has an aggregate type which can be
4408  //   initialized from the initializer list [...] the implicit conversion
4409  //   sequence is a user-defined conversion sequence.
4410  if (ToType->isAggregateType()) {
4411    // Type is an aggregate, argument is an init list. At this point it comes
4412    // down to checking whether the initialization works.
4413    // FIXME: Find out whether this parameter is consumed or not.
4414    InitializedEntity Entity =
4415        InitializedEntity::InitializeParameter(S.Context, ToType,
4416                                               /*Consumed=*/false);
4417    if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4418      Result.setUserDefined();
4419      Result.UserDefined.Before.setAsIdentityConversion();
4420      // Initializer lists don't have a type.
4421      Result.UserDefined.Before.setFromType(QualType());
4422      Result.UserDefined.Before.setAllToTypes(QualType());
4423
4424      Result.UserDefined.After.setAsIdentityConversion();
4425      Result.UserDefined.After.setFromType(ToType);
4426      Result.UserDefined.After.setAllToTypes(ToType);
4427      Result.UserDefined.ConversionFunction = 0;
4428    }
4429    return Result;
4430  }
4431
4432  // C++11 [over.ics.list]p5:
4433  //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4434  if (ToType->isReferenceType()) {
4435    // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4436    // mention initializer lists in any way. So we go by what list-
4437    // initialization would do and try to extrapolate from that.
4438
4439    QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4440
4441    // If the initializer list has a single element that is reference-related
4442    // to the parameter type, we initialize the reference from that.
4443    if (From->getNumInits() == 1) {
4444      Expr *Init = From->getInit(0);
4445
4446      QualType T2 = Init->getType();
4447
4448      // If the initializer is the address of an overloaded function, try
4449      // to resolve the overloaded function. If all goes well, T2 is the
4450      // type of the resulting function.
4451      if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4452        DeclAccessPair Found;
4453        if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4454                                   Init, ToType, false, Found))
4455          T2 = Fn->getType();
4456      }
4457
4458      // Compute some basic properties of the types and the initializer.
4459      bool dummy1 = false;
4460      bool dummy2 = false;
4461      bool dummy3 = false;
4462      Sema::ReferenceCompareResult RefRelationship
4463        = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4464                                         dummy2, dummy3);
4465
4466      if (RefRelationship >= Sema::Ref_Related)
4467        return TryReferenceInit(S, Init, ToType,
4468                                /*FIXME:*/From->getLocStart(),
4469                                SuppressUserConversions,
4470                                /*AllowExplicit=*/false);
4471    }
4472
4473    // Otherwise, we bind the reference to a temporary created from the
4474    // initializer list.
4475    Result = TryListConversion(S, From, T1, SuppressUserConversions,
4476                               InOverloadResolution,
4477                               AllowObjCWritebackConversion);
4478    if (Result.isFailure())
4479      return Result;
4480    assert(!Result.isEllipsis() &&
4481           "Sub-initialization cannot result in ellipsis conversion.");
4482
4483    // Can we even bind to a temporary?
4484    if (ToType->isRValueReferenceType() ||
4485        (T1.isConstQualified() && !T1.isVolatileQualified())) {
4486      StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4487                                            Result.UserDefined.After;
4488      SCS.ReferenceBinding = true;
4489      SCS.IsLvalueReference = ToType->isLValueReferenceType();
4490      SCS.BindsToRvalue = true;
4491      SCS.BindsToFunctionLvalue = false;
4492      SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4493      SCS.ObjCLifetimeConversionBinding = false;
4494    } else
4495      Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4496                    From, ToType);
4497    return Result;
4498  }
4499
4500  // C++11 [over.ics.list]p6:
4501  //   Otherwise, if the parameter type is not a class:
4502  if (!ToType->isRecordType()) {
4503    //    - if the initializer list has one element, the implicit conversion
4504    //      sequence is the one required to convert the element to the
4505    //      parameter type.
4506    unsigned NumInits = From->getNumInits();
4507    if (NumInits == 1)
4508      Result = TryCopyInitialization(S, From->getInit(0), ToType,
4509                                     SuppressUserConversions,
4510                                     InOverloadResolution,
4511                                     AllowObjCWritebackConversion);
4512    //    - if the initializer list has no elements, the implicit conversion
4513    //      sequence is the identity conversion.
4514    else if (NumInits == 0) {
4515      Result.setStandard();
4516      Result.Standard.setAsIdentityConversion();
4517      Result.Standard.setFromType(ToType);
4518      Result.Standard.setAllToTypes(ToType);
4519    }
4520    Result.setListInitializationSequence();
4521    return Result;
4522  }
4523
4524  // C++11 [over.ics.list]p7:
4525  //   In all cases other than those enumerated above, no conversion is possible
4526  return Result;
4527}
4528
4529/// TryCopyInitialization - Try to copy-initialize a value of type
4530/// ToType from the expression From. Return the implicit conversion
4531/// sequence required to pass this argument, which may be a bad
4532/// conversion sequence (meaning that the argument cannot be passed to
4533/// a parameter of this type). If @p SuppressUserConversions, then we
4534/// do not permit any user-defined conversion sequences.
4535static ImplicitConversionSequence
4536TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4537                      bool SuppressUserConversions,
4538                      bool InOverloadResolution,
4539                      bool AllowObjCWritebackConversion,
4540                      bool AllowExplicit) {
4541  if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4542    return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4543                             InOverloadResolution,AllowObjCWritebackConversion);
4544
4545  if (ToType->isReferenceType())
4546    return TryReferenceInit(S, From, ToType,
4547                            /*FIXME:*/From->getLocStart(),
4548                            SuppressUserConversions,
4549                            AllowExplicit);
4550
4551  return TryImplicitConversion(S, From, ToType,
4552                               SuppressUserConversions,
4553                               /*AllowExplicit=*/false,
4554                               InOverloadResolution,
4555                               /*CStyle=*/false,
4556                               AllowObjCWritebackConversion);
4557}
4558
4559static bool TryCopyInitialization(const CanQualType FromQTy,
4560                                  const CanQualType ToQTy,
4561                                  Sema &S,
4562                                  SourceLocation Loc,
4563                                  ExprValueKind FromVK) {
4564  OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4565  ImplicitConversionSequence ICS =
4566    TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4567
4568  return !ICS.isBad();
4569}
4570
4571/// TryObjectArgumentInitialization - Try to initialize the object
4572/// parameter of the given member function (@c Method) from the
4573/// expression @p From.
4574static ImplicitConversionSequence
4575TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
4576                                Expr::Classification FromClassification,
4577                                CXXMethodDecl *Method,
4578                                CXXRecordDecl *ActingContext) {
4579  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4580  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4581  //                 const volatile object.
4582  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4583    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4584  QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4585
4586  // Set up the conversion sequence as a "bad" conversion, to allow us
4587  // to exit early.
4588  ImplicitConversionSequence ICS;
4589
4590  // We need to have an object of class type.
4591  QualType FromType = OrigFromType;
4592  if (const PointerType *PT = FromType->getAs<PointerType>()) {
4593    FromType = PT->getPointeeType();
4594
4595    // When we had a pointer, it's implicitly dereferenced, so we
4596    // better have an lvalue.
4597    assert(FromClassification.isLValue());
4598  }
4599
4600  assert(FromType->isRecordType());
4601
4602  // C++0x [over.match.funcs]p4:
4603  //   For non-static member functions, the type of the implicit object
4604  //   parameter is
4605  //
4606  //     - "lvalue reference to cv X" for functions declared without a
4607  //        ref-qualifier or with the & ref-qualifier
4608  //     - "rvalue reference to cv X" for functions declared with the &&
4609  //        ref-qualifier
4610  //
4611  // where X is the class of which the function is a member and cv is the
4612  // cv-qualification on the member function declaration.
4613  //
4614  // However, when finding an implicit conversion sequence for the argument, we
4615  // are not allowed to create temporaries or perform user-defined conversions
4616  // (C++ [over.match.funcs]p5). We perform a simplified version of
4617  // reference binding here, that allows class rvalues to bind to
4618  // non-constant references.
4619
4620  // First check the qualifiers.
4621  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4622  if (ImplicitParamType.getCVRQualifiers()
4623                                    != FromTypeCanon.getLocalCVRQualifiers() &&
4624      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4625    ICS.setBad(BadConversionSequence::bad_qualifiers,
4626               OrigFromType, ImplicitParamType);
4627    return ICS;
4628  }
4629
4630  // Check that we have either the same type or a derived type. It
4631  // affects the conversion rank.
4632  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4633  ImplicitConversionKind SecondKind;
4634  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4635    SecondKind = ICK_Identity;
4636  } else if (S.IsDerivedFrom(FromType, ClassType))
4637    SecondKind = ICK_Derived_To_Base;
4638  else {
4639    ICS.setBad(BadConversionSequence::unrelated_class,
4640               FromType, ImplicitParamType);
4641    return ICS;
4642  }
4643
4644  // Check the ref-qualifier.
4645  switch (Method->getRefQualifier()) {
4646  case RQ_None:
4647    // Do nothing; we don't care about lvalueness or rvalueness.
4648    break;
4649
4650  case RQ_LValue:
4651    if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4652      // non-const lvalue reference cannot bind to an rvalue
4653      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4654                 ImplicitParamType);
4655      return ICS;
4656    }
4657    break;
4658
4659  case RQ_RValue:
4660    if (!FromClassification.isRValue()) {
4661      // rvalue reference cannot bind to an lvalue
4662      ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4663                 ImplicitParamType);
4664      return ICS;
4665    }
4666    break;
4667  }
4668
4669  // Success. Mark this as a reference binding.
4670  ICS.setStandard();
4671  ICS.Standard.setAsIdentityConversion();
4672  ICS.Standard.Second = SecondKind;
4673  ICS.Standard.setFromType(FromType);
4674  ICS.Standard.setAllToTypes(ImplicitParamType);
4675  ICS.Standard.ReferenceBinding = true;
4676  ICS.Standard.DirectBinding = true;
4677  ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4678  ICS.Standard.BindsToFunctionLvalue = false;
4679  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4680  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4681    = (Method->getRefQualifier() == RQ_None);
4682  return ICS;
4683}
4684
4685/// PerformObjectArgumentInitialization - Perform initialization of
4686/// the implicit object parameter for the given Method with the given
4687/// expression.
4688ExprResult
4689Sema::PerformObjectArgumentInitialization(Expr *From,
4690                                          NestedNameSpecifier *Qualifier,
4691                                          NamedDecl *FoundDecl,
4692                                          CXXMethodDecl *Method) {
4693  QualType FromRecordType, DestType;
4694  QualType ImplicitParamRecordType  =
4695    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4696
4697  Expr::Classification FromClassification;
4698  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4699    FromRecordType = PT->getPointeeType();
4700    DestType = Method->getThisType(Context);
4701    FromClassification = Expr::Classification::makeSimpleLValue();
4702  } else {
4703    FromRecordType = From->getType();
4704    DestType = ImplicitParamRecordType;
4705    FromClassification = From->Classify(Context);
4706  }
4707
4708  // Note that we always use the true parent context when performing
4709  // the actual argument initialization.
4710  ImplicitConversionSequence ICS
4711    = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4712                                      Method, Method->getParent());
4713  if (ICS.isBad()) {
4714    if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4715      Qualifiers FromQs = FromRecordType.getQualifiers();
4716      Qualifiers ToQs = DestType.getQualifiers();
4717      unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4718      if (CVR) {
4719        Diag(From->getLocStart(),
4720             diag::err_member_function_call_bad_cvr)
4721          << Method->getDeclName() << FromRecordType << (CVR - 1)
4722          << From->getSourceRange();
4723        Diag(Method->getLocation(), diag::note_previous_decl)
4724          << Method->getDeclName();
4725        return ExprError();
4726      }
4727    }
4728
4729    return Diag(From->getLocStart(),
4730                diag::err_implicit_object_parameter_init)
4731       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4732  }
4733
4734  if (ICS.Standard.Second == ICK_Derived_To_Base) {
4735    ExprResult FromRes =
4736      PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4737    if (FromRes.isInvalid())
4738      return ExprError();
4739    From = FromRes.take();
4740  }
4741
4742  if (!Context.hasSameType(From->getType(), DestType))
4743    From = ImpCastExprToType(From, DestType, CK_NoOp,
4744                             From->getValueKind()).take();
4745  return Owned(From);
4746}
4747
4748/// TryContextuallyConvertToBool - Attempt to contextually convert the
4749/// expression From to bool (C++0x [conv]p3).
4750static ImplicitConversionSequence
4751TryContextuallyConvertToBool(Sema &S, Expr *From) {
4752  // FIXME: This is pretty broken.
4753  return TryImplicitConversion(S, From, S.Context.BoolTy,
4754                               // FIXME: Are these flags correct?
4755                               /*SuppressUserConversions=*/false,
4756                               /*AllowExplicit=*/true,
4757                               /*InOverloadResolution=*/false,
4758                               /*CStyle=*/false,
4759                               /*AllowObjCWritebackConversion=*/false);
4760}
4761
4762/// PerformContextuallyConvertToBool - Perform a contextual conversion
4763/// of the expression From to bool (C++0x [conv]p3).
4764ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4765  if (checkPlaceholderForOverload(*this, From))
4766    return ExprError();
4767
4768  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4769  if (!ICS.isBad())
4770    return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4771
4772  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4773    return Diag(From->getLocStart(),
4774                diag::err_typecheck_bool_condition)
4775                  << From->getType() << From->getSourceRange();
4776  return ExprError();
4777}
4778
4779/// Check that the specified conversion is permitted in a converted constant
4780/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4781/// is acceptable.
4782static bool CheckConvertedConstantConversions(Sema &S,
4783                                              StandardConversionSequence &SCS) {
4784  // Since we know that the target type is an integral or unscoped enumeration
4785  // type, most conversion kinds are impossible. All possible First and Third
4786  // conversions are fine.
4787  switch (SCS.Second) {
4788  case ICK_Identity:
4789  case ICK_Integral_Promotion:
4790  case ICK_Integral_Conversion:
4791    return true;
4792
4793  case ICK_Boolean_Conversion:
4794    // Conversion from an integral or unscoped enumeration type to bool is
4795    // classified as ICK_Boolean_Conversion, but it's also an integral
4796    // conversion, so it's permitted in a converted constant expression.
4797    return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4798           SCS.getToType(2)->isBooleanType();
4799
4800  case ICK_Floating_Integral:
4801  case ICK_Complex_Real:
4802    return false;
4803
4804  case ICK_Lvalue_To_Rvalue:
4805  case ICK_Array_To_Pointer:
4806  case ICK_Function_To_Pointer:
4807  case ICK_NoReturn_Adjustment:
4808  case ICK_Qualification:
4809  case ICK_Compatible_Conversion:
4810  case ICK_Vector_Conversion:
4811  case ICK_Vector_Splat:
4812  case ICK_Derived_To_Base:
4813  case ICK_Pointer_Conversion:
4814  case ICK_Pointer_Member:
4815  case ICK_Block_Pointer_Conversion:
4816  case ICK_Writeback_Conversion:
4817  case ICK_Floating_Promotion:
4818  case ICK_Complex_Promotion:
4819  case ICK_Complex_Conversion:
4820  case ICK_Floating_Conversion:
4821  case ICK_TransparentUnionConversion:
4822    llvm_unreachable("unexpected second conversion kind");
4823
4824  case ICK_Num_Conversion_Kinds:
4825    break;
4826  }
4827
4828  llvm_unreachable("unknown conversion kind");
4829}
4830
4831/// CheckConvertedConstantExpression - Check that the expression From is a
4832/// converted constant expression of type T, perform the conversion and produce
4833/// the converted expression, per C++11 [expr.const]p3.
4834ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4835                                                  llvm::APSInt &Value,
4836                                                  CCEKind CCE) {
4837  assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4838  assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4839
4840  if (checkPlaceholderForOverload(*this, From))
4841    return ExprError();
4842
4843  // C++11 [expr.const]p3 with proposed wording fixes:
4844  //  A converted constant expression of type T is a core constant expression,
4845  //  implicitly converted to a prvalue of type T, where the converted
4846  //  expression is a literal constant expression and the implicit conversion
4847  //  sequence contains only user-defined conversions, lvalue-to-rvalue
4848  //  conversions, integral promotions, and integral conversions other than
4849  //  narrowing conversions.
4850  ImplicitConversionSequence ICS =
4851    TryImplicitConversion(From, T,
4852                          /*SuppressUserConversions=*/false,
4853                          /*AllowExplicit=*/false,
4854                          /*InOverloadResolution=*/false,
4855                          /*CStyle=*/false,
4856                          /*AllowObjcWritebackConversion=*/false);
4857  StandardConversionSequence *SCS = 0;
4858  switch (ICS.getKind()) {
4859  case ImplicitConversionSequence::StandardConversion:
4860    if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4861      return Diag(From->getLocStart(),
4862                  diag::err_typecheck_converted_constant_expression_disallowed)
4863               << From->getType() << From->getSourceRange() << T;
4864    SCS = &ICS.Standard;
4865    break;
4866  case ImplicitConversionSequence::UserDefinedConversion:
4867    // We are converting from class type to an integral or enumeration type, so
4868    // the Before sequence must be trivial.
4869    if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4870      return Diag(From->getLocStart(),
4871                  diag::err_typecheck_converted_constant_expression_disallowed)
4872               << From->getType() << From->getSourceRange() << T;
4873    SCS = &ICS.UserDefined.After;
4874    break;
4875  case ImplicitConversionSequence::AmbiguousConversion:
4876  case ImplicitConversionSequence::BadConversion:
4877    if (!DiagnoseMultipleUserDefinedConversion(From, T))
4878      return Diag(From->getLocStart(),
4879                  diag::err_typecheck_converted_constant_expression)
4880                    << From->getType() << From->getSourceRange() << T;
4881    return ExprError();
4882
4883  case ImplicitConversionSequence::EllipsisConversion:
4884    llvm_unreachable("ellipsis conversion in converted constant expression");
4885  }
4886
4887  ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4888  if (Result.isInvalid())
4889    return Result;
4890
4891  // Check for a narrowing implicit conversion.
4892  APValue PreNarrowingValue;
4893  QualType PreNarrowingType;
4894  switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4895                                PreNarrowingType)) {
4896  case NK_Variable_Narrowing:
4897    // Implicit conversion to a narrower type, and the value is not a constant
4898    // expression. We'll diagnose this in a moment.
4899  case NK_Not_Narrowing:
4900    break;
4901
4902  case NK_Constant_Narrowing:
4903    Diag(From->getLocStart(),
4904         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4905                             diag::err_cce_narrowing)
4906      << CCE << /*Constant*/1
4907      << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
4908    break;
4909
4910  case NK_Type_Narrowing:
4911    Diag(From->getLocStart(),
4912         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4913                             diag::err_cce_narrowing)
4914      << CCE << /*Constant*/0 << From->getType() << T;
4915    break;
4916  }
4917
4918  // Check the expression is a constant expression.
4919  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4920  Expr::EvalResult Eval;
4921  Eval.Diag = &Notes;
4922
4923  if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4924    // The expression can't be folded, so we can't keep it at this position in
4925    // the AST.
4926    Result = ExprError();
4927  } else {
4928    Value = Eval.Val.getInt();
4929
4930    if (Notes.empty()) {
4931      // It's a constant expression.
4932      return Result;
4933    }
4934  }
4935
4936  // It's not a constant expression. Produce an appropriate diagnostic.
4937  if (Notes.size() == 1 &&
4938      Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4939    Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4940  else {
4941    Diag(From->getLocStart(), diag::err_expr_not_cce)
4942      << CCE << From->getSourceRange();
4943    for (unsigned I = 0; I < Notes.size(); ++I)
4944      Diag(Notes[I].first, Notes[I].second);
4945  }
4946  return Result;
4947}
4948
4949/// dropPointerConversions - If the given standard conversion sequence
4950/// involves any pointer conversions, remove them.  This may change
4951/// the result type of the conversion sequence.
4952static void dropPointerConversion(StandardConversionSequence &SCS) {
4953  if (SCS.Second == ICK_Pointer_Conversion) {
4954    SCS.Second = ICK_Identity;
4955    SCS.Third = ICK_Identity;
4956    SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4957  }
4958}
4959
4960/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4961/// convert the expression From to an Objective-C pointer type.
4962static ImplicitConversionSequence
4963TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4964  // Do an implicit conversion to 'id'.
4965  QualType Ty = S.Context.getObjCIdType();
4966  ImplicitConversionSequence ICS
4967    = TryImplicitConversion(S, From, Ty,
4968                            // FIXME: Are these flags correct?
4969                            /*SuppressUserConversions=*/false,
4970                            /*AllowExplicit=*/true,
4971                            /*InOverloadResolution=*/false,
4972                            /*CStyle=*/false,
4973                            /*AllowObjCWritebackConversion=*/false);
4974
4975  // Strip off any final conversions to 'id'.
4976  switch (ICS.getKind()) {
4977  case ImplicitConversionSequence::BadConversion:
4978  case ImplicitConversionSequence::AmbiguousConversion:
4979  case ImplicitConversionSequence::EllipsisConversion:
4980    break;
4981
4982  case ImplicitConversionSequence::UserDefinedConversion:
4983    dropPointerConversion(ICS.UserDefined.After);
4984    break;
4985
4986  case ImplicitConversionSequence::StandardConversion:
4987    dropPointerConversion(ICS.Standard);
4988    break;
4989  }
4990
4991  return ICS;
4992}
4993
4994/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4995/// conversion of the expression From to an Objective-C pointer type.
4996ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
4997  if (checkPlaceholderForOverload(*this, From))
4998    return ExprError();
4999
5000  QualType Ty = Context.getObjCIdType();
5001  ImplicitConversionSequence ICS =
5002    TryContextuallyConvertToObjCPointer(*this, From);
5003  if (!ICS.isBad())
5004    return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5005  return ExprError();
5006}
5007
5008/// Determine whether the provided type is an integral type, or an enumeration
5009/// type of a permitted flavor.
5010static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5011  return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5012                         : T->isIntegralOrUnscopedEnumerationType();
5013}
5014
5015/// \brief Attempt to convert the given expression to an integral or
5016/// enumeration type.
5017///
5018/// This routine will attempt to convert an expression of class type to an
5019/// integral or enumeration type, if that class type only has a single
5020/// conversion to an integral or enumeration type.
5021///
5022/// \param Loc The source location of the construct that requires the
5023/// conversion.
5024///
5025/// \param From The expression we're converting from.
5026///
5027/// \param Diagnoser Used to output any diagnostics.
5028///
5029/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5030/// enumerations should be considered.
5031///
5032/// \returns The expression, converted to an integral or enumeration type if
5033/// successful.
5034ExprResult
5035Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
5036                                         ICEConvertDiagnoser &Diagnoser,
5037                                         bool AllowScopedEnumerations) {
5038  // We can't perform any more checking for type-dependent expressions.
5039  if (From->isTypeDependent())
5040    return Owned(From);
5041
5042  // Process placeholders immediately.
5043  if (From->hasPlaceholderType()) {
5044    ExprResult result = CheckPlaceholderExpr(From);
5045    if (result.isInvalid()) return result;
5046    From = result.take();
5047  }
5048
5049  // If the expression already has integral or enumeration type, we're golden.
5050  QualType T = From->getType();
5051  if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
5052    return DefaultLvalueConversion(From);
5053
5054  // FIXME: Check for missing '()' if T is a function type?
5055
5056  // If we don't have a class type in C++, there's no way we can get an
5057  // expression of integral or enumeration type.
5058  const RecordType *RecordTy = T->getAs<RecordType>();
5059  if (!RecordTy || !getLangOpts().CPlusPlus) {
5060    if (!Diagnoser.Suppress)
5061      Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
5062    return Owned(From);
5063  }
5064
5065  // We must have a complete class type.
5066  struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5067    ICEConvertDiagnoser &Diagnoser;
5068    Expr *From;
5069
5070    TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5071      : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
5072
5073    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5074      Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5075    }
5076  } IncompleteDiagnoser(Diagnoser, From);
5077
5078  if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5079    return Owned(From);
5080
5081  // Look for a conversion to an integral or enumeration type.
5082  UnresolvedSet<4> ViableConversions;
5083  UnresolvedSet<4> ExplicitConversions;
5084  const UnresolvedSetImpl *Conversions
5085    = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5086
5087  bool HadMultipleCandidates = (Conversions->size() > 1);
5088
5089  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5090                                   E = Conversions->end();
5091       I != E;
5092       ++I) {
5093    if (CXXConversionDecl *Conversion
5094          = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5095      if (isIntegralOrEnumerationType(
5096            Conversion->getConversionType().getNonReferenceType(),
5097            AllowScopedEnumerations)) {
5098        if (Conversion->isExplicit())
5099          ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5100        else
5101          ViableConversions.addDecl(I.getDecl(), I.getAccess());
5102      }
5103    }
5104  }
5105
5106  switch (ViableConversions.size()) {
5107  case 0:
5108    if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
5109      DeclAccessPair Found = ExplicitConversions[0];
5110      CXXConversionDecl *Conversion
5111        = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5112
5113      // The user probably meant to invoke the given explicit
5114      // conversion; use it.
5115      QualType ConvTy
5116        = Conversion->getConversionType().getNonReferenceType();
5117      std::string TypeStr;
5118      ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
5119
5120      Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
5121        << FixItHint::CreateInsertion(From->getLocStart(),
5122                                      "static_cast<" + TypeStr + ">(")
5123        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5124                                      ")");
5125      Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
5126
5127      // If we aren't in a SFINAE context, build a call to the
5128      // explicit conversion function.
5129      if (isSFINAEContext())
5130        return ExprError();
5131
5132      CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5133      ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5134                                                 HadMultipleCandidates);
5135      if (Result.isInvalid())
5136        return ExprError();
5137      // Record usage of conversion in an implicit cast.
5138      From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5139                                      CK_UserDefinedConversion,
5140                                      Result.get(), 0,
5141                                      Result.get()->getValueKind());
5142    }
5143
5144    // We'll complain below about a non-integral condition type.
5145    break;
5146
5147  case 1: {
5148    // Apply this conversion.
5149    DeclAccessPair Found = ViableConversions[0];
5150    CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5151
5152    CXXConversionDecl *Conversion
5153      = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5154    QualType ConvTy
5155      = Conversion->getConversionType().getNonReferenceType();
5156    if (!Diagnoser.SuppressConversion) {
5157      if (isSFINAEContext())
5158        return ExprError();
5159
5160      Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5161        << From->getSourceRange();
5162    }
5163
5164    ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5165                                               HadMultipleCandidates);
5166    if (Result.isInvalid())
5167      return ExprError();
5168    // Record usage of conversion in an implicit cast.
5169    From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5170                                    CK_UserDefinedConversion,
5171                                    Result.get(), 0,
5172                                    Result.get()->getValueKind());
5173    break;
5174  }
5175
5176  default:
5177    if (Diagnoser.Suppress)
5178      return ExprError();
5179
5180    Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
5181    for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5182      CXXConversionDecl *Conv
5183        = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5184      QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5185      Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
5186    }
5187    return Owned(From);
5188  }
5189
5190  if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5191      !Diagnoser.Suppress) {
5192    Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5193      << From->getSourceRange();
5194  }
5195
5196  return DefaultLvalueConversion(From);
5197}
5198
5199/// AddOverloadCandidate - Adds the given function to the set of
5200/// candidate functions, using the given function call arguments.  If
5201/// @p SuppressUserConversions, then don't allow user-defined
5202/// conversions via constructors or conversion operators.
5203///
5204/// \param PartialOverloading true if we are performing "partial" overloading
5205/// based on an incomplete set of function arguments. This feature is used by
5206/// code completion.
5207void
5208Sema::AddOverloadCandidate(FunctionDecl *Function,
5209                           DeclAccessPair FoundDecl,
5210                           llvm::ArrayRef<Expr *> Args,
5211                           OverloadCandidateSet& CandidateSet,
5212                           bool SuppressUserConversions,
5213                           bool PartialOverloading,
5214                           bool AllowExplicit) {
5215  const FunctionProtoType* Proto
5216    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5217  assert(Proto && "Functions without a prototype cannot be overloaded");
5218  assert(!Function->getDescribedFunctionTemplate() &&
5219         "Use AddTemplateOverloadCandidate for function templates");
5220
5221  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5222    if (!isa<CXXConstructorDecl>(Method)) {
5223      // If we get here, it's because we're calling a member function
5224      // that is named without a member access expression (e.g.,
5225      // "this->f") that was either written explicitly or created
5226      // implicitly. This can happen with a qualified call to a member
5227      // function, e.g., X::f(). We use an empty type for the implied
5228      // object argument (C++ [over.call.func]p3), and the acting context
5229      // is irrelevant.
5230      AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5231                         QualType(), Expr::Classification::makeSimpleLValue(),
5232                         Args, CandidateSet, SuppressUserConversions);
5233      return;
5234    }
5235    // We treat a constructor like a non-member function, since its object
5236    // argument doesn't participate in overload resolution.
5237  }
5238
5239  if (!CandidateSet.isNewCandidate(Function))
5240    return;
5241
5242  // Overload resolution is always an unevaluated context.
5243  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5244
5245  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5246    // C++ [class.copy]p3:
5247    //   A member function template is never instantiated to perform the copy
5248    //   of a class object to an object of its class type.
5249    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5250    if (Args.size() == 1 &&
5251        Constructor->isSpecializationCopyingObject() &&
5252        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5253         IsDerivedFrom(Args[0]->getType(), ClassType)))
5254      return;
5255  }
5256
5257  // Add this candidate
5258  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5259  Candidate.FoundDecl = FoundDecl;
5260  Candidate.Function = Function;
5261  Candidate.Viable = true;
5262  Candidate.IsSurrogate = false;
5263  Candidate.IgnoreObjectArgument = false;
5264  Candidate.ExplicitCallArguments = Args.size();
5265
5266  unsigned NumArgsInProto = Proto->getNumArgs();
5267
5268  // (C++ 13.3.2p2): A candidate function having fewer than m
5269  // parameters is viable only if it has an ellipsis in its parameter
5270  // list (8.3.5).
5271  if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5272      !Proto->isVariadic()) {
5273    Candidate.Viable = false;
5274    Candidate.FailureKind = ovl_fail_too_many_arguments;
5275    return;
5276  }
5277
5278  // (C++ 13.3.2p2): A candidate function having more than m parameters
5279  // is viable only if the (m+1)st parameter has a default argument
5280  // (8.3.6). For the purposes of overload resolution, the
5281  // parameter list is truncated on the right, so that there are
5282  // exactly m parameters.
5283  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5284  if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5285    // Not enough arguments.
5286    Candidate.Viable = false;
5287    Candidate.FailureKind = ovl_fail_too_few_arguments;
5288    return;
5289  }
5290
5291  // (CUDA B.1): Check for invalid calls between targets.
5292  if (getLangOpts().CUDA)
5293    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5294      if (CheckCUDATarget(Caller, Function)) {
5295        Candidate.Viable = false;
5296        Candidate.FailureKind = ovl_fail_bad_target;
5297        return;
5298      }
5299
5300  // Determine the implicit conversion sequences for each of the
5301  // arguments.
5302  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5303    if (ArgIdx < NumArgsInProto) {
5304      // (C++ 13.3.2p3): for F to be a viable function, there shall
5305      // exist for each argument an implicit conversion sequence
5306      // (13.3.3.1) that converts that argument to the corresponding
5307      // parameter of F.
5308      QualType ParamType = Proto->getArgType(ArgIdx);
5309      Candidate.Conversions[ArgIdx]
5310        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5311                                SuppressUserConversions,
5312                                /*InOverloadResolution=*/true,
5313                                /*AllowObjCWritebackConversion=*/
5314                                  getLangOpts().ObjCAutoRefCount,
5315                                AllowExplicit);
5316      if (Candidate.Conversions[ArgIdx].isBad()) {
5317        Candidate.Viable = false;
5318        Candidate.FailureKind = ovl_fail_bad_conversion;
5319        break;
5320      }
5321    } else {
5322      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5323      // argument for which there is no corresponding parameter is
5324      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5325      Candidate.Conversions[ArgIdx].setEllipsis();
5326    }
5327  }
5328}
5329
5330/// \brief Add all of the function declarations in the given function set to
5331/// the overload canddiate set.
5332void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5333                                 llvm::ArrayRef<Expr *> Args,
5334                                 OverloadCandidateSet& CandidateSet,
5335                                 bool SuppressUserConversions,
5336                               TemplateArgumentListInfo *ExplicitTemplateArgs) {
5337  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5338    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5339    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5340      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5341        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5342                           cast<CXXMethodDecl>(FD)->getParent(),
5343                           Args[0]->getType(), Args[0]->Classify(Context),
5344                           Args.slice(1), CandidateSet,
5345                           SuppressUserConversions);
5346      else
5347        AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5348                             SuppressUserConversions);
5349    } else {
5350      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5351      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5352          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5353        AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5354                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5355                                   ExplicitTemplateArgs,
5356                                   Args[0]->getType(),
5357                                   Args[0]->Classify(Context), Args.slice(1),
5358                                   CandidateSet, SuppressUserConversions);
5359      else
5360        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5361                                     ExplicitTemplateArgs, Args,
5362                                     CandidateSet, SuppressUserConversions);
5363    }
5364  }
5365}
5366
5367/// AddMethodCandidate - Adds a named decl (which is some kind of
5368/// method) as a method candidate to the given overload set.
5369void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5370                              QualType ObjectType,
5371                              Expr::Classification ObjectClassification,
5372                              Expr **Args, unsigned NumArgs,
5373                              OverloadCandidateSet& CandidateSet,
5374                              bool SuppressUserConversions) {
5375  NamedDecl *Decl = FoundDecl.getDecl();
5376  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5377
5378  if (isa<UsingShadowDecl>(Decl))
5379    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5380
5381  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5382    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5383           "Expected a member function template");
5384    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5385                               /*ExplicitArgs*/ 0,
5386                               ObjectType, ObjectClassification,
5387                               llvm::makeArrayRef(Args, NumArgs), CandidateSet,
5388                               SuppressUserConversions);
5389  } else {
5390    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5391                       ObjectType, ObjectClassification,
5392                       llvm::makeArrayRef(Args, NumArgs),
5393                       CandidateSet, SuppressUserConversions);
5394  }
5395}
5396
5397/// AddMethodCandidate - Adds the given C++ member function to the set
5398/// of candidate functions, using the given function call arguments
5399/// and the object argument (@c Object). For example, in a call
5400/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5401/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5402/// allow user-defined conversions via constructors or conversion
5403/// operators.
5404void
5405Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5406                         CXXRecordDecl *ActingContext, QualType ObjectType,
5407                         Expr::Classification ObjectClassification,
5408                         llvm::ArrayRef<Expr *> Args,
5409                         OverloadCandidateSet& CandidateSet,
5410                         bool SuppressUserConversions) {
5411  const FunctionProtoType* Proto
5412    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5413  assert(Proto && "Methods without a prototype cannot be overloaded");
5414  assert(!isa<CXXConstructorDecl>(Method) &&
5415         "Use AddOverloadCandidate for constructors");
5416
5417  if (!CandidateSet.isNewCandidate(Method))
5418    return;
5419
5420  // Overload resolution is always an unevaluated context.
5421  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5422
5423  // Add this candidate
5424  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5425  Candidate.FoundDecl = FoundDecl;
5426  Candidate.Function = Method;
5427  Candidate.IsSurrogate = false;
5428  Candidate.IgnoreObjectArgument = false;
5429  Candidate.ExplicitCallArguments = Args.size();
5430
5431  unsigned NumArgsInProto = Proto->getNumArgs();
5432
5433  // (C++ 13.3.2p2): A candidate function having fewer than m
5434  // parameters is viable only if it has an ellipsis in its parameter
5435  // list (8.3.5).
5436  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5437    Candidate.Viable = false;
5438    Candidate.FailureKind = ovl_fail_too_many_arguments;
5439    return;
5440  }
5441
5442  // (C++ 13.3.2p2): A candidate function having more than m parameters
5443  // is viable only if the (m+1)st parameter has a default argument
5444  // (8.3.6). For the purposes of overload resolution, the
5445  // parameter list is truncated on the right, so that there are
5446  // exactly m parameters.
5447  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5448  if (Args.size() < MinRequiredArgs) {
5449    // Not enough arguments.
5450    Candidate.Viable = false;
5451    Candidate.FailureKind = ovl_fail_too_few_arguments;
5452    return;
5453  }
5454
5455  Candidate.Viable = true;
5456
5457  if (Method->isStatic() || ObjectType.isNull())
5458    // The implicit object argument is ignored.
5459    Candidate.IgnoreObjectArgument = true;
5460  else {
5461    // Determine the implicit conversion sequence for the object
5462    // parameter.
5463    Candidate.Conversions[0]
5464      = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5465                                        Method, ActingContext);
5466    if (Candidate.Conversions[0].isBad()) {
5467      Candidate.Viable = false;
5468      Candidate.FailureKind = ovl_fail_bad_conversion;
5469      return;
5470    }
5471  }
5472
5473  // Determine the implicit conversion sequences for each of the
5474  // arguments.
5475  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5476    if (ArgIdx < NumArgsInProto) {
5477      // (C++ 13.3.2p3): for F to be a viable function, there shall
5478      // exist for each argument an implicit conversion sequence
5479      // (13.3.3.1) that converts that argument to the corresponding
5480      // parameter of F.
5481      QualType ParamType = Proto->getArgType(ArgIdx);
5482      Candidate.Conversions[ArgIdx + 1]
5483        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5484                                SuppressUserConversions,
5485                                /*InOverloadResolution=*/true,
5486                                /*AllowObjCWritebackConversion=*/
5487                                  getLangOpts().ObjCAutoRefCount);
5488      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5489        Candidate.Viable = false;
5490        Candidate.FailureKind = ovl_fail_bad_conversion;
5491        break;
5492      }
5493    } else {
5494      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5495      // argument for which there is no corresponding parameter is
5496      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5497      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5498    }
5499  }
5500}
5501
5502/// \brief Add a C++ member function template as a candidate to the candidate
5503/// set, using template argument deduction to produce an appropriate member
5504/// function template specialization.
5505void
5506Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5507                                 DeclAccessPair FoundDecl,
5508                                 CXXRecordDecl *ActingContext,
5509                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5510                                 QualType ObjectType,
5511                                 Expr::Classification ObjectClassification,
5512                                 llvm::ArrayRef<Expr *> Args,
5513                                 OverloadCandidateSet& CandidateSet,
5514                                 bool SuppressUserConversions) {
5515  if (!CandidateSet.isNewCandidate(MethodTmpl))
5516    return;
5517
5518  // C++ [over.match.funcs]p7:
5519  //   In each case where a candidate is a function template, candidate
5520  //   function template specializations are generated using template argument
5521  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5522  //   candidate functions in the usual way.113) A given name can refer to one
5523  //   or more function templates and also to a set of overloaded non-template
5524  //   functions. In such a case, the candidate functions generated from each
5525  //   function template are combined with the set of non-template candidate
5526  //   functions.
5527  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5528  FunctionDecl *Specialization = 0;
5529  if (TemplateDeductionResult Result
5530      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5531                                Specialization, Info)) {
5532    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5533    Candidate.FoundDecl = FoundDecl;
5534    Candidate.Function = MethodTmpl->getTemplatedDecl();
5535    Candidate.Viable = false;
5536    Candidate.FailureKind = ovl_fail_bad_deduction;
5537    Candidate.IsSurrogate = false;
5538    Candidate.IgnoreObjectArgument = false;
5539    Candidate.ExplicitCallArguments = Args.size();
5540    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5541                                                          Info);
5542    return;
5543  }
5544
5545  // Add the function template specialization produced by template argument
5546  // deduction as a candidate.
5547  assert(Specialization && "Missing member function template specialization?");
5548  assert(isa<CXXMethodDecl>(Specialization) &&
5549         "Specialization is not a member function?");
5550  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5551                     ActingContext, ObjectType, ObjectClassification, Args,
5552                     CandidateSet, SuppressUserConversions);
5553}
5554
5555/// \brief Add a C++ function template specialization as a candidate
5556/// in the candidate set, using template argument deduction to produce
5557/// an appropriate function template specialization.
5558void
5559Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5560                                   DeclAccessPair FoundDecl,
5561                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5562                                   llvm::ArrayRef<Expr *> Args,
5563                                   OverloadCandidateSet& CandidateSet,
5564                                   bool SuppressUserConversions) {
5565  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5566    return;
5567
5568  // C++ [over.match.funcs]p7:
5569  //   In each case where a candidate is a function template, candidate
5570  //   function template specializations are generated using template argument
5571  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5572  //   candidate functions in the usual way.113) A given name can refer to one
5573  //   or more function templates and also to a set of overloaded non-template
5574  //   functions. In such a case, the candidate functions generated from each
5575  //   function template are combined with the set of non-template candidate
5576  //   functions.
5577  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5578  FunctionDecl *Specialization = 0;
5579  if (TemplateDeductionResult Result
5580        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5581                                  Specialization, Info)) {
5582    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5583    Candidate.FoundDecl = FoundDecl;
5584    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5585    Candidate.Viable = false;
5586    Candidate.FailureKind = ovl_fail_bad_deduction;
5587    Candidate.IsSurrogate = false;
5588    Candidate.IgnoreObjectArgument = false;
5589    Candidate.ExplicitCallArguments = Args.size();
5590    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5591                                                          Info);
5592    return;
5593  }
5594
5595  // Add the function template specialization produced by template argument
5596  // deduction as a candidate.
5597  assert(Specialization && "Missing function template specialization?");
5598  AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5599                       SuppressUserConversions);
5600}
5601
5602/// AddConversionCandidate - Add a C++ conversion function as a
5603/// candidate in the candidate set (C++ [over.match.conv],
5604/// C++ [over.match.copy]). From is the expression we're converting from,
5605/// and ToType is the type that we're eventually trying to convert to
5606/// (which may or may not be the same type as the type that the
5607/// conversion function produces).
5608void
5609Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5610                             DeclAccessPair FoundDecl,
5611                             CXXRecordDecl *ActingContext,
5612                             Expr *From, QualType ToType,
5613                             OverloadCandidateSet& CandidateSet) {
5614  assert(!Conversion->getDescribedFunctionTemplate() &&
5615         "Conversion function templates use AddTemplateConversionCandidate");
5616  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5617  if (!CandidateSet.isNewCandidate(Conversion))
5618    return;
5619
5620  // Overload resolution is always an unevaluated context.
5621  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5622
5623  // Add this candidate
5624  OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5625  Candidate.FoundDecl = FoundDecl;
5626  Candidate.Function = Conversion;
5627  Candidate.IsSurrogate = false;
5628  Candidate.IgnoreObjectArgument = false;
5629  Candidate.FinalConversion.setAsIdentityConversion();
5630  Candidate.FinalConversion.setFromType(ConvType);
5631  Candidate.FinalConversion.setAllToTypes(ToType);
5632  Candidate.Viable = true;
5633  Candidate.ExplicitCallArguments = 1;
5634
5635  // C++ [over.match.funcs]p4:
5636  //   For conversion functions, the function is considered to be a member of
5637  //   the class of the implicit implied object argument for the purpose of
5638  //   defining the type of the implicit object parameter.
5639  //
5640  // Determine the implicit conversion sequence for the implicit
5641  // object parameter.
5642  QualType ImplicitParamType = From->getType();
5643  if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5644    ImplicitParamType = FromPtrType->getPointeeType();
5645  CXXRecordDecl *ConversionContext
5646    = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5647
5648  Candidate.Conversions[0]
5649    = TryObjectArgumentInitialization(*this, From->getType(),
5650                                      From->Classify(Context),
5651                                      Conversion, ConversionContext);
5652
5653  if (Candidate.Conversions[0].isBad()) {
5654    Candidate.Viable = false;
5655    Candidate.FailureKind = ovl_fail_bad_conversion;
5656    return;
5657  }
5658
5659  // We won't go through a user-define type conversion function to convert a
5660  // derived to base as such conversions are given Conversion Rank. They only
5661  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5662  QualType FromCanon
5663    = Context.getCanonicalType(From->getType().getUnqualifiedType());
5664  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5665  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5666    Candidate.Viable = false;
5667    Candidate.FailureKind = ovl_fail_trivial_conversion;
5668    return;
5669  }
5670
5671  // To determine what the conversion from the result of calling the
5672  // conversion function to the type we're eventually trying to
5673  // convert to (ToType), we need to synthesize a call to the
5674  // conversion function and attempt copy initialization from it. This
5675  // makes sure that we get the right semantics with respect to
5676  // lvalues/rvalues and the type. Fortunately, we can allocate this
5677  // call on the stack and we don't need its arguments to be
5678  // well-formed.
5679  DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5680                            VK_LValue, From->getLocStart());
5681  ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5682                                Context.getPointerType(Conversion->getType()),
5683                                CK_FunctionToPointerDecay,
5684                                &ConversionRef, VK_RValue);
5685
5686  QualType ConversionType = Conversion->getConversionType();
5687  if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5688    Candidate.Viable = false;
5689    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5690    return;
5691  }
5692
5693  ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5694
5695  // Note that it is safe to allocate CallExpr on the stack here because
5696  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5697  // allocator).
5698  QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5699  CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
5700                From->getLocStart());
5701  ImplicitConversionSequence ICS =
5702    TryCopyInitialization(*this, &Call, ToType,
5703                          /*SuppressUserConversions=*/true,
5704                          /*InOverloadResolution=*/false,
5705                          /*AllowObjCWritebackConversion=*/false);
5706
5707  switch (ICS.getKind()) {
5708  case ImplicitConversionSequence::StandardConversion:
5709    Candidate.FinalConversion = ICS.Standard;
5710
5711    // C++ [over.ics.user]p3:
5712    //   If the user-defined conversion is specified by a specialization of a
5713    //   conversion function template, the second standard conversion sequence
5714    //   shall have exact match rank.
5715    if (Conversion->getPrimaryTemplate() &&
5716        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5717      Candidate.Viable = false;
5718      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5719    }
5720
5721    // C++0x [dcl.init.ref]p5:
5722    //    In the second case, if the reference is an rvalue reference and
5723    //    the second standard conversion sequence of the user-defined
5724    //    conversion sequence includes an lvalue-to-rvalue conversion, the
5725    //    program is ill-formed.
5726    if (ToType->isRValueReferenceType() &&
5727        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5728      Candidate.Viable = false;
5729      Candidate.FailureKind = ovl_fail_bad_final_conversion;
5730    }
5731    break;
5732
5733  case ImplicitConversionSequence::BadConversion:
5734    Candidate.Viable = false;
5735    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5736    break;
5737
5738  default:
5739    llvm_unreachable(
5740           "Can only end up with a standard conversion sequence or failure");
5741  }
5742}
5743
5744/// \brief Adds a conversion function template specialization
5745/// candidate to the overload set, using template argument deduction
5746/// to deduce the template arguments of the conversion function
5747/// template from the type that we are converting to (C++
5748/// [temp.deduct.conv]).
5749void
5750Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
5751                                     DeclAccessPair FoundDecl,
5752                                     CXXRecordDecl *ActingDC,
5753                                     Expr *From, QualType ToType,
5754                                     OverloadCandidateSet &CandidateSet) {
5755  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5756         "Only conversion function templates permitted here");
5757
5758  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5759    return;
5760
5761  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5762  CXXConversionDecl *Specialization = 0;
5763  if (TemplateDeductionResult Result
5764        = DeduceTemplateArguments(FunctionTemplate, ToType,
5765                                  Specialization, Info)) {
5766    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5767    Candidate.FoundDecl = FoundDecl;
5768    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5769    Candidate.Viable = false;
5770    Candidate.FailureKind = ovl_fail_bad_deduction;
5771    Candidate.IsSurrogate = false;
5772    Candidate.IgnoreObjectArgument = false;
5773    Candidate.ExplicitCallArguments = 1;
5774    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5775                                                          Info);
5776    return;
5777  }
5778
5779  // Add the conversion function template specialization produced by
5780  // template argument deduction as a candidate.
5781  assert(Specialization && "Missing function template specialization?");
5782  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
5783                         CandidateSet);
5784}
5785
5786/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5787/// converts the given @c Object to a function pointer via the
5788/// conversion function @c Conversion, and then attempts to call it
5789/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5790/// the type of function that we'll eventually be calling.
5791void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
5792                                 DeclAccessPair FoundDecl,
5793                                 CXXRecordDecl *ActingContext,
5794                                 const FunctionProtoType *Proto,
5795                                 Expr *Object,
5796                                 llvm::ArrayRef<Expr *> Args,
5797                                 OverloadCandidateSet& CandidateSet) {
5798  if (!CandidateSet.isNewCandidate(Conversion))
5799    return;
5800
5801  // Overload resolution is always an unevaluated context.
5802  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5803
5804  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5805  Candidate.FoundDecl = FoundDecl;
5806  Candidate.Function = 0;
5807  Candidate.Surrogate = Conversion;
5808  Candidate.Viable = true;
5809  Candidate.IsSurrogate = true;
5810  Candidate.IgnoreObjectArgument = false;
5811  Candidate.ExplicitCallArguments = Args.size();
5812
5813  // Determine the implicit conversion sequence for the implicit
5814  // object parameter.
5815  ImplicitConversionSequence ObjectInit
5816    = TryObjectArgumentInitialization(*this, Object->getType(),
5817                                      Object->Classify(Context),
5818                                      Conversion, ActingContext);
5819  if (ObjectInit.isBad()) {
5820    Candidate.Viable = false;
5821    Candidate.FailureKind = ovl_fail_bad_conversion;
5822    Candidate.Conversions[0] = ObjectInit;
5823    return;
5824  }
5825
5826  // The first conversion is actually a user-defined conversion whose
5827  // first conversion is ObjectInit's standard conversion (which is
5828  // effectively a reference binding). Record it as such.
5829  Candidate.Conversions[0].setUserDefined();
5830  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
5831  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
5832  Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
5833  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
5834  Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
5835  Candidate.Conversions[0].UserDefined.After
5836    = Candidate.Conversions[0].UserDefined.Before;
5837  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5838
5839  // Find the
5840  unsigned NumArgsInProto = Proto->getNumArgs();
5841
5842  // (C++ 13.3.2p2): A candidate function having fewer than m
5843  // parameters is viable only if it has an ellipsis in its parameter
5844  // list (8.3.5).
5845  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5846    Candidate.Viable = false;
5847    Candidate.FailureKind = ovl_fail_too_many_arguments;
5848    return;
5849  }
5850
5851  // Function types don't have any default arguments, so just check if
5852  // we have enough arguments.
5853  if (Args.size() < NumArgsInProto) {
5854    // Not enough arguments.
5855    Candidate.Viable = false;
5856    Candidate.FailureKind = ovl_fail_too_few_arguments;
5857    return;
5858  }
5859
5860  // Determine the implicit conversion sequences for each of the
5861  // arguments.
5862  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5863    if (ArgIdx < NumArgsInProto) {
5864      // (C++ 13.3.2p3): for F to be a viable function, there shall
5865      // exist for each argument an implicit conversion sequence
5866      // (13.3.3.1) that converts that argument to the corresponding
5867      // parameter of F.
5868      QualType ParamType = Proto->getArgType(ArgIdx);
5869      Candidate.Conversions[ArgIdx + 1]
5870        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5871                                /*SuppressUserConversions=*/false,
5872                                /*InOverloadResolution=*/false,
5873                                /*AllowObjCWritebackConversion=*/
5874                                  getLangOpts().ObjCAutoRefCount);
5875      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5876        Candidate.Viable = false;
5877        Candidate.FailureKind = ovl_fail_bad_conversion;
5878        break;
5879      }
5880    } else {
5881      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5882      // argument for which there is no corresponding parameter is
5883      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5884      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5885    }
5886  }
5887}
5888
5889/// \brief Add overload candidates for overloaded operators that are
5890/// member functions.
5891///
5892/// Add the overloaded operator candidates that are member functions
5893/// for the operator Op that was used in an operator expression such
5894/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5895/// CandidateSet will store the added overload candidates. (C++
5896/// [over.match.oper]).
5897void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5898                                       SourceLocation OpLoc,
5899                                       Expr **Args, unsigned NumArgs,
5900                                       OverloadCandidateSet& CandidateSet,
5901                                       SourceRange OpRange) {
5902  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5903
5904  // C++ [over.match.oper]p3:
5905  //   For a unary operator @ with an operand of a type whose
5906  //   cv-unqualified version is T1, and for a binary operator @ with
5907  //   a left operand of a type whose cv-unqualified version is T1 and
5908  //   a right operand of a type whose cv-unqualified version is T2,
5909  //   three sets of candidate functions, designated member
5910  //   candidates, non-member candidates and built-in candidates, are
5911  //   constructed as follows:
5912  QualType T1 = Args[0]->getType();
5913
5914  //     -- If T1 is a class type, the set of member candidates is the
5915  //        result of the qualified lookup of T1::operator@
5916  //        (13.3.1.1.1); otherwise, the set of member candidates is
5917  //        empty.
5918  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
5919    // Complete the type if it can be completed. Otherwise, we're done.
5920    if (RequireCompleteType(OpLoc, T1, 0))
5921      return;
5922
5923    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5924    LookupQualifiedName(Operators, T1Rec->getDecl());
5925    Operators.suppressDiagnostics();
5926
5927    for (LookupResult::iterator Oper = Operators.begin(),
5928                             OperEnd = Operators.end();
5929         Oper != OperEnd;
5930         ++Oper)
5931      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
5932                         Args[0]->Classify(Context), Args + 1, NumArgs - 1,
5933                         CandidateSet,
5934                         /* SuppressUserConversions = */ false);
5935  }
5936}
5937
5938/// AddBuiltinCandidate - Add a candidate for a built-in
5939/// operator. ResultTy and ParamTys are the result and parameter types
5940/// of the built-in candidate, respectively. Args and NumArgs are the
5941/// arguments being passed to the candidate. IsAssignmentOperator
5942/// should be true when this built-in candidate is an assignment
5943/// operator. NumContextualBoolArguments is the number of arguments
5944/// (at the beginning of the argument list) that will be contextually
5945/// converted to bool.
5946void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
5947                               Expr **Args, unsigned NumArgs,
5948                               OverloadCandidateSet& CandidateSet,
5949                               bool IsAssignmentOperator,
5950                               unsigned NumContextualBoolArguments) {
5951  // Overload resolution is always an unevaluated context.
5952  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5953
5954  // Add this candidate
5955  OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
5956  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
5957  Candidate.Function = 0;
5958  Candidate.IsSurrogate = false;
5959  Candidate.IgnoreObjectArgument = false;
5960  Candidate.BuiltinTypes.ResultTy = ResultTy;
5961  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5962    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5963
5964  // Determine the implicit conversion sequences for each of the
5965  // arguments.
5966  Candidate.Viable = true;
5967  Candidate.ExplicitCallArguments = NumArgs;
5968  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5969    // C++ [over.match.oper]p4:
5970    //   For the built-in assignment operators, conversions of the
5971    //   left operand are restricted as follows:
5972    //     -- no temporaries are introduced to hold the left operand, and
5973    //     -- no user-defined conversions are applied to the left
5974    //        operand to achieve a type match with the left-most
5975    //        parameter of a built-in candidate.
5976    //
5977    // We block these conversions by turning off user-defined
5978    // conversions, since that is the only way that initialization of
5979    // a reference to a non-class type can occur from something that
5980    // is not of the same type.
5981    if (ArgIdx < NumContextualBoolArguments) {
5982      assert(ParamTys[ArgIdx] == Context.BoolTy &&
5983             "Contextual conversion to bool requires bool type");
5984      Candidate.Conversions[ArgIdx]
5985        = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
5986    } else {
5987      Candidate.Conversions[ArgIdx]
5988        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
5989                                ArgIdx == 0 && IsAssignmentOperator,
5990                                /*InOverloadResolution=*/false,
5991                                /*AllowObjCWritebackConversion=*/
5992                                  getLangOpts().ObjCAutoRefCount);
5993    }
5994    if (Candidate.Conversions[ArgIdx].isBad()) {
5995      Candidate.Viable = false;
5996      Candidate.FailureKind = ovl_fail_bad_conversion;
5997      break;
5998    }
5999  }
6000}
6001
6002/// BuiltinCandidateTypeSet - A set of types that will be used for the
6003/// candidate operator functions for built-in operators (C++
6004/// [over.built]). The types are separated into pointer types and
6005/// enumeration types.
6006class BuiltinCandidateTypeSet  {
6007  /// TypeSet - A set of types.
6008  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6009
6010  /// PointerTypes - The set of pointer types that will be used in the
6011  /// built-in candidates.
6012  TypeSet PointerTypes;
6013
6014  /// MemberPointerTypes - The set of member pointer types that will be
6015  /// used in the built-in candidates.
6016  TypeSet MemberPointerTypes;
6017
6018  /// EnumerationTypes - The set of enumeration types that will be
6019  /// used in the built-in candidates.
6020  TypeSet EnumerationTypes;
6021
6022  /// \brief The set of vector types that will be used in the built-in
6023  /// candidates.
6024  TypeSet VectorTypes;
6025
6026  /// \brief A flag indicating non-record types are viable candidates
6027  bool HasNonRecordTypes;
6028
6029  /// \brief A flag indicating whether either arithmetic or enumeration types
6030  /// were present in the candidate set.
6031  bool HasArithmeticOrEnumeralTypes;
6032
6033  /// \brief A flag indicating whether the nullptr type was present in the
6034  /// candidate set.
6035  bool HasNullPtrType;
6036
6037  /// Sema - The semantic analysis instance where we are building the
6038  /// candidate type set.
6039  Sema &SemaRef;
6040
6041  /// Context - The AST context in which we will build the type sets.
6042  ASTContext &Context;
6043
6044  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6045                                               const Qualifiers &VisibleQuals);
6046  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6047
6048public:
6049  /// iterator - Iterates through the types that are part of the set.
6050  typedef TypeSet::iterator iterator;
6051
6052  BuiltinCandidateTypeSet(Sema &SemaRef)
6053    : HasNonRecordTypes(false),
6054      HasArithmeticOrEnumeralTypes(false),
6055      HasNullPtrType(false),
6056      SemaRef(SemaRef),
6057      Context(SemaRef.Context) { }
6058
6059  void AddTypesConvertedFrom(QualType Ty,
6060                             SourceLocation Loc,
6061                             bool AllowUserConversions,
6062                             bool AllowExplicitConversions,
6063                             const Qualifiers &VisibleTypeConversionsQuals);
6064
6065  /// pointer_begin - First pointer type found;
6066  iterator pointer_begin() { return PointerTypes.begin(); }
6067
6068  /// pointer_end - Past the last pointer type found;
6069  iterator pointer_end() { return PointerTypes.end(); }
6070
6071  /// member_pointer_begin - First member pointer type found;
6072  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6073
6074  /// member_pointer_end - Past the last member pointer type found;
6075  iterator member_pointer_end() { return MemberPointerTypes.end(); }
6076
6077  /// enumeration_begin - First enumeration type found;
6078  iterator enumeration_begin() { return EnumerationTypes.begin(); }
6079
6080  /// enumeration_end - Past the last enumeration type found;
6081  iterator enumeration_end() { return EnumerationTypes.end(); }
6082
6083  iterator vector_begin() { return VectorTypes.begin(); }
6084  iterator vector_end() { return VectorTypes.end(); }
6085
6086  bool hasNonRecordTypes() { return HasNonRecordTypes; }
6087  bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6088  bool hasNullPtrType() const { return HasNullPtrType; }
6089};
6090
6091/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6092/// the set of pointer types along with any more-qualified variants of
6093/// that type. For example, if @p Ty is "int const *", this routine
6094/// will add "int const *", "int const volatile *", "int const
6095/// restrict *", and "int const volatile restrict *" to the set of
6096/// pointer types. Returns true if the add of @p Ty itself succeeded,
6097/// false otherwise.
6098///
6099/// FIXME: what to do about extended qualifiers?
6100bool
6101BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6102                                             const Qualifiers &VisibleQuals) {
6103
6104  // Insert this type.
6105  if (!PointerTypes.insert(Ty))
6106    return false;
6107
6108  QualType PointeeTy;
6109  const PointerType *PointerTy = Ty->getAs<PointerType>();
6110  bool buildObjCPtr = false;
6111  if (!PointerTy) {
6112    const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6113    PointeeTy = PTy->getPointeeType();
6114    buildObjCPtr = true;
6115  } else {
6116    PointeeTy = PointerTy->getPointeeType();
6117  }
6118
6119  // Don't add qualified variants of arrays. For one, they're not allowed
6120  // (the qualifier would sink to the element type), and for another, the
6121  // only overload situation where it matters is subscript or pointer +- int,
6122  // and those shouldn't have qualifier variants anyway.
6123  if (PointeeTy->isArrayType())
6124    return true;
6125
6126  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6127  bool hasVolatile = VisibleQuals.hasVolatile();
6128  bool hasRestrict = VisibleQuals.hasRestrict();
6129
6130  // Iterate through all strict supersets of BaseCVR.
6131  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6132    if ((CVR | BaseCVR) != CVR) continue;
6133    // Skip over volatile if no volatile found anywhere in the types.
6134    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6135
6136    // Skip over restrict if no restrict found anywhere in the types, or if
6137    // the type cannot be restrict-qualified.
6138    if ((CVR & Qualifiers::Restrict) &&
6139        (!hasRestrict ||
6140         (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6141      continue;
6142
6143    // Build qualified pointee type.
6144    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6145
6146    // Build qualified pointer type.
6147    QualType QPointerTy;
6148    if (!buildObjCPtr)
6149      QPointerTy = Context.getPointerType(QPointeeTy);
6150    else
6151      QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6152
6153    // Insert qualified pointer type.
6154    PointerTypes.insert(QPointerTy);
6155  }
6156
6157  return true;
6158}
6159
6160/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6161/// to the set of pointer types along with any more-qualified variants of
6162/// that type. For example, if @p Ty is "int const *", this routine
6163/// will add "int const *", "int const volatile *", "int const
6164/// restrict *", and "int const volatile restrict *" to the set of
6165/// pointer types. Returns true if the add of @p Ty itself succeeded,
6166/// false otherwise.
6167///
6168/// FIXME: what to do about extended qualifiers?
6169bool
6170BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6171    QualType Ty) {
6172  // Insert this type.
6173  if (!MemberPointerTypes.insert(Ty))
6174    return false;
6175
6176  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6177  assert(PointerTy && "type was not a member pointer type!");
6178
6179  QualType PointeeTy = PointerTy->getPointeeType();
6180  // Don't add qualified variants of arrays. For one, they're not allowed
6181  // (the qualifier would sink to the element type), and for another, the
6182  // only overload situation where it matters is subscript or pointer +- int,
6183  // and those shouldn't have qualifier variants anyway.
6184  if (PointeeTy->isArrayType())
6185    return true;
6186  const Type *ClassTy = PointerTy->getClass();
6187
6188  // Iterate through all strict supersets of the pointee type's CVR
6189  // qualifiers.
6190  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6191  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6192    if ((CVR | BaseCVR) != CVR) continue;
6193
6194    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6195    MemberPointerTypes.insert(
6196      Context.getMemberPointerType(QPointeeTy, ClassTy));
6197  }
6198
6199  return true;
6200}
6201
6202/// AddTypesConvertedFrom - Add each of the types to which the type @p
6203/// Ty can be implicit converted to the given set of @p Types. We're
6204/// primarily interested in pointer types and enumeration types. We also
6205/// take member pointer types, for the conditional operator.
6206/// AllowUserConversions is true if we should look at the conversion
6207/// functions of a class type, and AllowExplicitConversions if we
6208/// should also include the explicit conversion functions of a class
6209/// type.
6210void
6211BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6212                                               SourceLocation Loc,
6213                                               bool AllowUserConversions,
6214                                               bool AllowExplicitConversions,
6215                                               const Qualifiers &VisibleQuals) {
6216  // Only deal with canonical types.
6217  Ty = Context.getCanonicalType(Ty);
6218
6219  // Look through reference types; they aren't part of the type of an
6220  // expression for the purposes of conversions.
6221  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6222    Ty = RefTy->getPointeeType();
6223
6224  // If we're dealing with an array type, decay to the pointer.
6225  if (Ty->isArrayType())
6226    Ty = SemaRef.Context.getArrayDecayedType(Ty);
6227
6228  // Otherwise, we don't care about qualifiers on the type.
6229  Ty = Ty.getLocalUnqualifiedType();
6230
6231  // Flag if we ever add a non-record type.
6232  const RecordType *TyRec = Ty->getAs<RecordType>();
6233  HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6234
6235  // Flag if we encounter an arithmetic type.
6236  HasArithmeticOrEnumeralTypes =
6237    HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6238
6239  if (Ty->isObjCIdType() || Ty->isObjCClassType())
6240    PointerTypes.insert(Ty);
6241  else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6242    // Insert our type, and its more-qualified variants, into the set
6243    // of types.
6244    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6245      return;
6246  } else if (Ty->isMemberPointerType()) {
6247    // Member pointers are far easier, since the pointee can't be converted.
6248    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6249      return;
6250  } else if (Ty->isEnumeralType()) {
6251    HasArithmeticOrEnumeralTypes = true;
6252    EnumerationTypes.insert(Ty);
6253  } else if (Ty->isVectorType()) {
6254    // We treat vector types as arithmetic types in many contexts as an
6255    // extension.
6256    HasArithmeticOrEnumeralTypes = true;
6257    VectorTypes.insert(Ty);
6258  } else if (Ty->isNullPtrType()) {
6259    HasNullPtrType = true;
6260  } else if (AllowUserConversions && TyRec) {
6261    // No conversion functions in incomplete types.
6262    if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6263      return;
6264
6265    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6266    const UnresolvedSetImpl *Conversions
6267      = ClassDecl->getVisibleConversionFunctions();
6268    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6269           E = Conversions->end(); I != E; ++I) {
6270      NamedDecl *D = I.getDecl();
6271      if (isa<UsingShadowDecl>(D))
6272        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6273
6274      // Skip conversion function templates; they don't tell us anything
6275      // about which builtin types we can convert to.
6276      if (isa<FunctionTemplateDecl>(D))
6277        continue;
6278
6279      CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6280      if (AllowExplicitConversions || !Conv->isExplicit()) {
6281        AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6282                              VisibleQuals);
6283      }
6284    }
6285  }
6286}
6287
6288/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6289/// the volatile- and non-volatile-qualified assignment operators for the
6290/// given type to the candidate set.
6291static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6292                                                   QualType T,
6293                                                   Expr **Args,
6294                                                   unsigned NumArgs,
6295                                    OverloadCandidateSet &CandidateSet) {
6296  QualType ParamTypes[2];
6297
6298  // T& operator=(T&, T)
6299  ParamTypes[0] = S.Context.getLValueReferenceType(T);
6300  ParamTypes[1] = T;
6301  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6302                        /*IsAssignmentOperator=*/true);
6303
6304  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6305    // volatile T& operator=(volatile T&, T)
6306    ParamTypes[0]
6307      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6308    ParamTypes[1] = T;
6309    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6310                          /*IsAssignmentOperator=*/true);
6311  }
6312}
6313
6314/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6315/// if any, found in visible type conversion functions found in ArgExpr's type.
6316static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6317    Qualifiers VRQuals;
6318    const RecordType *TyRec;
6319    if (const MemberPointerType *RHSMPType =
6320        ArgExpr->getType()->getAs<MemberPointerType>())
6321      TyRec = RHSMPType->getClass()->getAs<RecordType>();
6322    else
6323      TyRec = ArgExpr->getType()->getAs<RecordType>();
6324    if (!TyRec) {
6325      // Just to be safe, assume the worst case.
6326      VRQuals.addVolatile();
6327      VRQuals.addRestrict();
6328      return VRQuals;
6329    }
6330
6331    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6332    if (!ClassDecl->hasDefinition())
6333      return VRQuals;
6334
6335    const UnresolvedSetImpl *Conversions =
6336      ClassDecl->getVisibleConversionFunctions();
6337
6338    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6339           E = Conversions->end(); I != E; ++I) {
6340      NamedDecl *D = I.getDecl();
6341      if (isa<UsingShadowDecl>(D))
6342        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6343      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6344        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6345        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6346          CanTy = ResTypeRef->getPointeeType();
6347        // Need to go down the pointer/mempointer chain and add qualifiers
6348        // as see them.
6349        bool done = false;
6350        while (!done) {
6351          if (CanTy.isRestrictQualified())
6352            VRQuals.addRestrict();
6353          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6354            CanTy = ResTypePtr->getPointeeType();
6355          else if (const MemberPointerType *ResTypeMPtr =
6356                CanTy->getAs<MemberPointerType>())
6357            CanTy = ResTypeMPtr->getPointeeType();
6358          else
6359            done = true;
6360          if (CanTy.isVolatileQualified())
6361            VRQuals.addVolatile();
6362          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6363            return VRQuals;
6364        }
6365      }
6366    }
6367    return VRQuals;
6368}
6369
6370namespace {
6371
6372/// \brief Helper class to manage the addition of builtin operator overload
6373/// candidates. It provides shared state and utility methods used throughout
6374/// the process, as well as a helper method to add each group of builtin
6375/// operator overloads from the standard to a candidate set.
6376class BuiltinOperatorOverloadBuilder {
6377  // Common instance state available to all overload candidate addition methods.
6378  Sema &S;
6379  Expr **Args;
6380  unsigned NumArgs;
6381  Qualifiers VisibleTypeConversionsQuals;
6382  bool HasArithmeticOrEnumeralCandidateType;
6383  SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6384  OverloadCandidateSet &CandidateSet;
6385
6386  // Define some constants used to index and iterate over the arithemetic types
6387  // provided via the getArithmeticType() method below.
6388  // The "promoted arithmetic types" are the arithmetic
6389  // types are that preserved by promotion (C++ [over.built]p2).
6390  static const unsigned FirstIntegralType = 3;
6391  static const unsigned LastIntegralType = 20;
6392  static const unsigned FirstPromotedIntegralType = 3,
6393                        LastPromotedIntegralType = 11;
6394  static const unsigned FirstPromotedArithmeticType = 0,
6395                        LastPromotedArithmeticType = 11;
6396  static const unsigned NumArithmeticTypes = 20;
6397
6398  /// \brief Get the canonical type for a given arithmetic type index.
6399  CanQualType getArithmeticType(unsigned index) {
6400    assert(index < NumArithmeticTypes);
6401    static CanQualType ASTContext::* const
6402      ArithmeticTypes[NumArithmeticTypes] = {
6403      // Start of promoted types.
6404      &ASTContext::FloatTy,
6405      &ASTContext::DoubleTy,
6406      &ASTContext::LongDoubleTy,
6407
6408      // Start of integral types.
6409      &ASTContext::IntTy,
6410      &ASTContext::LongTy,
6411      &ASTContext::LongLongTy,
6412      &ASTContext::Int128Ty,
6413      &ASTContext::UnsignedIntTy,
6414      &ASTContext::UnsignedLongTy,
6415      &ASTContext::UnsignedLongLongTy,
6416      &ASTContext::UnsignedInt128Ty,
6417      // End of promoted types.
6418
6419      &ASTContext::BoolTy,
6420      &ASTContext::CharTy,
6421      &ASTContext::WCharTy,
6422      &ASTContext::Char16Ty,
6423      &ASTContext::Char32Ty,
6424      &ASTContext::SignedCharTy,
6425      &ASTContext::ShortTy,
6426      &ASTContext::UnsignedCharTy,
6427      &ASTContext::UnsignedShortTy,
6428      // End of integral types.
6429      // FIXME: What about complex? What about half?
6430    };
6431    return S.Context.*ArithmeticTypes[index];
6432  }
6433
6434  /// \brief Gets the canonical type resulting from the usual arithemetic
6435  /// converions for the given arithmetic types.
6436  CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6437    // Accelerator table for performing the usual arithmetic conversions.
6438    // The rules are basically:
6439    //   - if either is floating-point, use the wider floating-point
6440    //   - if same signedness, use the higher rank
6441    //   - if same size, use unsigned of the higher rank
6442    //   - use the larger type
6443    // These rules, together with the axiom that higher ranks are
6444    // never smaller, are sufficient to precompute all of these results
6445    // *except* when dealing with signed types of higher rank.
6446    // (we could precompute SLL x UI for all known platforms, but it's
6447    // better not to make any assumptions).
6448    // We assume that int128 has a higher rank than long long on all platforms.
6449    enum PromotedType {
6450            Dep=-1,
6451            Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6452    };
6453    static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6454                                        [LastPromotedArithmeticType] = {
6455/* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6456/* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6457/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6458/*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6459/*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6460/* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6461/*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6462/*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6463/*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6464/* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6465/*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6466    };
6467
6468    assert(L < LastPromotedArithmeticType);
6469    assert(R < LastPromotedArithmeticType);
6470    int Idx = ConversionsTable[L][R];
6471
6472    // Fast path: the table gives us a concrete answer.
6473    if (Idx != Dep) return getArithmeticType(Idx);
6474
6475    // Slow path: we need to compare widths.
6476    // An invariant is that the signed type has higher rank.
6477    CanQualType LT = getArithmeticType(L),
6478                RT = getArithmeticType(R);
6479    unsigned LW = S.Context.getIntWidth(LT),
6480             RW = S.Context.getIntWidth(RT);
6481
6482    // If they're different widths, use the signed type.
6483    if (LW > RW) return LT;
6484    else if (LW < RW) return RT;
6485
6486    // Otherwise, use the unsigned type of the signed type's rank.
6487    if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6488    assert(L == SLL || R == SLL);
6489    return S.Context.UnsignedLongLongTy;
6490  }
6491
6492  /// \brief Helper method to factor out the common pattern of adding overloads
6493  /// for '++' and '--' builtin operators.
6494  void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6495                                           bool HasVolatile,
6496                                           bool HasRestrict) {
6497    QualType ParamTypes[2] = {
6498      S.Context.getLValueReferenceType(CandidateTy),
6499      S.Context.IntTy
6500    };
6501
6502    // Non-volatile version.
6503    if (NumArgs == 1)
6504      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6505    else
6506      S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6507
6508    // Use a heuristic to reduce number of builtin candidates in the set:
6509    // add volatile version only if there are conversions to a volatile type.
6510    if (HasVolatile) {
6511      ParamTypes[0] =
6512        S.Context.getLValueReferenceType(
6513          S.Context.getVolatileType(CandidateTy));
6514      if (NumArgs == 1)
6515        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6516      else
6517        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6518    }
6519
6520    // Add restrict version only if there are conversions to a restrict type
6521    // and our candidate type is a non-restrict-qualified pointer.
6522    if (HasRestrict && CandidateTy->isAnyPointerType() &&
6523        !CandidateTy.isRestrictQualified()) {
6524      ParamTypes[0]
6525        = S.Context.getLValueReferenceType(
6526            S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6527      if (NumArgs == 1)
6528        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6529      else
6530        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6531
6532      if (HasVolatile) {
6533        ParamTypes[0]
6534          = S.Context.getLValueReferenceType(
6535              S.Context.getCVRQualifiedType(CandidateTy,
6536                                            (Qualifiers::Volatile |
6537                                             Qualifiers::Restrict)));
6538        if (NumArgs == 1)
6539          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6540                                CandidateSet);
6541        else
6542          S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6543      }
6544    }
6545
6546  }
6547
6548public:
6549  BuiltinOperatorOverloadBuilder(
6550    Sema &S, Expr **Args, unsigned NumArgs,
6551    Qualifiers VisibleTypeConversionsQuals,
6552    bool HasArithmeticOrEnumeralCandidateType,
6553    SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6554    OverloadCandidateSet &CandidateSet)
6555    : S(S), Args(Args), NumArgs(NumArgs),
6556      VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6557      HasArithmeticOrEnumeralCandidateType(
6558        HasArithmeticOrEnumeralCandidateType),
6559      CandidateTypes(CandidateTypes),
6560      CandidateSet(CandidateSet) {
6561    // Validate some of our static helper constants in debug builds.
6562    assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6563           "Invalid first promoted integral type");
6564    assert(getArithmeticType(LastPromotedIntegralType - 1)
6565             == S.Context.UnsignedInt128Ty &&
6566           "Invalid last promoted integral type");
6567    assert(getArithmeticType(FirstPromotedArithmeticType)
6568             == S.Context.FloatTy &&
6569           "Invalid first promoted arithmetic type");
6570    assert(getArithmeticType(LastPromotedArithmeticType - 1)
6571             == S.Context.UnsignedInt128Ty &&
6572           "Invalid last promoted arithmetic type");
6573  }
6574
6575  // C++ [over.built]p3:
6576  //
6577  //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6578  //   is either volatile or empty, there exist candidate operator
6579  //   functions of the form
6580  //
6581  //       VQ T&      operator++(VQ T&);
6582  //       T          operator++(VQ T&, int);
6583  //
6584  // C++ [over.built]p4:
6585  //
6586  //   For every pair (T, VQ), where T is an arithmetic type other
6587  //   than bool, and VQ is either volatile or empty, there exist
6588  //   candidate operator functions of the form
6589  //
6590  //       VQ T&      operator--(VQ T&);
6591  //       T          operator--(VQ T&, int);
6592  void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6593    if (!HasArithmeticOrEnumeralCandidateType)
6594      return;
6595
6596    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6597         Arith < NumArithmeticTypes; ++Arith) {
6598      addPlusPlusMinusMinusStyleOverloads(
6599        getArithmeticType(Arith),
6600        VisibleTypeConversionsQuals.hasVolatile(),
6601        VisibleTypeConversionsQuals.hasRestrict());
6602    }
6603  }
6604
6605  // C++ [over.built]p5:
6606  //
6607  //   For every pair (T, VQ), where T is a cv-qualified or
6608  //   cv-unqualified object type, and VQ is either volatile or
6609  //   empty, there exist candidate operator functions of the form
6610  //
6611  //       T*VQ&      operator++(T*VQ&);
6612  //       T*VQ&      operator--(T*VQ&);
6613  //       T*         operator++(T*VQ&, int);
6614  //       T*         operator--(T*VQ&, int);
6615  void addPlusPlusMinusMinusPointerOverloads() {
6616    for (BuiltinCandidateTypeSet::iterator
6617              Ptr = CandidateTypes[0].pointer_begin(),
6618           PtrEnd = CandidateTypes[0].pointer_end();
6619         Ptr != PtrEnd; ++Ptr) {
6620      // Skip pointer types that aren't pointers to object types.
6621      if (!(*Ptr)->getPointeeType()->isObjectType())
6622        continue;
6623
6624      addPlusPlusMinusMinusStyleOverloads(*Ptr,
6625        (!(*Ptr).isVolatileQualified() &&
6626         VisibleTypeConversionsQuals.hasVolatile()),
6627        (!(*Ptr).isRestrictQualified() &&
6628         VisibleTypeConversionsQuals.hasRestrict()));
6629    }
6630  }
6631
6632  // C++ [over.built]p6:
6633  //   For every cv-qualified or cv-unqualified object type T, there
6634  //   exist candidate operator functions of the form
6635  //
6636  //       T&         operator*(T*);
6637  //
6638  // C++ [over.built]p7:
6639  //   For every function type T that does not have cv-qualifiers or a
6640  //   ref-qualifier, there exist candidate operator functions of the form
6641  //       T&         operator*(T*);
6642  void addUnaryStarPointerOverloads() {
6643    for (BuiltinCandidateTypeSet::iterator
6644              Ptr = CandidateTypes[0].pointer_begin(),
6645           PtrEnd = CandidateTypes[0].pointer_end();
6646         Ptr != PtrEnd; ++Ptr) {
6647      QualType ParamTy = *Ptr;
6648      QualType PointeeTy = ParamTy->getPointeeType();
6649      if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6650        continue;
6651
6652      if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6653        if (Proto->getTypeQuals() || Proto->getRefQualifier())
6654          continue;
6655
6656      S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6657                            &ParamTy, Args, 1, CandidateSet);
6658    }
6659  }
6660
6661  // C++ [over.built]p9:
6662  //  For every promoted arithmetic type T, there exist candidate
6663  //  operator functions of the form
6664  //
6665  //       T         operator+(T);
6666  //       T         operator-(T);
6667  void addUnaryPlusOrMinusArithmeticOverloads() {
6668    if (!HasArithmeticOrEnumeralCandidateType)
6669      return;
6670
6671    for (unsigned Arith = FirstPromotedArithmeticType;
6672         Arith < LastPromotedArithmeticType; ++Arith) {
6673      QualType ArithTy = getArithmeticType(Arith);
6674      S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6675    }
6676
6677    // Extension: We also add these operators for vector types.
6678    for (BuiltinCandidateTypeSet::iterator
6679              Vec = CandidateTypes[0].vector_begin(),
6680           VecEnd = CandidateTypes[0].vector_end();
6681         Vec != VecEnd; ++Vec) {
6682      QualType VecTy = *Vec;
6683      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6684    }
6685  }
6686
6687  // C++ [over.built]p8:
6688  //   For every type T, there exist candidate operator functions of
6689  //   the form
6690  //
6691  //       T*         operator+(T*);
6692  void addUnaryPlusPointerOverloads() {
6693    for (BuiltinCandidateTypeSet::iterator
6694              Ptr = CandidateTypes[0].pointer_begin(),
6695           PtrEnd = CandidateTypes[0].pointer_end();
6696         Ptr != PtrEnd; ++Ptr) {
6697      QualType ParamTy = *Ptr;
6698      S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6699    }
6700  }
6701
6702  // C++ [over.built]p10:
6703  //   For every promoted integral type T, there exist candidate
6704  //   operator functions of the form
6705  //
6706  //        T         operator~(T);
6707  void addUnaryTildePromotedIntegralOverloads() {
6708    if (!HasArithmeticOrEnumeralCandidateType)
6709      return;
6710
6711    for (unsigned Int = FirstPromotedIntegralType;
6712         Int < LastPromotedIntegralType; ++Int) {
6713      QualType IntTy = getArithmeticType(Int);
6714      S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6715    }
6716
6717    // Extension: We also add this operator for vector types.
6718    for (BuiltinCandidateTypeSet::iterator
6719              Vec = CandidateTypes[0].vector_begin(),
6720           VecEnd = CandidateTypes[0].vector_end();
6721         Vec != VecEnd; ++Vec) {
6722      QualType VecTy = *Vec;
6723      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6724    }
6725  }
6726
6727  // C++ [over.match.oper]p16:
6728  //   For every pointer to member type T, there exist candidate operator
6729  //   functions of the form
6730  //
6731  //        bool operator==(T,T);
6732  //        bool operator!=(T,T);
6733  void addEqualEqualOrNotEqualMemberPointerOverloads() {
6734    /// Set of (canonical) types that we've already handled.
6735    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6736
6737    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6738      for (BuiltinCandidateTypeSet::iterator
6739                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6740             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6741           MemPtr != MemPtrEnd;
6742           ++MemPtr) {
6743        // Don't add the same builtin candidate twice.
6744        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6745          continue;
6746
6747        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6748        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6749                              CandidateSet);
6750      }
6751    }
6752  }
6753
6754  // C++ [over.built]p15:
6755  //
6756  //   For every T, where T is an enumeration type, a pointer type, or
6757  //   std::nullptr_t, there exist candidate operator functions of the form
6758  //
6759  //        bool       operator<(T, T);
6760  //        bool       operator>(T, T);
6761  //        bool       operator<=(T, T);
6762  //        bool       operator>=(T, T);
6763  //        bool       operator==(T, T);
6764  //        bool       operator!=(T, T);
6765  void addRelationalPointerOrEnumeralOverloads() {
6766    // C++ [over.built]p1:
6767    //   If there is a user-written candidate with the same name and parameter
6768    //   types as a built-in candidate operator function, the built-in operator
6769    //   function is hidden and is not included in the set of candidate
6770    //   functions.
6771    //
6772    // The text is actually in a note, but if we don't implement it then we end
6773    // up with ambiguities when the user provides an overloaded operator for
6774    // an enumeration type. Note that only enumeration types have this problem,
6775    // so we track which enumeration types we've seen operators for. Also, the
6776    // only other overloaded operator with enumeration argumenst, operator=,
6777    // cannot be overloaded for enumeration types, so this is the only place
6778    // where we must suppress candidates like this.
6779    llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6780      UserDefinedBinaryOperators;
6781
6782    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6783      if (CandidateTypes[ArgIdx].enumeration_begin() !=
6784          CandidateTypes[ArgIdx].enumeration_end()) {
6785        for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6786                                         CEnd = CandidateSet.end();
6787             C != CEnd; ++C) {
6788          if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6789            continue;
6790
6791          QualType FirstParamType =
6792            C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6793          QualType SecondParamType =
6794            C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6795
6796          // Skip if either parameter isn't of enumeral type.
6797          if (!FirstParamType->isEnumeralType() ||
6798              !SecondParamType->isEnumeralType())
6799            continue;
6800
6801          // Add this operator to the set of known user-defined operators.
6802          UserDefinedBinaryOperators.insert(
6803            std::make_pair(S.Context.getCanonicalType(FirstParamType),
6804                           S.Context.getCanonicalType(SecondParamType)));
6805        }
6806      }
6807    }
6808
6809    /// Set of (canonical) types that we've already handled.
6810    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6811
6812    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6813      for (BuiltinCandidateTypeSet::iterator
6814                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6815             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6816           Ptr != PtrEnd; ++Ptr) {
6817        // Don't add the same builtin candidate twice.
6818        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6819          continue;
6820
6821        QualType ParamTypes[2] = { *Ptr, *Ptr };
6822        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6823                              CandidateSet);
6824      }
6825      for (BuiltinCandidateTypeSet::iterator
6826                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6827             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6828           Enum != EnumEnd; ++Enum) {
6829        CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6830
6831        // Don't add the same builtin candidate twice, or if a user defined
6832        // candidate exists.
6833        if (!AddedTypes.insert(CanonType) ||
6834            UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6835                                                            CanonType)))
6836          continue;
6837
6838        QualType ParamTypes[2] = { *Enum, *Enum };
6839        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6840                              CandidateSet);
6841      }
6842
6843      if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6844        CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6845        if (AddedTypes.insert(NullPtrTy) &&
6846            !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6847                                                             NullPtrTy))) {
6848          QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6849          S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6850                                CandidateSet);
6851        }
6852      }
6853    }
6854  }
6855
6856  // C++ [over.built]p13:
6857  //
6858  //   For every cv-qualified or cv-unqualified object type T
6859  //   there exist candidate operator functions of the form
6860  //
6861  //      T*         operator+(T*, ptrdiff_t);
6862  //      T&         operator[](T*, ptrdiff_t);    [BELOW]
6863  //      T*         operator-(T*, ptrdiff_t);
6864  //      T*         operator+(ptrdiff_t, T*);
6865  //      T&         operator[](ptrdiff_t, T*);    [BELOW]
6866  //
6867  // C++ [over.built]p14:
6868  //
6869  //   For every T, where T is a pointer to object type, there
6870  //   exist candidate operator functions of the form
6871  //
6872  //      ptrdiff_t  operator-(T, T);
6873  void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6874    /// Set of (canonical) types that we've already handled.
6875    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6876
6877    for (int Arg = 0; Arg < 2; ++Arg) {
6878      QualType AsymetricParamTypes[2] = {
6879        S.Context.getPointerDiffType(),
6880        S.Context.getPointerDiffType(),
6881      };
6882      for (BuiltinCandidateTypeSet::iterator
6883                Ptr = CandidateTypes[Arg].pointer_begin(),
6884             PtrEnd = CandidateTypes[Arg].pointer_end();
6885           Ptr != PtrEnd; ++Ptr) {
6886        QualType PointeeTy = (*Ptr)->getPointeeType();
6887        if (!PointeeTy->isObjectType())
6888          continue;
6889
6890        AsymetricParamTypes[Arg] = *Ptr;
6891        if (Arg == 0 || Op == OO_Plus) {
6892          // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6893          // T* operator+(ptrdiff_t, T*);
6894          S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6895                                CandidateSet);
6896        }
6897        if (Op == OO_Minus) {
6898          // ptrdiff_t operator-(T, T);
6899          if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6900            continue;
6901
6902          QualType ParamTypes[2] = { *Ptr, *Ptr };
6903          S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6904                                Args, 2, CandidateSet);
6905        }
6906      }
6907    }
6908  }
6909
6910  // C++ [over.built]p12:
6911  //
6912  //   For every pair of promoted arithmetic types L and R, there
6913  //   exist candidate operator functions of the form
6914  //
6915  //        LR         operator*(L, R);
6916  //        LR         operator/(L, R);
6917  //        LR         operator+(L, R);
6918  //        LR         operator-(L, R);
6919  //        bool       operator<(L, R);
6920  //        bool       operator>(L, R);
6921  //        bool       operator<=(L, R);
6922  //        bool       operator>=(L, R);
6923  //        bool       operator==(L, R);
6924  //        bool       operator!=(L, R);
6925  //
6926  //   where LR is the result of the usual arithmetic conversions
6927  //   between types L and R.
6928  //
6929  // C++ [over.built]p24:
6930  //
6931  //   For every pair of promoted arithmetic types L and R, there exist
6932  //   candidate operator functions of the form
6933  //
6934  //        LR       operator?(bool, L, R);
6935  //
6936  //   where LR is the result of the usual arithmetic conversions
6937  //   between types L and R.
6938  // Our candidates ignore the first parameter.
6939  void addGenericBinaryArithmeticOverloads(bool isComparison) {
6940    if (!HasArithmeticOrEnumeralCandidateType)
6941      return;
6942
6943    for (unsigned Left = FirstPromotedArithmeticType;
6944         Left < LastPromotedArithmeticType; ++Left) {
6945      for (unsigned Right = FirstPromotedArithmeticType;
6946           Right < LastPromotedArithmeticType; ++Right) {
6947        QualType LandR[2] = { getArithmeticType(Left),
6948                              getArithmeticType(Right) };
6949        QualType Result =
6950          isComparison ? S.Context.BoolTy
6951                       : getUsualArithmeticConversions(Left, Right);
6952        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6953      }
6954    }
6955
6956    // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6957    // conditional operator for vector types.
6958    for (BuiltinCandidateTypeSet::iterator
6959              Vec1 = CandidateTypes[0].vector_begin(),
6960           Vec1End = CandidateTypes[0].vector_end();
6961         Vec1 != Vec1End; ++Vec1) {
6962      for (BuiltinCandidateTypeSet::iterator
6963                Vec2 = CandidateTypes[1].vector_begin(),
6964             Vec2End = CandidateTypes[1].vector_end();
6965           Vec2 != Vec2End; ++Vec2) {
6966        QualType LandR[2] = { *Vec1, *Vec2 };
6967        QualType Result = S.Context.BoolTy;
6968        if (!isComparison) {
6969          if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6970            Result = *Vec1;
6971          else
6972            Result = *Vec2;
6973        }
6974
6975        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6976      }
6977    }
6978  }
6979
6980  // C++ [over.built]p17:
6981  //
6982  //   For every pair of promoted integral types L and R, there
6983  //   exist candidate operator functions of the form
6984  //
6985  //      LR         operator%(L, R);
6986  //      LR         operator&(L, R);
6987  //      LR         operator^(L, R);
6988  //      LR         operator|(L, R);
6989  //      L          operator<<(L, R);
6990  //      L          operator>>(L, R);
6991  //
6992  //   where LR is the result of the usual arithmetic conversions
6993  //   between types L and R.
6994  void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
6995    if (!HasArithmeticOrEnumeralCandidateType)
6996      return;
6997
6998    for (unsigned Left = FirstPromotedIntegralType;
6999         Left < LastPromotedIntegralType; ++Left) {
7000      for (unsigned Right = FirstPromotedIntegralType;
7001           Right < LastPromotedIntegralType; ++Right) {
7002        QualType LandR[2] = { getArithmeticType(Left),
7003                              getArithmeticType(Right) };
7004        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7005            ? LandR[0]
7006            : getUsualArithmeticConversions(Left, Right);
7007        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7008      }
7009    }
7010  }
7011
7012  // C++ [over.built]p20:
7013  //
7014  //   For every pair (T, VQ), where T is an enumeration or
7015  //   pointer to member type and VQ is either volatile or
7016  //   empty, there exist candidate operator functions of the form
7017  //
7018  //        VQ T&      operator=(VQ T&, T);
7019  void addAssignmentMemberPointerOrEnumeralOverloads() {
7020    /// Set of (canonical) types that we've already handled.
7021    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7022
7023    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7024      for (BuiltinCandidateTypeSet::iterator
7025                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7026             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7027           Enum != EnumEnd; ++Enum) {
7028        if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7029          continue;
7030
7031        AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7032                                               CandidateSet);
7033      }
7034
7035      for (BuiltinCandidateTypeSet::iterator
7036                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7037             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7038           MemPtr != MemPtrEnd; ++MemPtr) {
7039        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7040          continue;
7041
7042        AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7043                                               CandidateSet);
7044      }
7045    }
7046  }
7047
7048  // C++ [over.built]p19:
7049  //
7050  //   For every pair (T, VQ), where T is any type and VQ is either
7051  //   volatile or empty, there exist candidate operator functions
7052  //   of the form
7053  //
7054  //        T*VQ&      operator=(T*VQ&, T*);
7055  //
7056  // C++ [over.built]p21:
7057  //
7058  //   For every pair (T, VQ), where T is a cv-qualified or
7059  //   cv-unqualified object type and VQ is either volatile or
7060  //   empty, there exist candidate operator functions of the form
7061  //
7062  //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7063  //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7064  void addAssignmentPointerOverloads(bool isEqualOp) {
7065    /// Set of (canonical) types that we've already handled.
7066    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7067
7068    for (BuiltinCandidateTypeSet::iterator
7069              Ptr = CandidateTypes[0].pointer_begin(),
7070           PtrEnd = CandidateTypes[0].pointer_end();
7071         Ptr != PtrEnd; ++Ptr) {
7072      // If this is operator=, keep track of the builtin candidates we added.
7073      if (isEqualOp)
7074        AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7075      else if (!(*Ptr)->getPointeeType()->isObjectType())
7076        continue;
7077
7078      // non-volatile version
7079      QualType ParamTypes[2] = {
7080        S.Context.getLValueReferenceType(*Ptr),
7081        isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7082      };
7083      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7084                            /*IsAssigmentOperator=*/ isEqualOp);
7085
7086      bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7087                          VisibleTypeConversionsQuals.hasVolatile();
7088      if (NeedVolatile) {
7089        // volatile version
7090        ParamTypes[0] =
7091          S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7092        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7093                              /*IsAssigmentOperator=*/isEqualOp);
7094      }
7095
7096      if (!(*Ptr).isRestrictQualified() &&
7097          VisibleTypeConversionsQuals.hasRestrict()) {
7098        // restrict version
7099        ParamTypes[0]
7100          = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7101        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7102                              /*IsAssigmentOperator=*/isEqualOp);
7103
7104        if (NeedVolatile) {
7105          // volatile restrict version
7106          ParamTypes[0]
7107            = S.Context.getLValueReferenceType(
7108                S.Context.getCVRQualifiedType(*Ptr,
7109                                              (Qualifiers::Volatile |
7110                                               Qualifiers::Restrict)));
7111          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7112                                CandidateSet,
7113                                /*IsAssigmentOperator=*/isEqualOp);
7114        }
7115      }
7116    }
7117
7118    if (isEqualOp) {
7119      for (BuiltinCandidateTypeSet::iterator
7120                Ptr = CandidateTypes[1].pointer_begin(),
7121             PtrEnd = CandidateTypes[1].pointer_end();
7122           Ptr != PtrEnd; ++Ptr) {
7123        // Make sure we don't add the same candidate twice.
7124        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7125          continue;
7126
7127        QualType ParamTypes[2] = {
7128          S.Context.getLValueReferenceType(*Ptr),
7129          *Ptr,
7130        };
7131
7132        // non-volatile version
7133        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7134                              /*IsAssigmentOperator=*/true);
7135
7136        bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7137                           VisibleTypeConversionsQuals.hasVolatile();
7138        if (NeedVolatile) {
7139          // volatile version
7140          ParamTypes[0] =
7141            S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7142          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7143                                CandidateSet, /*IsAssigmentOperator=*/true);
7144        }
7145
7146        if (!(*Ptr).isRestrictQualified() &&
7147            VisibleTypeConversionsQuals.hasRestrict()) {
7148          // restrict version
7149          ParamTypes[0]
7150            = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7151          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7152                                CandidateSet, /*IsAssigmentOperator=*/true);
7153
7154          if (NeedVolatile) {
7155            // volatile restrict version
7156            ParamTypes[0]
7157              = S.Context.getLValueReferenceType(
7158                  S.Context.getCVRQualifiedType(*Ptr,
7159                                                (Qualifiers::Volatile |
7160                                                 Qualifiers::Restrict)));
7161            S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7162                                  CandidateSet, /*IsAssigmentOperator=*/true);
7163
7164          }
7165        }
7166      }
7167    }
7168  }
7169
7170  // C++ [over.built]p18:
7171  //
7172  //   For every triple (L, VQ, R), where L is an arithmetic type,
7173  //   VQ is either volatile or empty, and R is a promoted
7174  //   arithmetic type, there exist candidate operator functions of
7175  //   the form
7176  //
7177  //        VQ L&      operator=(VQ L&, R);
7178  //        VQ L&      operator*=(VQ L&, R);
7179  //        VQ L&      operator/=(VQ L&, R);
7180  //        VQ L&      operator+=(VQ L&, R);
7181  //        VQ L&      operator-=(VQ L&, R);
7182  void addAssignmentArithmeticOverloads(bool isEqualOp) {
7183    if (!HasArithmeticOrEnumeralCandidateType)
7184      return;
7185
7186    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7187      for (unsigned Right = FirstPromotedArithmeticType;
7188           Right < LastPromotedArithmeticType; ++Right) {
7189        QualType ParamTypes[2];
7190        ParamTypes[1] = getArithmeticType(Right);
7191
7192        // Add this built-in operator as a candidate (VQ is empty).
7193        ParamTypes[0] =
7194          S.Context.getLValueReferenceType(getArithmeticType(Left));
7195        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7196                              /*IsAssigmentOperator=*/isEqualOp);
7197
7198        // Add this built-in operator as a candidate (VQ is 'volatile').
7199        if (VisibleTypeConversionsQuals.hasVolatile()) {
7200          ParamTypes[0] =
7201            S.Context.getVolatileType(getArithmeticType(Left));
7202          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7203          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7204                                CandidateSet,
7205                                /*IsAssigmentOperator=*/isEqualOp);
7206        }
7207      }
7208    }
7209
7210    // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7211    for (BuiltinCandidateTypeSet::iterator
7212              Vec1 = CandidateTypes[0].vector_begin(),
7213           Vec1End = CandidateTypes[0].vector_end();
7214         Vec1 != Vec1End; ++Vec1) {
7215      for (BuiltinCandidateTypeSet::iterator
7216                Vec2 = CandidateTypes[1].vector_begin(),
7217             Vec2End = CandidateTypes[1].vector_end();
7218           Vec2 != Vec2End; ++Vec2) {
7219        QualType ParamTypes[2];
7220        ParamTypes[1] = *Vec2;
7221        // Add this built-in operator as a candidate (VQ is empty).
7222        ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7223        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7224                              /*IsAssigmentOperator=*/isEqualOp);
7225
7226        // Add this built-in operator as a candidate (VQ is 'volatile').
7227        if (VisibleTypeConversionsQuals.hasVolatile()) {
7228          ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7229          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7230          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7231                                CandidateSet,
7232                                /*IsAssigmentOperator=*/isEqualOp);
7233        }
7234      }
7235    }
7236  }
7237
7238  // C++ [over.built]p22:
7239  //
7240  //   For every triple (L, VQ, R), where L is an integral type, VQ
7241  //   is either volatile or empty, and R is a promoted integral
7242  //   type, there exist candidate operator functions of the form
7243  //
7244  //        VQ L&       operator%=(VQ L&, R);
7245  //        VQ L&       operator<<=(VQ L&, R);
7246  //        VQ L&       operator>>=(VQ L&, R);
7247  //        VQ L&       operator&=(VQ L&, R);
7248  //        VQ L&       operator^=(VQ L&, R);
7249  //        VQ L&       operator|=(VQ L&, R);
7250  void addAssignmentIntegralOverloads() {
7251    if (!HasArithmeticOrEnumeralCandidateType)
7252      return;
7253
7254    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7255      for (unsigned Right = FirstPromotedIntegralType;
7256           Right < LastPromotedIntegralType; ++Right) {
7257        QualType ParamTypes[2];
7258        ParamTypes[1] = getArithmeticType(Right);
7259
7260        // Add this built-in operator as a candidate (VQ is empty).
7261        ParamTypes[0] =
7262          S.Context.getLValueReferenceType(getArithmeticType(Left));
7263        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7264        if (VisibleTypeConversionsQuals.hasVolatile()) {
7265          // Add this built-in operator as a candidate (VQ is 'volatile').
7266          ParamTypes[0] = getArithmeticType(Left);
7267          ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7268          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7269          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7270                                CandidateSet);
7271        }
7272      }
7273    }
7274  }
7275
7276  // C++ [over.operator]p23:
7277  //
7278  //   There also exist candidate operator functions of the form
7279  //
7280  //        bool        operator!(bool);
7281  //        bool        operator&&(bool, bool);
7282  //        bool        operator||(bool, bool);
7283  void addExclaimOverload() {
7284    QualType ParamTy = S.Context.BoolTy;
7285    S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7286                          /*IsAssignmentOperator=*/false,
7287                          /*NumContextualBoolArguments=*/1);
7288  }
7289  void addAmpAmpOrPipePipeOverload() {
7290    QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7291    S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7292                          /*IsAssignmentOperator=*/false,
7293                          /*NumContextualBoolArguments=*/2);
7294  }
7295
7296  // C++ [over.built]p13:
7297  //
7298  //   For every cv-qualified or cv-unqualified object type T there
7299  //   exist candidate operator functions of the form
7300  //
7301  //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7302  //        T&         operator[](T*, ptrdiff_t);
7303  //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7304  //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7305  //        T&         operator[](ptrdiff_t, T*);
7306  void addSubscriptOverloads() {
7307    for (BuiltinCandidateTypeSet::iterator
7308              Ptr = CandidateTypes[0].pointer_begin(),
7309           PtrEnd = CandidateTypes[0].pointer_end();
7310         Ptr != PtrEnd; ++Ptr) {
7311      QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7312      QualType PointeeType = (*Ptr)->getPointeeType();
7313      if (!PointeeType->isObjectType())
7314        continue;
7315
7316      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7317
7318      // T& operator[](T*, ptrdiff_t)
7319      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7320    }
7321
7322    for (BuiltinCandidateTypeSet::iterator
7323              Ptr = CandidateTypes[1].pointer_begin(),
7324           PtrEnd = CandidateTypes[1].pointer_end();
7325         Ptr != PtrEnd; ++Ptr) {
7326      QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7327      QualType PointeeType = (*Ptr)->getPointeeType();
7328      if (!PointeeType->isObjectType())
7329        continue;
7330
7331      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7332
7333      // T& operator[](ptrdiff_t, T*)
7334      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7335    }
7336  }
7337
7338  // C++ [over.built]p11:
7339  //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7340  //    C1 is the same type as C2 or is a derived class of C2, T is an object
7341  //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7342  //    there exist candidate operator functions of the form
7343  //
7344  //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7345  //
7346  //    where CV12 is the union of CV1 and CV2.
7347  void addArrowStarOverloads() {
7348    for (BuiltinCandidateTypeSet::iterator
7349             Ptr = CandidateTypes[0].pointer_begin(),
7350           PtrEnd = CandidateTypes[0].pointer_end();
7351         Ptr != PtrEnd; ++Ptr) {
7352      QualType C1Ty = (*Ptr);
7353      QualType C1;
7354      QualifierCollector Q1;
7355      C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7356      if (!isa<RecordType>(C1))
7357        continue;
7358      // heuristic to reduce number of builtin candidates in the set.
7359      // Add volatile/restrict version only if there are conversions to a
7360      // volatile/restrict type.
7361      if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7362        continue;
7363      if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7364        continue;
7365      for (BuiltinCandidateTypeSet::iterator
7366                MemPtr = CandidateTypes[1].member_pointer_begin(),
7367             MemPtrEnd = CandidateTypes[1].member_pointer_end();
7368           MemPtr != MemPtrEnd; ++MemPtr) {
7369        const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7370        QualType C2 = QualType(mptr->getClass(), 0);
7371        C2 = C2.getUnqualifiedType();
7372        if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7373          break;
7374        QualType ParamTypes[2] = { *Ptr, *MemPtr };
7375        // build CV12 T&
7376        QualType T = mptr->getPointeeType();
7377        if (!VisibleTypeConversionsQuals.hasVolatile() &&
7378            T.isVolatileQualified())
7379          continue;
7380        if (!VisibleTypeConversionsQuals.hasRestrict() &&
7381            T.isRestrictQualified())
7382          continue;
7383        T = Q1.apply(S.Context, T);
7384        QualType ResultTy = S.Context.getLValueReferenceType(T);
7385        S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7386      }
7387    }
7388  }
7389
7390  // Note that we don't consider the first argument, since it has been
7391  // contextually converted to bool long ago. The candidates below are
7392  // therefore added as binary.
7393  //
7394  // C++ [over.built]p25:
7395  //   For every type T, where T is a pointer, pointer-to-member, or scoped
7396  //   enumeration type, there exist candidate operator functions of the form
7397  //
7398  //        T        operator?(bool, T, T);
7399  //
7400  void addConditionalOperatorOverloads() {
7401    /// Set of (canonical) types that we've already handled.
7402    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7403
7404    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7405      for (BuiltinCandidateTypeSet::iterator
7406                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7407             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7408           Ptr != PtrEnd; ++Ptr) {
7409        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7410          continue;
7411
7412        QualType ParamTypes[2] = { *Ptr, *Ptr };
7413        S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7414      }
7415
7416      for (BuiltinCandidateTypeSet::iterator
7417                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7418             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7419           MemPtr != MemPtrEnd; ++MemPtr) {
7420        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7421          continue;
7422
7423        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7424        S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7425      }
7426
7427      if (S.getLangOpts().CPlusPlus0x) {
7428        for (BuiltinCandidateTypeSet::iterator
7429                  Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7430               EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7431             Enum != EnumEnd; ++Enum) {
7432          if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7433            continue;
7434
7435          if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7436            continue;
7437
7438          QualType ParamTypes[2] = { *Enum, *Enum };
7439          S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7440        }
7441      }
7442    }
7443  }
7444};
7445
7446} // end anonymous namespace
7447
7448/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7449/// operator overloads to the candidate set (C++ [over.built]), based
7450/// on the operator @p Op and the arguments given. For example, if the
7451/// operator is a binary '+', this routine might add "int
7452/// operator+(int, int)" to cover integer addition.
7453void
7454Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7455                                   SourceLocation OpLoc,
7456                                   Expr **Args, unsigned NumArgs,
7457                                   OverloadCandidateSet& CandidateSet) {
7458  // Find all of the types that the arguments can convert to, but only
7459  // if the operator we're looking at has built-in operator candidates
7460  // that make use of these types. Also record whether we encounter non-record
7461  // candidate types or either arithmetic or enumeral candidate types.
7462  Qualifiers VisibleTypeConversionsQuals;
7463  VisibleTypeConversionsQuals.addConst();
7464  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7465    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7466
7467  bool HasNonRecordCandidateType = false;
7468  bool HasArithmeticOrEnumeralCandidateType = false;
7469  SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7470  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7471    CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7472    CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7473                                                 OpLoc,
7474                                                 true,
7475                                                 (Op == OO_Exclaim ||
7476                                                  Op == OO_AmpAmp ||
7477                                                  Op == OO_PipePipe),
7478                                                 VisibleTypeConversionsQuals);
7479    HasNonRecordCandidateType = HasNonRecordCandidateType ||
7480        CandidateTypes[ArgIdx].hasNonRecordTypes();
7481    HasArithmeticOrEnumeralCandidateType =
7482        HasArithmeticOrEnumeralCandidateType ||
7483        CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7484  }
7485
7486  // Exit early when no non-record types have been added to the candidate set
7487  // for any of the arguments to the operator.
7488  //
7489  // We can't exit early for !, ||, or &&, since there we have always have
7490  // 'bool' overloads.
7491  if (!HasNonRecordCandidateType &&
7492      !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7493    return;
7494
7495  // Setup an object to manage the common state for building overloads.
7496  BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7497                                           VisibleTypeConversionsQuals,
7498                                           HasArithmeticOrEnumeralCandidateType,
7499                                           CandidateTypes, CandidateSet);
7500
7501  // Dispatch over the operation to add in only those overloads which apply.
7502  switch (Op) {
7503  case OO_None:
7504  case NUM_OVERLOADED_OPERATORS:
7505    llvm_unreachable("Expected an overloaded operator");
7506
7507  case OO_New:
7508  case OO_Delete:
7509  case OO_Array_New:
7510  case OO_Array_Delete:
7511  case OO_Call:
7512    llvm_unreachable(
7513                    "Special operators don't use AddBuiltinOperatorCandidates");
7514
7515  case OO_Comma:
7516  case OO_Arrow:
7517    // C++ [over.match.oper]p3:
7518    //   -- For the operator ',', the unary operator '&', or the
7519    //      operator '->', the built-in candidates set is empty.
7520    break;
7521
7522  case OO_Plus: // '+' is either unary or binary
7523    if (NumArgs == 1)
7524      OpBuilder.addUnaryPlusPointerOverloads();
7525    // Fall through.
7526
7527  case OO_Minus: // '-' is either unary or binary
7528    if (NumArgs == 1) {
7529      OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7530    } else {
7531      OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7532      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7533    }
7534    break;
7535
7536  case OO_Star: // '*' is either unary or binary
7537    if (NumArgs == 1)
7538      OpBuilder.addUnaryStarPointerOverloads();
7539    else
7540      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7541    break;
7542
7543  case OO_Slash:
7544    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7545    break;
7546
7547  case OO_PlusPlus:
7548  case OO_MinusMinus:
7549    OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7550    OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7551    break;
7552
7553  case OO_EqualEqual:
7554  case OO_ExclaimEqual:
7555    OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7556    // Fall through.
7557
7558  case OO_Less:
7559  case OO_Greater:
7560  case OO_LessEqual:
7561  case OO_GreaterEqual:
7562    OpBuilder.addRelationalPointerOrEnumeralOverloads();
7563    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7564    break;
7565
7566  case OO_Percent:
7567  case OO_Caret:
7568  case OO_Pipe:
7569  case OO_LessLess:
7570  case OO_GreaterGreater:
7571    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7572    break;
7573
7574  case OO_Amp: // '&' is either unary or binary
7575    if (NumArgs == 1)
7576      // C++ [over.match.oper]p3:
7577      //   -- For the operator ',', the unary operator '&', or the
7578      //      operator '->', the built-in candidates set is empty.
7579      break;
7580
7581    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7582    break;
7583
7584  case OO_Tilde:
7585    OpBuilder.addUnaryTildePromotedIntegralOverloads();
7586    break;
7587
7588  case OO_Equal:
7589    OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7590    // Fall through.
7591
7592  case OO_PlusEqual:
7593  case OO_MinusEqual:
7594    OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7595    // Fall through.
7596
7597  case OO_StarEqual:
7598  case OO_SlashEqual:
7599    OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7600    break;
7601
7602  case OO_PercentEqual:
7603  case OO_LessLessEqual:
7604  case OO_GreaterGreaterEqual:
7605  case OO_AmpEqual:
7606  case OO_CaretEqual:
7607  case OO_PipeEqual:
7608    OpBuilder.addAssignmentIntegralOverloads();
7609    break;
7610
7611  case OO_Exclaim:
7612    OpBuilder.addExclaimOverload();
7613    break;
7614
7615  case OO_AmpAmp:
7616  case OO_PipePipe:
7617    OpBuilder.addAmpAmpOrPipePipeOverload();
7618    break;
7619
7620  case OO_Subscript:
7621    OpBuilder.addSubscriptOverloads();
7622    break;
7623
7624  case OO_ArrowStar:
7625    OpBuilder.addArrowStarOverloads();
7626    break;
7627
7628  case OO_Conditional:
7629    OpBuilder.addConditionalOperatorOverloads();
7630    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7631    break;
7632  }
7633}
7634
7635/// \brief Add function candidates found via argument-dependent lookup
7636/// to the set of overloading candidates.
7637///
7638/// This routine performs argument-dependent name lookup based on the
7639/// given function name (which may also be an operator name) and adds
7640/// all of the overload candidates found by ADL to the overload
7641/// candidate set (C++ [basic.lookup.argdep]).
7642void
7643Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7644                                           bool Operator, SourceLocation Loc,
7645                                           llvm::ArrayRef<Expr *> Args,
7646                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
7647                                           OverloadCandidateSet& CandidateSet,
7648                                           bool PartialOverloading,
7649                                           bool StdNamespaceIsAssociated) {
7650  ADLResult Fns;
7651
7652  // FIXME: This approach for uniquing ADL results (and removing
7653  // redundant candidates from the set) relies on pointer-equality,
7654  // which means we need to key off the canonical decl.  However,
7655  // always going back to the canonical decl might not get us the
7656  // right set of default arguments.  What default arguments are
7657  // we supposed to consider on ADL candidates, anyway?
7658
7659  // FIXME: Pass in the explicit template arguments?
7660  ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
7661                          StdNamespaceIsAssociated);
7662
7663  // Erase all of the candidates we already knew about.
7664  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7665                                   CandEnd = CandidateSet.end();
7666       Cand != CandEnd; ++Cand)
7667    if (Cand->Function) {
7668      Fns.erase(Cand->Function);
7669      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7670        Fns.erase(FunTmpl);
7671    }
7672
7673  // For each of the ADL candidates we found, add it to the overload
7674  // set.
7675  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7676    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7677    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7678      if (ExplicitTemplateArgs)
7679        continue;
7680
7681      AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7682                           PartialOverloading);
7683    } else
7684      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7685                                   FoundDecl, ExplicitTemplateArgs,
7686                                   Args, CandidateSet);
7687  }
7688}
7689
7690/// isBetterOverloadCandidate - Determines whether the first overload
7691/// candidate is a better candidate than the second (C++ 13.3.3p1).
7692bool
7693isBetterOverloadCandidate(Sema &S,
7694                          const OverloadCandidate &Cand1,
7695                          const OverloadCandidate &Cand2,
7696                          SourceLocation Loc,
7697                          bool UserDefinedConversion) {
7698  // Define viable functions to be better candidates than non-viable
7699  // functions.
7700  if (!Cand2.Viable)
7701    return Cand1.Viable;
7702  else if (!Cand1.Viable)
7703    return false;
7704
7705  // C++ [over.match.best]p1:
7706  //
7707  //   -- if F is a static member function, ICS1(F) is defined such
7708  //      that ICS1(F) is neither better nor worse than ICS1(G) for
7709  //      any function G, and, symmetrically, ICS1(G) is neither
7710  //      better nor worse than ICS1(F).
7711  unsigned StartArg = 0;
7712  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7713    StartArg = 1;
7714
7715  // C++ [over.match.best]p1:
7716  //   A viable function F1 is defined to be a better function than another
7717  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
7718  //   conversion sequence than ICSi(F2), and then...
7719  unsigned NumArgs = Cand1.NumConversions;
7720  assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7721  bool HasBetterConversion = false;
7722  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7723    switch (CompareImplicitConversionSequences(S,
7724                                               Cand1.Conversions[ArgIdx],
7725                                               Cand2.Conversions[ArgIdx])) {
7726    case ImplicitConversionSequence::Better:
7727      // Cand1 has a better conversion sequence.
7728      HasBetterConversion = true;
7729      break;
7730
7731    case ImplicitConversionSequence::Worse:
7732      // Cand1 can't be better than Cand2.
7733      return false;
7734
7735    case ImplicitConversionSequence::Indistinguishable:
7736      // Do nothing.
7737      break;
7738    }
7739  }
7740
7741  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
7742  //       ICSj(F2), or, if not that,
7743  if (HasBetterConversion)
7744    return true;
7745
7746  //     - F1 is a non-template function and F2 is a function template
7747  //       specialization, or, if not that,
7748  if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
7749      Cand2.Function && Cand2.Function->getPrimaryTemplate())
7750    return true;
7751
7752  //   -- F1 and F2 are function template specializations, and the function
7753  //      template for F1 is more specialized than the template for F2
7754  //      according to the partial ordering rules described in 14.5.5.2, or,
7755  //      if not that,
7756  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
7757      Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
7758    if (FunctionTemplateDecl *BetterTemplate
7759          = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7760                                         Cand2.Function->getPrimaryTemplate(),
7761                                         Loc,
7762                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
7763                                                             : TPOC_Call,
7764                                         Cand1.ExplicitCallArguments))
7765      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
7766  }
7767
7768  //   -- the context is an initialization by user-defined conversion
7769  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
7770  //      from the return type of F1 to the destination type (i.e.,
7771  //      the type of the entity being initialized) is a better
7772  //      conversion sequence than the standard conversion sequence
7773  //      from the return type of F2 to the destination type.
7774  if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
7775      isa<CXXConversionDecl>(Cand1.Function) &&
7776      isa<CXXConversionDecl>(Cand2.Function)) {
7777    // First check whether we prefer one of the conversion functions over the
7778    // other. This only distinguishes the results in non-standard, extension
7779    // cases such as the conversion from a lambda closure type to a function
7780    // pointer or block.
7781    ImplicitConversionSequence::CompareKind FuncResult
7782      = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7783    if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7784      return FuncResult;
7785
7786    switch (CompareStandardConversionSequences(S,
7787                                               Cand1.FinalConversion,
7788                                               Cand2.FinalConversion)) {
7789    case ImplicitConversionSequence::Better:
7790      // Cand1 has a better conversion sequence.
7791      return true;
7792
7793    case ImplicitConversionSequence::Worse:
7794      // Cand1 can't be better than Cand2.
7795      return false;
7796
7797    case ImplicitConversionSequence::Indistinguishable:
7798      // Do nothing
7799      break;
7800    }
7801  }
7802
7803  return false;
7804}
7805
7806/// \brief Computes the best viable function (C++ 13.3.3)
7807/// within an overload candidate set.
7808///
7809/// \param Loc The location of the function name (or operator symbol) for
7810/// which overload resolution occurs.
7811///
7812/// \param Best If overload resolution was successful or found a deleted
7813/// function, \p Best points to the candidate function found.
7814///
7815/// \returns The result of overload resolution.
7816OverloadingResult
7817OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
7818                                         iterator &Best,
7819                                         bool UserDefinedConversion) {
7820  // Find the best viable function.
7821  Best = end();
7822  for (iterator Cand = begin(); Cand != end(); ++Cand) {
7823    if (Cand->Viable)
7824      if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
7825                                                     UserDefinedConversion))
7826        Best = Cand;
7827  }
7828
7829  // If we didn't find any viable functions, abort.
7830  if (Best == end())
7831    return OR_No_Viable_Function;
7832
7833  // Make sure that this function is better than every other viable
7834  // function. If not, we have an ambiguity.
7835  for (iterator Cand = begin(); Cand != end(); ++Cand) {
7836    if (Cand->Viable &&
7837        Cand != Best &&
7838        !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
7839                                   UserDefinedConversion)) {
7840      Best = end();
7841      return OR_Ambiguous;
7842    }
7843  }
7844
7845  // Best is the best viable function.
7846  if (Best->Function &&
7847      (Best->Function->isDeleted() ||
7848       S.isFunctionConsideredUnavailable(Best->Function)))
7849    return OR_Deleted;
7850
7851  return OR_Success;
7852}
7853
7854namespace {
7855
7856enum OverloadCandidateKind {
7857  oc_function,
7858  oc_method,
7859  oc_constructor,
7860  oc_function_template,
7861  oc_method_template,
7862  oc_constructor_template,
7863  oc_implicit_default_constructor,
7864  oc_implicit_copy_constructor,
7865  oc_implicit_move_constructor,
7866  oc_implicit_copy_assignment,
7867  oc_implicit_move_assignment,
7868  oc_implicit_inherited_constructor
7869};
7870
7871OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7872                                                FunctionDecl *Fn,
7873                                                std::string &Description) {
7874  bool isTemplate = false;
7875
7876  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7877    isTemplate = true;
7878    Description = S.getTemplateArgumentBindingsText(
7879      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7880  }
7881
7882  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
7883    if (!Ctor->isImplicit())
7884      return isTemplate ? oc_constructor_template : oc_constructor;
7885
7886    if (Ctor->getInheritedConstructor())
7887      return oc_implicit_inherited_constructor;
7888
7889    if (Ctor->isDefaultConstructor())
7890      return oc_implicit_default_constructor;
7891
7892    if (Ctor->isMoveConstructor())
7893      return oc_implicit_move_constructor;
7894
7895    assert(Ctor->isCopyConstructor() &&
7896           "unexpected sort of implicit constructor");
7897    return oc_implicit_copy_constructor;
7898  }
7899
7900  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7901    // This actually gets spelled 'candidate function' for now, but
7902    // it doesn't hurt to split it out.
7903    if (!Meth->isImplicit())
7904      return isTemplate ? oc_method_template : oc_method;
7905
7906    if (Meth->isMoveAssignmentOperator())
7907      return oc_implicit_move_assignment;
7908
7909    if (Meth->isCopyAssignmentOperator())
7910      return oc_implicit_copy_assignment;
7911
7912    assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7913    return oc_method;
7914  }
7915
7916  return isTemplate ? oc_function_template : oc_function;
7917}
7918
7919void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7920  const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7921  if (!Ctor) return;
7922
7923  Ctor = Ctor->getInheritedConstructor();
7924  if (!Ctor) return;
7925
7926  S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7927}
7928
7929} // end anonymous namespace
7930
7931// Notes the location of an overload candidate.
7932void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
7933  std::string FnDesc;
7934  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
7935  PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7936                             << (unsigned) K << FnDesc;
7937  HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7938  Diag(Fn->getLocation(), PD);
7939  MaybeEmitInheritedConstructorNote(*this, Fn);
7940}
7941
7942//Notes the location of all overload candidates designated through
7943// OverloadedExpr
7944void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
7945  assert(OverloadedExpr->getType() == Context.OverloadTy);
7946
7947  OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7948  OverloadExpr *OvlExpr = Ovl.Expression;
7949
7950  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7951                            IEnd = OvlExpr->decls_end();
7952       I != IEnd; ++I) {
7953    if (FunctionTemplateDecl *FunTmpl =
7954                dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
7955      NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
7956    } else if (FunctionDecl *Fun
7957                      = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
7958      NoteOverloadCandidate(Fun, DestType);
7959    }
7960  }
7961}
7962
7963/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
7964/// "lead" diagnostic; it will be given two arguments, the source and
7965/// target types of the conversion.
7966void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7967                                 Sema &S,
7968                                 SourceLocation CaretLoc,
7969                                 const PartialDiagnostic &PDiag) const {
7970  S.Diag(CaretLoc, PDiag)
7971    << Ambiguous.getFromType() << Ambiguous.getToType();
7972  for (AmbiguousConversionSequence::const_iterator
7973         I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7974    S.NoteOverloadCandidate(*I);
7975  }
7976}
7977
7978namespace {
7979
7980void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7981  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7982  assert(Conv.isBad());
7983  assert(Cand->Function && "for now, candidate must be a function");
7984  FunctionDecl *Fn = Cand->Function;
7985
7986  // There's a conversion slot for the object argument if this is a
7987  // non-constructor method.  Note that 'I' corresponds the
7988  // conversion-slot index.
7989  bool isObjectArgument = false;
7990  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
7991    if (I == 0)
7992      isObjectArgument = true;
7993    else
7994      I--;
7995  }
7996
7997  std::string FnDesc;
7998  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7999
8000  Expr *FromExpr = Conv.Bad.FromExpr;
8001  QualType FromTy = Conv.Bad.getFromType();
8002  QualType ToTy = Conv.Bad.getToType();
8003
8004  if (FromTy == S.Context.OverloadTy) {
8005    assert(FromExpr && "overload set argument came from implicit argument?");
8006    Expr *E = FromExpr->IgnoreParens();
8007    if (isa<UnaryOperator>(E))
8008      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8009    DeclarationName Name = cast<OverloadExpr>(E)->getName();
8010
8011    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8012      << (unsigned) FnKind << FnDesc
8013      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8014      << ToTy << Name << I+1;
8015    MaybeEmitInheritedConstructorNote(S, Fn);
8016    return;
8017  }
8018
8019  // Do some hand-waving analysis to see if the non-viability is due
8020  // to a qualifier mismatch.
8021  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8022  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8023  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8024    CToTy = RT->getPointeeType();
8025  else {
8026    // TODO: detect and diagnose the full richness of const mismatches.
8027    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8028      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8029        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8030  }
8031
8032  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8033      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8034    Qualifiers FromQs = CFromTy.getQualifiers();
8035    Qualifiers ToQs = CToTy.getQualifiers();
8036
8037    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8038      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8039        << (unsigned) FnKind << FnDesc
8040        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8041        << FromTy
8042        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8043        << (unsigned) isObjectArgument << I+1;
8044      MaybeEmitInheritedConstructorNote(S, Fn);
8045      return;
8046    }
8047
8048    if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8049      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8050        << (unsigned) FnKind << FnDesc
8051        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8052        << FromTy
8053        << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8054        << (unsigned) isObjectArgument << I+1;
8055      MaybeEmitInheritedConstructorNote(S, Fn);
8056      return;
8057    }
8058
8059    if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8060      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8061      << (unsigned) FnKind << FnDesc
8062      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8063      << FromTy
8064      << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8065      << (unsigned) isObjectArgument << I+1;
8066      MaybeEmitInheritedConstructorNote(S, Fn);
8067      return;
8068    }
8069
8070    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8071    assert(CVR && "unexpected qualifiers mismatch");
8072
8073    if (isObjectArgument) {
8074      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8075        << (unsigned) FnKind << FnDesc
8076        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8077        << FromTy << (CVR - 1);
8078    } else {
8079      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8080        << (unsigned) FnKind << FnDesc
8081        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8082        << FromTy << (CVR - 1) << I+1;
8083    }
8084    MaybeEmitInheritedConstructorNote(S, Fn);
8085    return;
8086  }
8087
8088  // Special diagnostic for failure to convert an initializer list, since
8089  // telling the user that it has type void is not useful.
8090  if (FromExpr && isa<InitListExpr>(FromExpr)) {
8091    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8092      << (unsigned) FnKind << FnDesc
8093      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8094      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8095    MaybeEmitInheritedConstructorNote(S, Fn);
8096    return;
8097  }
8098
8099  // Diagnose references or pointers to incomplete types differently,
8100  // since it's far from impossible that the incompleteness triggered
8101  // the failure.
8102  QualType TempFromTy = FromTy.getNonReferenceType();
8103  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8104    TempFromTy = PTy->getPointeeType();
8105  if (TempFromTy->isIncompleteType()) {
8106    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8107      << (unsigned) FnKind << FnDesc
8108      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8109      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8110    MaybeEmitInheritedConstructorNote(S, Fn);
8111    return;
8112  }
8113
8114  // Diagnose base -> derived pointer conversions.
8115  unsigned BaseToDerivedConversion = 0;
8116  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8117    if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8118      if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8119                                               FromPtrTy->getPointeeType()) &&
8120          !FromPtrTy->getPointeeType()->isIncompleteType() &&
8121          !ToPtrTy->getPointeeType()->isIncompleteType() &&
8122          S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8123                          FromPtrTy->getPointeeType()))
8124        BaseToDerivedConversion = 1;
8125    }
8126  } else if (const ObjCObjectPointerType *FromPtrTy
8127                                    = FromTy->getAs<ObjCObjectPointerType>()) {
8128    if (const ObjCObjectPointerType *ToPtrTy
8129                                        = ToTy->getAs<ObjCObjectPointerType>())
8130      if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8131        if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8132          if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8133                                                FromPtrTy->getPointeeType()) &&
8134              FromIface->isSuperClassOf(ToIface))
8135            BaseToDerivedConversion = 2;
8136  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8137    if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8138        !FromTy->isIncompleteType() &&
8139        !ToRefTy->getPointeeType()->isIncompleteType() &&
8140        S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8141      BaseToDerivedConversion = 3;
8142    } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8143               ToTy.getNonReferenceType().getCanonicalType() ==
8144               FromTy.getNonReferenceType().getCanonicalType()) {
8145      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8146        << (unsigned) FnKind << FnDesc
8147        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8148        << (unsigned) isObjectArgument << I + 1;
8149      MaybeEmitInheritedConstructorNote(S, Fn);
8150      return;
8151    }
8152  }
8153
8154  if (BaseToDerivedConversion) {
8155    S.Diag(Fn->getLocation(),
8156           diag::note_ovl_candidate_bad_base_to_derived_conv)
8157      << (unsigned) FnKind << FnDesc
8158      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8159      << (BaseToDerivedConversion - 1)
8160      << FromTy << ToTy << I+1;
8161    MaybeEmitInheritedConstructorNote(S, Fn);
8162    return;
8163  }
8164
8165  if (isa<ObjCObjectPointerType>(CFromTy) &&
8166      isa<PointerType>(CToTy)) {
8167      Qualifiers FromQs = CFromTy.getQualifiers();
8168      Qualifiers ToQs = CToTy.getQualifiers();
8169      if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8170        S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8171        << (unsigned) FnKind << FnDesc
8172        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8173        << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8174        MaybeEmitInheritedConstructorNote(S, Fn);
8175        return;
8176      }
8177  }
8178
8179  // Emit the generic diagnostic and, optionally, add the hints to it.
8180  PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8181  FDiag << (unsigned) FnKind << FnDesc
8182    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8183    << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8184    << (unsigned) (Cand->Fix.Kind);
8185
8186  // If we can fix the conversion, suggest the FixIts.
8187  for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8188       HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8189    FDiag << *HI;
8190  S.Diag(Fn->getLocation(), FDiag);
8191
8192  MaybeEmitInheritedConstructorNote(S, Fn);
8193}
8194
8195void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8196                           unsigned NumFormalArgs) {
8197  // TODO: treat calls to a missing default constructor as a special case
8198
8199  FunctionDecl *Fn = Cand->Function;
8200  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8201
8202  unsigned MinParams = Fn->getMinRequiredArguments();
8203
8204  // With invalid overloaded operators, it's possible that we think we
8205  // have an arity mismatch when it fact it looks like we have the
8206  // right number of arguments, because only overloaded operators have
8207  // the weird behavior of overloading member and non-member functions.
8208  // Just don't report anything.
8209  if (Fn->isInvalidDecl() &&
8210      Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8211    return;
8212
8213  // at least / at most / exactly
8214  unsigned mode, modeCount;
8215  if (NumFormalArgs < MinParams) {
8216    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8217           (Cand->FailureKind == ovl_fail_bad_deduction &&
8218            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8219    if (MinParams != FnTy->getNumArgs() ||
8220        FnTy->isVariadic() || FnTy->isTemplateVariadic())
8221      mode = 0; // "at least"
8222    else
8223      mode = 2; // "exactly"
8224    modeCount = MinParams;
8225  } else {
8226    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8227           (Cand->FailureKind == ovl_fail_bad_deduction &&
8228            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8229    if (MinParams != FnTy->getNumArgs())
8230      mode = 1; // "at most"
8231    else
8232      mode = 2; // "exactly"
8233    modeCount = FnTy->getNumArgs();
8234  }
8235
8236  std::string Description;
8237  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8238
8239  if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8240    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8241      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8242      << Fn->getParamDecl(0) << NumFormalArgs;
8243  else
8244    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8245      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8246      << modeCount << NumFormalArgs;
8247  MaybeEmitInheritedConstructorNote(S, Fn);
8248}
8249
8250/// Diagnose a failed template-argument deduction.
8251void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
8252                          unsigned NumArgs) {
8253  FunctionDecl *Fn = Cand->Function; // pattern
8254
8255  TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
8256  NamedDecl *ParamD;
8257  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8258  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8259  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8260  switch (Cand->DeductionFailure.Result) {
8261  case Sema::TDK_Success:
8262    llvm_unreachable("TDK_success while diagnosing bad deduction");
8263
8264  case Sema::TDK_Incomplete: {
8265    assert(ParamD && "no parameter found for incomplete deduction result");
8266    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8267      << ParamD->getDeclName();
8268    MaybeEmitInheritedConstructorNote(S, Fn);
8269    return;
8270  }
8271
8272  case Sema::TDK_Underqualified: {
8273    assert(ParamD && "no parameter found for bad qualifiers deduction result");
8274    TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8275
8276    QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8277
8278    // Param will have been canonicalized, but it should just be a
8279    // qualified version of ParamD, so move the qualifiers to that.
8280    QualifierCollector Qs;
8281    Qs.strip(Param);
8282    QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8283    assert(S.Context.hasSameType(Param, NonCanonParam));
8284
8285    // Arg has also been canonicalized, but there's nothing we can do
8286    // about that.  It also doesn't matter as much, because it won't
8287    // have any template parameters in it (because deduction isn't
8288    // done on dependent types).
8289    QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8290
8291    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8292      << ParamD->getDeclName() << Arg << NonCanonParam;
8293    MaybeEmitInheritedConstructorNote(S, Fn);
8294    return;
8295  }
8296
8297  case Sema::TDK_Inconsistent: {
8298    assert(ParamD && "no parameter found for inconsistent deduction result");
8299    int which = 0;
8300    if (isa<TemplateTypeParmDecl>(ParamD))
8301      which = 0;
8302    else if (isa<NonTypeTemplateParmDecl>(ParamD))
8303      which = 1;
8304    else {
8305      which = 2;
8306    }
8307
8308    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
8309      << which << ParamD->getDeclName()
8310      << *Cand->DeductionFailure.getFirstArg()
8311      << *Cand->DeductionFailure.getSecondArg();
8312    MaybeEmitInheritedConstructorNote(S, Fn);
8313    return;
8314  }
8315
8316  case Sema::TDK_InvalidExplicitArguments:
8317    assert(ParamD && "no parameter found for invalid explicit arguments");
8318    if (ParamD->getDeclName())
8319      S.Diag(Fn->getLocation(),
8320             diag::note_ovl_candidate_explicit_arg_mismatch_named)
8321        << ParamD->getDeclName();
8322    else {
8323      int index = 0;
8324      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8325        index = TTP->getIndex();
8326      else if (NonTypeTemplateParmDecl *NTTP
8327                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8328        index = NTTP->getIndex();
8329      else
8330        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8331      S.Diag(Fn->getLocation(),
8332             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8333        << (index + 1);
8334    }
8335    MaybeEmitInheritedConstructorNote(S, Fn);
8336    return;
8337
8338  case Sema::TDK_TooManyArguments:
8339  case Sema::TDK_TooFewArguments:
8340    DiagnoseArityMismatch(S, Cand, NumArgs);
8341    return;
8342
8343  case Sema::TDK_InstantiationDepth:
8344    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
8345    MaybeEmitInheritedConstructorNote(S, Fn);
8346    return;
8347
8348  case Sema::TDK_SubstitutionFailure: {
8349    // Format the template argument list into the argument string.
8350    llvm::SmallString<128> TemplateArgString;
8351    if (TemplateArgumentList *Args =
8352          Cand->DeductionFailure.getTemplateArgumentList()) {
8353      TemplateArgString = " ";
8354      TemplateArgString += S.getTemplateArgumentBindingsText(
8355          Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8356    }
8357
8358    // If this candidate was disabled by enable_if, say so.
8359    PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8360    if (PDiag && PDiag->second.getDiagID() ==
8361          diag::err_typename_nested_not_found_enable_if) {
8362      // FIXME: Use the source range of the condition, and the fully-qualified
8363      //        name of the enable_if template. These are both present in PDiag.
8364      S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8365        << "'enable_if'" << TemplateArgString;
8366      return;
8367    }
8368
8369    // Format the SFINAE diagnostic into the argument string.
8370    // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8371    //        formatted message in another diagnostic.
8372    llvm::SmallString<128> SFINAEArgString;
8373    SourceRange R;
8374    if (PDiag) {
8375      SFINAEArgString = ": ";
8376      R = SourceRange(PDiag->first, PDiag->first);
8377      PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8378    }
8379
8380    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8381      << TemplateArgString << SFINAEArgString << R;
8382    MaybeEmitInheritedConstructorNote(S, Fn);
8383    return;
8384  }
8385
8386  // TODO: diagnose these individually, then kill off
8387  // note_ovl_candidate_bad_deduction, which is uselessly vague.
8388  case Sema::TDK_NonDeducedMismatch:
8389  case Sema::TDK_FailedOverloadResolution:
8390    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
8391    MaybeEmitInheritedConstructorNote(S, Fn);
8392    return;
8393  }
8394}
8395
8396/// CUDA: diagnose an invalid call across targets.
8397void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8398  FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8399  FunctionDecl *Callee = Cand->Function;
8400
8401  Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8402                           CalleeTarget = S.IdentifyCUDATarget(Callee);
8403
8404  std::string FnDesc;
8405  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8406
8407  S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8408      << (unsigned) FnKind << CalleeTarget << CallerTarget;
8409}
8410
8411/// Generates a 'note' diagnostic for an overload candidate.  We've
8412/// already generated a primary error at the call site.
8413///
8414/// It really does need to be a single diagnostic with its caret
8415/// pointed at the candidate declaration.  Yes, this creates some
8416/// major challenges of technical writing.  Yes, this makes pointing
8417/// out problems with specific arguments quite awkward.  It's still
8418/// better than generating twenty screens of text for every failed
8419/// overload.
8420///
8421/// It would be great to be able to express per-candidate problems
8422/// more richly for those diagnostic clients that cared, but we'd
8423/// still have to be just as careful with the default diagnostics.
8424void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8425                           unsigned NumArgs) {
8426  FunctionDecl *Fn = Cand->Function;
8427
8428  // Note deleted candidates, but only if they're viable.
8429  if (Cand->Viable && (Fn->isDeleted() ||
8430      S.isFunctionConsideredUnavailable(Fn))) {
8431    std::string FnDesc;
8432    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8433
8434    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8435      << FnKind << FnDesc
8436      << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8437    MaybeEmitInheritedConstructorNote(S, Fn);
8438    return;
8439  }
8440
8441  // We don't really have anything else to say about viable candidates.
8442  if (Cand->Viable) {
8443    S.NoteOverloadCandidate(Fn);
8444    return;
8445  }
8446
8447  switch (Cand->FailureKind) {
8448  case ovl_fail_too_many_arguments:
8449  case ovl_fail_too_few_arguments:
8450    return DiagnoseArityMismatch(S, Cand, NumArgs);
8451
8452  case ovl_fail_bad_deduction:
8453    return DiagnoseBadDeduction(S, Cand, NumArgs);
8454
8455  case ovl_fail_trivial_conversion:
8456  case ovl_fail_bad_final_conversion:
8457  case ovl_fail_final_conversion_not_exact:
8458    return S.NoteOverloadCandidate(Fn);
8459
8460  case ovl_fail_bad_conversion: {
8461    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8462    for (unsigned N = Cand->NumConversions; I != N; ++I)
8463      if (Cand->Conversions[I].isBad())
8464        return DiagnoseBadConversion(S, Cand, I);
8465
8466    // FIXME: this currently happens when we're called from SemaInit
8467    // when user-conversion overload fails.  Figure out how to handle
8468    // those conditions and diagnose them well.
8469    return S.NoteOverloadCandidate(Fn);
8470  }
8471
8472  case ovl_fail_bad_target:
8473    return DiagnoseBadTarget(S, Cand);
8474  }
8475}
8476
8477void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8478  // Desugar the type of the surrogate down to a function type,
8479  // retaining as many typedefs as possible while still showing
8480  // the function type (and, therefore, its parameter types).
8481  QualType FnType = Cand->Surrogate->getConversionType();
8482  bool isLValueReference = false;
8483  bool isRValueReference = false;
8484  bool isPointer = false;
8485  if (const LValueReferenceType *FnTypeRef =
8486        FnType->getAs<LValueReferenceType>()) {
8487    FnType = FnTypeRef->getPointeeType();
8488    isLValueReference = true;
8489  } else if (const RValueReferenceType *FnTypeRef =
8490               FnType->getAs<RValueReferenceType>()) {
8491    FnType = FnTypeRef->getPointeeType();
8492    isRValueReference = true;
8493  }
8494  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8495    FnType = FnTypePtr->getPointeeType();
8496    isPointer = true;
8497  }
8498  // Desugar down to a function type.
8499  FnType = QualType(FnType->getAs<FunctionType>(), 0);
8500  // Reconstruct the pointer/reference as appropriate.
8501  if (isPointer) FnType = S.Context.getPointerType(FnType);
8502  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8503  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8504
8505  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8506    << FnType;
8507  MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8508}
8509
8510void NoteBuiltinOperatorCandidate(Sema &S,
8511                                  const char *Opc,
8512                                  SourceLocation OpLoc,
8513                                  OverloadCandidate *Cand) {
8514  assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8515  std::string TypeStr("operator");
8516  TypeStr += Opc;
8517  TypeStr += "(";
8518  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8519  if (Cand->NumConversions == 1) {
8520    TypeStr += ")";
8521    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8522  } else {
8523    TypeStr += ", ";
8524    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8525    TypeStr += ")";
8526    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8527  }
8528}
8529
8530void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8531                                  OverloadCandidate *Cand) {
8532  unsigned NoOperands = Cand->NumConversions;
8533  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8534    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8535    if (ICS.isBad()) break; // all meaningless after first invalid
8536    if (!ICS.isAmbiguous()) continue;
8537
8538    ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8539                              S.PDiag(diag::note_ambiguous_type_conversion));
8540  }
8541}
8542
8543SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8544  if (Cand->Function)
8545    return Cand->Function->getLocation();
8546  if (Cand->IsSurrogate)
8547    return Cand->Surrogate->getLocation();
8548  return SourceLocation();
8549}
8550
8551static unsigned
8552RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
8553  switch ((Sema::TemplateDeductionResult)DFI.Result) {
8554  case Sema::TDK_Success:
8555    llvm_unreachable("TDK_success while diagnosing bad deduction");
8556
8557  case Sema::TDK_Incomplete:
8558    return 1;
8559
8560  case Sema::TDK_Underqualified:
8561  case Sema::TDK_Inconsistent:
8562    return 2;
8563
8564  case Sema::TDK_SubstitutionFailure:
8565  case Sema::TDK_NonDeducedMismatch:
8566    return 3;
8567
8568  case Sema::TDK_InstantiationDepth:
8569  case Sema::TDK_FailedOverloadResolution:
8570    return 4;
8571
8572  case Sema::TDK_InvalidExplicitArguments:
8573    return 5;
8574
8575  case Sema::TDK_TooManyArguments:
8576  case Sema::TDK_TooFewArguments:
8577    return 6;
8578  }
8579  llvm_unreachable("Unhandled deduction result");
8580}
8581
8582struct CompareOverloadCandidatesForDisplay {
8583  Sema &S;
8584  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8585
8586  bool operator()(const OverloadCandidate *L,
8587                  const OverloadCandidate *R) {
8588    // Fast-path this check.
8589    if (L == R) return false;
8590
8591    // Order first by viability.
8592    if (L->Viable) {
8593      if (!R->Viable) return true;
8594
8595      // TODO: introduce a tri-valued comparison for overload
8596      // candidates.  Would be more worthwhile if we had a sort
8597      // that could exploit it.
8598      if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8599      if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8600    } else if (R->Viable)
8601      return false;
8602
8603    assert(L->Viable == R->Viable);
8604
8605    // Criteria by which we can sort non-viable candidates:
8606    if (!L->Viable) {
8607      // 1. Arity mismatches come after other candidates.
8608      if (L->FailureKind == ovl_fail_too_many_arguments ||
8609          L->FailureKind == ovl_fail_too_few_arguments)
8610        return false;
8611      if (R->FailureKind == ovl_fail_too_many_arguments ||
8612          R->FailureKind == ovl_fail_too_few_arguments)
8613        return true;
8614
8615      // 2. Bad conversions come first and are ordered by the number
8616      // of bad conversions and quality of good conversions.
8617      if (L->FailureKind == ovl_fail_bad_conversion) {
8618        if (R->FailureKind != ovl_fail_bad_conversion)
8619          return true;
8620
8621        // The conversion that can be fixed with a smaller number of changes,
8622        // comes first.
8623        unsigned numLFixes = L->Fix.NumConversionsFixed;
8624        unsigned numRFixes = R->Fix.NumConversionsFixed;
8625        numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8626        numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8627        if (numLFixes != numRFixes) {
8628          if (numLFixes < numRFixes)
8629            return true;
8630          else
8631            return false;
8632        }
8633
8634        // If there's any ordering between the defined conversions...
8635        // FIXME: this might not be transitive.
8636        assert(L->NumConversions == R->NumConversions);
8637
8638        int leftBetter = 0;
8639        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8640        for (unsigned E = L->NumConversions; I != E; ++I) {
8641          switch (CompareImplicitConversionSequences(S,
8642                                                     L->Conversions[I],
8643                                                     R->Conversions[I])) {
8644          case ImplicitConversionSequence::Better:
8645            leftBetter++;
8646            break;
8647
8648          case ImplicitConversionSequence::Worse:
8649            leftBetter--;
8650            break;
8651
8652          case ImplicitConversionSequence::Indistinguishable:
8653            break;
8654          }
8655        }
8656        if (leftBetter > 0) return true;
8657        if (leftBetter < 0) return false;
8658
8659      } else if (R->FailureKind == ovl_fail_bad_conversion)
8660        return false;
8661
8662      if (L->FailureKind == ovl_fail_bad_deduction) {
8663        if (R->FailureKind != ovl_fail_bad_deduction)
8664          return true;
8665
8666        if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8667          return RankDeductionFailure(L->DeductionFailure)
8668               < RankDeductionFailure(R->DeductionFailure);
8669      } else if (R->FailureKind == ovl_fail_bad_deduction)
8670        return false;
8671
8672      // TODO: others?
8673    }
8674
8675    // Sort everything else by location.
8676    SourceLocation LLoc = GetLocationForCandidate(L);
8677    SourceLocation RLoc = GetLocationForCandidate(R);
8678
8679    // Put candidates without locations (e.g. builtins) at the end.
8680    if (LLoc.isInvalid()) return false;
8681    if (RLoc.isInvalid()) return true;
8682
8683    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8684  }
8685};
8686
8687/// CompleteNonViableCandidate - Normally, overload resolution only
8688/// computes up to the first. Produces the FixIt set if possible.
8689void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8690                                llvm::ArrayRef<Expr *> Args) {
8691  assert(!Cand->Viable);
8692
8693  // Don't do anything on failures other than bad conversion.
8694  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8695
8696  // We only want the FixIts if all the arguments can be corrected.
8697  bool Unfixable = false;
8698  // Use a implicit copy initialization to check conversion fixes.
8699  Cand->Fix.setConversionChecker(TryCopyInitialization);
8700
8701  // Skip forward to the first bad conversion.
8702  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
8703  unsigned ConvCount = Cand->NumConversions;
8704  while (true) {
8705    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8706    ConvIdx++;
8707    if (Cand->Conversions[ConvIdx - 1].isBad()) {
8708      Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
8709      break;
8710    }
8711  }
8712
8713  if (ConvIdx == ConvCount)
8714    return;
8715
8716  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8717         "remaining conversion is initialized?");
8718
8719  // FIXME: this should probably be preserved from the overload
8720  // operation somehow.
8721  bool SuppressUserConversions = false;
8722
8723  const FunctionProtoType* Proto;
8724  unsigned ArgIdx = ConvIdx;
8725
8726  if (Cand->IsSurrogate) {
8727    QualType ConvType
8728      = Cand->Surrogate->getConversionType().getNonReferenceType();
8729    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8730      ConvType = ConvPtrType->getPointeeType();
8731    Proto = ConvType->getAs<FunctionProtoType>();
8732    ArgIdx--;
8733  } else if (Cand->Function) {
8734    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8735    if (isa<CXXMethodDecl>(Cand->Function) &&
8736        !isa<CXXConstructorDecl>(Cand->Function))
8737      ArgIdx--;
8738  } else {
8739    // Builtin binary operator with a bad first conversion.
8740    assert(ConvCount <= 3);
8741    for (; ConvIdx != ConvCount; ++ConvIdx)
8742      Cand->Conversions[ConvIdx]
8743        = TryCopyInitialization(S, Args[ConvIdx],
8744                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
8745                                SuppressUserConversions,
8746                                /*InOverloadResolution*/ true,
8747                                /*AllowObjCWritebackConversion=*/
8748                                  S.getLangOpts().ObjCAutoRefCount);
8749    return;
8750  }
8751
8752  // Fill in the rest of the conversions.
8753  unsigned NumArgsInProto = Proto->getNumArgs();
8754  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
8755    if (ArgIdx < NumArgsInProto) {
8756      Cand->Conversions[ConvIdx]
8757        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
8758                                SuppressUserConversions,
8759                                /*InOverloadResolution=*/true,
8760                                /*AllowObjCWritebackConversion=*/
8761                                  S.getLangOpts().ObjCAutoRefCount);
8762      // Store the FixIt in the candidate if it exists.
8763      if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
8764        Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
8765    }
8766    else
8767      Cand->Conversions[ConvIdx].setEllipsis();
8768  }
8769}
8770
8771} // end anonymous namespace
8772
8773/// PrintOverloadCandidates - When overload resolution fails, prints
8774/// diagnostic messages containing the candidates in the candidate
8775/// set.
8776void OverloadCandidateSet::NoteCandidates(Sema &S,
8777                                          OverloadCandidateDisplayKind OCD,
8778                                          llvm::ArrayRef<Expr *> Args,
8779                                          const char *Opc,
8780                                          SourceLocation OpLoc) {
8781  // Sort the candidates by viability and position.  Sorting directly would
8782  // be prohibitive, so we make a set of pointers and sort those.
8783  SmallVector<OverloadCandidate*, 32> Cands;
8784  if (OCD == OCD_AllCandidates) Cands.reserve(size());
8785  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
8786    if (Cand->Viable)
8787      Cands.push_back(Cand);
8788    else if (OCD == OCD_AllCandidates) {
8789      CompleteNonViableCandidate(S, Cand, Args);
8790      if (Cand->Function || Cand->IsSurrogate)
8791        Cands.push_back(Cand);
8792      // Otherwise, this a non-viable builtin candidate.  We do not, in general,
8793      // want to list every possible builtin candidate.
8794    }
8795  }
8796
8797  std::sort(Cands.begin(), Cands.end(),
8798            CompareOverloadCandidatesForDisplay(S));
8799
8800  bool ReportedAmbiguousConversions = false;
8801
8802  SmallVectorImpl<OverloadCandidate*>::iterator I, E;
8803  const DiagnosticsEngine::OverloadsShown ShowOverloads =
8804      S.Diags.getShowOverloads();
8805  unsigned CandsShown = 0;
8806  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8807    OverloadCandidate *Cand = *I;
8808
8809    // Set an arbitrary limit on the number of candidate functions we'll spam
8810    // the user with.  FIXME: This limit should depend on details of the
8811    // candidate list.
8812    if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
8813      break;
8814    }
8815    ++CandsShown;
8816
8817    if (Cand->Function)
8818      NoteFunctionCandidate(S, Cand, Args.size());
8819    else if (Cand->IsSurrogate)
8820      NoteSurrogateCandidate(S, Cand);
8821    else {
8822      assert(Cand->Viable &&
8823             "Non-viable built-in candidates are not added to Cands.");
8824      // Generally we only see ambiguities including viable builtin
8825      // operators if overload resolution got screwed up by an
8826      // ambiguous user-defined conversion.
8827      //
8828      // FIXME: It's quite possible for different conversions to see
8829      // different ambiguities, though.
8830      if (!ReportedAmbiguousConversions) {
8831        NoteAmbiguousUserConversions(S, OpLoc, Cand);
8832        ReportedAmbiguousConversions = true;
8833      }
8834
8835      // If this is a viable builtin, print it.
8836      NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
8837    }
8838  }
8839
8840  if (I != E)
8841    S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
8842}
8843
8844// [PossiblyAFunctionType]  -->   [Return]
8845// NonFunctionType --> NonFunctionType
8846// R (A) --> R(A)
8847// R (*)(A) --> R (A)
8848// R (&)(A) --> R (A)
8849// R (S::*)(A) --> R (A)
8850QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8851  QualType Ret = PossiblyAFunctionType;
8852  if (const PointerType *ToTypePtr =
8853    PossiblyAFunctionType->getAs<PointerType>())
8854    Ret = ToTypePtr->getPointeeType();
8855  else if (const ReferenceType *ToTypeRef =
8856    PossiblyAFunctionType->getAs<ReferenceType>())
8857    Ret = ToTypeRef->getPointeeType();
8858  else if (const MemberPointerType *MemTypePtr =
8859    PossiblyAFunctionType->getAs<MemberPointerType>())
8860    Ret = MemTypePtr->getPointeeType();
8861  Ret =
8862    Context.getCanonicalType(Ret).getUnqualifiedType();
8863  return Ret;
8864}
8865
8866// A helper class to help with address of function resolution
8867// - allows us to avoid passing around all those ugly parameters
8868class AddressOfFunctionResolver
8869{
8870  Sema& S;
8871  Expr* SourceExpr;
8872  const QualType& TargetType;
8873  QualType TargetFunctionType; // Extracted function type from target type
8874
8875  bool Complain;
8876  //DeclAccessPair& ResultFunctionAccessPair;
8877  ASTContext& Context;
8878
8879  bool TargetTypeIsNonStaticMemberFunction;
8880  bool FoundNonTemplateFunction;
8881
8882  OverloadExpr::FindResult OvlExprInfo;
8883  OverloadExpr *OvlExpr;
8884  TemplateArgumentListInfo OvlExplicitTemplateArgs;
8885  SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
8886
8887public:
8888  AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8889                            const QualType& TargetType, bool Complain)
8890    : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8891      Complain(Complain), Context(S.getASTContext()),
8892      TargetTypeIsNonStaticMemberFunction(
8893                                    !!TargetType->getAs<MemberPointerType>()),
8894      FoundNonTemplateFunction(false),
8895      OvlExprInfo(OverloadExpr::find(SourceExpr)),
8896      OvlExpr(OvlExprInfo.Expression)
8897  {
8898    ExtractUnqualifiedFunctionTypeFromTargetType();
8899
8900    if (!TargetFunctionType->isFunctionType()) {
8901      if (OvlExpr->hasExplicitTemplateArgs()) {
8902        DeclAccessPair dap;
8903        if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
8904                                            OvlExpr, false, &dap) ) {
8905
8906          if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8907            if (!Method->isStatic()) {
8908              // If the target type is a non-function type and the function
8909              // found is a non-static member function, pretend as if that was
8910              // the target, it's the only possible type to end up with.
8911              TargetTypeIsNonStaticMemberFunction = true;
8912
8913              // And skip adding the function if its not in the proper form.
8914              // We'll diagnose this due to an empty set of functions.
8915              if (!OvlExprInfo.HasFormOfMemberPointer)
8916                return;
8917            }
8918          }
8919
8920          Matches.push_back(std::make_pair(dap,Fn));
8921        }
8922      }
8923      return;
8924    }
8925
8926    if (OvlExpr->hasExplicitTemplateArgs())
8927      OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
8928
8929    if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8930      // C++ [over.over]p4:
8931      //   If more than one function is selected, [...]
8932      if (Matches.size() > 1) {
8933        if (FoundNonTemplateFunction)
8934          EliminateAllTemplateMatches();
8935        else
8936          EliminateAllExceptMostSpecializedTemplate();
8937      }
8938    }
8939  }
8940
8941private:
8942  bool isTargetTypeAFunction() const {
8943    return TargetFunctionType->isFunctionType();
8944  }
8945
8946  // [ToType]     [Return]
8947
8948  // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8949  // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8950  // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8951  void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8952    TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8953  }
8954
8955  // return true if any matching specializations were found
8956  bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8957                                   const DeclAccessPair& CurAccessFunPair) {
8958    if (CXXMethodDecl *Method
8959              = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8960      // Skip non-static function templates when converting to pointer, and
8961      // static when converting to member pointer.
8962      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8963        return false;
8964    }
8965    else if (TargetTypeIsNonStaticMemberFunction)
8966      return false;
8967
8968    // C++ [over.over]p2:
8969    //   If the name is a function template, template argument deduction is
8970    //   done (14.8.2.2), and if the argument deduction succeeds, the
8971    //   resulting template argument list is used to generate a single
8972    //   function template specialization, which is added to the set of
8973    //   overloaded functions considered.
8974    FunctionDecl *Specialization = 0;
8975    TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8976    if (Sema::TemplateDeductionResult Result
8977          = S.DeduceTemplateArguments(FunctionTemplate,
8978                                      &OvlExplicitTemplateArgs,
8979                                      TargetFunctionType, Specialization,
8980                                      Info)) {
8981      // FIXME: make a note of the failed deduction for diagnostics.
8982      (void)Result;
8983      return false;
8984    }
8985
8986    // Template argument deduction ensures that we have an exact match.
8987    // This function template specicalization works.
8988    Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8989    assert(TargetFunctionType
8990                      == Context.getCanonicalType(Specialization->getType()));
8991    Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8992    return true;
8993  }
8994
8995  bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8996                                      const DeclAccessPair& CurAccessFunPair) {
8997    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8998      // Skip non-static functions when converting to pointer, and static
8999      // when converting to member pointer.
9000      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9001        return false;
9002    }
9003    else if (TargetTypeIsNonStaticMemberFunction)
9004      return false;
9005
9006    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9007      if (S.getLangOpts().CUDA)
9008        if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9009          if (S.CheckCUDATarget(Caller, FunDecl))
9010            return false;
9011
9012      QualType ResultTy;
9013      if (Context.hasSameUnqualifiedType(TargetFunctionType,
9014                                         FunDecl->getType()) ||
9015          S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9016                                 ResultTy)) {
9017        Matches.push_back(std::make_pair(CurAccessFunPair,
9018          cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9019        FoundNonTemplateFunction = true;
9020        return true;
9021      }
9022    }
9023
9024    return false;
9025  }
9026
9027  bool FindAllFunctionsThatMatchTargetTypeExactly() {
9028    bool Ret = false;
9029
9030    // If the overload expression doesn't have the form of a pointer to
9031    // member, don't try to convert it to a pointer-to-member type.
9032    if (IsInvalidFormOfPointerToMemberFunction())
9033      return false;
9034
9035    for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9036                               E = OvlExpr->decls_end();
9037         I != E; ++I) {
9038      // Look through any using declarations to find the underlying function.
9039      NamedDecl *Fn = (*I)->getUnderlyingDecl();
9040
9041      // C++ [over.over]p3:
9042      //   Non-member functions and static member functions match
9043      //   targets of type "pointer-to-function" or "reference-to-function."
9044      //   Nonstatic member functions match targets of
9045      //   type "pointer-to-member-function."
9046      // Note that according to DR 247, the containing class does not matter.
9047      if (FunctionTemplateDecl *FunctionTemplate
9048                                        = dyn_cast<FunctionTemplateDecl>(Fn)) {
9049        if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9050          Ret = true;
9051      }
9052      // If we have explicit template arguments supplied, skip non-templates.
9053      else if (!OvlExpr->hasExplicitTemplateArgs() &&
9054               AddMatchingNonTemplateFunction(Fn, I.getPair()))
9055        Ret = true;
9056    }
9057    assert(Ret || Matches.empty());
9058    return Ret;
9059  }
9060
9061  void EliminateAllExceptMostSpecializedTemplate() {
9062    //   [...] and any given function template specialization F1 is
9063    //   eliminated if the set contains a second function template
9064    //   specialization whose function template is more specialized
9065    //   than the function template of F1 according to the partial
9066    //   ordering rules of 14.5.5.2.
9067
9068    // The algorithm specified above is quadratic. We instead use a
9069    // two-pass algorithm (similar to the one used to identify the
9070    // best viable function in an overload set) that identifies the
9071    // best function template (if it exists).
9072
9073    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9074    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9075      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9076
9077    UnresolvedSetIterator Result =
9078      S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9079                           TPOC_Other, 0, SourceExpr->getLocStart(),
9080                           S.PDiag(),
9081                           S.PDiag(diag::err_addr_ovl_ambiguous)
9082                             << Matches[0].second->getDeclName(),
9083                           S.PDiag(diag::note_ovl_candidate)
9084                             << (unsigned) oc_function_template,
9085                           Complain, TargetFunctionType);
9086
9087    if (Result != MatchesCopy.end()) {
9088      // Make it the first and only element
9089      Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9090      Matches[0].second = cast<FunctionDecl>(*Result);
9091      Matches.resize(1);
9092    }
9093  }
9094
9095  void EliminateAllTemplateMatches() {
9096    //   [...] any function template specializations in the set are
9097    //   eliminated if the set also contains a non-template function, [...]
9098    for (unsigned I = 0, N = Matches.size(); I != N; ) {
9099      if (Matches[I].second->getPrimaryTemplate() == 0)
9100        ++I;
9101      else {
9102        Matches[I] = Matches[--N];
9103        Matches.set_size(N);
9104      }
9105    }
9106  }
9107
9108public:
9109  void ComplainNoMatchesFound() const {
9110    assert(Matches.empty());
9111    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9112        << OvlExpr->getName() << TargetFunctionType
9113        << OvlExpr->getSourceRange();
9114    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9115  }
9116
9117  bool IsInvalidFormOfPointerToMemberFunction() const {
9118    return TargetTypeIsNonStaticMemberFunction &&
9119      !OvlExprInfo.HasFormOfMemberPointer;
9120  }
9121
9122  void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9123      // TODO: Should we condition this on whether any functions might
9124      // have matched, or is it more appropriate to do that in callers?
9125      // TODO: a fixit wouldn't hurt.
9126      S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9127        << TargetType << OvlExpr->getSourceRange();
9128  }
9129
9130  void ComplainOfInvalidConversion() const {
9131    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9132      << OvlExpr->getName() << TargetType;
9133  }
9134
9135  void ComplainMultipleMatchesFound() const {
9136    assert(Matches.size() > 1);
9137    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9138      << OvlExpr->getName()
9139      << OvlExpr->getSourceRange();
9140    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9141  }
9142
9143  bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9144
9145  int getNumMatches() const { return Matches.size(); }
9146
9147  FunctionDecl* getMatchingFunctionDecl() const {
9148    if (Matches.size() != 1) return 0;
9149    return Matches[0].second;
9150  }
9151
9152  const DeclAccessPair* getMatchingFunctionAccessPair() const {
9153    if (Matches.size() != 1) return 0;
9154    return &Matches[0].first;
9155  }
9156};
9157
9158/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9159/// an overloaded function (C++ [over.over]), where @p From is an
9160/// expression with overloaded function type and @p ToType is the type
9161/// we're trying to resolve to. For example:
9162///
9163/// @code
9164/// int f(double);
9165/// int f(int);
9166///
9167/// int (*pfd)(double) = f; // selects f(double)
9168/// @endcode
9169///
9170/// This routine returns the resulting FunctionDecl if it could be
9171/// resolved, and NULL otherwise. When @p Complain is true, this
9172/// routine will emit diagnostics if there is an error.
9173FunctionDecl *
9174Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9175                                         QualType TargetType,
9176                                         bool Complain,
9177                                         DeclAccessPair &FoundResult,
9178                                         bool *pHadMultipleCandidates) {
9179  assert(AddressOfExpr->getType() == Context.OverloadTy);
9180
9181  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9182                                     Complain);
9183  int NumMatches = Resolver.getNumMatches();
9184  FunctionDecl* Fn = 0;
9185  if (NumMatches == 0 && Complain) {
9186    if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9187      Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9188    else
9189      Resolver.ComplainNoMatchesFound();
9190  }
9191  else if (NumMatches > 1 && Complain)
9192    Resolver.ComplainMultipleMatchesFound();
9193  else if (NumMatches == 1) {
9194    Fn = Resolver.getMatchingFunctionDecl();
9195    assert(Fn);
9196    FoundResult = *Resolver.getMatchingFunctionAccessPair();
9197    MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
9198    if (Complain)
9199      CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9200  }
9201
9202  if (pHadMultipleCandidates)
9203    *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9204  return Fn;
9205}
9206
9207/// \brief Given an expression that refers to an overloaded function, try to
9208/// resolve that overloaded function expression down to a single function.
9209///
9210/// This routine can only resolve template-ids that refer to a single function
9211/// template, where that template-id refers to a single template whose template
9212/// arguments are either provided by the template-id or have defaults,
9213/// as described in C++0x [temp.arg.explicit]p3.
9214FunctionDecl *
9215Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9216                                                  bool Complain,
9217                                                  DeclAccessPair *FoundResult) {
9218  // C++ [over.over]p1:
9219  //   [...] [Note: any redundant set of parentheses surrounding the
9220  //   overloaded function name is ignored (5.1). ]
9221  // C++ [over.over]p1:
9222  //   [...] The overloaded function name can be preceded by the &
9223  //   operator.
9224
9225  // If we didn't actually find any template-ids, we're done.
9226  if (!ovl->hasExplicitTemplateArgs())
9227    return 0;
9228
9229  TemplateArgumentListInfo ExplicitTemplateArgs;
9230  ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9231
9232  // Look through all of the overloaded functions, searching for one
9233  // whose type matches exactly.
9234  FunctionDecl *Matched = 0;
9235  for (UnresolvedSetIterator I = ovl->decls_begin(),
9236         E = ovl->decls_end(); I != E; ++I) {
9237    // C++0x [temp.arg.explicit]p3:
9238    //   [...] In contexts where deduction is done and fails, or in contexts
9239    //   where deduction is not done, if a template argument list is
9240    //   specified and it, along with any default template arguments,
9241    //   identifies a single function template specialization, then the
9242    //   template-id is an lvalue for the function template specialization.
9243    FunctionTemplateDecl *FunctionTemplate
9244      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9245
9246    // C++ [over.over]p2:
9247    //   If the name is a function template, template argument deduction is
9248    //   done (14.8.2.2), and if the argument deduction succeeds, the
9249    //   resulting template argument list is used to generate a single
9250    //   function template specialization, which is added to the set of
9251    //   overloaded functions considered.
9252    FunctionDecl *Specialization = 0;
9253    TemplateDeductionInfo Info(Context, ovl->getNameLoc());
9254    if (TemplateDeductionResult Result
9255          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9256                                    Specialization, Info)) {
9257      // FIXME: make a note of the failed deduction for diagnostics.
9258      (void)Result;
9259      continue;
9260    }
9261
9262    assert(Specialization && "no specialization and no error?");
9263
9264    // Multiple matches; we can't resolve to a single declaration.
9265    if (Matched) {
9266      if (Complain) {
9267        Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9268          << ovl->getName();
9269        NoteAllOverloadCandidates(ovl);
9270      }
9271      return 0;
9272    }
9273
9274    Matched = Specialization;
9275    if (FoundResult) *FoundResult = I.getPair();
9276  }
9277
9278  return Matched;
9279}
9280
9281
9282
9283
9284// Resolve and fix an overloaded expression that can be resolved
9285// because it identifies a single function template specialization.
9286//
9287// Last three arguments should only be supplied if Complain = true
9288//
9289// Return true if it was logically possible to so resolve the
9290// expression, regardless of whether or not it succeeded.  Always
9291// returns true if 'complain' is set.
9292bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9293                      ExprResult &SrcExpr, bool doFunctionPointerConverion,
9294                   bool complain, const SourceRange& OpRangeForComplaining,
9295                                           QualType DestTypeForComplaining,
9296                                            unsigned DiagIDForComplaining) {
9297  assert(SrcExpr.get()->getType() == Context.OverloadTy);
9298
9299  OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9300
9301  DeclAccessPair found;
9302  ExprResult SingleFunctionExpression;
9303  if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9304                           ovl.Expression, /*complain*/ false, &found)) {
9305    if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9306      SrcExpr = ExprError();
9307      return true;
9308    }
9309
9310    // It is only correct to resolve to an instance method if we're
9311    // resolving a form that's permitted to be a pointer to member.
9312    // Otherwise we'll end up making a bound member expression, which
9313    // is illegal in all the contexts we resolve like this.
9314    if (!ovl.HasFormOfMemberPointer &&
9315        isa<CXXMethodDecl>(fn) &&
9316        cast<CXXMethodDecl>(fn)->isInstance()) {
9317      if (!complain) return false;
9318
9319      Diag(ovl.Expression->getExprLoc(),
9320           diag::err_bound_member_function)
9321        << 0 << ovl.Expression->getSourceRange();
9322
9323      // TODO: I believe we only end up here if there's a mix of
9324      // static and non-static candidates (otherwise the expression
9325      // would have 'bound member' type, not 'overload' type).
9326      // Ideally we would note which candidate was chosen and why
9327      // the static candidates were rejected.
9328      SrcExpr = ExprError();
9329      return true;
9330    }
9331
9332    // Fix the expresion to refer to 'fn'.
9333    SingleFunctionExpression =
9334      Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9335
9336    // If desired, do function-to-pointer decay.
9337    if (doFunctionPointerConverion) {
9338      SingleFunctionExpression =
9339        DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9340      if (SingleFunctionExpression.isInvalid()) {
9341        SrcExpr = ExprError();
9342        return true;
9343      }
9344    }
9345  }
9346
9347  if (!SingleFunctionExpression.isUsable()) {
9348    if (complain) {
9349      Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9350        << ovl.Expression->getName()
9351        << DestTypeForComplaining
9352        << OpRangeForComplaining
9353        << ovl.Expression->getQualifierLoc().getSourceRange();
9354      NoteAllOverloadCandidates(SrcExpr.get());
9355
9356      SrcExpr = ExprError();
9357      return true;
9358    }
9359
9360    return false;
9361  }
9362
9363  SrcExpr = SingleFunctionExpression;
9364  return true;
9365}
9366
9367/// \brief Add a single candidate to the overload set.
9368static void AddOverloadedCallCandidate(Sema &S,
9369                                       DeclAccessPair FoundDecl,
9370                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
9371                                       llvm::ArrayRef<Expr *> Args,
9372                                       OverloadCandidateSet &CandidateSet,
9373                                       bool PartialOverloading,
9374                                       bool KnownValid) {
9375  NamedDecl *Callee = FoundDecl.getDecl();
9376  if (isa<UsingShadowDecl>(Callee))
9377    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9378
9379  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9380    if (ExplicitTemplateArgs) {
9381      assert(!KnownValid && "Explicit template arguments?");
9382      return;
9383    }
9384    S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9385                           PartialOverloading);
9386    return;
9387  }
9388
9389  if (FunctionTemplateDecl *FuncTemplate
9390      = dyn_cast<FunctionTemplateDecl>(Callee)) {
9391    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9392                                   ExplicitTemplateArgs, Args, CandidateSet);
9393    return;
9394  }
9395
9396  assert(!KnownValid && "unhandled case in overloaded call candidate");
9397}
9398
9399/// \brief Add the overload candidates named by callee and/or found by argument
9400/// dependent lookup to the given overload set.
9401void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9402                                       llvm::ArrayRef<Expr *> Args,
9403                                       OverloadCandidateSet &CandidateSet,
9404                                       bool PartialOverloading) {
9405
9406#ifndef NDEBUG
9407  // Verify that ArgumentDependentLookup is consistent with the rules
9408  // in C++0x [basic.lookup.argdep]p3:
9409  //
9410  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9411  //   and let Y be the lookup set produced by argument dependent
9412  //   lookup (defined as follows). If X contains
9413  //
9414  //     -- a declaration of a class member, or
9415  //
9416  //     -- a block-scope function declaration that is not a
9417  //        using-declaration, or
9418  //
9419  //     -- a declaration that is neither a function or a function
9420  //        template
9421  //
9422  //   then Y is empty.
9423
9424  if (ULE->requiresADL()) {
9425    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9426           E = ULE->decls_end(); I != E; ++I) {
9427      assert(!(*I)->getDeclContext()->isRecord());
9428      assert(isa<UsingShadowDecl>(*I) ||
9429             !(*I)->getDeclContext()->isFunctionOrMethod());
9430      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9431    }
9432  }
9433#endif
9434
9435  // It would be nice to avoid this copy.
9436  TemplateArgumentListInfo TABuffer;
9437  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9438  if (ULE->hasExplicitTemplateArgs()) {
9439    ULE->copyTemplateArgumentsInto(TABuffer);
9440    ExplicitTemplateArgs = &TABuffer;
9441  }
9442
9443  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9444         E = ULE->decls_end(); I != E; ++I)
9445    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9446                               CandidateSet, PartialOverloading,
9447                               /*KnownValid*/ true);
9448
9449  if (ULE->requiresADL())
9450    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9451                                         ULE->getExprLoc(),
9452                                         Args, ExplicitTemplateArgs,
9453                                         CandidateSet, PartialOverloading,
9454                                         ULE->isStdAssociatedNamespace());
9455}
9456
9457/// Attempt to recover from an ill-formed use of a non-dependent name in a
9458/// template, where the non-dependent name was declared after the template
9459/// was defined. This is common in code written for a compilers which do not
9460/// correctly implement two-stage name lookup.
9461///
9462/// Returns true if a viable candidate was found and a diagnostic was issued.
9463static bool
9464DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9465                       const CXXScopeSpec &SS, LookupResult &R,
9466                       TemplateArgumentListInfo *ExplicitTemplateArgs,
9467                       llvm::ArrayRef<Expr *> Args) {
9468  if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9469    return false;
9470
9471  for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9472    if (DC->isTransparentContext())
9473      continue;
9474
9475    SemaRef.LookupQualifiedName(R, DC);
9476
9477    if (!R.empty()) {
9478      R.suppressDiagnostics();
9479
9480      if (isa<CXXRecordDecl>(DC)) {
9481        // Don't diagnose names we find in classes; we get much better
9482        // diagnostics for these from DiagnoseEmptyLookup.
9483        R.clear();
9484        return false;
9485      }
9486
9487      OverloadCandidateSet Candidates(FnLoc);
9488      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9489        AddOverloadedCallCandidate(SemaRef, I.getPair(),
9490                                   ExplicitTemplateArgs, Args,
9491                                   Candidates, false, /*KnownValid*/ false);
9492
9493      OverloadCandidateSet::iterator Best;
9494      if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9495        // No viable functions. Don't bother the user with notes for functions
9496        // which don't work and shouldn't be found anyway.
9497        R.clear();
9498        return false;
9499      }
9500
9501      // Find the namespaces where ADL would have looked, and suggest
9502      // declaring the function there instead.
9503      Sema::AssociatedNamespaceSet AssociatedNamespaces;
9504      Sema::AssociatedClassSet AssociatedClasses;
9505      SemaRef.FindAssociatedClassesAndNamespaces(Args,
9506                                                 AssociatedNamespaces,
9507                                                 AssociatedClasses);
9508      // Never suggest declaring a function within namespace 'std'.
9509      Sema::AssociatedNamespaceSet SuggestedNamespaces;
9510      if (DeclContext *Std = SemaRef.getStdNamespace()) {
9511        for (Sema::AssociatedNamespaceSet::iterator
9512               it = AssociatedNamespaces.begin(),
9513               end = AssociatedNamespaces.end(); it != end; ++it) {
9514          if (!Std->Encloses(*it))
9515            SuggestedNamespaces.insert(*it);
9516        }
9517      } else {
9518        // Lacking the 'std::' namespace, use all of the associated namespaces.
9519        SuggestedNamespaces = AssociatedNamespaces;
9520      }
9521
9522      SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9523        << R.getLookupName();
9524      if (SuggestedNamespaces.empty()) {
9525        SemaRef.Diag(Best->Function->getLocation(),
9526                     diag::note_not_found_by_two_phase_lookup)
9527          << R.getLookupName() << 0;
9528      } else if (SuggestedNamespaces.size() == 1) {
9529        SemaRef.Diag(Best->Function->getLocation(),
9530                     diag::note_not_found_by_two_phase_lookup)
9531          << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
9532      } else {
9533        // FIXME: It would be useful to list the associated namespaces here,
9534        // but the diagnostics infrastructure doesn't provide a way to produce
9535        // a localized representation of a list of items.
9536        SemaRef.Diag(Best->Function->getLocation(),
9537                     diag::note_not_found_by_two_phase_lookup)
9538          << R.getLookupName() << 2;
9539      }
9540
9541      // Try to recover by calling this function.
9542      return true;
9543    }
9544
9545    R.clear();
9546  }
9547
9548  return false;
9549}
9550
9551/// Attempt to recover from ill-formed use of a non-dependent operator in a
9552/// template, where the non-dependent operator was declared after the template
9553/// was defined.
9554///
9555/// Returns true if a viable candidate was found and a diagnostic was issued.
9556static bool
9557DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9558                               SourceLocation OpLoc,
9559                               llvm::ArrayRef<Expr *> Args) {
9560  DeclarationName OpName =
9561    SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9562  LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9563  return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9564                                /*ExplicitTemplateArgs=*/0, Args);
9565}
9566
9567namespace {
9568// Callback to limit the allowed keywords and to only accept typo corrections
9569// that are keywords or whose decls refer to functions (or template functions)
9570// that accept the given number of arguments.
9571class RecoveryCallCCC : public CorrectionCandidateCallback {
9572 public:
9573  RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9574      : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9575    WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
9576    WantRemainingKeywords = false;
9577  }
9578
9579  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9580    if (!candidate.getCorrectionDecl())
9581      return candidate.isKeyword();
9582
9583    for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9584           DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9585      FunctionDecl *FD = 0;
9586      NamedDecl *ND = (*DI)->getUnderlyingDecl();
9587      if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9588        FD = FTD->getTemplatedDecl();
9589      if (!HasExplicitTemplateArgs && !FD) {
9590        if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9591          // If the Decl is neither a function nor a template function,
9592          // determine if it is a pointer or reference to a function. If so,
9593          // check against the number of arguments expected for the pointee.
9594          QualType ValType = cast<ValueDecl>(ND)->getType();
9595          if (ValType->isAnyPointerType() || ValType->isReferenceType())
9596            ValType = ValType->getPointeeType();
9597          if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9598            if (FPT->getNumArgs() == NumArgs)
9599              return true;
9600        }
9601      }
9602      if (FD && FD->getNumParams() >= NumArgs &&
9603          FD->getMinRequiredArguments() <= NumArgs)
9604        return true;
9605    }
9606    return false;
9607  }
9608
9609 private:
9610  unsigned NumArgs;
9611  bool HasExplicitTemplateArgs;
9612};
9613
9614// Callback that effectively disabled typo correction
9615class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9616 public:
9617  NoTypoCorrectionCCC() {
9618    WantTypeSpecifiers = false;
9619    WantExpressionKeywords = false;
9620    WantCXXNamedCasts = false;
9621    WantRemainingKeywords = false;
9622  }
9623
9624  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9625    return false;
9626  }
9627};
9628}
9629
9630/// Attempts to recover from a call where no functions were found.
9631///
9632/// Returns true if new candidates were found.
9633static ExprResult
9634BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9635                      UnresolvedLookupExpr *ULE,
9636                      SourceLocation LParenLoc,
9637                      llvm::MutableArrayRef<Expr *> Args,
9638                      SourceLocation RParenLoc,
9639                      bool EmptyLookup, bool AllowTypoCorrection) {
9640
9641  CXXScopeSpec SS;
9642  SS.Adopt(ULE->getQualifierLoc());
9643  SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
9644
9645  TemplateArgumentListInfo TABuffer;
9646  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9647  if (ULE->hasExplicitTemplateArgs()) {
9648    ULE->copyTemplateArgumentsInto(TABuffer);
9649    ExplicitTemplateArgs = &TABuffer;
9650  }
9651
9652  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9653                 Sema::LookupOrdinaryName);
9654  RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
9655  NoTypoCorrectionCCC RejectAll;
9656  CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9657      (CorrectionCandidateCallback*)&Validator :
9658      (CorrectionCandidateCallback*)&RejectAll;
9659  if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9660                              ExplicitTemplateArgs, Args) &&
9661      (!EmptyLookup ||
9662       SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
9663                                   ExplicitTemplateArgs, Args)))
9664    return ExprError();
9665
9666  assert(!R.empty() && "lookup results empty despite recovery");
9667
9668  // Build an implicit member call if appropriate.  Just drop the
9669  // casts and such from the call, we don't really care.
9670  ExprResult NewFn = ExprError();
9671  if ((*R.begin())->isCXXClassMember())
9672    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9673                                                    R, ExplicitTemplateArgs);
9674  else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
9675    NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
9676                                        ExplicitTemplateArgs);
9677  else
9678    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9679
9680  if (NewFn.isInvalid())
9681    return ExprError();
9682
9683  // This shouldn't cause an infinite loop because we're giving it
9684  // an expression with viable lookup results, which should never
9685  // end up here.
9686  return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
9687                               MultiExprArg(Args.data(), Args.size()),
9688                               RParenLoc);
9689}
9690
9691/// ResolveOverloadedCallFn - Given the call expression that calls Fn
9692/// (which eventually refers to the declaration Func) and the call
9693/// arguments Args/NumArgs, attempt to resolve the function call down
9694/// to a specific function. If overload resolution succeeds, returns
9695/// the function declaration produced by overload
9696/// resolution. Otherwise, emits diagnostics, deletes all of the
9697/// arguments and Fn, and returns NULL.
9698ExprResult
9699Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
9700                              SourceLocation LParenLoc,
9701                              Expr **Args, unsigned NumArgs,
9702                              SourceLocation RParenLoc,
9703                              Expr *ExecConfig,
9704                              bool AllowTypoCorrection) {
9705#ifndef NDEBUG
9706  if (ULE->requiresADL()) {
9707    // To do ADL, we must have found an unqualified name.
9708    assert(!ULE->getQualifier() && "qualified name with ADL");
9709
9710    // We don't perform ADL for implicit declarations of builtins.
9711    // Verify that this was correctly set up.
9712    FunctionDecl *F;
9713    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9714        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9715        F->getBuiltinID() && F->isImplicit())
9716      llvm_unreachable("performing ADL for builtin");
9717
9718    // We don't perform ADL in C.
9719    assert(getLangOpts().CPlusPlus && "ADL enabled in C");
9720  } else
9721    assert(!ULE->isStdAssociatedNamespace() &&
9722           "std is associated namespace but not doing ADL");
9723#endif
9724
9725  UnbridgedCastsSet UnbridgedCasts;
9726  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9727    return ExprError();
9728
9729  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9730
9731  // Add the functions denoted by the callee to the set of candidate
9732  // functions, including those from argument-dependent lookup.
9733  AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9734                              CandidateSet);
9735
9736  // If we found nothing, try to recover.
9737  // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9738  // out if it fails.
9739  if (CandidateSet.empty()) {
9740    // In Microsoft mode, if we are inside a template class member function then
9741    // create a type dependent CallExpr. The goal is to postpone name lookup
9742    // to instantiation time to be able to search into type dependent base
9743    // classes.
9744    if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
9745        (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
9746      CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9747                                          Context.DependentTy, VK_RValue,
9748                                          RParenLoc);
9749      CE->setTypeDependent(true);
9750      return Owned(CE);
9751    }
9752    return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9753                                 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9754                                 RParenLoc, /*EmptyLookup=*/true,
9755                                 AllowTypoCorrection);
9756  }
9757
9758  UnbridgedCasts.restore();
9759
9760  OverloadCandidateSet::iterator Best;
9761  switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
9762  case OR_Success: {
9763    FunctionDecl *FDecl = Best->Function;
9764    MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9765    CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
9766    DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9767    Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9768    return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9769                                 ExecConfig);
9770  }
9771
9772  case OR_No_Viable_Function: {
9773    // Try to recover by looking for viable functions which the user might
9774    // have meant to call.
9775    ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9776                                  llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9777                                                RParenLoc,
9778                                                /*EmptyLookup=*/false,
9779                                                AllowTypoCorrection);
9780    if (!Recovery.isInvalid())
9781      return Recovery;
9782
9783    Diag(Fn->getLocStart(),
9784         diag::err_ovl_no_viable_function_in_call)
9785      << ULE->getName() << Fn->getSourceRange();
9786    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9787                                llvm::makeArrayRef(Args, NumArgs));
9788    break;
9789  }
9790
9791  case OR_Ambiguous:
9792    Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
9793      << ULE->getName() << Fn->getSourceRange();
9794    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9795                                llvm::makeArrayRef(Args, NumArgs));
9796    break;
9797
9798  case OR_Deleted:
9799    {
9800      Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9801        << Best->Function->isDeleted()
9802        << ULE->getName()
9803        << getDeletedOrUnavailableSuffix(Best->Function)
9804        << Fn->getSourceRange();
9805      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9806                                  llvm::makeArrayRef(Args, NumArgs));
9807
9808      // We emitted an error for the unvailable/deleted function call but keep
9809      // the call in the AST.
9810      FunctionDecl *FDecl = Best->Function;
9811      Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9812      return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9813                                   RParenLoc, ExecConfig);
9814    }
9815  }
9816
9817  // Overload resolution failed.
9818  return ExprError();
9819}
9820
9821static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
9822  return Functions.size() > 1 ||
9823    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9824}
9825
9826/// \brief Create a unary operation that may resolve to an overloaded
9827/// operator.
9828///
9829/// \param OpLoc The location of the operator itself (e.g., '*').
9830///
9831/// \param OpcIn The UnaryOperator::Opcode that describes this
9832/// operator.
9833///
9834/// \param Fns The set of non-member functions that will be
9835/// considered by overload resolution. The caller needs to build this
9836/// set based on the context using, e.g.,
9837/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9838/// set should not contain any member functions; those will be added
9839/// by CreateOverloadedUnaryOp().
9840///
9841/// \param Input The input argument.
9842ExprResult
9843Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9844                              const UnresolvedSetImpl &Fns,
9845                              Expr *Input) {
9846  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
9847
9848  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9849  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9850  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9851  // TODO: provide better source location info.
9852  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
9853
9854  if (checkPlaceholderForOverload(*this, Input))
9855    return ExprError();
9856
9857  Expr *Args[2] = { Input, 0 };
9858  unsigned NumArgs = 1;
9859
9860  // For post-increment and post-decrement, add the implicit '0' as
9861  // the second argument, so that we know this is a post-increment or
9862  // post-decrement.
9863  if (Opc == UO_PostInc || Opc == UO_PostDec) {
9864    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
9865    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9866                                     SourceLocation());
9867    NumArgs = 2;
9868  }
9869
9870  if (Input->isTypeDependent()) {
9871    if (Fns.empty())
9872      return Owned(new (Context) UnaryOperator(Input,
9873                                               Opc,
9874                                               Context.DependentTy,
9875                                               VK_RValue, OK_Ordinary,
9876                                               OpLoc));
9877
9878    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
9879    UnresolvedLookupExpr *Fn
9880      = UnresolvedLookupExpr::Create(Context, NamingClass,
9881                                     NestedNameSpecifierLoc(), OpNameInfo,
9882                                     /*ADL*/ true, IsOverloaded(Fns),
9883                                     Fns.begin(), Fns.end());
9884    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
9885                                                  &Args[0], NumArgs,
9886                                                   Context.DependentTy,
9887                                                   VK_RValue,
9888                                                   OpLoc));
9889  }
9890
9891  // Build an empty overload set.
9892  OverloadCandidateSet CandidateSet(OpLoc);
9893
9894  // Add the candidates from the given function set.
9895  AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9896                        false);
9897
9898  // Add operator candidates that are member functions.
9899  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9900
9901  // Add candidates from ADL.
9902  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9903                                       OpLoc, llvm::makeArrayRef(Args, NumArgs),
9904                                       /*ExplicitTemplateArgs*/ 0,
9905                                       CandidateSet);
9906
9907  // Add builtin operator candidates.
9908  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9909
9910  bool HadMultipleCandidates = (CandidateSet.size() > 1);
9911
9912  // Perform overload resolution.
9913  OverloadCandidateSet::iterator Best;
9914  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
9915  case OR_Success: {
9916    // We found a built-in operator or an overloaded operator.
9917    FunctionDecl *FnDecl = Best->Function;
9918
9919    if (FnDecl) {
9920      // We matched an overloaded operator. Build a call to that
9921      // operator.
9922
9923      MarkFunctionReferenced(OpLoc, FnDecl);
9924
9925      // Convert the arguments.
9926      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
9927        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
9928
9929        ExprResult InputRes =
9930          PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9931                                              Best->FoundDecl, Method);
9932        if (InputRes.isInvalid())
9933          return ExprError();
9934        Input = InputRes.take();
9935      } else {
9936        // Convert the arguments.
9937        ExprResult InputInit
9938          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
9939                                                      Context,
9940                                                      FnDecl->getParamDecl(0)),
9941                                      SourceLocation(),
9942                                      Input);
9943        if (InputInit.isInvalid())
9944          return ExprError();
9945        Input = InputInit.take();
9946      }
9947
9948      DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9949
9950      // Determine the result type.
9951      QualType ResultTy = FnDecl->getResultType();
9952      ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9953      ResultTy = ResultTy.getNonLValueExprType(Context);
9954
9955      // Build the actual expression node.
9956      ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9957                                                HadMultipleCandidates, OpLoc);
9958      if (FnExpr.isInvalid())
9959        return ExprError();
9960
9961      Args[0] = Input;
9962      CallExpr *TheCall =
9963        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
9964                                          Args, NumArgs, ResultTy, VK, OpLoc);
9965
9966      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
9967                              FnDecl))
9968        return ExprError();
9969
9970      return MaybeBindToTemporary(TheCall);
9971    } else {
9972      // We matched a built-in operator. Convert the arguments, then
9973      // break out so that we will build the appropriate built-in
9974      // operator node.
9975      ExprResult InputRes =
9976        PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9977                                  Best->Conversions[0], AA_Passing);
9978      if (InputRes.isInvalid())
9979        return ExprError();
9980      Input = InputRes.take();
9981      break;
9982    }
9983  }
9984
9985  case OR_No_Viable_Function:
9986    // This is an erroneous use of an operator which can be overloaded by
9987    // a non-member function. Check for non-member operators which were
9988    // defined too late to be candidates.
9989    if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9990                                       llvm::makeArrayRef(Args, NumArgs)))
9991      // FIXME: Recover by calling the found function.
9992      return ExprError();
9993
9994    // No viable function; fall through to handling this as a
9995    // built-in operator, which will produce an error message for us.
9996    break;
9997
9998  case OR_Ambiguous:
9999    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10000        << UnaryOperator::getOpcodeStr(Opc)
10001        << Input->getType()
10002        << Input->getSourceRange();
10003    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10004                                llvm::makeArrayRef(Args, NumArgs),
10005                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10006    return ExprError();
10007
10008  case OR_Deleted:
10009    Diag(OpLoc, diag::err_ovl_deleted_oper)
10010      << Best->Function->isDeleted()
10011      << UnaryOperator::getOpcodeStr(Opc)
10012      << getDeletedOrUnavailableSuffix(Best->Function)
10013      << Input->getSourceRange();
10014    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10015                                llvm::makeArrayRef(Args, NumArgs),
10016                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10017    return ExprError();
10018  }
10019
10020  // Either we found no viable overloaded operator or we matched a
10021  // built-in operator. In either case, fall through to trying to
10022  // build a built-in operation.
10023  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10024}
10025
10026/// \brief Create a binary operation that may resolve to an overloaded
10027/// operator.
10028///
10029/// \param OpLoc The location of the operator itself (e.g., '+').
10030///
10031/// \param OpcIn The BinaryOperator::Opcode that describes this
10032/// operator.
10033///
10034/// \param Fns The set of non-member functions that will be
10035/// considered by overload resolution. The caller needs to build this
10036/// set based on the context using, e.g.,
10037/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10038/// set should not contain any member functions; those will be added
10039/// by CreateOverloadedBinOp().
10040///
10041/// \param LHS Left-hand argument.
10042/// \param RHS Right-hand argument.
10043ExprResult
10044Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10045                            unsigned OpcIn,
10046                            const UnresolvedSetImpl &Fns,
10047                            Expr *LHS, Expr *RHS) {
10048  Expr *Args[2] = { LHS, RHS };
10049  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
10050
10051  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10052  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10053  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10054
10055  // If either side is type-dependent, create an appropriate dependent
10056  // expression.
10057  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10058    if (Fns.empty()) {
10059      // If there are no functions to store, just build a dependent
10060      // BinaryOperator or CompoundAssignment.
10061      if (Opc <= BO_Assign || Opc > BO_OrAssign)
10062        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
10063                                                  Context.DependentTy,
10064                                                  VK_RValue, OK_Ordinary,
10065                                                  OpLoc));
10066
10067      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10068                                                        Context.DependentTy,
10069                                                        VK_LValue,
10070                                                        OK_Ordinary,
10071                                                        Context.DependentTy,
10072                                                        Context.DependentTy,
10073                                                        OpLoc));
10074    }
10075
10076    // FIXME: save results of ADL from here?
10077    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10078    // TODO: provide better source location info in DNLoc component.
10079    DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10080    UnresolvedLookupExpr *Fn
10081      = UnresolvedLookupExpr::Create(Context, NamingClass,
10082                                     NestedNameSpecifierLoc(), OpNameInfo,
10083                                     /*ADL*/ true, IsOverloaded(Fns),
10084                                     Fns.begin(), Fns.end());
10085    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
10086                                                   Args, 2,
10087                                                   Context.DependentTy,
10088                                                   VK_RValue,
10089                                                   OpLoc));
10090  }
10091
10092  // Always do placeholder-like conversions on the RHS.
10093  if (checkPlaceholderForOverload(*this, Args[1]))
10094    return ExprError();
10095
10096  // Do placeholder-like conversion on the LHS; note that we should
10097  // not get here with a PseudoObject LHS.
10098  assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10099  if (checkPlaceholderForOverload(*this, Args[0]))
10100    return ExprError();
10101
10102  // If this is the assignment operator, we only perform overload resolution
10103  // if the left-hand side is a class or enumeration type. This is actually
10104  // a hack. The standard requires that we do overload resolution between the
10105  // various built-in candidates, but as DR507 points out, this can lead to
10106  // problems. So we do it this way, which pretty much follows what GCC does.
10107  // Note that we go the traditional code path for compound assignment forms.
10108  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10109    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10110
10111  // If this is the .* operator, which is not overloadable, just
10112  // create a built-in binary operator.
10113  if (Opc == BO_PtrMemD)
10114    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10115
10116  // Build an empty overload set.
10117  OverloadCandidateSet CandidateSet(OpLoc);
10118
10119  // Add the candidates from the given function set.
10120  AddFunctionCandidates(Fns, Args, CandidateSet, false);
10121
10122  // Add operator candidates that are member functions.
10123  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10124
10125  // Add candidates from ADL.
10126  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10127                                       OpLoc, Args,
10128                                       /*ExplicitTemplateArgs*/ 0,
10129                                       CandidateSet);
10130
10131  // Add builtin operator candidates.
10132  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10133
10134  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10135
10136  // Perform overload resolution.
10137  OverloadCandidateSet::iterator Best;
10138  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10139    case OR_Success: {
10140      // We found a built-in operator or an overloaded operator.
10141      FunctionDecl *FnDecl = Best->Function;
10142
10143      if (FnDecl) {
10144        // We matched an overloaded operator. Build a call to that
10145        // operator.
10146
10147        MarkFunctionReferenced(OpLoc, FnDecl);
10148
10149        // Convert the arguments.
10150        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10151          // Best->Access is only meaningful for class members.
10152          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10153
10154          ExprResult Arg1 =
10155            PerformCopyInitialization(
10156              InitializedEntity::InitializeParameter(Context,
10157                                                     FnDecl->getParamDecl(0)),
10158              SourceLocation(), Owned(Args[1]));
10159          if (Arg1.isInvalid())
10160            return ExprError();
10161
10162          ExprResult Arg0 =
10163            PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10164                                                Best->FoundDecl, Method);
10165          if (Arg0.isInvalid())
10166            return ExprError();
10167          Args[0] = Arg0.takeAs<Expr>();
10168          Args[1] = RHS = Arg1.takeAs<Expr>();
10169        } else {
10170          // Convert the arguments.
10171          ExprResult Arg0 = PerformCopyInitialization(
10172            InitializedEntity::InitializeParameter(Context,
10173                                                   FnDecl->getParamDecl(0)),
10174            SourceLocation(), Owned(Args[0]));
10175          if (Arg0.isInvalid())
10176            return ExprError();
10177
10178          ExprResult Arg1 =
10179            PerformCopyInitialization(
10180              InitializedEntity::InitializeParameter(Context,
10181                                                     FnDecl->getParamDecl(1)),
10182              SourceLocation(), Owned(Args[1]));
10183          if (Arg1.isInvalid())
10184            return ExprError();
10185          Args[0] = LHS = Arg0.takeAs<Expr>();
10186          Args[1] = RHS = Arg1.takeAs<Expr>();
10187        }
10188
10189        DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10190
10191        // Determine the result type.
10192        QualType ResultTy = FnDecl->getResultType();
10193        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10194        ResultTy = ResultTy.getNonLValueExprType(Context);
10195
10196        // Build the actual expression node.
10197        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10198                                                  HadMultipleCandidates, OpLoc);
10199        if (FnExpr.isInvalid())
10200          return ExprError();
10201
10202        CXXOperatorCallExpr *TheCall =
10203          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10204                                            Args, 2, ResultTy, VK, OpLoc);
10205
10206        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10207                                FnDecl))
10208          return ExprError();
10209
10210        return MaybeBindToTemporary(TheCall);
10211      } else {
10212        // We matched a built-in operator. Convert the arguments, then
10213        // break out so that we will build the appropriate built-in
10214        // operator node.
10215        ExprResult ArgsRes0 =
10216          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10217                                    Best->Conversions[0], AA_Passing);
10218        if (ArgsRes0.isInvalid())
10219          return ExprError();
10220        Args[0] = ArgsRes0.take();
10221
10222        ExprResult ArgsRes1 =
10223          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10224                                    Best->Conversions[1], AA_Passing);
10225        if (ArgsRes1.isInvalid())
10226          return ExprError();
10227        Args[1] = ArgsRes1.take();
10228        break;
10229      }
10230    }
10231
10232    case OR_No_Viable_Function: {
10233      // C++ [over.match.oper]p9:
10234      //   If the operator is the operator , [...] and there are no
10235      //   viable functions, then the operator is assumed to be the
10236      //   built-in operator and interpreted according to clause 5.
10237      if (Opc == BO_Comma)
10238        break;
10239
10240      // For class as left operand for assignment or compound assigment
10241      // operator do not fall through to handling in built-in, but report that
10242      // no overloaded assignment operator found
10243      ExprResult Result = ExprError();
10244      if (Args[0]->getType()->isRecordType() &&
10245          Opc >= BO_Assign && Opc <= BO_OrAssign) {
10246        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10247             << BinaryOperator::getOpcodeStr(Opc)
10248             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10249      } else {
10250        // This is an erroneous use of an operator which can be overloaded by
10251        // a non-member function. Check for non-member operators which were
10252        // defined too late to be candidates.
10253        if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10254          // FIXME: Recover by calling the found function.
10255          return ExprError();
10256
10257        // No viable function; try to create a built-in operation, which will
10258        // produce an error. Then, show the non-viable candidates.
10259        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10260      }
10261      assert(Result.isInvalid() &&
10262             "C++ binary operator overloading is missing candidates!");
10263      if (Result.isInvalid())
10264        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10265                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
10266      return move(Result);
10267    }
10268
10269    case OR_Ambiguous:
10270      Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10271          << BinaryOperator::getOpcodeStr(Opc)
10272          << Args[0]->getType() << Args[1]->getType()
10273          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10274      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10275                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10276      return ExprError();
10277
10278    case OR_Deleted:
10279      if (isImplicitlyDeleted(Best->Function)) {
10280        CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10281        Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10282          << getSpecialMember(Method)
10283          << BinaryOperator::getOpcodeStr(Opc)
10284          << getDeletedOrUnavailableSuffix(Best->Function);
10285
10286        if (getSpecialMember(Method) != CXXInvalid) {
10287          // The user probably meant to call this special member. Just
10288          // explain why it's deleted.
10289          NoteDeletedFunction(Method);
10290          return ExprError();
10291        }
10292      } else {
10293        Diag(OpLoc, diag::err_ovl_deleted_oper)
10294          << Best->Function->isDeleted()
10295          << BinaryOperator::getOpcodeStr(Opc)
10296          << getDeletedOrUnavailableSuffix(Best->Function)
10297          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10298      }
10299      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10300                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10301      return ExprError();
10302  }
10303
10304  // We matched a built-in operator; build it.
10305  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10306}
10307
10308ExprResult
10309Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10310                                         SourceLocation RLoc,
10311                                         Expr *Base, Expr *Idx) {
10312  Expr *Args[2] = { Base, Idx };
10313  DeclarationName OpName =
10314      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10315
10316  // If either side is type-dependent, create an appropriate dependent
10317  // expression.
10318  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10319
10320    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10321    // CHECKME: no 'operator' keyword?
10322    DeclarationNameInfo OpNameInfo(OpName, LLoc);
10323    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10324    UnresolvedLookupExpr *Fn
10325      = UnresolvedLookupExpr::Create(Context, NamingClass,
10326                                     NestedNameSpecifierLoc(), OpNameInfo,
10327                                     /*ADL*/ true, /*Overloaded*/ false,
10328                                     UnresolvedSetIterator(),
10329                                     UnresolvedSetIterator());
10330    // Can't add any actual overloads yet
10331
10332    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10333                                                   Args, 2,
10334                                                   Context.DependentTy,
10335                                                   VK_RValue,
10336                                                   RLoc));
10337  }
10338
10339  // Handle placeholders on both operands.
10340  if (checkPlaceholderForOverload(*this, Args[0]))
10341    return ExprError();
10342  if (checkPlaceholderForOverload(*this, Args[1]))
10343    return ExprError();
10344
10345  // Build an empty overload set.
10346  OverloadCandidateSet CandidateSet(LLoc);
10347
10348  // Subscript can only be overloaded as a member function.
10349
10350  // Add operator candidates that are member functions.
10351  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10352
10353  // Add builtin operator candidates.
10354  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10355
10356  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10357
10358  // Perform overload resolution.
10359  OverloadCandidateSet::iterator Best;
10360  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10361    case OR_Success: {
10362      // We found a built-in operator or an overloaded operator.
10363      FunctionDecl *FnDecl = Best->Function;
10364
10365      if (FnDecl) {
10366        // We matched an overloaded operator. Build a call to that
10367        // operator.
10368
10369        MarkFunctionReferenced(LLoc, FnDecl);
10370
10371        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10372        DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
10373
10374        // Convert the arguments.
10375        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10376        ExprResult Arg0 =
10377          PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10378                                              Best->FoundDecl, Method);
10379        if (Arg0.isInvalid())
10380          return ExprError();
10381        Args[0] = Arg0.take();
10382
10383        // Convert the arguments.
10384        ExprResult InputInit
10385          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10386                                                      Context,
10387                                                      FnDecl->getParamDecl(0)),
10388                                      SourceLocation(),
10389                                      Owned(Args[1]));
10390        if (InputInit.isInvalid())
10391          return ExprError();
10392
10393        Args[1] = InputInit.takeAs<Expr>();
10394
10395        // Determine the result type
10396        QualType ResultTy = FnDecl->getResultType();
10397        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10398        ResultTy = ResultTy.getNonLValueExprType(Context);
10399
10400        // Build the actual expression node.
10401        DeclarationNameInfo OpLocInfo(OpName, LLoc);
10402        OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10403        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10404                                                  HadMultipleCandidates,
10405                                                  OpLocInfo.getLoc(),
10406                                                  OpLocInfo.getInfo());
10407        if (FnExpr.isInvalid())
10408          return ExprError();
10409
10410        CXXOperatorCallExpr *TheCall =
10411          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10412                                            FnExpr.take(), Args, 2,
10413                                            ResultTy, VK, RLoc);
10414
10415        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10416                                FnDecl))
10417          return ExprError();
10418
10419        return MaybeBindToTemporary(TheCall);
10420      } else {
10421        // We matched a built-in operator. Convert the arguments, then
10422        // break out so that we will build the appropriate built-in
10423        // operator node.
10424        ExprResult ArgsRes0 =
10425          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10426                                    Best->Conversions[0], AA_Passing);
10427        if (ArgsRes0.isInvalid())
10428          return ExprError();
10429        Args[0] = ArgsRes0.take();
10430
10431        ExprResult ArgsRes1 =
10432          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10433                                    Best->Conversions[1], AA_Passing);
10434        if (ArgsRes1.isInvalid())
10435          return ExprError();
10436        Args[1] = ArgsRes1.take();
10437
10438        break;
10439      }
10440    }
10441
10442    case OR_No_Viable_Function: {
10443      if (CandidateSet.empty())
10444        Diag(LLoc, diag::err_ovl_no_oper)
10445          << Args[0]->getType() << /*subscript*/ 0
10446          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10447      else
10448        Diag(LLoc, diag::err_ovl_no_viable_subscript)
10449          << Args[0]->getType()
10450          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10451      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10452                                  "[]", LLoc);
10453      return ExprError();
10454    }
10455
10456    case OR_Ambiguous:
10457      Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10458          << "[]"
10459          << Args[0]->getType() << Args[1]->getType()
10460          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10461      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10462                                  "[]", LLoc);
10463      return ExprError();
10464
10465    case OR_Deleted:
10466      Diag(LLoc, diag::err_ovl_deleted_oper)
10467        << Best->Function->isDeleted() << "[]"
10468        << getDeletedOrUnavailableSuffix(Best->Function)
10469        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10470      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10471                                  "[]", LLoc);
10472      return ExprError();
10473    }
10474
10475  // We matched a built-in operator; build it.
10476  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10477}
10478
10479/// BuildCallToMemberFunction - Build a call to a member
10480/// function. MemExpr is the expression that refers to the member
10481/// function (and includes the object parameter), Args/NumArgs are the
10482/// arguments to the function call (not including the object
10483/// parameter). The caller needs to validate that the member
10484/// expression refers to a non-static member function or an overloaded
10485/// member function.
10486ExprResult
10487Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10488                                SourceLocation LParenLoc, Expr **Args,
10489                                unsigned NumArgs, SourceLocation RParenLoc) {
10490  assert(MemExprE->getType() == Context.BoundMemberTy ||
10491         MemExprE->getType() == Context.OverloadTy);
10492
10493  // Dig out the member expression. This holds both the object
10494  // argument and the member function we're referring to.
10495  Expr *NakedMemExpr = MemExprE->IgnoreParens();
10496
10497  // Determine whether this is a call to a pointer-to-member function.
10498  if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10499    assert(op->getType() == Context.BoundMemberTy);
10500    assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10501
10502    QualType fnType =
10503      op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10504
10505    const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10506    QualType resultType = proto->getCallResultType(Context);
10507    ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10508
10509    // Check that the object type isn't more qualified than the
10510    // member function we're calling.
10511    Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10512
10513    QualType objectType = op->getLHS()->getType();
10514    if (op->getOpcode() == BO_PtrMemI)
10515      objectType = objectType->castAs<PointerType>()->getPointeeType();
10516    Qualifiers objectQuals = objectType.getQualifiers();
10517
10518    Qualifiers difference = objectQuals - funcQuals;
10519    difference.removeObjCGCAttr();
10520    difference.removeAddressSpace();
10521    if (difference) {
10522      std::string qualsString = difference.getAsString();
10523      Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10524        << fnType.getUnqualifiedType()
10525        << qualsString
10526        << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10527    }
10528
10529    CXXMemberCallExpr *call
10530      = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10531                                        resultType, valueKind, RParenLoc);
10532
10533    if (CheckCallReturnType(proto->getResultType(),
10534                            op->getRHS()->getLocStart(),
10535                            call, 0))
10536      return ExprError();
10537
10538    if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10539      return ExprError();
10540
10541    return MaybeBindToTemporary(call);
10542  }
10543
10544  UnbridgedCastsSet UnbridgedCasts;
10545  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10546    return ExprError();
10547
10548  MemberExpr *MemExpr;
10549  CXXMethodDecl *Method = 0;
10550  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
10551  NestedNameSpecifier *Qualifier = 0;
10552  if (isa<MemberExpr>(NakedMemExpr)) {
10553    MemExpr = cast<MemberExpr>(NakedMemExpr);
10554    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
10555    FoundDecl = MemExpr->getFoundDecl();
10556    Qualifier = MemExpr->getQualifier();
10557    UnbridgedCasts.restore();
10558  } else {
10559    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
10560    Qualifier = UnresExpr->getQualifier();
10561
10562    QualType ObjectType = UnresExpr->getBaseType();
10563    Expr::Classification ObjectClassification
10564      = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10565                            : UnresExpr->getBase()->Classify(Context);
10566
10567    // Add overload candidates
10568    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
10569
10570    // FIXME: avoid copy.
10571    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10572    if (UnresExpr->hasExplicitTemplateArgs()) {
10573      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10574      TemplateArgs = &TemplateArgsBuffer;
10575    }
10576
10577    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10578           E = UnresExpr->decls_end(); I != E; ++I) {
10579
10580      NamedDecl *Func = *I;
10581      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10582      if (isa<UsingShadowDecl>(Func))
10583        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10584
10585
10586      // Microsoft supports direct constructor calls.
10587      if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
10588        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10589                             llvm::makeArrayRef(Args, NumArgs), CandidateSet);
10590      } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
10591        // If explicit template arguments were provided, we can't call a
10592        // non-template member function.
10593        if (TemplateArgs)
10594          continue;
10595
10596        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
10597                           ObjectClassification,
10598                           llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10599                           /*SuppressUserConversions=*/false);
10600      } else {
10601        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
10602                                   I.getPair(), ActingDC, TemplateArgs,
10603                                   ObjectType,  ObjectClassification,
10604                                   llvm::makeArrayRef(Args, NumArgs),
10605                                   CandidateSet,
10606                                   /*SuppressUsedConversions=*/false);
10607      }
10608    }
10609
10610    DeclarationName DeclName = UnresExpr->getMemberName();
10611
10612    UnbridgedCasts.restore();
10613
10614    OverloadCandidateSet::iterator Best;
10615    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
10616                                            Best)) {
10617    case OR_Success:
10618      Method = cast<CXXMethodDecl>(Best->Function);
10619      MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
10620      FoundDecl = Best->FoundDecl;
10621      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
10622      DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
10623      break;
10624
10625    case OR_No_Viable_Function:
10626      Diag(UnresExpr->getMemberLoc(),
10627           diag::err_ovl_no_viable_member_function_in_call)
10628        << DeclName << MemExprE->getSourceRange();
10629      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10630                                  llvm::makeArrayRef(Args, NumArgs));
10631      // FIXME: Leaking incoming expressions!
10632      return ExprError();
10633
10634    case OR_Ambiguous:
10635      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
10636        << DeclName << MemExprE->getSourceRange();
10637      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10638                                  llvm::makeArrayRef(Args, NumArgs));
10639      // FIXME: Leaking incoming expressions!
10640      return ExprError();
10641
10642    case OR_Deleted:
10643      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
10644        << Best->Function->isDeleted()
10645        << DeclName
10646        << getDeletedOrUnavailableSuffix(Best->Function)
10647        << MemExprE->getSourceRange();
10648      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10649                                  llvm::makeArrayRef(Args, NumArgs));
10650      // FIXME: Leaking incoming expressions!
10651      return ExprError();
10652    }
10653
10654    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
10655
10656    // If overload resolution picked a static member, build a
10657    // non-member call based on that function.
10658    if (Method->isStatic()) {
10659      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10660                                   Args, NumArgs, RParenLoc);
10661    }
10662
10663    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
10664  }
10665
10666  QualType ResultType = Method->getResultType();
10667  ExprValueKind VK = Expr::getValueKindForType(ResultType);
10668  ResultType = ResultType.getNonLValueExprType(Context);
10669
10670  assert(Method && "Member call to something that isn't a method?");
10671  CXXMemberCallExpr *TheCall =
10672    new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10673                                    ResultType, VK, RParenLoc);
10674
10675  // Check for a valid return type.
10676  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
10677                          TheCall, Method))
10678    return ExprError();
10679
10680  // Convert the object argument (for a non-static member function call).
10681  // We only need to do this if there was actually an overload; otherwise
10682  // it was done at lookup.
10683  if (!Method->isStatic()) {
10684    ExprResult ObjectArg =
10685      PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10686                                          FoundDecl, Method);
10687    if (ObjectArg.isInvalid())
10688      return ExprError();
10689    MemExpr->setBase(ObjectArg.take());
10690  }
10691
10692  // Convert the rest of the arguments
10693  const FunctionProtoType *Proto =
10694    Method->getType()->getAs<FunctionProtoType>();
10695  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
10696                              RParenLoc))
10697    return ExprError();
10698
10699  DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10700
10701  if (CheckFunctionCall(Method, TheCall, Proto))
10702    return ExprError();
10703
10704  if ((isa<CXXConstructorDecl>(CurContext) ||
10705       isa<CXXDestructorDecl>(CurContext)) &&
10706      TheCall->getMethodDecl()->isPure()) {
10707    const CXXMethodDecl *MD = TheCall->getMethodDecl();
10708
10709    if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
10710      Diag(MemExpr->getLocStart(),
10711           diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10712        << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10713        << MD->getParent()->getDeclName();
10714
10715      Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
10716    }
10717  }
10718  return MaybeBindToTemporary(TheCall);
10719}
10720
10721/// BuildCallToObjectOfClassType - Build a call to an object of class
10722/// type (C++ [over.call.object]), which can end up invoking an
10723/// overloaded function call operator (@c operator()) or performing a
10724/// user-defined conversion on the object argument.
10725ExprResult
10726Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
10727                                   SourceLocation LParenLoc,
10728                                   Expr **Args, unsigned NumArgs,
10729                                   SourceLocation RParenLoc) {
10730  if (checkPlaceholderForOverload(*this, Obj))
10731    return ExprError();
10732  ExprResult Object = Owned(Obj);
10733
10734  UnbridgedCastsSet UnbridgedCasts;
10735  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10736    return ExprError();
10737
10738  assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10739  const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
10740
10741  // C++ [over.call.object]p1:
10742  //  If the primary-expression E in the function call syntax
10743  //  evaluates to a class object of type "cv T", then the set of
10744  //  candidate functions includes at least the function call
10745  //  operators of T. The function call operators of T are obtained by
10746  //  ordinary lookup of the name operator() in the context of
10747  //  (E).operator().
10748  OverloadCandidateSet CandidateSet(LParenLoc);
10749  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
10750
10751  if (RequireCompleteType(LParenLoc, Object.get()->getType(),
10752                          diag::err_incomplete_object_call, Object.get()))
10753    return true;
10754
10755  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10756  LookupQualifiedName(R, Record->getDecl());
10757  R.suppressDiagnostics();
10758
10759  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10760       Oper != OperEnd; ++Oper) {
10761    AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10762                       Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
10763                       /*SuppressUserConversions=*/ false);
10764  }
10765
10766  // C++ [over.call.object]p2:
10767  //   In addition, for each (non-explicit in C++0x) conversion function
10768  //   declared in T of the form
10769  //
10770  //        operator conversion-type-id () cv-qualifier;
10771  //
10772  //   where cv-qualifier is the same cv-qualification as, or a
10773  //   greater cv-qualification than, cv, and where conversion-type-id
10774  //   denotes the type "pointer to function of (P1,...,Pn) returning
10775  //   R", or the type "reference to pointer to function of
10776  //   (P1,...,Pn) returning R", or the type "reference to function
10777  //   of (P1,...,Pn) returning R", a surrogate call function [...]
10778  //   is also considered as a candidate function. Similarly,
10779  //   surrogate call functions are added to the set of candidate
10780  //   functions for each conversion function declared in an
10781  //   accessible base class provided the function is not hidden
10782  //   within T by another intervening declaration.
10783  const UnresolvedSetImpl *Conversions
10784    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
10785  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
10786         E = Conversions->end(); I != E; ++I) {
10787    NamedDecl *D = *I;
10788    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10789    if (isa<UsingShadowDecl>(D))
10790      D = cast<UsingShadowDecl>(D)->getTargetDecl();
10791
10792    // Skip over templated conversion functions; they aren't
10793    // surrogates.
10794    if (isa<FunctionTemplateDecl>(D))
10795      continue;
10796
10797    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
10798    if (!Conv->isExplicit()) {
10799      // Strip the reference type (if any) and then the pointer type (if
10800      // any) to get down to what might be a function type.
10801      QualType ConvType = Conv->getConversionType().getNonReferenceType();
10802      if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10803        ConvType = ConvPtrType->getPointeeType();
10804
10805      if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10806      {
10807        AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10808                              Object.get(), llvm::makeArrayRef(Args, NumArgs),
10809                              CandidateSet);
10810      }
10811    }
10812  }
10813
10814  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10815
10816  // Perform overload resolution.
10817  OverloadCandidateSet::iterator Best;
10818  switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
10819                             Best)) {
10820  case OR_Success:
10821    // Overload resolution succeeded; we'll build the appropriate call
10822    // below.
10823    break;
10824
10825  case OR_No_Viable_Function:
10826    if (CandidateSet.empty())
10827      Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
10828        << Object.get()->getType() << /*call*/ 1
10829        << Object.get()->getSourceRange();
10830    else
10831      Diag(Object.get()->getLocStart(),
10832           diag::err_ovl_no_viable_object_call)
10833        << Object.get()->getType() << Object.get()->getSourceRange();
10834    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10835                                llvm::makeArrayRef(Args, NumArgs));
10836    break;
10837
10838  case OR_Ambiguous:
10839    Diag(Object.get()->getLocStart(),
10840         diag::err_ovl_ambiguous_object_call)
10841      << Object.get()->getType() << Object.get()->getSourceRange();
10842    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10843                                llvm::makeArrayRef(Args, NumArgs));
10844    break;
10845
10846  case OR_Deleted:
10847    Diag(Object.get()->getLocStart(),
10848         diag::err_ovl_deleted_object_call)
10849      << Best->Function->isDeleted()
10850      << Object.get()->getType()
10851      << getDeletedOrUnavailableSuffix(Best->Function)
10852      << Object.get()->getSourceRange();
10853    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10854                                llvm::makeArrayRef(Args, NumArgs));
10855    break;
10856  }
10857
10858  if (Best == CandidateSet.end())
10859    return true;
10860
10861  UnbridgedCasts.restore();
10862
10863  if (Best->Function == 0) {
10864    // Since there is no function declaration, this is one of the
10865    // surrogate candidates. Dig out the conversion function.
10866    CXXConversionDecl *Conv
10867      = cast<CXXConversionDecl>(
10868                         Best->Conversions[0].UserDefined.ConversionFunction);
10869
10870    CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
10871    DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
10872
10873    // We selected one of the surrogate functions that converts the
10874    // object parameter to a function pointer. Perform the conversion
10875    // on the object argument, then let ActOnCallExpr finish the job.
10876
10877    // Create an implicit member expr to refer to the conversion operator.
10878    // and then call it.
10879    ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10880                                             Conv, HadMultipleCandidates);
10881    if (Call.isInvalid())
10882      return ExprError();
10883    // Record usage of conversion in an implicit cast.
10884    Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10885                                          CK_UserDefinedConversion,
10886                                          Call.get(), 0, VK_RValue));
10887
10888    return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
10889                         RParenLoc);
10890  }
10891
10892  MarkFunctionReferenced(LParenLoc, Best->Function);
10893  CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
10894  DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
10895
10896  // We found an overloaded operator(). Build a CXXOperatorCallExpr
10897  // that calls this method, using Object for the implicit object
10898  // parameter and passing along the remaining arguments.
10899  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10900  const FunctionProtoType *Proto =
10901    Method->getType()->getAs<FunctionProtoType>();
10902
10903  unsigned NumArgsInProto = Proto->getNumArgs();
10904  unsigned NumArgsToCheck = NumArgs;
10905
10906  // Build the full argument list for the method call (the
10907  // implicit object parameter is placed at the beginning of the
10908  // list).
10909  Expr **MethodArgs;
10910  if (NumArgs < NumArgsInProto) {
10911    NumArgsToCheck = NumArgsInProto;
10912    MethodArgs = new Expr*[NumArgsInProto + 1];
10913  } else {
10914    MethodArgs = new Expr*[NumArgs + 1];
10915  }
10916  MethodArgs[0] = Object.get();
10917  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10918    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
10919
10920  DeclarationNameInfo OpLocInfo(
10921               Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10922  OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
10923  ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10924                                           HadMultipleCandidates,
10925                                           OpLocInfo.getLoc(),
10926                                           OpLocInfo.getInfo());
10927  if (NewFn.isInvalid())
10928    return true;
10929
10930  // Once we've built TheCall, all of the expressions are properly
10931  // owned.
10932  QualType ResultTy = Method->getResultType();
10933  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10934  ResultTy = ResultTy.getNonLValueExprType(Context);
10935
10936  CXXOperatorCallExpr *TheCall =
10937    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
10938                                      MethodArgs, NumArgs + 1,
10939                                      ResultTy, VK, RParenLoc);
10940  delete [] MethodArgs;
10941
10942  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
10943                          Method))
10944    return true;
10945
10946  // We may have default arguments. If so, we need to allocate more
10947  // slots in the call for them.
10948  if (NumArgs < NumArgsInProto)
10949    TheCall->setNumArgs(Context, NumArgsInProto + 1);
10950  else if (NumArgs > NumArgsInProto)
10951    NumArgsToCheck = NumArgsInProto;
10952
10953  bool IsError = false;
10954
10955  // Initialize the implicit object parameter.
10956  ExprResult ObjRes =
10957    PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10958                                        Best->FoundDecl, Method);
10959  if (ObjRes.isInvalid())
10960    IsError = true;
10961  else
10962    Object = move(ObjRes);
10963  TheCall->setArg(0, Object.take());
10964
10965  // Check the argument types.
10966  for (unsigned i = 0; i != NumArgsToCheck; i++) {
10967    Expr *Arg;
10968    if (i < NumArgs) {
10969      Arg = Args[i];
10970
10971      // Pass the argument.
10972
10973      ExprResult InputInit
10974        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10975                                                    Context,
10976                                                    Method->getParamDecl(i)),
10977                                    SourceLocation(), Arg);
10978
10979      IsError |= InputInit.isInvalid();
10980      Arg = InputInit.takeAs<Expr>();
10981    } else {
10982      ExprResult DefArg
10983        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10984      if (DefArg.isInvalid()) {
10985        IsError = true;
10986        break;
10987      }
10988
10989      Arg = DefArg.takeAs<Expr>();
10990    }
10991
10992    TheCall->setArg(i + 1, Arg);
10993  }
10994
10995  // If this is a variadic call, handle args passed through "...".
10996  if (Proto->isVariadic()) {
10997    // Promote the arguments (C99 6.5.2.2p7).
10998    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
10999      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11000      IsError |= Arg.isInvalid();
11001      TheCall->setArg(i + 1, Arg.take());
11002    }
11003  }
11004
11005  if (IsError) return true;
11006
11007  DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11008
11009  if (CheckFunctionCall(Method, TheCall, Proto))
11010    return true;
11011
11012  return MaybeBindToTemporary(TheCall);
11013}
11014
11015/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11016///  (if one exists), where @c Base is an expression of class type and
11017/// @c Member is the name of the member we're trying to find.
11018ExprResult
11019Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
11020  assert(Base->getType()->isRecordType() &&
11021         "left-hand side must have class type");
11022
11023  if (checkPlaceholderForOverload(*this, Base))
11024    return ExprError();
11025
11026  SourceLocation Loc = Base->getExprLoc();
11027
11028  // C++ [over.ref]p1:
11029  //
11030  //   [...] An expression x->m is interpreted as (x.operator->())->m
11031  //   for a class object x of type T if T::operator->() exists and if
11032  //   the operator is selected as the best match function by the
11033  //   overload resolution mechanism (13.3).
11034  DeclarationName OpName =
11035    Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11036  OverloadCandidateSet CandidateSet(Loc);
11037  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11038
11039  if (RequireCompleteType(Loc, Base->getType(),
11040                          diag::err_typecheck_incomplete_tag, Base))
11041    return ExprError();
11042
11043  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11044  LookupQualifiedName(R, BaseRecord->getDecl());
11045  R.suppressDiagnostics();
11046
11047  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11048       Oper != OperEnd; ++Oper) {
11049    AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11050                       0, 0, CandidateSet, /*SuppressUserConversions=*/false);
11051  }
11052
11053  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11054
11055  // Perform overload resolution.
11056  OverloadCandidateSet::iterator Best;
11057  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11058  case OR_Success:
11059    // Overload resolution succeeded; we'll build the call below.
11060    break;
11061
11062  case OR_No_Viable_Function:
11063    if (CandidateSet.empty())
11064      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11065        << Base->getType() << Base->getSourceRange();
11066    else
11067      Diag(OpLoc, diag::err_ovl_no_viable_oper)
11068        << "operator->" << Base->getSourceRange();
11069    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11070    return ExprError();
11071
11072  case OR_Ambiguous:
11073    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11074      << "->" << Base->getType() << Base->getSourceRange();
11075    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11076    return ExprError();
11077
11078  case OR_Deleted:
11079    Diag(OpLoc,  diag::err_ovl_deleted_oper)
11080      << Best->Function->isDeleted()
11081      << "->"
11082      << getDeletedOrUnavailableSuffix(Best->Function)
11083      << Base->getSourceRange();
11084    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11085    return ExprError();
11086  }
11087
11088  MarkFunctionReferenced(OpLoc, Best->Function);
11089  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11090  DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
11091
11092  // Convert the object parameter.
11093  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11094  ExprResult BaseResult =
11095    PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11096                                        Best->FoundDecl, Method);
11097  if (BaseResult.isInvalid())
11098    return ExprError();
11099  Base = BaseResult.take();
11100
11101  // Build the operator call.
11102  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
11103                                            HadMultipleCandidates, OpLoc);
11104  if (FnExpr.isInvalid())
11105    return ExprError();
11106
11107  QualType ResultTy = Method->getResultType();
11108  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11109  ResultTy = ResultTy.getNonLValueExprType(Context);
11110  CXXOperatorCallExpr *TheCall =
11111    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11112                                      &Base, 1, ResultTy, VK, OpLoc);
11113
11114  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11115                          Method))
11116          return ExprError();
11117
11118  return MaybeBindToTemporary(TheCall);
11119}
11120
11121/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11122/// a literal operator described by the provided lookup results.
11123ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11124                                          DeclarationNameInfo &SuffixInfo,
11125                                          ArrayRef<Expr*> Args,
11126                                          SourceLocation LitEndLoc,
11127                                       TemplateArgumentListInfo *TemplateArgs) {
11128  SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11129
11130  OverloadCandidateSet CandidateSet(UDSuffixLoc);
11131  AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11132                        TemplateArgs);
11133
11134  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11135
11136  // Perform overload resolution. This will usually be trivial, but might need
11137  // to perform substitutions for a literal operator template.
11138  OverloadCandidateSet::iterator Best;
11139  switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11140  case OR_Success:
11141  case OR_Deleted:
11142    break;
11143
11144  case OR_No_Viable_Function:
11145    Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11146      << R.getLookupName();
11147    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11148    return ExprError();
11149
11150  case OR_Ambiguous:
11151    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11152    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11153    return ExprError();
11154  }
11155
11156  FunctionDecl *FD = Best->Function;
11157  MarkFunctionReferenced(UDSuffixLoc, FD);
11158  DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
11159
11160  ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11161                                        SuffixInfo.getLoc(),
11162                                        SuffixInfo.getInfo());
11163  if (Fn.isInvalid())
11164    return true;
11165
11166  // Check the argument types. This should almost always be a no-op, except
11167  // that array-to-pointer decay is applied to string literals.
11168  Expr *ConvArgs[2];
11169  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11170    ExprResult InputInit = PerformCopyInitialization(
11171      InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11172      SourceLocation(), Args[ArgIdx]);
11173    if (InputInit.isInvalid())
11174      return true;
11175    ConvArgs[ArgIdx] = InputInit.take();
11176  }
11177
11178  QualType ResultTy = FD->getResultType();
11179  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11180  ResultTy = ResultTy.getNonLValueExprType(Context);
11181
11182  UserDefinedLiteral *UDL =
11183    new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11184                                     ResultTy, VK, LitEndLoc, UDSuffixLoc);
11185
11186  if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11187    return ExprError();
11188
11189  if (CheckFunctionCall(FD, UDL, NULL))
11190    return ExprError();
11191
11192  return MaybeBindToTemporary(UDL);
11193}
11194
11195/// FixOverloadedFunctionReference - E is an expression that refers to
11196/// a C++ overloaded function (possibly with some parentheses and
11197/// perhaps a '&' around it). We have resolved the overloaded function
11198/// to the function declaration Fn, so patch up the expression E to
11199/// refer (possibly indirectly) to Fn. Returns the new expr.
11200Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11201                                           FunctionDecl *Fn) {
11202  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11203    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11204                                                   Found, Fn);
11205    if (SubExpr == PE->getSubExpr())
11206      return PE;
11207
11208    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11209  }
11210
11211  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11212    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11213                                                   Found, Fn);
11214    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11215                               SubExpr->getType()) &&
11216           "Implicit cast type cannot be determined from overload");
11217    assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11218    if (SubExpr == ICE->getSubExpr())
11219      return ICE;
11220
11221    return ImplicitCastExpr::Create(Context, ICE->getType(),
11222                                    ICE->getCastKind(),
11223                                    SubExpr, 0,
11224                                    ICE->getValueKind());
11225  }
11226
11227  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11228    assert(UnOp->getOpcode() == UO_AddrOf &&
11229           "Can only take the address of an overloaded function");
11230    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11231      if (Method->isStatic()) {
11232        // Do nothing: static member functions aren't any different
11233        // from non-member functions.
11234      } else {
11235        // Fix the sub expression, which really has to be an
11236        // UnresolvedLookupExpr holding an overloaded member function
11237        // or template.
11238        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11239                                                       Found, Fn);
11240        if (SubExpr == UnOp->getSubExpr())
11241          return UnOp;
11242
11243        assert(isa<DeclRefExpr>(SubExpr)
11244               && "fixed to something other than a decl ref");
11245        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11246               && "fixed to a member ref with no nested name qualifier");
11247
11248        // We have taken the address of a pointer to member
11249        // function. Perform the computation here so that we get the
11250        // appropriate pointer to member type.
11251        QualType ClassType
11252          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11253        QualType MemPtrType
11254          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11255
11256        return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11257                                           VK_RValue, OK_Ordinary,
11258                                           UnOp->getOperatorLoc());
11259      }
11260    }
11261    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11262                                                   Found, Fn);
11263    if (SubExpr == UnOp->getSubExpr())
11264      return UnOp;
11265
11266    return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11267                                     Context.getPointerType(SubExpr->getType()),
11268                                       VK_RValue, OK_Ordinary,
11269                                       UnOp->getOperatorLoc());
11270  }
11271
11272  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11273    // FIXME: avoid copy.
11274    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11275    if (ULE->hasExplicitTemplateArgs()) {
11276      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11277      TemplateArgs = &TemplateArgsBuffer;
11278    }
11279
11280    DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11281                                           ULE->getQualifierLoc(),
11282                                           ULE->getTemplateKeywordLoc(),
11283                                           Fn,
11284                                           /*enclosing*/ false, // FIXME?
11285                                           ULE->getNameLoc(),
11286                                           Fn->getType(),
11287                                           VK_LValue,
11288                                           Found.getDecl(),
11289                                           TemplateArgs);
11290    MarkDeclRefReferenced(DRE);
11291    DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11292    return DRE;
11293  }
11294
11295  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11296    // FIXME: avoid copy.
11297    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11298    if (MemExpr->hasExplicitTemplateArgs()) {
11299      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11300      TemplateArgs = &TemplateArgsBuffer;
11301    }
11302
11303    Expr *Base;
11304
11305    // If we're filling in a static method where we used to have an
11306    // implicit member access, rewrite to a simple decl ref.
11307    if (MemExpr->isImplicitAccess()) {
11308      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11309        DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11310                                               MemExpr->getQualifierLoc(),
11311                                               MemExpr->getTemplateKeywordLoc(),
11312                                               Fn,
11313                                               /*enclosing*/ false,
11314                                               MemExpr->getMemberLoc(),
11315                                               Fn->getType(),
11316                                               VK_LValue,
11317                                               Found.getDecl(),
11318                                               TemplateArgs);
11319        MarkDeclRefReferenced(DRE);
11320        DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11321        return DRE;
11322      } else {
11323        SourceLocation Loc = MemExpr->getMemberLoc();
11324        if (MemExpr->getQualifier())
11325          Loc = MemExpr->getQualifierLoc().getBeginLoc();
11326        CheckCXXThisCapture(Loc);
11327        Base = new (Context) CXXThisExpr(Loc,
11328                                         MemExpr->getBaseType(),
11329                                         /*isImplicit=*/true);
11330      }
11331    } else
11332      Base = MemExpr->getBase();
11333
11334    ExprValueKind valueKind;
11335    QualType type;
11336    if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11337      valueKind = VK_LValue;
11338      type = Fn->getType();
11339    } else {
11340      valueKind = VK_RValue;
11341      type = Context.BoundMemberTy;
11342    }
11343
11344    MemberExpr *ME = MemberExpr::Create(Context, Base,
11345                                        MemExpr->isArrow(),
11346                                        MemExpr->getQualifierLoc(),
11347                                        MemExpr->getTemplateKeywordLoc(),
11348                                        Fn,
11349                                        Found,
11350                                        MemExpr->getMemberNameInfo(),
11351                                        TemplateArgs,
11352                                        type, valueKind, OK_Ordinary);
11353    ME->setHadMultipleCandidates(true);
11354    return ME;
11355  }
11356
11357  llvm_unreachable("Invalid reference to overloaded function");
11358}
11359
11360ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11361                                                DeclAccessPair Found,
11362                                                FunctionDecl *Fn) {
11363  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11364}
11365
11366} // end namespace clang
11367