SemaOverload.cpp revision f5a6aefa37d73fff3c47953e2c447f074e726a0e
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/Overload.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/AST/TypeOrdering.h"
22#include "clang/Basic/Diagnostic.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
30#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallString.h"
34#include <algorithm>
35
36namespace clang {
37using namespace sema;
38
39/// A convenience routine for creating a decayed reference to a function.
40static ExprResult
41CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
42                      bool HadMultipleCandidates,
43                      SourceLocation Loc = SourceLocation(),
44                      const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
45  DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
46                                                 VK_LValue, Loc, LocInfo);
47  if (HadMultipleCandidates)
48    DRE->setHadMultipleCandidates(true);
49
50  S.MarkDeclRefReferenced(DRE);
51  S.DiagnoseUseOfDecl(FoundDecl, Loc);
52
53  ExprResult E = S.Owned(DRE);
54  E = S.DefaultFunctionArrayConversion(E.take());
55  if (E.isInvalid())
56    return ExprError();
57  return E;
58}
59
60static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
61                                 bool InOverloadResolution,
62                                 StandardConversionSequence &SCS,
63                                 bool CStyle,
64                                 bool AllowObjCWritebackConversion);
65
66static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
67                                                 QualType &ToType,
68                                                 bool InOverloadResolution,
69                                                 StandardConversionSequence &SCS,
70                                                 bool CStyle);
71static OverloadingResult
72IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
73                        UserDefinedConversionSequence& User,
74                        OverloadCandidateSet& Conversions,
75                        bool AllowExplicit);
76
77
78static ImplicitConversionSequence::CompareKind
79CompareStandardConversionSequences(Sema &S,
80                                   const StandardConversionSequence& SCS1,
81                                   const StandardConversionSequence& SCS2);
82
83static ImplicitConversionSequence::CompareKind
84CompareQualificationConversions(Sema &S,
85                                const StandardConversionSequence& SCS1,
86                                const StandardConversionSequence& SCS2);
87
88static ImplicitConversionSequence::CompareKind
89CompareDerivedToBaseConversions(Sema &S,
90                                const StandardConversionSequence& SCS1,
91                                const StandardConversionSequence& SCS2);
92
93
94
95/// GetConversionCategory - Retrieve the implicit conversion
96/// category corresponding to the given implicit conversion kind.
97ImplicitConversionCategory
98GetConversionCategory(ImplicitConversionKind Kind) {
99  static const ImplicitConversionCategory
100    Category[(int)ICK_Num_Conversion_Kinds] = {
101    ICC_Identity,
102    ICC_Lvalue_Transformation,
103    ICC_Lvalue_Transformation,
104    ICC_Lvalue_Transformation,
105    ICC_Identity,
106    ICC_Qualification_Adjustment,
107    ICC_Promotion,
108    ICC_Promotion,
109    ICC_Promotion,
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    ICC_Conversion,
119    ICC_Conversion,
120    ICC_Conversion,
121    ICC_Conversion,
122    ICC_Conversion
123  };
124  return Category[(int)Kind];
125}
126
127/// GetConversionRank - Retrieve the implicit conversion rank
128/// corresponding to the given implicit conversion kind.
129ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
130  static const ImplicitConversionRank
131    Rank[(int)ICK_Num_Conversion_Kinds] = {
132    ICR_Exact_Match,
133    ICR_Exact_Match,
134    ICR_Exact_Match,
135    ICR_Exact_Match,
136    ICR_Exact_Match,
137    ICR_Exact_Match,
138    ICR_Promotion,
139    ICR_Promotion,
140    ICR_Promotion,
141    ICR_Conversion,
142    ICR_Conversion,
143    ICR_Conversion,
144    ICR_Conversion,
145    ICR_Conversion,
146    ICR_Conversion,
147    ICR_Conversion,
148    ICR_Conversion,
149    ICR_Conversion,
150    ICR_Conversion,
151    ICR_Conversion,
152    ICR_Complex_Real_Conversion,
153    ICR_Conversion,
154    ICR_Conversion,
155    ICR_Writeback_Conversion
156  };
157  return Rank[(int)Kind];
158}
159
160/// GetImplicitConversionName - Return the name of this kind of
161/// implicit conversion.
162const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
163  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
164    "No conversion",
165    "Lvalue-to-rvalue",
166    "Array-to-pointer",
167    "Function-to-pointer",
168    "Noreturn adjustment",
169    "Qualification",
170    "Integral promotion",
171    "Floating point promotion",
172    "Complex promotion",
173    "Integral conversion",
174    "Floating conversion",
175    "Complex conversion",
176    "Floating-integral conversion",
177    "Pointer conversion",
178    "Pointer-to-member conversion",
179    "Boolean conversion",
180    "Compatible-types conversion",
181    "Derived-to-base conversion",
182    "Vector conversion",
183    "Vector splat",
184    "Complex-real conversion",
185    "Block Pointer conversion",
186    "Transparent Union Conversion"
187    "Writeback conversion"
188  };
189  return Name[Kind];
190}
191
192/// StandardConversionSequence - Set the standard conversion
193/// sequence to the identity conversion.
194void StandardConversionSequence::setAsIdentityConversion() {
195  First = ICK_Identity;
196  Second = ICK_Identity;
197  Third = ICK_Identity;
198  DeprecatedStringLiteralToCharPtr = false;
199  QualificationIncludesObjCLifetime = false;
200  ReferenceBinding = false;
201  DirectBinding = false;
202  IsLvalueReference = true;
203  BindsToFunctionLvalue = false;
204  BindsToRvalue = false;
205  BindsImplicitObjectArgumentWithoutRefQualifier = false;
206  ObjCLifetimeConversionBinding = false;
207  CopyConstructor = 0;
208}
209
210/// getRank - Retrieve the rank of this standard conversion sequence
211/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
212/// implicit conversions.
213ImplicitConversionRank StandardConversionSequence::getRank() const {
214  ImplicitConversionRank Rank = ICR_Exact_Match;
215  if  (GetConversionRank(First) > Rank)
216    Rank = GetConversionRank(First);
217  if  (GetConversionRank(Second) > Rank)
218    Rank = GetConversionRank(Second);
219  if  (GetConversionRank(Third) > Rank)
220    Rank = GetConversionRank(Third);
221  return Rank;
222}
223
224/// isPointerConversionToBool - Determines whether this conversion is
225/// a conversion of a pointer or pointer-to-member to bool. This is
226/// used as part of the ranking of standard conversion sequences
227/// (C++ 13.3.3.2p4).
228bool StandardConversionSequence::isPointerConversionToBool() const {
229  // Note that FromType has not necessarily been transformed by the
230  // array-to-pointer or function-to-pointer implicit conversions, so
231  // check for their presence as well as checking whether FromType is
232  // a pointer.
233  if (getToType(1)->isBooleanType() &&
234      (getFromType()->isPointerType() ||
235       getFromType()->isObjCObjectPointerType() ||
236       getFromType()->isBlockPointerType() ||
237       getFromType()->isNullPtrType() ||
238       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
239    return true;
240
241  return false;
242}
243
244/// isPointerConversionToVoidPointer - Determines whether this
245/// conversion is a conversion of a pointer to a void pointer. This is
246/// used as part of the ranking of standard conversion sequences (C++
247/// 13.3.3.2p4).
248bool
249StandardConversionSequence::
250isPointerConversionToVoidPointer(ASTContext& Context) const {
251  QualType FromType = getFromType();
252  QualType ToType = getToType(1);
253
254  // Note that FromType has not necessarily been transformed by the
255  // array-to-pointer implicit conversion, so check for its presence
256  // and redo the conversion to get a pointer.
257  if (First == ICK_Array_To_Pointer)
258    FromType = Context.getArrayDecayedType(FromType);
259
260  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
261    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
262      return ToPtrType->getPointeeType()->isVoidType();
263
264  return false;
265}
266
267/// Skip any implicit casts which could be either part of a narrowing conversion
268/// or after one in an implicit conversion.
269static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
270  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
271    switch (ICE->getCastKind()) {
272    case CK_NoOp:
273    case CK_IntegralCast:
274    case CK_IntegralToBoolean:
275    case CK_IntegralToFloating:
276    case CK_FloatingToIntegral:
277    case CK_FloatingToBoolean:
278    case CK_FloatingCast:
279      Converted = ICE->getSubExpr();
280      continue;
281
282    default:
283      return Converted;
284    }
285  }
286
287  return Converted;
288}
289
290/// Check if this standard conversion sequence represents a narrowing
291/// conversion, according to C++11 [dcl.init.list]p7.
292///
293/// \param Ctx  The AST context.
294/// \param Converted  The result of applying this standard conversion sequence.
295/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
296///        value of the expression prior to the narrowing conversion.
297/// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
298///        type of the expression prior to the narrowing conversion.
299NarrowingKind
300StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
301                                             const Expr *Converted,
302                                             APValue &ConstantValue,
303                                             QualType &ConstantType) const {
304  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
305
306  // C++11 [dcl.init.list]p7:
307  //   A narrowing conversion is an implicit conversion ...
308  QualType FromType = getToType(0);
309  QualType ToType = getToType(1);
310  switch (Second) {
311  // -- from a floating-point type to an integer type, or
312  //
313  // -- from an integer type or unscoped enumeration type to a floating-point
314  //    type, except where the source is a constant expression and the actual
315  //    value after conversion will fit into the target type and will produce
316  //    the original value when converted back to the original type, or
317  case ICK_Floating_Integral:
318    if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
319      return NK_Type_Narrowing;
320    } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
321      llvm::APSInt IntConstantValue;
322      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
323      if (Initializer &&
324          Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
325        // Convert the integer to the floating type.
326        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
327        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
328                                llvm::APFloat::rmNearestTiesToEven);
329        // And back.
330        llvm::APSInt ConvertedValue = IntConstantValue;
331        bool ignored;
332        Result.convertToInteger(ConvertedValue,
333                                llvm::APFloat::rmTowardZero, &ignored);
334        // If the resulting value is different, this was a narrowing conversion.
335        if (IntConstantValue != ConvertedValue) {
336          ConstantValue = APValue(IntConstantValue);
337          ConstantType = Initializer->getType();
338          return NK_Constant_Narrowing;
339        }
340      } else {
341        // Variables are always narrowings.
342        return NK_Variable_Narrowing;
343      }
344    }
345    return NK_Not_Narrowing;
346
347  // -- from long double to double or float, or from double to float, except
348  //    where the source is a constant expression and the actual value after
349  //    conversion is within the range of values that can be represented (even
350  //    if it cannot be represented exactly), or
351  case ICK_Floating_Conversion:
352    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
353        Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
354      // FromType is larger than ToType.
355      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
356      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
357        // Constant!
358        assert(ConstantValue.isFloat());
359        llvm::APFloat FloatVal = ConstantValue.getFloat();
360        // Convert the source value into the target type.
361        bool ignored;
362        llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
363          Ctx.getFloatTypeSemantics(ToType),
364          llvm::APFloat::rmNearestTiesToEven, &ignored);
365        // If there was no overflow, the source value is within the range of
366        // values that can be represented.
367        if (ConvertStatus & llvm::APFloat::opOverflow) {
368          ConstantType = Initializer->getType();
369          return NK_Constant_Narrowing;
370        }
371      } else {
372        return NK_Variable_Narrowing;
373      }
374    }
375    return NK_Not_Narrowing;
376
377  // -- from an integer type or unscoped enumeration type to an integer type
378  //    that cannot represent all the values of the original type, except where
379  //    the source is a constant expression and the actual value after
380  //    conversion will fit into the target type and will produce the original
381  //    value when converted back to the original type.
382  case ICK_Boolean_Conversion:  // Bools are integers too.
383    if (!FromType->isIntegralOrUnscopedEnumerationType()) {
384      // Boolean conversions can be from pointers and pointers to members
385      // [conv.bool], and those aren't considered narrowing conversions.
386      return NK_Not_Narrowing;
387    }  // Otherwise, fall through to the integral case.
388  case ICK_Integral_Conversion: {
389    assert(FromType->isIntegralOrUnscopedEnumerationType());
390    assert(ToType->isIntegralOrUnscopedEnumerationType());
391    const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
392    const unsigned FromWidth = Ctx.getIntWidth(FromType);
393    const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
394    const unsigned ToWidth = Ctx.getIntWidth(ToType);
395
396    if (FromWidth > ToWidth ||
397        (FromWidth == ToWidth && FromSigned != ToSigned) ||
398        (FromSigned && !ToSigned)) {
399      // Not all values of FromType can be represented in ToType.
400      llvm::APSInt InitializerValue;
401      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
402      if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
403        // Such conversions on variables are always narrowing.
404        return NK_Variable_Narrowing;
405      }
406      bool Narrowing = false;
407      if (FromWidth < ToWidth) {
408        // Negative -> unsigned is narrowing. Otherwise, more bits is never
409        // narrowing.
410        if (InitializerValue.isSigned() && InitializerValue.isNegative())
411          Narrowing = true;
412      } else {
413        // Add a bit to the InitializerValue so we don't have to worry about
414        // signed vs. unsigned comparisons.
415        InitializerValue = InitializerValue.extend(
416          InitializerValue.getBitWidth() + 1);
417        // Convert the initializer to and from the target width and signed-ness.
418        llvm::APSInt ConvertedValue = InitializerValue;
419        ConvertedValue = ConvertedValue.trunc(ToWidth);
420        ConvertedValue.setIsSigned(ToSigned);
421        ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
422        ConvertedValue.setIsSigned(InitializerValue.isSigned());
423        // If the result is different, this was a narrowing conversion.
424        if (ConvertedValue != InitializerValue)
425          Narrowing = true;
426      }
427      if (Narrowing) {
428        ConstantType = Initializer->getType();
429        ConstantValue = APValue(InitializerValue);
430        return NK_Constant_Narrowing;
431      }
432    }
433    return NK_Not_Narrowing;
434  }
435
436  default:
437    // Other kinds of conversions are not narrowings.
438    return NK_Not_Narrowing;
439  }
440}
441
442/// DebugPrint - Print this standard conversion sequence to standard
443/// error. Useful for debugging overloading issues.
444void StandardConversionSequence::DebugPrint() const {
445  raw_ostream &OS = llvm::errs();
446  bool PrintedSomething = false;
447  if (First != ICK_Identity) {
448    OS << GetImplicitConversionName(First);
449    PrintedSomething = true;
450  }
451
452  if (Second != ICK_Identity) {
453    if (PrintedSomething) {
454      OS << " -> ";
455    }
456    OS << GetImplicitConversionName(Second);
457
458    if (CopyConstructor) {
459      OS << " (by copy constructor)";
460    } else if (DirectBinding) {
461      OS << " (direct reference binding)";
462    } else if (ReferenceBinding) {
463      OS << " (reference binding)";
464    }
465    PrintedSomething = true;
466  }
467
468  if (Third != ICK_Identity) {
469    if (PrintedSomething) {
470      OS << " -> ";
471    }
472    OS << GetImplicitConversionName(Third);
473    PrintedSomething = true;
474  }
475
476  if (!PrintedSomething) {
477    OS << "No conversions required";
478  }
479}
480
481/// DebugPrint - Print this user-defined conversion sequence to standard
482/// error. Useful for debugging overloading issues.
483void UserDefinedConversionSequence::DebugPrint() const {
484  raw_ostream &OS = llvm::errs();
485  if (Before.First || Before.Second || Before.Third) {
486    Before.DebugPrint();
487    OS << " -> ";
488  }
489  if (ConversionFunction)
490    OS << '\'' << *ConversionFunction << '\'';
491  else
492    OS << "aggregate initialization";
493  if (After.First || After.Second || After.Third) {
494    OS << " -> ";
495    After.DebugPrint();
496  }
497}
498
499/// DebugPrint - Print this implicit conversion sequence to standard
500/// error. Useful for debugging overloading issues.
501void ImplicitConversionSequence::DebugPrint() const {
502  raw_ostream &OS = llvm::errs();
503  switch (ConversionKind) {
504  case StandardConversion:
505    OS << "Standard conversion: ";
506    Standard.DebugPrint();
507    break;
508  case UserDefinedConversion:
509    OS << "User-defined conversion: ";
510    UserDefined.DebugPrint();
511    break;
512  case EllipsisConversion:
513    OS << "Ellipsis conversion";
514    break;
515  case AmbiguousConversion:
516    OS << "Ambiguous conversion";
517    break;
518  case BadConversion:
519    OS << "Bad conversion";
520    break;
521  }
522
523  OS << "\n";
524}
525
526void AmbiguousConversionSequence::construct() {
527  new (&conversions()) ConversionSet();
528}
529
530void AmbiguousConversionSequence::destruct() {
531  conversions().~ConversionSet();
532}
533
534void
535AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
536  FromTypePtr = O.FromTypePtr;
537  ToTypePtr = O.ToTypePtr;
538  new (&conversions()) ConversionSet(O.conversions());
539}
540
541namespace {
542  // Structure used by OverloadCandidate::DeductionFailureInfo to store
543  // template argument information.
544  struct DFIArguments {
545    TemplateArgument FirstArg;
546    TemplateArgument SecondArg;
547  };
548  // Structure used by OverloadCandidate::DeductionFailureInfo to store
549  // template parameter and template argument information.
550  struct DFIParamWithArguments : DFIArguments {
551    TemplateParameter Param;
552  };
553}
554
555/// \brief Convert from Sema's representation of template deduction information
556/// to the form used in overload-candidate information.
557OverloadCandidate::DeductionFailureInfo
558static MakeDeductionFailureInfo(ASTContext &Context,
559                                Sema::TemplateDeductionResult TDK,
560                                TemplateDeductionInfo &Info) {
561  OverloadCandidate::DeductionFailureInfo Result;
562  Result.Result = static_cast<unsigned>(TDK);
563  Result.HasDiagnostic = false;
564  Result.Data = 0;
565  switch (TDK) {
566  case Sema::TDK_Success:
567  case Sema::TDK_Invalid:
568  case Sema::TDK_InstantiationDepth:
569  case Sema::TDK_TooManyArguments:
570  case Sema::TDK_TooFewArguments:
571    break;
572
573  case Sema::TDK_Incomplete:
574  case Sema::TDK_InvalidExplicitArguments:
575    Result.Data = Info.Param.getOpaqueValue();
576    break;
577
578  case Sema::TDK_NonDeducedMismatch: {
579    // FIXME: Should allocate from normal heap so that we can free this later.
580    DFIArguments *Saved = new (Context) DFIArguments;
581    Saved->FirstArg = Info.FirstArg;
582    Saved->SecondArg = Info.SecondArg;
583    Result.Data = Saved;
584    break;
585  }
586
587  case Sema::TDK_Inconsistent:
588  case Sema::TDK_Underqualified: {
589    // FIXME: Should allocate from normal heap so that we can free this later.
590    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
591    Saved->Param = Info.Param;
592    Saved->FirstArg = Info.FirstArg;
593    Saved->SecondArg = Info.SecondArg;
594    Result.Data = Saved;
595    break;
596  }
597
598  case Sema::TDK_SubstitutionFailure:
599    Result.Data = Info.take();
600    if (Info.hasSFINAEDiagnostic()) {
601      PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
602          SourceLocation(), PartialDiagnostic::NullDiagnostic());
603      Info.takeSFINAEDiagnostic(*Diag);
604      Result.HasDiagnostic = true;
605    }
606    break;
607
608  case Sema::TDK_FailedOverloadResolution:
609    Result.Data = Info.Expression;
610    break;
611
612  case Sema::TDK_MiscellaneousDeductionFailure:
613    break;
614  }
615
616  return Result;
617}
618
619void OverloadCandidate::DeductionFailureInfo::Destroy() {
620  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
621  case Sema::TDK_Success:
622  case Sema::TDK_Invalid:
623  case Sema::TDK_InstantiationDepth:
624  case Sema::TDK_Incomplete:
625  case Sema::TDK_TooManyArguments:
626  case Sema::TDK_TooFewArguments:
627  case Sema::TDK_InvalidExplicitArguments:
628  case Sema::TDK_FailedOverloadResolution:
629    break;
630
631  case Sema::TDK_Inconsistent:
632  case Sema::TDK_Underqualified:
633  case Sema::TDK_NonDeducedMismatch:
634    // FIXME: Destroy the data?
635    Data = 0;
636    break;
637
638  case Sema::TDK_SubstitutionFailure:
639    // FIXME: Destroy the template argument list?
640    Data = 0;
641    if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
642      Diag->~PartialDiagnosticAt();
643      HasDiagnostic = false;
644    }
645    break;
646
647  // Unhandled
648  case Sema::TDK_MiscellaneousDeductionFailure:
649    break;
650  }
651}
652
653PartialDiagnosticAt *
654OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
655  if (HasDiagnostic)
656    return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
657  return 0;
658}
659
660TemplateParameter
661OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
662  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
663  case Sema::TDK_Success:
664  case Sema::TDK_Invalid:
665  case Sema::TDK_InstantiationDepth:
666  case Sema::TDK_TooManyArguments:
667  case Sema::TDK_TooFewArguments:
668  case Sema::TDK_SubstitutionFailure:
669  case Sema::TDK_NonDeducedMismatch:
670  case Sema::TDK_FailedOverloadResolution:
671    return TemplateParameter();
672
673  case Sema::TDK_Incomplete:
674  case Sema::TDK_InvalidExplicitArguments:
675    return TemplateParameter::getFromOpaqueValue(Data);
676
677  case Sema::TDK_Inconsistent:
678  case Sema::TDK_Underqualified:
679    return static_cast<DFIParamWithArguments*>(Data)->Param;
680
681  // Unhandled
682  case Sema::TDK_MiscellaneousDeductionFailure:
683    break;
684  }
685
686  return TemplateParameter();
687}
688
689TemplateArgumentList *
690OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
691  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
692  case Sema::TDK_Success:
693  case Sema::TDK_Invalid:
694  case Sema::TDK_InstantiationDepth:
695  case Sema::TDK_TooManyArguments:
696  case Sema::TDK_TooFewArguments:
697  case Sema::TDK_Incomplete:
698  case Sema::TDK_InvalidExplicitArguments:
699  case Sema::TDK_Inconsistent:
700  case Sema::TDK_Underqualified:
701  case Sema::TDK_NonDeducedMismatch:
702  case Sema::TDK_FailedOverloadResolution:
703    return 0;
704
705  case Sema::TDK_SubstitutionFailure:
706    return static_cast<TemplateArgumentList*>(Data);
707
708  // Unhandled
709  case Sema::TDK_MiscellaneousDeductionFailure:
710    break;
711  }
712
713  return 0;
714}
715
716const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
717  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
718  case Sema::TDK_Success:
719  case Sema::TDK_Invalid:
720  case Sema::TDK_InstantiationDepth:
721  case Sema::TDK_Incomplete:
722  case Sema::TDK_TooManyArguments:
723  case Sema::TDK_TooFewArguments:
724  case Sema::TDK_InvalidExplicitArguments:
725  case Sema::TDK_SubstitutionFailure:
726  case Sema::TDK_FailedOverloadResolution:
727    return 0;
728
729  case Sema::TDK_Inconsistent:
730  case Sema::TDK_Underqualified:
731  case Sema::TDK_NonDeducedMismatch:
732    return &static_cast<DFIArguments*>(Data)->FirstArg;
733
734  // Unhandled
735  case Sema::TDK_MiscellaneousDeductionFailure:
736    break;
737  }
738
739  return 0;
740}
741
742const TemplateArgument *
743OverloadCandidate::DeductionFailureInfo::getSecondArg() {
744  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745  case Sema::TDK_Success:
746  case Sema::TDK_Invalid:
747  case Sema::TDK_InstantiationDepth:
748  case Sema::TDK_Incomplete:
749  case Sema::TDK_TooManyArguments:
750  case Sema::TDK_TooFewArguments:
751  case Sema::TDK_InvalidExplicitArguments:
752  case Sema::TDK_SubstitutionFailure:
753  case Sema::TDK_FailedOverloadResolution:
754    return 0;
755
756  case Sema::TDK_Inconsistent:
757  case Sema::TDK_Underqualified:
758  case Sema::TDK_NonDeducedMismatch:
759    return &static_cast<DFIArguments*>(Data)->SecondArg;
760
761  // Unhandled
762  case Sema::TDK_MiscellaneousDeductionFailure:
763    break;
764  }
765
766  return 0;
767}
768
769Expr *
770OverloadCandidate::DeductionFailureInfo::getExpr() {
771  if (static_cast<Sema::TemplateDeductionResult>(Result) ==
772        Sema::TDK_FailedOverloadResolution)
773    return static_cast<Expr*>(Data);
774
775  return 0;
776}
777
778void OverloadCandidateSet::destroyCandidates() {
779  for (iterator i = begin(), e = end(); i != e; ++i) {
780    for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
781      i->Conversions[ii].~ImplicitConversionSequence();
782    if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
783      i->DeductionFailure.Destroy();
784  }
785}
786
787void OverloadCandidateSet::clear() {
788  destroyCandidates();
789  NumInlineSequences = 0;
790  Candidates.clear();
791  Functions.clear();
792}
793
794namespace {
795  class UnbridgedCastsSet {
796    struct Entry {
797      Expr **Addr;
798      Expr *Saved;
799    };
800    SmallVector<Entry, 2> Entries;
801
802  public:
803    void save(Sema &S, Expr *&E) {
804      assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
805      Entry entry = { &E, E };
806      Entries.push_back(entry);
807      E = S.stripARCUnbridgedCast(E);
808    }
809
810    void restore() {
811      for (SmallVectorImpl<Entry>::iterator
812             i = Entries.begin(), e = Entries.end(); i != e; ++i)
813        *i->Addr = i->Saved;
814    }
815  };
816}
817
818/// checkPlaceholderForOverload - Do any interesting placeholder-like
819/// preprocessing on the given expression.
820///
821/// \param unbridgedCasts a collection to which to add unbridged casts;
822///   without this, they will be immediately diagnosed as errors
823///
824/// Return true on unrecoverable error.
825static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
826                                        UnbridgedCastsSet *unbridgedCasts = 0) {
827  if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
828    // We can't handle overloaded expressions here because overload
829    // resolution might reasonably tweak them.
830    if (placeholder->getKind() == BuiltinType::Overload) return false;
831
832    // If the context potentially accepts unbridged ARC casts, strip
833    // the unbridged cast and add it to the collection for later restoration.
834    if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
835        unbridgedCasts) {
836      unbridgedCasts->save(S, E);
837      return false;
838    }
839
840    // Go ahead and check everything else.
841    ExprResult result = S.CheckPlaceholderExpr(E);
842    if (result.isInvalid())
843      return true;
844
845    E = result.take();
846    return false;
847  }
848
849  // Nothing to do.
850  return false;
851}
852
853/// checkArgPlaceholdersForOverload - Check a set of call operands for
854/// placeholders.
855static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
856                                            unsigned numArgs,
857                                            UnbridgedCastsSet &unbridged) {
858  for (unsigned i = 0; i != numArgs; ++i)
859    if (checkPlaceholderForOverload(S, args[i], &unbridged))
860      return true;
861
862  return false;
863}
864
865// IsOverload - Determine whether the given New declaration is an
866// overload of the declarations in Old. This routine returns false if
867// New and Old cannot be overloaded, e.g., if New has the same
868// signature as some function in Old (C++ 1.3.10) or if the Old
869// declarations aren't functions (or function templates) at all. When
870// it does return false, MatchedDecl will point to the decl that New
871// cannot be overloaded with.  This decl may be a UsingShadowDecl on
872// top of the underlying declaration.
873//
874// Example: Given the following input:
875//
876//   void f(int, float); // #1
877//   void f(int, int); // #2
878//   int f(int, int); // #3
879//
880// When we process #1, there is no previous declaration of "f",
881// so IsOverload will not be used.
882//
883// When we process #2, Old contains only the FunctionDecl for #1.  By
884// comparing the parameter types, we see that #1 and #2 are overloaded
885// (since they have different signatures), so this routine returns
886// false; MatchedDecl is unchanged.
887//
888// When we process #3, Old is an overload set containing #1 and #2. We
889// compare the signatures of #3 to #1 (they're overloaded, so we do
890// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
891// identical (return types of functions are not part of the
892// signature), IsOverload returns false and MatchedDecl will be set to
893// point to the FunctionDecl for #2.
894//
895// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
896// into a class by a using declaration.  The rules for whether to hide
897// shadow declarations ignore some properties which otherwise figure
898// into a function template's signature.
899Sema::OverloadKind
900Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
901                    NamedDecl *&Match, bool NewIsUsingDecl) {
902  for (LookupResult::iterator I = Old.begin(), E = Old.end();
903         I != E; ++I) {
904    NamedDecl *OldD = *I;
905
906    bool OldIsUsingDecl = false;
907    if (isa<UsingShadowDecl>(OldD)) {
908      OldIsUsingDecl = true;
909
910      // We can always introduce two using declarations into the same
911      // context, even if they have identical signatures.
912      if (NewIsUsingDecl) continue;
913
914      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
915    }
916
917    // If either declaration was introduced by a using declaration,
918    // we'll need to use slightly different rules for matching.
919    // Essentially, these rules are the normal rules, except that
920    // function templates hide function templates with different
921    // return types or template parameter lists.
922    bool UseMemberUsingDeclRules =
923      (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
924
925    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
926      if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
927        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
928          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
929          continue;
930        }
931
932        Match = *I;
933        return Ovl_Match;
934      }
935    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
936      if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
937        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
938          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
939          continue;
940        }
941
942        Match = *I;
943        return Ovl_Match;
944      }
945    } else if (isa<UsingDecl>(OldD)) {
946      // We can overload with these, which can show up when doing
947      // redeclaration checks for UsingDecls.
948      assert(Old.getLookupKind() == LookupUsingDeclName);
949    } else if (isa<TagDecl>(OldD)) {
950      // We can always overload with tags by hiding them.
951    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
952      // Optimistically assume that an unresolved using decl will
953      // overload; if it doesn't, we'll have to diagnose during
954      // template instantiation.
955    } else {
956      // (C++ 13p1):
957      //   Only function declarations can be overloaded; object and type
958      //   declarations cannot be overloaded.
959      Match = *I;
960      return Ovl_NonFunction;
961    }
962  }
963
964  return Ovl_Overload;
965}
966
967static bool canBeOverloaded(const FunctionDecl &D) {
968  if (D.getAttr<OverloadableAttr>())
969    return true;
970  if (D.hasCLanguageLinkage())
971    return false;
972
973  // Main cannot be overloaded (basic.start.main).
974  if (D.isMain())
975    return false;
976
977  return true;
978}
979
980bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
981                      bool UseUsingDeclRules) {
982  // If both of the functions are extern "C", then they are not
983  // overloads.
984  if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
985    return false;
986
987  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
988  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
989
990  // C++ [temp.fct]p2:
991  //   A function template can be overloaded with other function templates
992  //   and with normal (non-template) functions.
993  if ((OldTemplate == 0) != (NewTemplate == 0))
994    return true;
995
996  // Is the function New an overload of the function Old?
997  QualType OldQType = Context.getCanonicalType(Old->getType());
998  QualType NewQType = Context.getCanonicalType(New->getType());
999
1000  // Compare the signatures (C++ 1.3.10) of the two functions to
1001  // determine whether they are overloads. If we find any mismatch
1002  // in the signature, they are overloads.
1003
1004  // If either of these functions is a K&R-style function (no
1005  // prototype), then we consider them to have matching signatures.
1006  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1007      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1008    return false;
1009
1010  const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1011  const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
1012
1013  // The signature of a function includes the types of its
1014  // parameters (C++ 1.3.10), which includes the presence or absence
1015  // of the ellipsis; see C++ DR 357).
1016  if (OldQType != NewQType &&
1017      (OldType->getNumArgs() != NewType->getNumArgs() ||
1018       OldType->isVariadic() != NewType->isVariadic() ||
1019       !FunctionArgTypesAreEqual(OldType, NewType)))
1020    return true;
1021
1022  // C++ [temp.over.link]p4:
1023  //   The signature of a function template consists of its function
1024  //   signature, its return type and its template parameter list. The names
1025  //   of the template parameters are significant only for establishing the
1026  //   relationship between the template parameters and the rest of the
1027  //   signature.
1028  //
1029  // We check the return type and template parameter lists for function
1030  // templates first; the remaining checks follow.
1031  //
1032  // However, we don't consider either of these when deciding whether
1033  // a member introduced by a shadow declaration is hidden.
1034  if (!UseUsingDeclRules && NewTemplate &&
1035      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1036                                       OldTemplate->getTemplateParameters(),
1037                                       false, TPL_TemplateMatch) ||
1038       OldType->getResultType() != NewType->getResultType()))
1039    return true;
1040
1041  // If the function is a class member, its signature includes the
1042  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1043  //
1044  // As part of this, also check whether one of the member functions
1045  // is static, in which case they are not overloads (C++
1046  // 13.1p2). While not part of the definition of the signature,
1047  // this check is important to determine whether these functions
1048  // can be overloaded.
1049  CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1050  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1051  if (OldMethod && NewMethod &&
1052      !OldMethod->isStatic() && !NewMethod->isStatic()) {
1053    if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1054      if (!UseUsingDeclRules &&
1055          (OldMethod->getRefQualifier() == RQ_None ||
1056           NewMethod->getRefQualifier() == RQ_None)) {
1057        // C++0x [over.load]p2:
1058        //   - Member function declarations with the same name and the same
1059        //     parameter-type-list as well as member function template
1060        //     declarations with the same name, the same parameter-type-list, and
1061        //     the same template parameter lists cannot be overloaded if any of
1062        //     them, but not all, have a ref-qualifier (8.3.5).
1063        Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1064          << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1065        Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1066      }
1067      return true;
1068    }
1069
1070    // We may not have applied the implicit const for a constexpr member
1071    // function yet (because we haven't yet resolved whether this is a static
1072    // or non-static member function). Add it now, on the assumption that this
1073    // is a redeclaration of OldMethod.
1074    unsigned NewQuals = NewMethod->getTypeQualifiers();
1075    if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod))
1076      NewQuals |= Qualifiers::Const;
1077    if (OldMethod->getTypeQualifiers() != NewQuals)
1078      return true;
1079  }
1080
1081  // The signatures match; this is not an overload.
1082  return false;
1083}
1084
1085/// \brief Checks availability of the function depending on the current
1086/// function context. Inside an unavailable function, unavailability is ignored.
1087///
1088/// \returns true if \arg FD is unavailable and current context is inside
1089/// an available function, false otherwise.
1090bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1091  return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1092}
1093
1094/// \brief Tries a user-defined conversion from From to ToType.
1095///
1096/// Produces an implicit conversion sequence for when a standard conversion
1097/// is not an option. See TryImplicitConversion for more information.
1098static ImplicitConversionSequence
1099TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1100                         bool SuppressUserConversions,
1101                         bool AllowExplicit,
1102                         bool InOverloadResolution,
1103                         bool CStyle,
1104                         bool AllowObjCWritebackConversion) {
1105  ImplicitConversionSequence ICS;
1106
1107  if (SuppressUserConversions) {
1108    // We're not in the case above, so there is no conversion that
1109    // we can perform.
1110    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1111    return ICS;
1112  }
1113
1114  // Attempt user-defined conversion.
1115  OverloadCandidateSet Conversions(From->getExprLoc());
1116  OverloadingResult UserDefResult
1117    = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1118                              AllowExplicit);
1119
1120  if (UserDefResult == OR_Success) {
1121    ICS.setUserDefined();
1122    // C++ [over.ics.user]p4:
1123    //   A conversion of an expression of class type to the same class
1124    //   type is given Exact Match rank, and a conversion of an
1125    //   expression of class type to a base class of that type is
1126    //   given Conversion rank, in spite of the fact that a copy
1127    //   constructor (i.e., a user-defined conversion function) is
1128    //   called for those cases.
1129    if (CXXConstructorDecl *Constructor
1130          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1131      QualType FromCanon
1132        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1133      QualType ToCanon
1134        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1135      if (Constructor->isCopyConstructor() &&
1136          (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1137        // Turn this into a "standard" conversion sequence, so that it
1138        // gets ranked with standard conversion sequences.
1139        ICS.setStandard();
1140        ICS.Standard.setAsIdentityConversion();
1141        ICS.Standard.setFromType(From->getType());
1142        ICS.Standard.setAllToTypes(ToType);
1143        ICS.Standard.CopyConstructor = Constructor;
1144        if (ToCanon != FromCanon)
1145          ICS.Standard.Second = ICK_Derived_To_Base;
1146      }
1147    }
1148
1149    // C++ [over.best.ics]p4:
1150    //   However, when considering the argument of a user-defined
1151    //   conversion function that is a candidate by 13.3.1.3 when
1152    //   invoked for the copying of the temporary in the second step
1153    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1154    //   13.3.1.6 in all cases, only standard conversion sequences and
1155    //   ellipsis conversion sequences are allowed.
1156    if (SuppressUserConversions && ICS.isUserDefined()) {
1157      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1158    }
1159  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1160    ICS.setAmbiguous();
1161    ICS.Ambiguous.setFromType(From->getType());
1162    ICS.Ambiguous.setToType(ToType);
1163    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1164         Cand != Conversions.end(); ++Cand)
1165      if (Cand->Viable)
1166        ICS.Ambiguous.addConversion(Cand->Function);
1167  } else {
1168    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1169  }
1170
1171  return ICS;
1172}
1173
1174/// TryImplicitConversion - Attempt to perform an implicit conversion
1175/// from the given expression (Expr) to the given type (ToType). This
1176/// function returns an implicit conversion sequence that can be used
1177/// to perform the initialization. Given
1178///
1179///   void f(float f);
1180///   void g(int i) { f(i); }
1181///
1182/// this routine would produce an implicit conversion sequence to
1183/// describe the initialization of f from i, which will be a standard
1184/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1185/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1186//
1187/// Note that this routine only determines how the conversion can be
1188/// performed; it does not actually perform the conversion. As such,
1189/// it will not produce any diagnostics if no conversion is available,
1190/// but will instead return an implicit conversion sequence of kind
1191/// "BadConversion".
1192///
1193/// If @p SuppressUserConversions, then user-defined conversions are
1194/// not permitted.
1195/// If @p AllowExplicit, then explicit user-defined conversions are
1196/// permitted.
1197///
1198/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1199/// writeback conversion, which allows __autoreleasing id* parameters to
1200/// be initialized with __strong id* or __weak id* arguments.
1201static ImplicitConversionSequence
1202TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1203                      bool SuppressUserConversions,
1204                      bool AllowExplicit,
1205                      bool InOverloadResolution,
1206                      bool CStyle,
1207                      bool AllowObjCWritebackConversion) {
1208  ImplicitConversionSequence ICS;
1209  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1210                           ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1211    ICS.setStandard();
1212    return ICS;
1213  }
1214
1215  if (!S.getLangOpts().CPlusPlus) {
1216    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1217    return ICS;
1218  }
1219
1220  // C++ [over.ics.user]p4:
1221  //   A conversion of an expression of class type to the same class
1222  //   type is given Exact Match rank, and a conversion of an
1223  //   expression of class type to a base class of that type is
1224  //   given Conversion rank, in spite of the fact that a copy/move
1225  //   constructor (i.e., a user-defined conversion function) is
1226  //   called for those cases.
1227  QualType FromType = From->getType();
1228  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1229      (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1230       S.IsDerivedFrom(FromType, ToType))) {
1231    ICS.setStandard();
1232    ICS.Standard.setAsIdentityConversion();
1233    ICS.Standard.setFromType(FromType);
1234    ICS.Standard.setAllToTypes(ToType);
1235
1236    // We don't actually check at this point whether there is a valid
1237    // copy/move constructor, since overloading just assumes that it
1238    // exists. When we actually perform initialization, we'll find the
1239    // appropriate constructor to copy the returned object, if needed.
1240    ICS.Standard.CopyConstructor = 0;
1241
1242    // Determine whether this is considered a derived-to-base conversion.
1243    if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1244      ICS.Standard.Second = ICK_Derived_To_Base;
1245
1246    return ICS;
1247  }
1248
1249  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1250                                  AllowExplicit, InOverloadResolution, CStyle,
1251                                  AllowObjCWritebackConversion);
1252}
1253
1254ImplicitConversionSequence
1255Sema::TryImplicitConversion(Expr *From, QualType ToType,
1256                            bool SuppressUserConversions,
1257                            bool AllowExplicit,
1258                            bool InOverloadResolution,
1259                            bool CStyle,
1260                            bool AllowObjCWritebackConversion) {
1261  return clang::TryImplicitConversion(*this, From, ToType,
1262                                      SuppressUserConversions, AllowExplicit,
1263                                      InOverloadResolution, CStyle,
1264                                      AllowObjCWritebackConversion);
1265}
1266
1267/// PerformImplicitConversion - Perform an implicit conversion of the
1268/// expression From to the type ToType. Returns the
1269/// converted expression. Flavor is the kind of conversion we're
1270/// performing, used in the error message. If @p AllowExplicit,
1271/// explicit user-defined conversions are permitted.
1272ExprResult
1273Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1274                                AssignmentAction Action, bool AllowExplicit) {
1275  ImplicitConversionSequence ICS;
1276  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1277}
1278
1279ExprResult
1280Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1281                                AssignmentAction Action, bool AllowExplicit,
1282                                ImplicitConversionSequence& ICS) {
1283  if (checkPlaceholderForOverload(*this, From))
1284    return ExprError();
1285
1286  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1287  bool AllowObjCWritebackConversion
1288    = getLangOpts().ObjCAutoRefCount &&
1289      (Action == AA_Passing || Action == AA_Sending);
1290
1291  ICS = clang::TryImplicitConversion(*this, From, ToType,
1292                                     /*SuppressUserConversions=*/false,
1293                                     AllowExplicit,
1294                                     /*InOverloadResolution=*/false,
1295                                     /*CStyle=*/false,
1296                                     AllowObjCWritebackConversion);
1297  return PerformImplicitConversion(From, ToType, ICS, Action);
1298}
1299
1300/// \brief Determine whether the conversion from FromType to ToType is a valid
1301/// conversion that strips "noreturn" off the nested function type.
1302bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1303                                QualType &ResultTy) {
1304  if (Context.hasSameUnqualifiedType(FromType, ToType))
1305    return false;
1306
1307  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1308  // where F adds one of the following at most once:
1309  //   - a pointer
1310  //   - a member pointer
1311  //   - a block pointer
1312  CanQualType CanTo = Context.getCanonicalType(ToType);
1313  CanQualType CanFrom = Context.getCanonicalType(FromType);
1314  Type::TypeClass TyClass = CanTo->getTypeClass();
1315  if (TyClass != CanFrom->getTypeClass()) return false;
1316  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1317    if (TyClass == Type::Pointer) {
1318      CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1319      CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1320    } else if (TyClass == Type::BlockPointer) {
1321      CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1322      CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1323    } else if (TyClass == Type::MemberPointer) {
1324      CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1325      CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1326    } else {
1327      return false;
1328    }
1329
1330    TyClass = CanTo->getTypeClass();
1331    if (TyClass != CanFrom->getTypeClass()) return false;
1332    if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1333      return false;
1334  }
1335
1336  const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1337  FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1338  if (!EInfo.getNoReturn()) return false;
1339
1340  FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1341  assert(QualType(FromFn, 0).isCanonical());
1342  if (QualType(FromFn, 0) != CanTo) return false;
1343
1344  ResultTy = ToType;
1345  return true;
1346}
1347
1348/// \brief Determine whether the conversion from FromType to ToType is a valid
1349/// vector conversion.
1350///
1351/// \param ICK Will be set to the vector conversion kind, if this is a vector
1352/// conversion.
1353static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1354                               QualType ToType, ImplicitConversionKind &ICK) {
1355  // We need at least one of these types to be a vector type to have a vector
1356  // conversion.
1357  if (!ToType->isVectorType() && !FromType->isVectorType())
1358    return false;
1359
1360  // Identical types require no conversions.
1361  if (Context.hasSameUnqualifiedType(FromType, ToType))
1362    return false;
1363
1364  // There are no conversions between extended vector types, only identity.
1365  if (ToType->isExtVectorType()) {
1366    // There are no conversions between extended vector types other than the
1367    // identity conversion.
1368    if (FromType->isExtVectorType())
1369      return false;
1370
1371    // Vector splat from any arithmetic type to a vector.
1372    if (FromType->isArithmeticType()) {
1373      ICK = ICK_Vector_Splat;
1374      return true;
1375    }
1376  }
1377
1378  // We can perform the conversion between vector types in the following cases:
1379  // 1)vector types are equivalent AltiVec and GCC vector types
1380  // 2)lax vector conversions are permitted and the vector types are of the
1381  //   same size
1382  if (ToType->isVectorType() && FromType->isVectorType()) {
1383    if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1384        (Context.getLangOpts().LaxVectorConversions &&
1385         (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1386      ICK = ICK_Vector_Conversion;
1387      return true;
1388    }
1389  }
1390
1391  return false;
1392}
1393
1394static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1395                                bool InOverloadResolution,
1396                                StandardConversionSequence &SCS,
1397                                bool CStyle);
1398
1399/// IsStandardConversion - Determines whether there is a standard
1400/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1401/// expression From to the type ToType. Standard conversion sequences
1402/// only consider non-class types; for conversions that involve class
1403/// types, use TryImplicitConversion. If a conversion exists, SCS will
1404/// contain the standard conversion sequence required to perform this
1405/// conversion and this routine will return true. Otherwise, this
1406/// routine will return false and the value of SCS is unspecified.
1407static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1408                                 bool InOverloadResolution,
1409                                 StandardConversionSequence &SCS,
1410                                 bool CStyle,
1411                                 bool AllowObjCWritebackConversion) {
1412  QualType FromType = From->getType();
1413
1414  // Standard conversions (C++ [conv])
1415  SCS.setAsIdentityConversion();
1416  SCS.DeprecatedStringLiteralToCharPtr = false;
1417  SCS.IncompatibleObjC = false;
1418  SCS.setFromType(FromType);
1419  SCS.CopyConstructor = 0;
1420
1421  // There are no standard conversions for class types in C++, so
1422  // abort early. When overloading in C, however, we do permit
1423  if (FromType->isRecordType() || ToType->isRecordType()) {
1424    if (S.getLangOpts().CPlusPlus)
1425      return false;
1426
1427    // When we're overloading in C, we allow, as standard conversions,
1428  }
1429
1430  // The first conversion can be an lvalue-to-rvalue conversion,
1431  // array-to-pointer conversion, or function-to-pointer conversion
1432  // (C++ 4p1).
1433
1434  if (FromType == S.Context.OverloadTy) {
1435    DeclAccessPair AccessPair;
1436    if (FunctionDecl *Fn
1437          = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1438                                                 AccessPair)) {
1439      // We were able to resolve the address of the overloaded function,
1440      // so we can convert to the type of that function.
1441      FromType = Fn->getType();
1442
1443      // we can sometimes resolve &foo<int> regardless of ToType, so check
1444      // if the type matches (identity) or we are converting to bool
1445      if (!S.Context.hasSameUnqualifiedType(
1446                      S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1447        QualType resultTy;
1448        // if the function type matches except for [[noreturn]], it's ok
1449        if (!S.IsNoReturnConversion(FromType,
1450              S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1451          // otherwise, only a boolean conversion is standard
1452          if (!ToType->isBooleanType())
1453            return false;
1454      }
1455
1456      // Check if the "from" expression is taking the address of an overloaded
1457      // function and recompute the FromType accordingly. Take advantage of the
1458      // fact that non-static member functions *must* have such an address-of
1459      // expression.
1460      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1461      if (Method && !Method->isStatic()) {
1462        assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1463               "Non-unary operator on non-static member address");
1464        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1465               == UO_AddrOf &&
1466               "Non-address-of operator on non-static member address");
1467        const Type *ClassType
1468          = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1469        FromType = S.Context.getMemberPointerType(FromType, ClassType);
1470      } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1471        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1472               UO_AddrOf &&
1473               "Non-address-of operator for overloaded function expression");
1474        FromType = S.Context.getPointerType(FromType);
1475      }
1476
1477      // Check that we've computed the proper type after overload resolution.
1478      assert(S.Context.hasSameType(
1479        FromType,
1480        S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1481    } else {
1482      return false;
1483    }
1484  }
1485  // Lvalue-to-rvalue conversion (C++11 4.1):
1486  //   A glvalue (3.10) of a non-function, non-array type T can
1487  //   be converted to a prvalue.
1488  bool argIsLValue = From->isGLValue();
1489  if (argIsLValue &&
1490      !FromType->isFunctionType() && !FromType->isArrayType() &&
1491      S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1492    SCS.First = ICK_Lvalue_To_Rvalue;
1493
1494    // C11 6.3.2.1p2:
1495    //   ... if the lvalue has atomic type, the value has the non-atomic version
1496    //   of the type of the lvalue ...
1497    if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1498      FromType = Atomic->getValueType();
1499
1500    // If T is a non-class type, the type of the rvalue is the
1501    // cv-unqualified version of T. Otherwise, the type of the rvalue
1502    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1503    // just strip the qualifiers because they don't matter.
1504    FromType = FromType.getUnqualifiedType();
1505  } else if (FromType->isArrayType()) {
1506    // Array-to-pointer conversion (C++ 4.2)
1507    SCS.First = ICK_Array_To_Pointer;
1508
1509    // An lvalue or rvalue of type "array of N T" or "array of unknown
1510    // bound of T" can be converted to an rvalue of type "pointer to
1511    // T" (C++ 4.2p1).
1512    FromType = S.Context.getArrayDecayedType(FromType);
1513
1514    if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1515      // This conversion is deprecated. (C++ D.4).
1516      SCS.DeprecatedStringLiteralToCharPtr = true;
1517
1518      // For the purpose of ranking in overload resolution
1519      // (13.3.3.1.1), this conversion is considered an
1520      // array-to-pointer conversion followed by a qualification
1521      // conversion (4.4). (C++ 4.2p2)
1522      SCS.Second = ICK_Identity;
1523      SCS.Third = ICK_Qualification;
1524      SCS.QualificationIncludesObjCLifetime = false;
1525      SCS.setAllToTypes(FromType);
1526      return true;
1527    }
1528  } else if (FromType->isFunctionType() && argIsLValue) {
1529    // Function-to-pointer conversion (C++ 4.3).
1530    SCS.First = ICK_Function_To_Pointer;
1531
1532    // An lvalue of function type T can be converted to an rvalue of
1533    // type "pointer to T." The result is a pointer to the
1534    // function. (C++ 4.3p1).
1535    FromType = S.Context.getPointerType(FromType);
1536  } else {
1537    // We don't require any conversions for the first step.
1538    SCS.First = ICK_Identity;
1539  }
1540  SCS.setToType(0, FromType);
1541
1542  // The second conversion can be an integral promotion, floating
1543  // point promotion, integral conversion, floating point conversion,
1544  // floating-integral conversion, pointer conversion,
1545  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1546  // For overloading in C, this can also be a "compatible-type"
1547  // conversion.
1548  bool IncompatibleObjC = false;
1549  ImplicitConversionKind SecondICK = ICK_Identity;
1550  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1551    // The unqualified versions of the types are the same: there's no
1552    // conversion to do.
1553    SCS.Second = ICK_Identity;
1554  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1555    // Integral promotion (C++ 4.5).
1556    SCS.Second = ICK_Integral_Promotion;
1557    FromType = ToType.getUnqualifiedType();
1558  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1559    // Floating point promotion (C++ 4.6).
1560    SCS.Second = ICK_Floating_Promotion;
1561    FromType = ToType.getUnqualifiedType();
1562  } else if (S.IsComplexPromotion(FromType, ToType)) {
1563    // Complex promotion (Clang extension)
1564    SCS.Second = ICK_Complex_Promotion;
1565    FromType = ToType.getUnqualifiedType();
1566  } else if (ToType->isBooleanType() &&
1567             (FromType->isArithmeticType() ||
1568              FromType->isAnyPointerType() ||
1569              FromType->isBlockPointerType() ||
1570              FromType->isMemberPointerType() ||
1571              FromType->isNullPtrType())) {
1572    // Boolean conversions (C++ 4.12).
1573    SCS.Second = ICK_Boolean_Conversion;
1574    FromType = S.Context.BoolTy;
1575  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1576             ToType->isIntegralType(S.Context)) {
1577    // Integral conversions (C++ 4.7).
1578    SCS.Second = ICK_Integral_Conversion;
1579    FromType = ToType.getUnqualifiedType();
1580  } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1581    // Complex conversions (C99 6.3.1.6)
1582    SCS.Second = ICK_Complex_Conversion;
1583    FromType = ToType.getUnqualifiedType();
1584  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1585             (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1586    // Complex-real conversions (C99 6.3.1.7)
1587    SCS.Second = ICK_Complex_Real;
1588    FromType = ToType.getUnqualifiedType();
1589  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1590    // Floating point conversions (C++ 4.8).
1591    SCS.Second = ICK_Floating_Conversion;
1592    FromType = ToType.getUnqualifiedType();
1593  } else if ((FromType->isRealFloatingType() &&
1594              ToType->isIntegralType(S.Context)) ||
1595             (FromType->isIntegralOrUnscopedEnumerationType() &&
1596              ToType->isRealFloatingType())) {
1597    // Floating-integral conversions (C++ 4.9).
1598    SCS.Second = ICK_Floating_Integral;
1599    FromType = ToType.getUnqualifiedType();
1600  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1601    SCS.Second = ICK_Block_Pointer_Conversion;
1602  } else if (AllowObjCWritebackConversion &&
1603             S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1604    SCS.Second = ICK_Writeback_Conversion;
1605  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1606                                   FromType, IncompatibleObjC)) {
1607    // Pointer conversions (C++ 4.10).
1608    SCS.Second = ICK_Pointer_Conversion;
1609    SCS.IncompatibleObjC = IncompatibleObjC;
1610    FromType = FromType.getUnqualifiedType();
1611  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1612                                         InOverloadResolution, FromType)) {
1613    // Pointer to member conversions (4.11).
1614    SCS.Second = ICK_Pointer_Member;
1615  } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1616    SCS.Second = SecondICK;
1617    FromType = ToType.getUnqualifiedType();
1618  } else if (!S.getLangOpts().CPlusPlus &&
1619             S.Context.typesAreCompatible(ToType, FromType)) {
1620    // Compatible conversions (Clang extension for C function overloading)
1621    SCS.Second = ICK_Compatible_Conversion;
1622    FromType = ToType.getUnqualifiedType();
1623  } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1624    // Treat a conversion that strips "noreturn" as an identity conversion.
1625    SCS.Second = ICK_NoReturn_Adjustment;
1626  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1627                                             InOverloadResolution,
1628                                             SCS, CStyle)) {
1629    SCS.Second = ICK_TransparentUnionConversion;
1630    FromType = ToType;
1631  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1632                                 CStyle)) {
1633    // tryAtomicConversion has updated the standard conversion sequence
1634    // appropriately.
1635    return true;
1636  } else {
1637    // No second conversion required.
1638    SCS.Second = ICK_Identity;
1639  }
1640  SCS.setToType(1, FromType);
1641
1642  QualType CanonFrom;
1643  QualType CanonTo;
1644  // The third conversion can be a qualification conversion (C++ 4p1).
1645  bool ObjCLifetimeConversion;
1646  if (S.IsQualificationConversion(FromType, ToType, CStyle,
1647                                  ObjCLifetimeConversion)) {
1648    SCS.Third = ICK_Qualification;
1649    SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1650    FromType = ToType;
1651    CanonFrom = S.Context.getCanonicalType(FromType);
1652    CanonTo = S.Context.getCanonicalType(ToType);
1653  } else {
1654    // No conversion required
1655    SCS.Third = ICK_Identity;
1656
1657    // C++ [over.best.ics]p6:
1658    //   [...] Any difference in top-level cv-qualification is
1659    //   subsumed by the initialization itself and does not constitute
1660    //   a conversion. [...]
1661    CanonFrom = S.Context.getCanonicalType(FromType);
1662    CanonTo = S.Context.getCanonicalType(ToType);
1663    if (CanonFrom.getLocalUnqualifiedType()
1664                                       == CanonTo.getLocalUnqualifiedType() &&
1665        (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1666         || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1667         || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
1668      FromType = ToType;
1669      CanonFrom = CanonTo;
1670    }
1671  }
1672  SCS.setToType(2, FromType);
1673
1674  // If we have not converted the argument type to the parameter type,
1675  // this is a bad conversion sequence.
1676  if (CanonFrom != CanonTo)
1677    return false;
1678
1679  return true;
1680}
1681
1682static bool
1683IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1684                                     QualType &ToType,
1685                                     bool InOverloadResolution,
1686                                     StandardConversionSequence &SCS,
1687                                     bool CStyle) {
1688
1689  const RecordType *UT = ToType->getAsUnionType();
1690  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1691    return false;
1692  // The field to initialize within the transparent union.
1693  RecordDecl *UD = UT->getDecl();
1694  // It's compatible if the expression matches any of the fields.
1695  for (RecordDecl::field_iterator it = UD->field_begin(),
1696       itend = UD->field_end();
1697       it != itend; ++it) {
1698    if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1699                             CStyle, /*ObjCWritebackConversion=*/false)) {
1700      ToType = it->getType();
1701      return true;
1702    }
1703  }
1704  return false;
1705}
1706
1707/// IsIntegralPromotion - Determines whether the conversion from the
1708/// expression From (whose potentially-adjusted type is FromType) to
1709/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1710/// sets PromotedType to the promoted type.
1711bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1712  const BuiltinType *To = ToType->getAs<BuiltinType>();
1713  // All integers are built-in.
1714  if (!To) {
1715    return false;
1716  }
1717
1718  // An rvalue of type char, signed char, unsigned char, short int, or
1719  // unsigned short int can be converted to an rvalue of type int if
1720  // int can represent all the values of the source type; otherwise,
1721  // the source rvalue can be converted to an rvalue of type unsigned
1722  // int (C++ 4.5p1).
1723  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1724      !FromType->isEnumeralType()) {
1725    if (// We can promote any signed, promotable integer type to an int
1726        (FromType->isSignedIntegerType() ||
1727         // We can promote any unsigned integer type whose size is
1728         // less than int to an int.
1729         (!FromType->isSignedIntegerType() &&
1730          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1731      return To->getKind() == BuiltinType::Int;
1732    }
1733
1734    return To->getKind() == BuiltinType::UInt;
1735  }
1736
1737  // C++11 [conv.prom]p3:
1738  //   A prvalue of an unscoped enumeration type whose underlying type is not
1739  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1740  //   following types that can represent all the values of the enumeration
1741  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1742  //   unsigned int, long int, unsigned long int, long long int, or unsigned
1743  //   long long int. If none of the types in that list can represent all the
1744  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1745  //   type can be converted to an rvalue a prvalue of the extended integer type
1746  //   with lowest integer conversion rank (4.13) greater than the rank of long
1747  //   long in which all the values of the enumeration can be represented. If
1748  //   there are two such extended types, the signed one is chosen.
1749  // C++11 [conv.prom]p4:
1750  //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1751  //   can be converted to a prvalue of its underlying type. Moreover, if
1752  //   integral promotion can be applied to its underlying type, a prvalue of an
1753  //   unscoped enumeration type whose underlying type is fixed can also be
1754  //   converted to a prvalue of the promoted underlying type.
1755  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1756    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1757    // provided for a scoped enumeration.
1758    if (FromEnumType->getDecl()->isScoped())
1759      return false;
1760
1761    // We can perform an integral promotion to the underlying type of the enum,
1762    // even if that's not the promoted type.
1763    if (FromEnumType->getDecl()->isFixed()) {
1764      QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1765      return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1766             IsIntegralPromotion(From, Underlying, ToType);
1767    }
1768
1769    // We have already pre-calculated the promotion type, so this is trivial.
1770    if (ToType->isIntegerType() &&
1771        !RequireCompleteType(From->getLocStart(), FromType, 0))
1772      return Context.hasSameUnqualifiedType(ToType,
1773                                FromEnumType->getDecl()->getPromotionType());
1774  }
1775
1776  // C++0x [conv.prom]p2:
1777  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1778  //   to an rvalue a prvalue of the first of the following types that can
1779  //   represent all the values of its underlying type: int, unsigned int,
1780  //   long int, unsigned long int, long long int, or unsigned long long int.
1781  //   If none of the types in that list can represent all the values of its
1782  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1783  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1784  //   type.
1785  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1786      ToType->isIntegerType()) {
1787    // Determine whether the type we're converting from is signed or
1788    // unsigned.
1789    bool FromIsSigned = FromType->isSignedIntegerType();
1790    uint64_t FromSize = Context.getTypeSize(FromType);
1791
1792    // The types we'll try to promote to, in the appropriate
1793    // order. Try each of these types.
1794    QualType PromoteTypes[6] = {
1795      Context.IntTy, Context.UnsignedIntTy,
1796      Context.LongTy, Context.UnsignedLongTy ,
1797      Context.LongLongTy, Context.UnsignedLongLongTy
1798    };
1799    for (int Idx = 0; Idx < 6; ++Idx) {
1800      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1801      if (FromSize < ToSize ||
1802          (FromSize == ToSize &&
1803           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1804        // We found the type that we can promote to. If this is the
1805        // type we wanted, we have a promotion. Otherwise, no
1806        // promotion.
1807        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1808      }
1809    }
1810  }
1811
1812  // An rvalue for an integral bit-field (9.6) can be converted to an
1813  // rvalue of type int if int can represent all the values of the
1814  // bit-field; otherwise, it can be converted to unsigned int if
1815  // unsigned int can represent all the values of the bit-field. If
1816  // the bit-field is larger yet, no integral promotion applies to
1817  // it. If the bit-field has an enumerated type, it is treated as any
1818  // other value of that type for promotion purposes (C++ 4.5p3).
1819  // FIXME: We should delay checking of bit-fields until we actually perform the
1820  // conversion.
1821  using llvm::APSInt;
1822  if (From)
1823    if (FieldDecl *MemberDecl = From->getBitField()) {
1824      APSInt BitWidth;
1825      if (FromType->isIntegralType(Context) &&
1826          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1827        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1828        ToSize = Context.getTypeSize(ToType);
1829
1830        // Are we promoting to an int from a bitfield that fits in an int?
1831        if (BitWidth < ToSize ||
1832            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1833          return To->getKind() == BuiltinType::Int;
1834        }
1835
1836        // Are we promoting to an unsigned int from an unsigned bitfield
1837        // that fits into an unsigned int?
1838        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1839          return To->getKind() == BuiltinType::UInt;
1840        }
1841
1842        return false;
1843      }
1844    }
1845
1846  // An rvalue of type bool can be converted to an rvalue of type int,
1847  // with false becoming zero and true becoming one (C++ 4.5p4).
1848  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1849    return true;
1850  }
1851
1852  return false;
1853}
1854
1855/// IsFloatingPointPromotion - Determines whether the conversion from
1856/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1857/// returns true and sets PromotedType to the promoted type.
1858bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1859  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1860    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1861      /// An rvalue of type float can be converted to an rvalue of type
1862      /// double. (C++ 4.6p1).
1863      if (FromBuiltin->getKind() == BuiltinType::Float &&
1864          ToBuiltin->getKind() == BuiltinType::Double)
1865        return true;
1866
1867      // C99 6.3.1.5p1:
1868      //   When a float is promoted to double or long double, or a
1869      //   double is promoted to long double [...].
1870      if (!getLangOpts().CPlusPlus &&
1871          (FromBuiltin->getKind() == BuiltinType::Float ||
1872           FromBuiltin->getKind() == BuiltinType::Double) &&
1873          (ToBuiltin->getKind() == BuiltinType::LongDouble))
1874        return true;
1875
1876      // Half can be promoted to float.
1877      if (!getLangOpts().NativeHalfType &&
1878           FromBuiltin->getKind() == BuiltinType::Half &&
1879          ToBuiltin->getKind() == BuiltinType::Float)
1880        return true;
1881    }
1882
1883  return false;
1884}
1885
1886/// \brief Determine if a conversion is a complex promotion.
1887///
1888/// A complex promotion is defined as a complex -> complex conversion
1889/// where the conversion between the underlying real types is a
1890/// floating-point or integral promotion.
1891bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1892  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1893  if (!FromComplex)
1894    return false;
1895
1896  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1897  if (!ToComplex)
1898    return false;
1899
1900  return IsFloatingPointPromotion(FromComplex->getElementType(),
1901                                  ToComplex->getElementType()) ||
1902    IsIntegralPromotion(0, FromComplex->getElementType(),
1903                        ToComplex->getElementType());
1904}
1905
1906/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1907/// the pointer type FromPtr to a pointer to type ToPointee, with the
1908/// same type qualifiers as FromPtr has on its pointee type. ToType,
1909/// if non-empty, will be a pointer to ToType that may or may not have
1910/// the right set of qualifiers on its pointee.
1911///
1912static QualType
1913BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1914                                   QualType ToPointee, QualType ToType,
1915                                   ASTContext &Context,
1916                                   bool StripObjCLifetime = false) {
1917  assert((FromPtr->getTypeClass() == Type::Pointer ||
1918          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1919         "Invalid similarly-qualified pointer type");
1920
1921  /// Conversions to 'id' subsume cv-qualifier conversions.
1922  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1923    return ToType.getUnqualifiedType();
1924
1925  QualType CanonFromPointee
1926    = Context.getCanonicalType(FromPtr->getPointeeType());
1927  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1928  Qualifiers Quals = CanonFromPointee.getQualifiers();
1929
1930  if (StripObjCLifetime)
1931    Quals.removeObjCLifetime();
1932
1933  // Exact qualifier match -> return the pointer type we're converting to.
1934  if (CanonToPointee.getLocalQualifiers() == Quals) {
1935    // ToType is exactly what we need. Return it.
1936    if (!ToType.isNull())
1937      return ToType.getUnqualifiedType();
1938
1939    // Build a pointer to ToPointee. It has the right qualifiers
1940    // already.
1941    if (isa<ObjCObjectPointerType>(ToType))
1942      return Context.getObjCObjectPointerType(ToPointee);
1943    return Context.getPointerType(ToPointee);
1944  }
1945
1946  // Just build a canonical type that has the right qualifiers.
1947  QualType QualifiedCanonToPointee
1948    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1949
1950  if (isa<ObjCObjectPointerType>(ToType))
1951    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1952  return Context.getPointerType(QualifiedCanonToPointee);
1953}
1954
1955static bool isNullPointerConstantForConversion(Expr *Expr,
1956                                               bool InOverloadResolution,
1957                                               ASTContext &Context) {
1958  // Handle value-dependent integral null pointer constants correctly.
1959  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1960  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1961      Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1962    return !InOverloadResolution;
1963
1964  return Expr->isNullPointerConstant(Context,
1965                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1966                                        : Expr::NPC_ValueDependentIsNull);
1967}
1968
1969/// IsPointerConversion - Determines whether the conversion of the
1970/// expression From, which has the (possibly adjusted) type FromType,
1971/// can be converted to the type ToType via a pointer conversion (C++
1972/// 4.10). If so, returns true and places the converted type (that
1973/// might differ from ToType in its cv-qualifiers at some level) into
1974/// ConvertedType.
1975///
1976/// This routine also supports conversions to and from block pointers
1977/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1978/// pointers to interfaces. FIXME: Once we've determined the
1979/// appropriate overloading rules for Objective-C, we may want to
1980/// split the Objective-C checks into a different routine; however,
1981/// GCC seems to consider all of these conversions to be pointer
1982/// conversions, so for now they live here. IncompatibleObjC will be
1983/// set if the conversion is an allowed Objective-C conversion that
1984/// should result in a warning.
1985bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1986                               bool InOverloadResolution,
1987                               QualType& ConvertedType,
1988                               bool &IncompatibleObjC) {
1989  IncompatibleObjC = false;
1990  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1991                              IncompatibleObjC))
1992    return true;
1993
1994  // Conversion from a null pointer constant to any Objective-C pointer type.
1995  if (ToType->isObjCObjectPointerType() &&
1996      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1997    ConvertedType = ToType;
1998    return true;
1999  }
2000
2001  // Blocks: Block pointers can be converted to void*.
2002  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2003      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2004    ConvertedType = ToType;
2005    return true;
2006  }
2007  // Blocks: A null pointer constant can be converted to a block
2008  // pointer type.
2009  if (ToType->isBlockPointerType() &&
2010      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2011    ConvertedType = ToType;
2012    return true;
2013  }
2014
2015  // If the left-hand-side is nullptr_t, the right side can be a null
2016  // pointer constant.
2017  if (ToType->isNullPtrType() &&
2018      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2019    ConvertedType = ToType;
2020    return true;
2021  }
2022
2023  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2024  if (!ToTypePtr)
2025    return false;
2026
2027  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2028  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2029    ConvertedType = ToType;
2030    return true;
2031  }
2032
2033  // Beyond this point, both types need to be pointers
2034  // , including objective-c pointers.
2035  QualType ToPointeeType = ToTypePtr->getPointeeType();
2036  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2037      !getLangOpts().ObjCAutoRefCount) {
2038    ConvertedType = BuildSimilarlyQualifiedPointerType(
2039                                      FromType->getAs<ObjCObjectPointerType>(),
2040                                                       ToPointeeType,
2041                                                       ToType, Context);
2042    return true;
2043  }
2044  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2045  if (!FromTypePtr)
2046    return false;
2047
2048  QualType FromPointeeType = FromTypePtr->getPointeeType();
2049
2050  // If the unqualified pointee types are the same, this can't be a
2051  // pointer conversion, so don't do all of the work below.
2052  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2053    return false;
2054
2055  // An rvalue of type "pointer to cv T," where T is an object type,
2056  // can be converted to an rvalue of type "pointer to cv void" (C++
2057  // 4.10p2).
2058  if (FromPointeeType->isIncompleteOrObjectType() &&
2059      ToPointeeType->isVoidType()) {
2060    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2061                                                       ToPointeeType,
2062                                                       ToType, Context,
2063                                                   /*StripObjCLifetime=*/true);
2064    return true;
2065  }
2066
2067  // MSVC allows implicit function to void* type conversion.
2068  if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2069      ToPointeeType->isVoidType()) {
2070    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2071                                                       ToPointeeType,
2072                                                       ToType, Context);
2073    return true;
2074  }
2075
2076  // When we're overloading in C, we allow a special kind of pointer
2077  // conversion for compatible-but-not-identical pointee types.
2078  if (!getLangOpts().CPlusPlus &&
2079      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2080    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2081                                                       ToPointeeType,
2082                                                       ToType, Context);
2083    return true;
2084  }
2085
2086  // C++ [conv.ptr]p3:
2087  //
2088  //   An rvalue of type "pointer to cv D," where D is a class type,
2089  //   can be converted to an rvalue of type "pointer to cv B," where
2090  //   B is a base class (clause 10) of D. If B is an inaccessible
2091  //   (clause 11) or ambiguous (10.2) base class of D, a program that
2092  //   necessitates this conversion is ill-formed. The result of the
2093  //   conversion is a pointer to the base class sub-object of the
2094  //   derived class object. The null pointer value is converted to
2095  //   the null pointer value of the destination type.
2096  //
2097  // Note that we do not check for ambiguity or inaccessibility
2098  // here. That is handled by CheckPointerConversion.
2099  if (getLangOpts().CPlusPlus &&
2100      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2101      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2102      !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2103      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2104    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2105                                                       ToPointeeType,
2106                                                       ToType, Context);
2107    return true;
2108  }
2109
2110  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2111      Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2112    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2113                                                       ToPointeeType,
2114                                                       ToType, Context);
2115    return true;
2116  }
2117
2118  return false;
2119}
2120
2121/// \brief Adopt the given qualifiers for the given type.
2122static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2123  Qualifiers TQs = T.getQualifiers();
2124
2125  // Check whether qualifiers already match.
2126  if (TQs == Qs)
2127    return T;
2128
2129  if (Qs.compatiblyIncludes(TQs))
2130    return Context.getQualifiedType(T, Qs);
2131
2132  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2133}
2134
2135/// isObjCPointerConversion - Determines whether this is an
2136/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2137/// with the same arguments and return values.
2138bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2139                                   QualType& ConvertedType,
2140                                   bool &IncompatibleObjC) {
2141  if (!getLangOpts().ObjC1)
2142    return false;
2143
2144  // The set of qualifiers on the type we're converting from.
2145  Qualifiers FromQualifiers = FromType.getQualifiers();
2146
2147  // First, we handle all conversions on ObjC object pointer types.
2148  const ObjCObjectPointerType* ToObjCPtr =
2149    ToType->getAs<ObjCObjectPointerType>();
2150  const ObjCObjectPointerType *FromObjCPtr =
2151    FromType->getAs<ObjCObjectPointerType>();
2152
2153  if (ToObjCPtr && FromObjCPtr) {
2154    // If the pointee types are the same (ignoring qualifications),
2155    // then this is not a pointer conversion.
2156    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2157                                       FromObjCPtr->getPointeeType()))
2158      return false;
2159
2160    // Check for compatible
2161    // Objective C++: We're able to convert between "id" or "Class" and a
2162    // pointer to any interface (in both directions).
2163    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2164      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2165      return true;
2166    }
2167    // Conversions with Objective-C's id<...>.
2168    if ((FromObjCPtr->isObjCQualifiedIdType() ||
2169         ToObjCPtr->isObjCQualifiedIdType()) &&
2170        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2171                                                  /*compare=*/false)) {
2172      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2173      return true;
2174    }
2175    // Objective C++: We're able to convert from a pointer to an
2176    // interface to a pointer to a different interface.
2177    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2178      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2179      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2180      if (getLangOpts().CPlusPlus && LHS && RHS &&
2181          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2182                                                FromObjCPtr->getPointeeType()))
2183        return false;
2184      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2185                                                   ToObjCPtr->getPointeeType(),
2186                                                         ToType, Context);
2187      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2188      return true;
2189    }
2190
2191    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2192      // Okay: this is some kind of implicit downcast of Objective-C
2193      // interfaces, which is permitted. However, we're going to
2194      // complain about it.
2195      IncompatibleObjC = true;
2196      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2197                                                   ToObjCPtr->getPointeeType(),
2198                                                         ToType, Context);
2199      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2200      return true;
2201    }
2202  }
2203  // Beyond this point, both types need to be C pointers or block pointers.
2204  QualType ToPointeeType;
2205  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2206    ToPointeeType = ToCPtr->getPointeeType();
2207  else if (const BlockPointerType *ToBlockPtr =
2208            ToType->getAs<BlockPointerType>()) {
2209    // Objective C++: We're able to convert from a pointer to any object
2210    // to a block pointer type.
2211    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2212      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2213      return true;
2214    }
2215    ToPointeeType = ToBlockPtr->getPointeeType();
2216  }
2217  else if (FromType->getAs<BlockPointerType>() &&
2218           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2219    // Objective C++: We're able to convert from a block pointer type to a
2220    // pointer to any object.
2221    ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2222    return true;
2223  }
2224  else
2225    return false;
2226
2227  QualType FromPointeeType;
2228  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2229    FromPointeeType = FromCPtr->getPointeeType();
2230  else if (const BlockPointerType *FromBlockPtr =
2231           FromType->getAs<BlockPointerType>())
2232    FromPointeeType = FromBlockPtr->getPointeeType();
2233  else
2234    return false;
2235
2236  // If we have pointers to pointers, recursively check whether this
2237  // is an Objective-C conversion.
2238  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2239      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2240                              IncompatibleObjC)) {
2241    // We always complain about this conversion.
2242    IncompatibleObjC = true;
2243    ConvertedType = Context.getPointerType(ConvertedType);
2244    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2245    return true;
2246  }
2247  // Allow conversion of pointee being objective-c pointer to another one;
2248  // as in I* to id.
2249  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2250      ToPointeeType->getAs<ObjCObjectPointerType>() &&
2251      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2252                              IncompatibleObjC)) {
2253
2254    ConvertedType = Context.getPointerType(ConvertedType);
2255    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2256    return true;
2257  }
2258
2259  // If we have pointers to functions or blocks, check whether the only
2260  // differences in the argument and result types are in Objective-C
2261  // pointer conversions. If so, we permit the conversion (but
2262  // complain about it).
2263  const FunctionProtoType *FromFunctionType
2264    = FromPointeeType->getAs<FunctionProtoType>();
2265  const FunctionProtoType *ToFunctionType
2266    = ToPointeeType->getAs<FunctionProtoType>();
2267  if (FromFunctionType && ToFunctionType) {
2268    // If the function types are exactly the same, this isn't an
2269    // Objective-C pointer conversion.
2270    if (Context.getCanonicalType(FromPointeeType)
2271          == Context.getCanonicalType(ToPointeeType))
2272      return false;
2273
2274    // Perform the quick checks that will tell us whether these
2275    // function types are obviously different.
2276    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2277        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2278        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2279      return false;
2280
2281    bool HasObjCConversion = false;
2282    if (Context.getCanonicalType(FromFunctionType->getResultType())
2283          == Context.getCanonicalType(ToFunctionType->getResultType())) {
2284      // Okay, the types match exactly. Nothing to do.
2285    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2286                                       ToFunctionType->getResultType(),
2287                                       ConvertedType, IncompatibleObjC)) {
2288      // Okay, we have an Objective-C pointer conversion.
2289      HasObjCConversion = true;
2290    } else {
2291      // Function types are too different. Abort.
2292      return false;
2293    }
2294
2295    // Check argument types.
2296    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2297         ArgIdx != NumArgs; ++ArgIdx) {
2298      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2299      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2300      if (Context.getCanonicalType(FromArgType)
2301            == Context.getCanonicalType(ToArgType)) {
2302        // Okay, the types match exactly. Nothing to do.
2303      } else if (isObjCPointerConversion(FromArgType, ToArgType,
2304                                         ConvertedType, IncompatibleObjC)) {
2305        // Okay, we have an Objective-C pointer conversion.
2306        HasObjCConversion = true;
2307      } else {
2308        // Argument types are too different. Abort.
2309        return false;
2310      }
2311    }
2312
2313    if (HasObjCConversion) {
2314      // We had an Objective-C conversion. Allow this pointer
2315      // conversion, but complain about it.
2316      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2317      IncompatibleObjC = true;
2318      return true;
2319    }
2320  }
2321
2322  return false;
2323}
2324
2325/// \brief Determine whether this is an Objective-C writeback conversion,
2326/// used for parameter passing when performing automatic reference counting.
2327///
2328/// \param FromType The type we're converting form.
2329///
2330/// \param ToType The type we're converting to.
2331///
2332/// \param ConvertedType The type that will be produced after applying
2333/// this conversion.
2334bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2335                                     QualType &ConvertedType) {
2336  if (!getLangOpts().ObjCAutoRefCount ||
2337      Context.hasSameUnqualifiedType(FromType, ToType))
2338    return false;
2339
2340  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2341  QualType ToPointee;
2342  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2343    ToPointee = ToPointer->getPointeeType();
2344  else
2345    return false;
2346
2347  Qualifiers ToQuals = ToPointee.getQualifiers();
2348  if (!ToPointee->isObjCLifetimeType() ||
2349      ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2350      !ToQuals.withoutObjCLifetime().empty())
2351    return false;
2352
2353  // Argument must be a pointer to __strong to __weak.
2354  QualType FromPointee;
2355  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2356    FromPointee = FromPointer->getPointeeType();
2357  else
2358    return false;
2359
2360  Qualifiers FromQuals = FromPointee.getQualifiers();
2361  if (!FromPointee->isObjCLifetimeType() ||
2362      (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2363       FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2364    return false;
2365
2366  // Make sure that we have compatible qualifiers.
2367  FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2368  if (!ToQuals.compatiblyIncludes(FromQuals))
2369    return false;
2370
2371  // Remove qualifiers from the pointee type we're converting from; they
2372  // aren't used in the compatibility check belong, and we'll be adding back
2373  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2374  FromPointee = FromPointee.getUnqualifiedType();
2375
2376  // The unqualified form of the pointee types must be compatible.
2377  ToPointee = ToPointee.getUnqualifiedType();
2378  bool IncompatibleObjC;
2379  if (Context.typesAreCompatible(FromPointee, ToPointee))
2380    FromPointee = ToPointee;
2381  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2382                                    IncompatibleObjC))
2383    return false;
2384
2385  /// \brief Construct the type we're converting to, which is a pointer to
2386  /// __autoreleasing pointee.
2387  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2388  ConvertedType = Context.getPointerType(FromPointee);
2389  return true;
2390}
2391
2392bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2393                                    QualType& ConvertedType) {
2394  QualType ToPointeeType;
2395  if (const BlockPointerType *ToBlockPtr =
2396        ToType->getAs<BlockPointerType>())
2397    ToPointeeType = ToBlockPtr->getPointeeType();
2398  else
2399    return false;
2400
2401  QualType FromPointeeType;
2402  if (const BlockPointerType *FromBlockPtr =
2403      FromType->getAs<BlockPointerType>())
2404    FromPointeeType = FromBlockPtr->getPointeeType();
2405  else
2406    return false;
2407  // We have pointer to blocks, check whether the only
2408  // differences in the argument and result types are in Objective-C
2409  // pointer conversions. If so, we permit the conversion.
2410
2411  const FunctionProtoType *FromFunctionType
2412    = FromPointeeType->getAs<FunctionProtoType>();
2413  const FunctionProtoType *ToFunctionType
2414    = ToPointeeType->getAs<FunctionProtoType>();
2415
2416  if (!FromFunctionType || !ToFunctionType)
2417    return false;
2418
2419  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2420    return true;
2421
2422  // Perform the quick checks that will tell us whether these
2423  // function types are obviously different.
2424  if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2425      FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2426    return false;
2427
2428  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2429  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2430  if (FromEInfo != ToEInfo)
2431    return false;
2432
2433  bool IncompatibleObjC = false;
2434  if (Context.hasSameType(FromFunctionType->getResultType(),
2435                          ToFunctionType->getResultType())) {
2436    // Okay, the types match exactly. Nothing to do.
2437  } else {
2438    QualType RHS = FromFunctionType->getResultType();
2439    QualType LHS = ToFunctionType->getResultType();
2440    if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2441        !RHS.hasQualifiers() && LHS.hasQualifiers())
2442       LHS = LHS.getUnqualifiedType();
2443
2444     if (Context.hasSameType(RHS,LHS)) {
2445       // OK exact match.
2446     } else if (isObjCPointerConversion(RHS, LHS,
2447                                        ConvertedType, IncompatibleObjC)) {
2448     if (IncompatibleObjC)
2449       return false;
2450     // Okay, we have an Objective-C pointer conversion.
2451     }
2452     else
2453       return false;
2454   }
2455
2456   // Check argument types.
2457   for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2458        ArgIdx != NumArgs; ++ArgIdx) {
2459     IncompatibleObjC = false;
2460     QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2461     QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2462     if (Context.hasSameType(FromArgType, ToArgType)) {
2463       // Okay, the types match exactly. Nothing to do.
2464     } else if (isObjCPointerConversion(ToArgType, FromArgType,
2465                                        ConvertedType, IncompatibleObjC)) {
2466       if (IncompatibleObjC)
2467         return false;
2468       // Okay, we have an Objective-C pointer conversion.
2469     } else
2470       // Argument types are too different. Abort.
2471       return false;
2472   }
2473   if (LangOpts.ObjCAutoRefCount &&
2474       !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2475                                                    ToFunctionType))
2476     return false;
2477
2478   ConvertedType = ToType;
2479   return true;
2480}
2481
2482enum {
2483  ft_default,
2484  ft_different_class,
2485  ft_parameter_arity,
2486  ft_parameter_mismatch,
2487  ft_return_type,
2488  ft_qualifer_mismatch
2489};
2490
2491/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2492/// function types.  Catches different number of parameter, mismatch in
2493/// parameter types, and different return types.
2494void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2495                                      QualType FromType, QualType ToType) {
2496  // If either type is not valid, include no extra info.
2497  if (FromType.isNull() || ToType.isNull()) {
2498    PDiag << ft_default;
2499    return;
2500  }
2501
2502  // Get the function type from the pointers.
2503  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2504    const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2505                            *ToMember = ToType->getAs<MemberPointerType>();
2506    if (FromMember->getClass() != ToMember->getClass()) {
2507      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2508            << QualType(FromMember->getClass(), 0);
2509      return;
2510    }
2511    FromType = FromMember->getPointeeType();
2512    ToType = ToMember->getPointeeType();
2513  }
2514
2515  if (FromType->isPointerType())
2516    FromType = FromType->getPointeeType();
2517  if (ToType->isPointerType())
2518    ToType = ToType->getPointeeType();
2519
2520  // Remove references.
2521  FromType = FromType.getNonReferenceType();
2522  ToType = ToType.getNonReferenceType();
2523
2524  // Don't print extra info for non-specialized template functions.
2525  if (FromType->isInstantiationDependentType() &&
2526      !FromType->getAs<TemplateSpecializationType>()) {
2527    PDiag << ft_default;
2528    return;
2529  }
2530
2531  // No extra info for same types.
2532  if (Context.hasSameType(FromType, ToType)) {
2533    PDiag << ft_default;
2534    return;
2535  }
2536
2537  const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2538                          *ToFunction = ToType->getAs<FunctionProtoType>();
2539
2540  // Both types need to be function types.
2541  if (!FromFunction || !ToFunction) {
2542    PDiag << ft_default;
2543    return;
2544  }
2545
2546  if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2547    PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2548          << FromFunction->getNumArgs();
2549    return;
2550  }
2551
2552  // Handle different parameter types.
2553  unsigned ArgPos;
2554  if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2555    PDiag << ft_parameter_mismatch << ArgPos + 1
2556          << ToFunction->getArgType(ArgPos)
2557          << FromFunction->getArgType(ArgPos);
2558    return;
2559  }
2560
2561  // Handle different return type.
2562  if (!Context.hasSameType(FromFunction->getResultType(),
2563                           ToFunction->getResultType())) {
2564    PDiag << ft_return_type << ToFunction->getResultType()
2565          << FromFunction->getResultType();
2566    return;
2567  }
2568
2569  unsigned FromQuals = FromFunction->getTypeQuals(),
2570           ToQuals = ToFunction->getTypeQuals();
2571  if (FromQuals != ToQuals) {
2572    PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2573    return;
2574  }
2575
2576  // Unable to find a difference, so add no extra info.
2577  PDiag << ft_default;
2578}
2579
2580/// FunctionArgTypesAreEqual - This routine checks two function proto types
2581/// for equality of their argument types. Caller has already checked that
2582/// they have same number of arguments. This routine assumes that Objective-C
2583/// pointer types which only differ in their protocol qualifiers are equal.
2584/// If the parameters are different, ArgPos will have the parameter index
2585/// of the first different parameter.
2586bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2587                                    const FunctionProtoType *NewType,
2588                                    unsigned *ArgPos) {
2589  if (!getLangOpts().ObjC1) {
2590    for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2591         N = NewType->arg_type_begin(),
2592         E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2593      if (!Context.hasSameType(*O, *N)) {
2594        if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2595        return false;
2596      }
2597    }
2598    return true;
2599  }
2600
2601  for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2602       N = NewType->arg_type_begin(),
2603       E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2604    QualType ToType = (*O);
2605    QualType FromType = (*N);
2606    if (!Context.hasSameType(ToType, FromType)) {
2607      if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2608        if (const PointerType *PTFr = FromType->getAs<PointerType>())
2609          if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2610               PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2611              (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2612               PTFr->getPointeeType()->isObjCQualifiedClassType()))
2613            continue;
2614      }
2615      else if (const ObjCObjectPointerType *PTTo =
2616                 ToType->getAs<ObjCObjectPointerType>()) {
2617        if (const ObjCObjectPointerType *PTFr =
2618              FromType->getAs<ObjCObjectPointerType>())
2619          if (Context.hasSameUnqualifiedType(
2620                PTTo->getObjectType()->getBaseType(),
2621                PTFr->getObjectType()->getBaseType()))
2622            continue;
2623      }
2624      if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2625      return false;
2626    }
2627  }
2628  return true;
2629}
2630
2631/// CheckPointerConversion - Check the pointer conversion from the
2632/// expression From to the type ToType. This routine checks for
2633/// ambiguous or inaccessible derived-to-base pointer
2634/// conversions for which IsPointerConversion has already returned
2635/// true. It returns true and produces a diagnostic if there was an
2636/// error, or returns false otherwise.
2637bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2638                                  CastKind &Kind,
2639                                  CXXCastPath& BasePath,
2640                                  bool IgnoreBaseAccess) {
2641  QualType FromType = From->getType();
2642  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2643
2644  Kind = CK_BitCast;
2645
2646  if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2647      From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2648      Expr::NPCK_ZeroExpression) {
2649    if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2650      DiagRuntimeBehavior(From->getExprLoc(), From,
2651                          PDiag(diag::warn_impcast_bool_to_null_pointer)
2652                            << ToType << From->getSourceRange());
2653    else if (!isUnevaluatedContext())
2654      Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2655        << ToType << From->getSourceRange();
2656  }
2657  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2658    if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2659      QualType FromPointeeType = FromPtrType->getPointeeType(),
2660               ToPointeeType   = ToPtrType->getPointeeType();
2661
2662      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2663          !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2664        // We must have a derived-to-base conversion. Check an
2665        // ambiguous or inaccessible conversion.
2666        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2667                                         From->getExprLoc(),
2668                                         From->getSourceRange(), &BasePath,
2669                                         IgnoreBaseAccess))
2670          return true;
2671
2672        // The conversion was successful.
2673        Kind = CK_DerivedToBase;
2674      }
2675    }
2676  } else if (const ObjCObjectPointerType *ToPtrType =
2677               ToType->getAs<ObjCObjectPointerType>()) {
2678    if (const ObjCObjectPointerType *FromPtrType =
2679          FromType->getAs<ObjCObjectPointerType>()) {
2680      // Objective-C++ conversions are always okay.
2681      // FIXME: We should have a different class of conversions for the
2682      // Objective-C++ implicit conversions.
2683      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2684        return false;
2685    } else if (FromType->isBlockPointerType()) {
2686      Kind = CK_BlockPointerToObjCPointerCast;
2687    } else {
2688      Kind = CK_CPointerToObjCPointerCast;
2689    }
2690  } else if (ToType->isBlockPointerType()) {
2691    if (!FromType->isBlockPointerType())
2692      Kind = CK_AnyPointerToBlockPointerCast;
2693  }
2694
2695  // We shouldn't fall into this case unless it's valid for other
2696  // reasons.
2697  if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2698    Kind = CK_NullToPointer;
2699
2700  return false;
2701}
2702
2703/// IsMemberPointerConversion - Determines whether the conversion of the
2704/// expression From, which has the (possibly adjusted) type FromType, can be
2705/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2706/// If so, returns true and places the converted type (that might differ from
2707/// ToType in its cv-qualifiers at some level) into ConvertedType.
2708bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2709                                     QualType ToType,
2710                                     bool InOverloadResolution,
2711                                     QualType &ConvertedType) {
2712  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2713  if (!ToTypePtr)
2714    return false;
2715
2716  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2717  if (From->isNullPointerConstant(Context,
2718                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2719                                        : Expr::NPC_ValueDependentIsNull)) {
2720    ConvertedType = ToType;
2721    return true;
2722  }
2723
2724  // Otherwise, both types have to be member pointers.
2725  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2726  if (!FromTypePtr)
2727    return false;
2728
2729  // A pointer to member of B can be converted to a pointer to member of D,
2730  // where D is derived from B (C++ 4.11p2).
2731  QualType FromClass(FromTypePtr->getClass(), 0);
2732  QualType ToClass(ToTypePtr->getClass(), 0);
2733
2734  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2735      !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2736      IsDerivedFrom(ToClass, FromClass)) {
2737    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2738                                                 ToClass.getTypePtr());
2739    return true;
2740  }
2741
2742  return false;
2743}
2744
2745/// CheckMemberPointerConversion - Check the member pointer conversion from the
2746/// expression From to the type ToType. This routine checks for ambiguous or
2747/// virtual or inaccessible base-to-derived member pointer conversions
2748/// for which IsMemberPointerConversion has already returned true. It returns
2749/// true and produces a diagnostic if there was an error, or returns false
2750/// otherwise.
2751bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2752                                        CastKind &Kind,
2753                                        CXXCastPath &BasePath,
2754                                        bool IgnoreBaseAccess) {
2755  QualType FromType = From->getType();
2756  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2757  if (!FromPtrType) {
2758    // This must be a null pointer to member pointer conversion
2759    assert(From->isNullPointerConstant(Context,
2760                                       Expr::NPC_ValueDependentIsNull) &&
2761           "Expr must be null pointer constant!");
2762    Kind = CK_NullToMemberPointer;
2763    return false;
2764  }
2765
2766  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2767  assert(ToPtrType && "No member pointer cast has a target type "
2768                      "that is not a member pointer.");
2769
2770  QualType FromClass = QualType(FromPtrType->getClass(), 0);
2771  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2772
2773  // FIXME: What about dependent types?
2774  assert(FromClass->isRecordType() && "Pointer into non-class.");
2775  assert(ToClass->isRecordType() && "Pointer into non-class.");
2776
2777  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2778                     /*DetectVirtual=*/true);
2779  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2780  assert(DerivationOkay &&
2781         "Should not have been called if derivation isn't OK.");
2782  (void)DerivationOkay;
2783
2784  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2785                                  getUnqualifiedType())) {
2786    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2787    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2788      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2789    return true;
2790  }
2791
2792  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2793    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2794      << FromClass << ToClass << QualType(VBase, 0)
2795      << From->getSourceRange();
2796    return true;
2797  }
2798
2799  if (!IgnoreBaseAccess)
2800    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2801                         Paths.front(),
2802                         diag::err_downcast_from_inaccessible_base);
2803
2804  // Must be a base to derived member conversion.
2805  BuildBasePathArray(Paths, BasePath);
2806  Kind = CK_BaseToDerivedMemberPointer;
2807  return false;
2808}
2809
2810/// IsQualificationConversion - Determines whether the conversion from
2811/// an rvalue of type FromType to ToType is a qualification conversion
2812/// (C++ 4.4).
2813///
2814/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2815/// when the qualification conversion involves a change in the Objective-C
2816/// object lifetime.
2817bool
2818Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2819                                bool CStyle, bool &ObjCLifetimeConversion) {
2820  FromType = Context.getCanonicalType(FromType);
2821  ToType = Context.getCanonicalType(ToType);
2822  ObjCLifetimeConversion = false;
2823
2824  // If FromType and ToType are the same type, this is not a
2825  // qualification conversion.
2826  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2827    return false;
2828
2829  // (C++ 4.4p4):
2830  //   A conversion can add cv-qualifiers at levels other than the first
2831  //   in multi-level pointers, subject to the following rules: [...]
2832  bool PreviousToQualsIncludeConst = true;
2833  bool UnwrappedAnyPointer = false;
2834  while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2835    // Within each iteration of the loop, we check the qualifiers to
2836    // determine if this still looks like a qualification
2837    // conversion. Then, if all is well, we unwrap one more level of
2838    // pointers or pointers-to-members and do it all again
2839    // until there are no more pointers or pointers-to-members left to
2840    // unwrap.
2841    UnwrappedAnyPointer = true;
2842
2843    Qualifiers FromQuals = FromType.getQualifiers();
2844    Qualifiers ToQuals = ToType.getQualifiers();
2845
2846    // Objective-C ARC:
2847    //   Check Objective-C lifetime conversions.
2848    if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2849        UnwrappedAnyPointer) {
2850      if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2851        ObjCLifetimeConversion = true;
2852        FromQuals.removeObjCLifetime();
2853        ToQuals.removeObjCLifetime();
2854      } else {
2855        // Qualification conversions cannot cast between different
2856        // Objective-C lifetime qualifiers.
2857        return false;
2858      }
2859    }
2860
2861    // Allow addition/removal of GC attributes but not changing GC attributes.
2862    if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2863        (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2864      FromQuals.removeObjCGCAttr();
2865      ToQuals.removeObjCGCAttr();
2866    }
2867
2868    //   -- for every j > 0, if const is in cv 1,j then const is in cv
2869    //      2,j, and similarly for volatile.
2870    if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2871      return false;
2872
2873    //   -- if the cv 1,j and cv 2,j are different, then const is in
2874    //      every cv for 0 < k < j.
2875    if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2876        && !PreviousToQualsIncludeConst)
2877      return false;
2878
2879    // Keep track of whether all prior cv-qualifiers in the "to" type
2880    // include const.
2881    PreviousToQualsIncludeConst
2882      = PreviousToQualsIncludeConst && ToQuals.hasConst();
2883  }
2884
2885  // We are left with FromType and ToType being the pointee types
2886  // after unwrapping the original FromType and ToType the same number
2887  // of types. If we unwrapped any pointers, and if FromType and
2888  // ToType have the same unqualified type (since we checked
2889  // qualifiers above), then this is a qualification conversion.
2890  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2891}
2892
2893/// \brief - Determine whether this is a conversion from a scalar type to an
2894/// atomic type.
2895///
2896/// If successful, updates \c SCS's second and third steps in the conversion
2897/// sequence to finish the conversion.
2898static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2899                                bool InOverloadResolution,
2900                                StandardConversionSequence &SCS,
2901                                bool CStyle) {
2902  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2903  if (!ToAtomic)
2904    return false;
2905
2906  StandardConversionSequence InnerSCS;
2907  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2908                            InOverloadResolution, InnerSCS,
2909                            CStyle, /*AllowObjCWritebackConversion=*/false))
2910    return false;
2911
2912  SCS.Second = InnerSCS.Second;
2913  SCS.setToType(1, InnerSCS.getToType(1));
2914  SCS.Third = InnerSCS.Third;
2915  SCS.QualificationIncludesObjCLifetime
2916    = InnerSCS.QualificationIncludesObjCLifetime;
2917  SCS.setToType(2, InnerSCS.getToType(2));
2918  return true;
2919}
2920
2921static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2922                                              CXXConstructorDecl *Constructor,
2923                                              QualType Type) {
2924  const FunctionProtoType *CtorType =
2925      Constructor->getType()->getAs<FunctionProtoType>();
2926  if (CtorType->getNumArgs() > 0) {
2927    QualType FirstArg = CtorType->getArgType(0);
2928    if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2929      return true;
2930  }
2931  return false;
2932}
2933
2934static OverloadingResult
2935IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2936                                       CXXRecordDecl *To,
2937                                       UserDefinedConversionSequence &User,
2938                                       OverloadCandidateSet &CandidateSet,
2939                                       bool AllowExplicit) {
2940  DeclContext::lookup_result R = S.LookupConstructors(To);
2941  for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2942       Con != ConEnd; ++Con) {
2943    NamedDecl *D = *Con;
2944    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2945
2946    // Find the constructor (which may be a template).
2947    CXXConstructorDecl *Constructor = 0;
2948    FunctionTemplateDecl *ConstructorTmpl
2949      = dyn_cast<FunctionTemplateDecl>(D);
2950    if (ConstructorTmpl)
2951      Constructor
2952        = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2953    else
2954      Constructor = cast<CXXConstructorDecl>(D);
2955
2956    bool Usable = !Constructor->isInvalidDecl() &&
2957                  S.isInitListConstructor(Constructor) &&
2958                  (AllowExplicit || !Constructor->isExplicit());
2959    if (Usable) {
2960      // If the first argument is (a reference to) the target type,
2961      // suppress conversions.
2962      bool SuppressUserConversions =
2963          isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2964      if (ConstructorTmpl)
2965        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2966                                       /*ExplicitArgs*/ 0,
2967                                       From, CandidateSet,
2968                                       SuppressUserConversions);
2969      else
2970        S.AddOverloadCandidate(Constructor, FoundDecl,
2971                               From, CandidateSet,
2972                               SuppressUserConversions);
2973    }
2974  }
2975
2976  bool HadMultipleCandidates = (CandidateSet.size() > 1);
2977
2978  OverloadCandidateSet::iterator Best;
2979  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2980  case OR_Success: {
2981    // Record the standard conversion we used and the conversion function.
2982    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2983    QualType ThisType = Constructor->getThisType(S.Context);
2984    // Initializer lists don't have conversions as such.
2985    User.Before.setAsIdentityConversion();
2986    User.HadMultipleCandidates = HadMultipleCandidates;
2987    User.ConversionFunction = Constructor;
2988    User.FoundConversionFunction = Best->FoundDecl;
2989    User.After.setAsIdentityConversion();
2990    User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2991    User.After.setAllToTypes(ToType);
2992    return OR_Success;
2993  }
2994
2995  case OR_No_Viable_Function:
2996    return OR_No_Viable_Function;
2997  case OR_Deleted:
2998    return OR_Deleted;
2999  case OR_Ambiguous:
3000    return OR_Ambiguous;
3001  }
3002
3003  llvm_unreachable("Invalid OverloadResult!");
3004}
3005
3006/// Determines whether there is a user-defined conversion sequence
3007/// (C++ [over.ics.user]) that converts expression From to the type
3008/// ToType. If such a conversion exists, User will contain the
3009/// user-defined conversion sequence that performs such a conversion
3010/// and this routine will return true. Otherwise, this routine returns
3011/// false and User is unspecified.
3012///
3013/// \param AllowExplicit  true if the conversion should consider C++0x
3014/// "explicit" conversion functions as well as non-explicit conversion
3015/// functions (C++0x [class.conv.fct]p2).
3016static OverloadingResult
3017IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3018                        UserDefinedConversionSequence &User,
3019                        OverloadCandidateSet &CandidateSet,
3020                        bool AllowExplicit) {
3021  // Whether we will only visit constructors.
3022  bool ConstructorsOnly = false;
3023
3024  // If the type we are conversion to is a class type, enumerate its
3025  // constructors.
3026  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3027    // C++ [over.match.ctor]p1:
3028    //   When objects of class type are direct-initialized (8.5), or
3029    //   copy-initialized from an expression of the same or a
3030    //   derived class type (8.5), overload resolution selects the
3031    //   constructor. [...] For copy-initialization, the candidate
3032    //   functions are all the converting constructors (12.3.1) of
3033    //   that class. The argument list is the expression-list within
3034    //   the parentheses of the initializer.
3035    if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3036        (From->getType()->getAs<RecordType>() &&
3037         S.IsDerivedFrom(From->getType(), ToType)))
3038      ConstructorsOnly = true;
3039
3040    S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3041    // RequireCompleteType may have returned true due to some invalid decl
3042    // during template instantiation, but ToType may be complete enough now
3043    // to try to recover.
3044    if (ToType->isIncompleteType()) {
3045      // We're not going to find any constructors.
3046    } else if (CXXRecordDecl *ToRecordDecl
3047                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3048
3049      Expr **Args = &From;
3050      unsigned NumArgs = 1;
3051      bool ListInitializing = false;
3052      if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3053        // But first, see if there is an init-list-contructor that will work.
3054        OverloadingResult Result = IsInitializerListConstructorConversion(
3055            S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3056        if (Result != OR_No_Viable_Function)
3057          return Result;
3058        // Never mind.
3059        CandidateSet.clear();
3060
3061        // If we're list-initializing, we pass the individual elements as
3062        // arguments, not the entire list.
3063        Args = InitList->getInits();
3064        NumArgs = InitList->getNumInits();
3065        ListInitializing = true;
3066      }
3067
3068      DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3069      for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3070           Con != ConEnd; ++Con) {
3071        NamedDecl *D = *Con;
3072        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3073
3074        // Find the constructor (which may be a template).
3075        CXXConstructorDecl *Constructor = 0;
3076        FunctionTemplateDecl *ConstructorTmpl
3077          = dyn_cast<FunctionTemplateDecl>(D);
3078        if (ConstructorTmpl)
3079          Constructor
3080            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3081        else
3082          Constructor = cast<CXXConstructorDecl>(D);
3083
3084        bool Usable = !Constructor->isInvalidDecl();
3085        if (ListInitializing)
3086          Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3087        else
3088          Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3089        if (Usable) {
3090          bool SuppressUserConversions = !ConstructorsOnly;
3091          if (SuppressUserConversions && ListInitializing) {
3092            SuppressUserConversions = false;
3093            if (NumArgs == 1) {
3094              // If the first argument is (a reference to) the target type,
3095              // suppress conversions.
3096              SuppressUserConversions = isFirstArgumentCompatibleWithType(
3097                                                S.Context, Constructor, ToType);
3098            }
3099          }
3100          if (ConstructorTmpl)
3101            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3102                                           /*ExplicitArgs*/ 0,
3103                                           llvm::makeArrayRef(Args, NumArgs),
3104                                           CandidateSet, SuppressUserConversions);
3105          else
3106            // Allow one user-defined conversion when user specifies a
3107            // From->ToType conversion via an static cast (c-style, etc).
3108            S.AddOverloadCandidate(Constructor, FoundDecl,
3109                                   llvm::makeArrayRef(Args, NumArgs),
3110                                   CandidateSet, SuppressUserConversions);
3111        }
3112      }
3113    }
3114  }
3115
3116  // Enumerate conversion functions, if we're allowed to.
3117  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3118  } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3119    // No conversion functions from incomplete types.
3120  } else if (const RecordType *FromRecordType
3121                                   = From->getType()->getAs<RecordType>()) {
3122    if (CXXRecordDecl *FromRecordDecl
3123         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3124      // Add all of the conversion functions as candidates.
3125      std::pair<CXXRecordDecl::conversion_iterator,
3126                CXXRecordDecl::conversion_iterator>
3127        Conversions = FromRecordDecl->getVisibleConversionFunctions();
3128      for (CXXRecordDecl::conversion_iterator
3129             I = Conversions.first, E = Conversions.second; I != E; ++I) {
3130        DeclAccessPair FoundDecl = I.getPair();
3131        NamedDecl *D = FoundDecl.getDecl();
3132        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3133        if (isa<UsingShadowDecl>(D))
3134          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3135
3136        CXXConversionDecl *Conv;
3137        FunctionTemplateDecl *ConvTemplate;
3138        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3139          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3140        else
3141          Conv = cast<CXXConversionDecl>(D);
3142
3143        if (AllowExplicit || !Conv->isExplicit()) {
3144          if (ConvTemplate)
3145            S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3146                                             ActingContext, From, ToType,
3147                                             CandidateSet);
3148          else
3149            S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3150                                     From, ToType, CandidateSet);
3151        }
3152      }
3153    }
3154  }
3155
3156  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3157
3158  OverloadCandidateSet::iterator Best;
3159  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3160  case OR_Success:
3161    // Record the standard conversion we used and the conversion function.
3162    if (CXXConstructorDecl *Constructor
3163          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3164      // C++ [over.ics.user]p1:
3165      //   If the user-defined conversion is specified by a
3166      //   constructor (12.3.1), the initial standard conversion
3167      //   sequence converts the source type to the type required by
3168      //   the argument of the constructor.
3169      //
3170      QualType ThisType = Constructor->getThisType(S.Context);
3171      if (isa<InitListExpr>(From)) {
3172        // Initializer lists don't have conversions as such.
3173        User.Before.setAsIdentityConversion();
3174      } else {
3175        if (Best->Conversions[0].isEllipsis())
3176          User.EllipsisConversion = true;
3177        else {
3178          User.Before = Best->Conversions[0].Standard;
3179          User.EllipsisConversion = false;
3180        }
3181      }
3182      User.HadMultipleCandidates = HadMultipleCandidates;
3183      User.ConversionFunction = Constructor;
3184      User.FoundConversionFunction = Best->FoundDecl;
3185      User.After.setAsIdentityConversion();
3186      User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3187      User.After.setAllToTypes(ToType);
3188      return OR_Success;
3189    }
3190    if (CXXConversionDecl *Conversion
3191                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3192      // C++ [over.ics.user]p1:
3193      //
3194      //   [...] If the user-defined conversion is specified by a
3195      //   conversion function (12.3.2), the initial standard
3196      //   conversion sequence converts the source type to the
3197      //   implicit object parameter of the conversion function.
3198      User.Before = Best->Conversions[0].Standard;
3199      User.HadMultipleCandidates = HadMultipleCandidates;
3200      User.ConversionFunction = Conversion;
3201      User.FoundConversionFunction = Best->FoundDecl;
3202      User.EllipsisConversion = false;
3203
3204      // C++ [over.ics.user]p2:
3205      //   The second standard conversion sequence converts the
3206      //   result of the user-defined conversion to the target type
3207      //   for the sequence. Since an implicit conversion sequence
3208      //   is an initialization, the special rules for
3209      //   initialization by user-defined conversion apply when
3210      //   selecting the best user-defined conversion for a
3211      //   user-defined conversion sequence (see 13.3.3 and
3212      //   13.3.3.1).
3213      User.After = Best->FinalConversion;
3214      return OR_Success;
3215    }
3216    llvm_unreachable("Not a constructor or conversion function?");
3217
3218  case OR_No_Viable_Function:
3219    return OR_No_Viable_Function;
3220  case OR_Deleted:
3221    // No conversion here! We're done.
3222    return OR_Deleted;
3223
3224  case OR_Ambiguous:
3225    return OR_Ambiguous;
3226  }
3227
3228  llvm_unreachable("Invalid OverloadResult!");
3229}
3230
3231bool
3232Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3233  ImplicitConversionSequence ICS;
3234  OverloadCandidateSet CandidateSet(From->getExprLoc());
3235  OverloadingResult OvResult =
3236    IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3237                            CandidateSet, false);
3238  if (OvResult == OR_Ambiguous)
3239    Diag(From->getLocStart(),
3240         diag::err_typecheck_ambiguous_condition)
3241          << From->getType() << ToType << From->getSourceRange();
3242  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3243    Diag(From->getLocStart(),
3244         diag::err_typecheck_nonviable_condition)
3245    << From->getType() << ToType << From->getSourceRange();
3246  else
3247    return false;
3248  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3249  return true;
3250}
3251
3252/// \brief Compare the user-defined conversion functions or constructors
3253/// of two user-defined conversion sequences to determine whether any ordering
3254/// is possible.
3255static ImplicitConversionSequence::CompareKind
3256compareConversionFunctions(Sema &S,
3257                           FunctionDecl *Function1,
3258                           FunctionDecl *Function2) {
3259  if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3260    return ImplicitConversionSequence::Indistinguishable;
3261
3262  // Objective-C++:
3263  //   If both conversion functions are implicitly-declared conversions from
3264  //   a lambda closure type to a function pointer and a block pointer,
3265  //   respectively, always prefer the conversion to a function pointer,
3266  //   because the function pointer is more lightweight and is more likely
3267  //   to keep code working.
3268  CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3269  if (!Conv1)
3270    return ImplicitConversionSequence::Indistinguishable;
3271
3272  CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3273  if (!Conv2)
3274    return ImplicitConversionSequence::Indistinguishable;
3275
3276  if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3277    bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3278    bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3279    if (Block1 != Block2)
3280      return Block1? ImplicitConversionSequence::Worse
3281                   : ImplicitConversionSequence::Better;
3282  }
3283
3284  return ImplicitConversionSequence::Indistinguishable;
3285}
3286
3287/// CompareImplicitConversionSequences - Compare two implicit
3288/// conversion sequences to determine whether one is better than the
3289/// other or if they are indistinguishable (C++ 13.3.3.2).
3290static ImplicitConversionSequence::CompareKind
3291CompareImplicitConversionSequences(Sema &S,
3292                                   const ImplicitConversionSequence& ICS1,
3293                                   const ImplicitConversionSequence& ICS2)
3294{
3295  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3296  // conversion sequences (as defined in 13.3.3.1)
3297  //   -- a standard conversion sequence (13.3.3.1.1) is a better
3298  //      conversion sequence than a user-defined conversion sequence or
3299  //      an ellipsis conversion sequence, and
3300  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3301  //      conversion sequence than an ellipsis conversion sequence
3302  //      (13.3.3.1.3).
3303  //
3304  // C++0x [over.best.ics]p10:
3305  //   For the purpose of ranking implicit conversion sequences as
3306  //   described in 13.3.3.2, the ambiguous conversion sequence is
3307  //   treated as a user-defined sequence that is indistinguishable
3308  //   from any other user-defined conversion sequence.
3309  if (ICS1.getKindRank() < ICS2.getKindRank())
3310    return ImplicitConversionSequence::Better;
3311  if (ICS2.getKindRank() < ICS1.getKindRank())
3312    return ImplicitConversionSequence::Worse;
3313
3314  // The following checks require both conversion sequences to be of
3315  // the same kind.
3316  if (ICS1.getKind() != ICS2.getKind())
3317    return ImplicitConversionSequence::Indistinguishable;
3318
3319  ImplicitConversionSequence::CompareKind Result =
3320      ImplicitConversionSequence::Indistinguishable;
3321
3322  // Two implicit conversion sequences of the same form are
3323  // indistinguishable conversion sequences unless one of the
3324  // following rules apply: (C++ 13.3.3.2p3):
3325  if (ICS1.isStandard())
3326    Result = CompareStandardConversionSequences(S,
3327                                                ICS1.Standard, ICS2.Standard);
3328  else if (ICS1.isUserDefined()) {
3329    // User-defined conversion sequence U1 is a better conversion
3330    // sequence than another user-defined conversion sequence U2 if
3331    // they contain the same user-defined conversion function or
3332    // constructor and if the second standard conversion sequence of
3333    // U1 is better than the second standard conversion sequence of
3334    // U2 (C++ 13.3.3.2p3).
3335    if (ICS1.UserDefined.ConversionFunction ==
3336          ICS2.UserDefined.ConversionFunction)
3337      Result = CompareStandardConversionSequences(S,
3338                                                  ICS1.UserDefined.After,
3339                                                  ICS2.UserDefined.After);
3340    else
3341      Result = compareConversionFunctions(S,
3342                                          ICS1.UserDefined.ConversionFunction,
3343                                          ICS2.UserDefined.ConversionFunction);
3344  }
3345
3346  // List-initialization sequence L1 is a better conversion sequence than
3347  // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3348  // for some X and L2 does not.
3349  if (Result == ImplicitConversionSequence::Indistinguishable &&
3350      !ICS1.isBad() &&
3351      ICS1.isListInitializationSequence() &&
3352      ICS2.isListInitializationSequence()) {
3353    if (ICS1.isStdInitializerListElement() &&
3354        !ICS2.isStdInitializerListElement())
3355      return ImplicitConversionSequence::Better;
3356    if (!ICS1.isStdInitializerListElement() &&
3357        ICS2.isStdInitializerListElement())
3358      return ImplicitConversionSequence::Worse;
3359  }
3360
3361  return Result;
3362}
3363
3364static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3365  while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3366    Qualifiers Quals;
3367    T1 = Context.getUnqualifiedArrayType(T1, Quals);
3368    T2 = Context.getUnqualifiedArrayType(T2, Quals);
3369  }
3370
3371  return Context.hasSameUnqualifiedType(T1, T2);
3372}
3373
3374// Per 13.3.3.2p3, compare the given standard conversion sequences to
3375// determine if one is a proper subset of the other.
3376static ImplicitConversionSequence::CompareKind
3377compareStandardConversionSubsets(ASTContext &Context,
3378                                 const StandardConversionSequence& SCS1,
3379                                 const StandardConversionSequence& SCS2) {
3380  ImplicitConversionSequence::CompareKind Result
3381    = ImplicitConversionSequence::Indistinguishable;
3382
3383  // the identity conversion sequence is considered to be a subsequence of
3384  // any non-identity conversion sequence
3385  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3386    return ImplicitConversionSequence::Better;
3387  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3388    return ImplicitConversionSequence::Worse;
3389
3390  if (SCS1.Second != SCS2.Second) {
3391    if (SCS1.Second == ICK_Identity)
3392      Result = ImplicitConversionSequence::Better;
3393    else if (SCS2.Second == ICK_Identity)
3394      Result = ImplicitConversionSequence::Worse;
3395    else
3396      return ImplicitConversionSequence::Indistinguishable;
3397  } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3398    return ImplicitConversionSequence::Indistinguishable;
3399
3400  if (SCS1.Third == SCS2.Third) {
3401    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3402                             : ImplicitConversionSequence::Indistinguishable;
3403  }
3404
3405  if (SCS1.Third == ICK_Identity)
3406    return Result == ImplicitConversionSequence::Worse
3407             ? ImplicitConversionSequence::Indistinguishable
3408             : ImplicitConversionSequence::Better;
3409
3410  if (SCS2.Third == ICK_Identity)
3411    return Result == ImplicitConversionSequence::Better
3412             ? ImplicitConversionSequence::Indistinguishable
3413             : ImplicitConversionSequence::Worse;
3414
3415  return ImplicitConversionSequence::Indistinguishable;
3416}
3417
3418/// \brief Determine whether one of the given reference bindings is better
3419/// than the other based on what kind of bindings they are.
3420static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3421                                       const StandardConversionSequence &SCS2) {
3422  // C++0x [over.ics.rank]p3b4:
3423  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3424  //      implicit object parameter of a non-static member function declared
3425  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3426  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3427  //      lvalue reference to a function lvalue and S2 binds an rvalue
3428  //      reference*.
3429  //
3430  // FIXME: Rvalue references. We're going rogue with the above edits,
3431  // because the semantics in the current C++0x working paper (N3225 at the
3432  // time of this writing) break the standard definition of std::forward
3433  // and std::reference_wrapper when dealing with references to functions.
3434  // Proposed wording changes submitted to CWG for consideration.
3435  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3436      SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3437    return false;
3438
3439  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3440          SCS2.IsLvalueReference) ||
3441         (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3442          !SCS2.IsLvalueReference);
3443}
3444
3445/// CompareStandardConversionSequences - Compare two standard
3446/// conversion sequences to determine whether one is better than the
3447/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3448static ImplicitConversionSequence::CompareKind
3449CompareStandardConversionSequences(Sema &S,
3450                                   const StandardConversionSequence& SCS1,
3451                                   const StandardConversionSequence& SCS2)
3452{
3453  // Standard conversion sequence S1 is a better conversion sequence
3454  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3455
3456  //  -- S1 is a proper subsequence of S2 (comparing the conversion
3457  //     sequences in the canonical form defined by 13.3.3.1.1,
3458  //     excluding any Lvalue Transformation; the identity conversion
3459  //     sequence is considered to be a subsequence of any
3460  //     non-identity conversion sequence) or, if not that,
3461  if (ImplicitConversionSequence::CompareKind CK
3462        = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3463    return CK;
3464
3465  //  -- the rank of S1 is better than the rank of S2 (by the rules
3466  //     defined below), or, if not that,
3467  ImplicitConversionRank Rank1 = SCS1.getRank();
3468  ImplicitConversionRank Rank2 = SCS2.getRank();
3469  if (Rank1 < Rank2)
3470    return ImplicitConversionSequence::Better;
3471  else if (Rank2 < Rank1)
3472    return ImplicitConversionSequence::Worse;
3473
3474  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3475  // are indistinguishable unless one of the following rules
3476  // applies:
3477
3478  //   A conversion that is not a conversion of a pointer, or
3479  //   pointer to member, to bool is better than another conversion
3480  //   that is such a conversion.
3481  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3482    return SCS2.isPointerConversionToBool()
3483             ? ImplicitConversionSequence::Better
3484             : ImplicitConversionSequence::Worse;
3485
3486  // C++ [over.ics.rank]p4b2:
3487  //
3488  //   If class B is derived directly or indirectly from class A,
3489  //   conversion of B* to A* is better than conversion of B* to
3490  //   void*, and conversion of A* to void* is better than conversion
3491  //   of B* to void*.
3492  bool SCS1ConvertsToVoid
3493    = SCS1.isPointerConversionToVoidPointer(S.Context);
3494  bool SCS2ConvertsToVoid
3495    = SCS2.isPointerConversionToVoidPointer(S.Context);
3496  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3497    // Exactly one of the conversion sequences is a conversion to
3498    // a void pointer; it's the worse conversion.
3499    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3500                              : ImplicitConversionSequence::Worse;
3501  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3502    // Neither conversion sequence converts to a void pointer; compare
3503    // their derived-to-base conversions.
3504    if (ImplicitConversionSequence::CompareKind DerivedCK
3505          = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3506      return DerivedCK;
3507  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3508             !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3509    // Both conversion sequences are conversions to void
3510    // pointers. Compare the source types to determine if there's an
3511    // inheritance relationship in their sources.
3512    QualType FromType1 = SCS1.getFromType();
3513    QualType FromType2 = SCS2.getFromType();
3514
3515    // Adjust the types we're converting from via the array-to-pointer
3516    // conversion, if we need to.
3517    if (SCS1.First == ICK_Array_To_Pointer)
3518      FromType1 = S.Context.getArrayDecayedType(FromType1);
3519    if (SCS2.First == ICK_Array_To_Pointer)
3520      FromType2 = S.Context.getArrayDecayedType(FromType2);
3521
3522    QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3523    QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3524
3525    if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3526      return ImplicitConversionSequence::Better;
3527    else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3528      return ImplicitConversionSequence::Worse;
3529
3530    // Objective-C++: If one interface is more specific than the
3531    // other, it is the better one.
3532    const ObjCObjectPointerType* FromObjCPtr1
3533      = FromType1->getAs<ObjCObjectPointerType>();
3534    const ObjCObjectPointerType* FromObjCPtr2
3535      = FromType2->getAs<ObjCObjectPointerType>();
3536    if (FromObjCPtr1 && FromObjCPtr2) {
3537      bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3538                                                          FromObjCPtr2);
3539      bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3540                                                           FromObjCPtr1);
3541      if (AssignLeft != AssignRight) {
3542        return AssignLeft? ImplicitConversionSequence::Better
3543                         : ImplicitConversionSequence::Worse;
3544      }
3545    }
3546  }
3547
3548  // Compare based on qualification conversions (C++ 13.3.3.2p3,
3549  // bullet 3).
3550  if (ImplicitConversionSequence::CompareKind QualCK
3551        = CompareQualificationConversions(S, SCS1, SCS2))
3552    return QualCK;
3553
3554  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3555    // Check for a better reference binding based on the kind of bindings.
3556    if (isBetterReferenceBindingKind(SCS1, SCS2))
3557      return ImplicitConversionSequence::Better;
3558    else if (isBetterReferenceBindingKind(SCS2, SCS1))
3559      return ImplicitConversionSequence::Worse;
3560
3561    // C++ [over.ics.rank]p3b4:
3562    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3563    //      which the references refer are the same type except for
3564    //      top-level cv-qualifiers, and the type to which the reference
3565    //      initialized by S2 refers is more cv-qualified than the type
3566    //      to which the reference initialized by S1 refers.
3567    QualType T1 = SCS1.getToType(2);
3568    QualType T2 = SCS2.getToType(2);
3569    T1 = S.Context.getCanonicalType(T1);
3570    T2 = S.Context.getCanonicalType(T2);
3571    Qualifiers T1Quals, T2Quals;
3572    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3573    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3574    if (UnqualT1 == UnqualT2) {
3575      // Objective-C++ ARC: If the references refer to objects with different
3576      // lifetimes, prefer bindings that don't change lifetime.
3577      if (SCS1.ObjCLifetimeConversionBinding !=
3578                                          SCS2.ObjCLifetimeConversionBinding) {
3579        return SCS1.ObjCLifetimeConversionBinding
3580                                           ? ImplicitConversionSequence::Worse
3581                                           : ImplicitConversionSequence::Better;
3582      }
3583
3584      // If the type is an array type, promote the element qualifiers to the
3585      // type for comparison.
3586      if (isa<ArrayType>(T1) && T1Quals)
3587        T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3588      if (isa<ArrayType>(T2) && T2Quals)
3589        T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3590      if (T2.isMoreQualifiedThan(T1))
3591        return ImplicitConversionSequence::Better;
3592      else if (T1.isMoreQualifiedThan(T2))
3593        return ImplicitConversionSequence::Worse;
3594    }
3595  }
3596
3597  // In Microsoft mode, prefer an integral conversion to a
3598  // floating-to-integral conversion if the integral conversion
3599  // is between types of the same size.
3600  // For example:
3601  // void f(float);
3602  // void f(int);
3603  // int main {
3604  //    long a;
3605  //    f(a);
3606  // }
3607  // Here, MSVC will call f(int) instead of generating a compile error
3608  // as clang will do in standard mode.
3609  if (S.getLangOpts().MicrosoftMode &&
3610      SCS1.Second == ICK_Integral_Conversion &&
3611      SCS2.Second == ICK_Floating_Integral &&
3612      S.Context.getTypeSize(SCS1.getFromType()) ==
3613      S.Context.getTypeSize(SCS1.getToType(2)))
3614    return ImplicitConversionSequence::Better;
3615
3616  return ImplicitConversionSequence::Indistinguishable;
3617}
3618
3619/// CompareQualificationConversions - Compares two standard conversion
3620/// sequences to determine whether they can be ranked based on their
3621/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3622ImplicitConversionSequence::CompareKind
3623CompareQualificationConversions(Sema &S,
3624                                const StandardConversionSequence& SCS1,
3625                                const StandardConversionSequence& SCS2) {
3626  // C++ 13.3.3.2p3:
3627  //  -- S1 and S2 differ only in their qualification conversion and
3628  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3629  //     cv-qualification signature of type T1 is a proper subset of
3630  //     the cv-qualification signature of type T2, and S1 is not the
3631  //     deprecated string literal array-to-pointer conversion (4.2).
3632  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3633      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3634    return ImplicitConversionSequence::Indistinguishable;
3635
3636  // FIXME: the example in the standard doesn't use a qualification
3637  // conversion (!)
3638  QualType T1 = SCS1.getToType(2);
3639  QualType T2 = SCS2.getToType(2);
3640  T1 = S.Context.getCanonicalType(T1);
3641  T2 = S.Context.getCanonicalType(T2);
3642  Qualifiers T1Quals, T2Quals;
3643  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3644  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3645
3646  // If the types are the same, we won't learn anything by unwrapped
3647  // them.
3648  if (UnqualT1 == UnqualT2)
3649    return ImplicitConversionSequence::Indistinguishable;
3650
3651  // If the type is an array type, promote the element qualifiers to the type
3652  // for comparison.
3653  if (isa<ArrayType>(T1) && T1Quals)
3654    T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3655  if (isa<ArrayType>(T2) && T2Quals)
3656    T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3657
3658  ImplicitConversionSequence::CompareKind Result
3659    = ImplicitConversionSequence::Indistinguishable;
3660
3661  // Objective-C++ ARC:
3662  //   Prefer qualification conversions not involving a change in lifetime
3663  //   to qualification conversions that do not change lifetime.
3664  if (SCS1.QualificationIncludesObjCLifetime !=
3665                                      SCS2.QualificationIncludesObjCLifetime) {
3666    Result = SCS1.QualificationIncludesObjCLifetime
3667               ? ImplicitConversionSequence::Worse
3668               : ImplicitConversionSequence::Better;
3669  }
3670
3671  while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3672    // Within each iteration of the loop, we check the qualifiers to
3673    // determine if this still looks like a qualification
3674    // conversion. Then, if all is well, we unwrap one more level of
3675    // pointers or pointers-to-members and do it all again
3676    // until there are no more pointers or pointers-to-members left
3677    // to unwrap. This essentially mimics what
3678    // IsQualificationConversion does, but here we're checking for a
3679    // strict subset of qualifiers.
3680    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3681      // The qualifiers are the same, so this doesn't tell us anything
3682      // about how the sequences rank.
3683      ;
3684    else if (T2.isMoreQualifiedThan(T1)) {
3685      // T1 has fewer qualifiers, so it could be the better sequence.
3686      if (Result == ImplicitConversionSequence::Worse)
3687        // Neither has qualifiers that are a subset of the other's
3688        // qualifiers.
3689        return ImplicitConversionSequence::Indistinguishable;
3690
3691      Result = ImplicitConversionSequence::Better;
3692    } else if (T1.isMoreQualifiedThan(T2)) {
3693      // T2 has fewer qualifiers, so it could be the better sequence.
3694      if (Result == ImplicitConversionSequence::Better)
3695        // Neither has qualifiers that are a subset of the other's
3696        // qualifiers.
3697        return ImplicitConversionSequence::Indistinguishable;
3698
3699      Result = ImplicitConversionSequence::Worse;
3700    } else {
3701      // Qualifiers are disjoint.
3702      return ImplicitConversionSequence::Indistinguishable;
3703    }
3704
3705    // If the types after this point are equivalent, we're done.
3706    if (S.Context.hasSameUnqualifiedType(T1, T2))
3707      break;
3708  }
3709
3710  // Check that the winning standard conversion sequence isn't using
3711  // the deprecated string literal array to pointer conversion.
3712  switch (Result) {
3713  case ImplicitConversionSequence::Better:
3714    if (SCS1.DeprecatedStringLiteralToCharPtr)
3715      Result = ImplicitConversionSequence::Indistinguishable;
3716    break;
3717
3718  case ImplicitConversionSequence::Indistinguishable:
3719    break;
3720
3721  case ImplicitConversionSequence::Worse:
3722    if (SCS2.DeprecatedStringLiteralToCharPtr)
3723      Result = ImplicitConversionSequence::Indistinguishable;
3724    break;
3725  }
3726
3727  return Result;
3728}
3729
3730/// CompareDerivedToBaseConversions - Compares two standard conversion
3731/// sequences to determine whether they can be ranked based on their
3732/// various kinds of derived-to-base conversions (C++
3733/// [over.ics.rank]p4b3).  As part of these checks, we also look at
3734/// conversions between Objective-C interface types.
3735ImplicitConversionSequence::CompareKind
3736CompareDerivedToBaseConversions(Sema &S,
3737                                const StandardConversionSequence& SCS1,
3738                                const StandardConversionSequence& SCS2) {
3739  QualType FromType1 = SCS1.getFromType();
3740  QualType ToType1 = SCS1.getToType(1);
3741  QualType FromType2 = SCS2.getFromType();
3742  QualType ToType2 = SCS2.getToType(1);
3743
3744  // Adjust the types we're converting from via the array-to-pointer
3745  // conversion, if we need to.
3746  if (SCS1.First == ICK_Array_To_Pointer)
3747    FromType1 = S.Context.getArrayDecayedType(FromType1);
3748  if (SCS2.First == ICK_Array_To_Pointer)
3749    FromType2 = S.Context.getArrayDecayedType(FromType2);
3750
3751  // Canonicalize all of the types.
3752  FromType1 = S.Context.getCanonicalType(FromType1);
3753  ToType1 = S.Context.getCanonicalType(ToType1);
3754  FromType2 = S.Context.getCanonicalType(FromType2);
3755  ToType2 = S.Context.getCanonicalType(ToType2);
3756
3757  // C++ [over.ics.rank]p4b3:
3758  //
3759  //   If class B is derived directly or indirectly from class A and
3760  //   class C is derived directly or indirectly from B,
3761  //
3762  // Compare based on pointer conversions.
3763  if (SCS1.Second == ICK_Pointer_Conversion &&
3764      SCS2.Second == ICK_Pointer_Conversion &&
3765      /*FIXME: Remove if Objective-C id conversions get their own rank*/
3766      FromType1->isPointerType() && FromType2->isPointerType() &&
3767      ToType1->isPointerType() && ToType2->isPointerType()) {
3768    QualType FromPointee1
3769      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3770    QualType ToPointee1
3771      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3772    QualType FromPointee2
3773      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3774    QualType ToPointee2
3775      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3776
3777    //   -- conversion of C* to B* is better than conversion of C* to A*,
3778    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3779      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3780        return ImplicitConversionSequence::Better;
3781      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3782        return ImplicitConversionSequence::Worse;
3783    }
3784
3785    //   -- conversion of B* to A* is better than conversion of C* to A*,
3786    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3787      if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3788        return ImplicitConversionSequence::Better;
3789      else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3790        return ImplicitConversionSequence::Worse;
3791    }
3792  } else if (SCS1.Second == ICK_Pointer_Conversion &&
3793             SCS2.Second == ICK_Pointer_Conversion) {
3794    const ObjCObjectPointerType *FromPtr1
3795      = FromType1->getAs<ObjCObjectPointerType>();
3796    const ObjCObjectPointerType *FromPtr2
3797      = FromType2->getAs<ObjCObjectPointerType>();
3798    const ObjCObjectPointerType *ToPtr1
3799      = ToType1->getAs<ObjCObjectPointerType>();
3800    const ObjCObjectPointerType *ToPtr2
3801      = ToType2->getAs<ObjCObjectPointerType>();
3802
3803    if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3804      // Apply the same conversion ranking rules for Objective-C pointer types
3805      // that we do for C++ pointers to class types. However, we employ the
3806      // Objective-C pseudo-subtyping relationship used for assignment of
3807      // Objective-C pointer types.
3808      bool FromAssignLeft
3809        = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3810      bool FromAssignRight
3811        = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3812      bool ToAssignLeft
3813        = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3814      bool ToAssignRight
3815        = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3816
3817      // A conversion to an a non-id object pointer type or qualified 'id'
3818      // type is better than a conversion to 'id'.
3819      if (ToPtr1->isObjCIdType() &&
3820          (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3821        return ImplicitConversionSequence::Worse;
3822      if (ToPtr2->isObjCIdType() &&
3823          (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3824        return ImplicitConversionSequence::Better;
3825
3826      // A conversion to a non-id object pointer type is better than a
3827      // conversion to a qualified 'id' type
3828      if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3829        return ImplicitConversionSequence::Worse;
3830      if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3831        return ImplicitConversionSequence::Better;
3832
3833      // A conversion to an a non-Class object pointer type or qualified 'Class'
3834      // type is better than a conversion to 'Class'.
3835      if (ToPtr1->isObjCClassType() &&
3836          (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3837        return ImplicitConversionSequence::Worse;
3838      if (ToPtr2->isObjCClassType() &&
3839          (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3840        return ImplicitConversionSequence::Better;
3841
3842      // A conversion to a non-Class object pointer type is better than a
3843      // conversion to a qualified 'Class' type.
3844      if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3845        return ImplicitConversionSequence::Worse;
3846      if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3847        return ImplicitConversionSequence::Better;
3848
3849      //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3850      if (S.Context.hasSameType(FromType1, FromType2) &&
3851          !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3852          (ToAssignLeft != ToAssignRight))
3853        return ToAssignLeft? ImplicitConversionSequence::Worse
3854                           : ImplicitConversionSequence::Better;
3855
3856      //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3857      if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3858          (FromAssignLeft != FromAssignRight))
3859        return FromAssignLeft? ImplicitConversionSequence::Better
3860        : ImplicitConversionSequence::Worse;
3861    }
3862  }
3863
3864  // Ranking of member-pointer types.
3865  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3866      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3867      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3868    const MemberPointerType * FromMemPointer1 =
3869                                        FromType1->getAs<MemberPointerType>();
3870    const MemberPointerType * ToMemPointer1 =
3871                                          ToType1->getAs<MemberPointerType>();
3872    const MemberPointerType * FromMemPointer2 =
3873                                          FromType2->getAs<MemberPointerType>();
3874    const MemberPointerType * ToMemPointer2 =
3875                                          ToType2->getAs<MemberPointerType>();
3876    const Type *FromPointeeType1 = FromMemPointer1->getClass();
3877    const Type *ToPointeeType1 = ToMemPointer1->getClass();
3878    const Type *FromPointeeType2 = FromMemPointer2->getClass();
3879    const Type *ToPointeeType2 = ToMemPointer2->getClass();
3880    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3881    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3882    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3883    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3884    // conversion of A::* to B::* is better than conversion of A::* to C::*,
3885    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3886      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3887        return ImplicitConversionSequence::Worse;
3888      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3889        return ImplicitConversionSequence::Better;
3890    }
3891    // conversion of B::* to C::* is better than conversion of A::* to C::*
3892    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3893      if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3894        return ImplicitConversionSequence::Better;
3895      else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3896        return ImplicitConversionSequence::Worse;
3897    }
3898  }
3899
3900  if (SCS1.Second == ICK_Derived_To_Base) {
3901    //   -- conversion of C to B is better than conversion of C to A,
3902    //   -- binding of an expression of type C to a reference of type
3903    //      B& is better than binding an expression of type C to a
3904    //      reference of type A&,
3905    if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3906        !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3907      if (S.IsDerivedFrom(ToType1, ToType2))
3908        return ImplicitConversionSequence::Better;
3909      else if (S.IsDerivedFrom(ToType2, ToType1))
3910        return ImplicitConversionSequence::Worse;
3911    }
3912
3913    //   -- conversion of B to A is better than conversion of C to A.
3914    //   -- binding of an expression of type B to a reference of type
3915    //      A& is better than binding an expression of type C to a
3916    //      reference of type A&,
3917    if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3918        S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3919      if (S.IsDerivedFrom(FromType2, FromType1))
3920        return ImplicitConversionSequence::Better;
3921      else if (S.IsDerivedFrom(FromType1, FromType2))
3922        return ImplicitConversionSequence::Worse;
3923    }
3924  }
3925
3926  return ImplicitConversionSequence::Indistinguishable;
3927}
3928
3929/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3930/// determine whether they are reference-related,
3931/// reference-compatible, reference-compatible with added
3932/// qualification, or incompatible, for use in C++ initialization by
3933/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3934/// type, and the first type (T1) is the pointee type of the reference
3935/// type being initialized.
3936Sema::ReferenceCompareResult
3937Sema::CompareReferenceRelationship(SourceLocation Loc,
3938                                   QualType OrigT1, QualType OrigT2,
3939                                   bool &DerivedToBase,
3940                                   bool &ObjCConversion,
3941                                   bool &ObjCLifetimeConversion) {
3942  assert(!OrigT1->isReferenceType() &&
3943    "T1 must be the pointee type of the reference type");
3944  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3945
3946  QualType T1 = Context.getCanonicalType(OrigT1);
3947  QualType T2 = Context.getCanonicalType(OrigT2);
3948  Qualifiers T1Quals, T2Quals;
3949  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3950  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3951
3952  // C++ [dcl.init.ref]p4:
3953  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3954  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3955  //   T1 is a base class of T2.
3956  DerivedToBase = false;
3957  ObjCConversion = false;
3958  ObjCLifetimeConversion = false;
3959  if (UnqualT1 == UnqualT2) {
3960    // Nothing to do.
3961  } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3962           IsDerivedFrom(UnqualT2, UnqualT1))
3963    DerivedToBase = true;
3964  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3965           UnqualT2->isObjCObjectOrInterfaceType() &&
3966           Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3967    ObjCConversion = true;
3968  else
3969    return Ref_Incompatible;
3970
3971  // At this point, we know that T1 and T2 are reference-related (at
3972  // least).
3973
3974  // If the type is an array type, promote the element qualifiers to the type
3975  // for comparison.
3976  if (isa<ArrayType>(T1) && T1Quals)
3977    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3978  if (isa<ArrayType>(T2) && T2Quals)
3979    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3980
3981  // C++ [dcl.init.ref]p4:
3982  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3983  //   reference-related to T2 and cv1 is the same cv-qualification
3984  //   as, or greater cv-qualification than, cv2. For purposes of
3985  //   overload resolution, cases for which cv1 is greater
3986  //   cv-qualification than cv2 are identified as
3987  //   reference-compatible with added qualification (see 13.3.3.2).
3988  //
3989  // Note that we also require equivalence of Objective-C GC and address-space
3990  // qualifiers when performing these computations, so that e.g., an int in
3991  // address space 1 is not reference-compatible with an int in address
3992  // space 2.
3993  if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3994      T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3995    T1Quals.removeObjCLifetime();
3996    T2Quals.removeObjCLifetime();
3997    ObjCLifetimeConversion = true;
3998  }
3999
4000  if (T1Quals == T2Quals)
4001    return Ref_Compatible;
4002  else if (T1Quals.compatiblyIncludes(T2Quals))
4003    return Ref_Compatible_With_Added_Qualification;
4004  else
4005    return Ref_Related;
4006}
4007
4008/// \brief Look for a user-defined conversion to an value reference-compatible
4009///        with DeclType. Return true if something definite is found.
4010static bool
4011FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4012                         QualType DeclType, SourceLocation DeclLoc,
4013                         Expr *Init, QualType T2, bool AllowRvalues,
4014                         bool AllowExplicit) {
4015  assert(T2->isRecordType() && "Can only find conversions of record types.");
4016  CXXRecordDecl *T2RecordDecl
4017    = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4018
4019  OverloadCandidateSet CandidateSet(DeclLoc);
4020  std::pair<CXXRecordDecl::conversion_iterator,
4021            CXXRecordDecl::conversion_iterator>
4022    Conversions = T2RecordDecl->getVisibleConversionFunctions();
4023  for (CXXRecordDecl::conversion_iterator
4024         I = Conversions.first, E = Conversions.second; I != E; ++I) {
4025    NamedDecl *D = *I;
4026    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4027    if (isa<UsingShadowDecl>(D))
4028      D = cast<UsingShadowDecl>(D)->getTargetDecl();
4029
4030    FunctionTemplateDecl *ConvTemplate
4031      = dyn_cast<FunctionTemplateDecl>(D);
4032    CXXConversionDecl *Conv;
4033    if (ConvTemplate)
4034      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4035    else
4036      Conv = cast<CXXConversionDecl>(D);
4037
4038    // If this is an explicit conversion, and we're not allowed to consider
4039    // explicit conversions, skip it.
4040    if (!AllowExplicit && Conv->isExplicit())
4041      continue;
4042
4043    if (AllowRvalues) {
4044      bool DerivedToBase = false;
4045      bool ObjCConversion = false;
4046      bool ObjCLifetimeConversion = false;
4047
4048      // If we are initializing an rvalue reference, don't permit conversion
4049      // functions that return lvalues.
4050      if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4051        const ReferenceType *RefType
4052          = Conv->getConversionType()->getAs<LValueReferenceType>();
4053        if (RefType && !RefType->getPointeeType()->isFunctionType())
4054          continue;
4055      }
4056
4057      if (!ConvTemplate &&
4058          S.CompareReferenceRelationship(
4059            DeclLoc,
4060            Conv->getConversionType().getNonReferenceType()
4061              .getUnqualifiedType(),
4062            DeclType.getNonReferenceType().getUnqualifiedType(),
4063            DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4064          Sema::Ref_Incompatible)
4065        continue;
4066    } else {
4067      // If the conversion function doesn't return a reference type,
4068      // it can't be considered for this conversion. An rvalue reference
4069      // is only acceptable if its referencee is a function type.
4070
4071      const ReferenceType *RefType =
4072        Conv->getConversionType()->getAs<ReferenceType>();
4073      if (!RefType ||
4074          (!RefType->isLValueReferenceType() &&
4075           !RefType->getPointeeType()->isFunctionType()))
4076        continue;
4077    }
4078
4079    if (ConvTemplate)
4080      S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4081                                       Init, DeclType, CandidateSet);
4082    else
4083      S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4084                               DeclType, CandidateSet);
4085  }
4086
4087  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4088
4089  OverloadCandidateSet::iterator Best;
4090  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4091  case OR_Success:
4092    // C++ [over.ics.ref]p1:
4093    //
4094    //   [...] If the parameter binds directly to the result of
4095    //   applying a conversion function to the argument
4096    //   expression, the implicit conversion sequence is a
4097    //   user-defined conversion sequence (13.3.3.1.2), with the
4098    //   second standard conversion sequence either an identity
4099    //   conversion or, if the conversion function returns an
4100    //   entity of a type that is a derived class of the parameter
4101    //   type, a derived-to-base Conversion.
4102    if (!Best->FinalConversion.DirectBinding)
4103      return false;
4104
4105    ICS.setUserDefined();
4106    ICS.UserDefined.Before = Best->Conversions[0].Standard;
4107    ICS.UserDefined.After = Best->FinalConversion;
4108    ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4109    ICS.UserDefined.ConversionFunction = Best->Function;
4110    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4111    ICS.UserDefined.EllipsisConversion = false;
4112    assert(ICS.UserDefined.After.ReferenceBinding &&
4113           ICS.UserDefined.After.DirectBinding &&
4114           "Expected a direct reference binding!");
4115    return true;
4116
4117  case OR_Ambiguous:
4118    ICS.setAmbiguous();
4119    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4120         Cand != CandidateSet.end(); ++Cand)
4121      if (Cand->Viable)
4122        ICS.Ambiguous.addConversion(Cand->Function);
4123    return true;
4124
4125  case OR_No_Viable_Function:
4126  case OR_Deleted:
4127    // There was no suitable conversion, or we found a deleted
4128    // conversion; continue with other checks.
4129    return false;
4130  }
4131
4132  llvm_unreachable("Invalid OverloadResult!");
4133}
4134
4135/// \brief Compute an implicit conversion sequence for reference
4136/// initialization.
4137static ImplicitConversionSequence
4138TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4139                 SourceLocation DeclLoc,
4140                 bool SuppressUserConversions,
4141                 bool AllowExplicit) {
4142  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4143
4144  // Most paths end in a failed conversion.
4145  ImplicitConversionSequence ICS;
4146  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4147
4148  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4149  QualType T2 = Init->getType();
4150
4151  // If the initializer is the address of an overloaded function, try
4152  // to resolve the overloaded function. If all goes well, T2 is the
4153  // type of the resulting function.
4154  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4155    DeclAccessPair Found;
4156    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4157                                                                false, Found))
4158      T2 = Fn->getType();
4159  }
4160
4161  // Compute some basic properties of the types and the initializer.
4162  bool isRValRef = DeclType->isRValueReferenceType();
4163  bool DerivedToBase = false;
4164  bool ObjCConversion = false;
4165  bool ObjCLifetimeConversion = false;
4166  Expr::Classification InitCategory = Init->Classify(S.Context);
4167  Sema::ReferenceCompareResult RefRelationship
4168    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4169                                     ObjCConversion, ObjCLifetimeConversion);
4170
4171
4172  // C++0x [dcl.init.ref]p5:
4173  //   A reference to type "cv1 T1" is initialized by an expression
4174  //   of type "cv2 T2" as follows:
4175
4176  //     -- If reference is an lvalue reference and the initializer expression
4177  if (!isRValRef) {
4178    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4179    //        reference-compatible with "cv2 T2," or
4180    //
4181    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4182    if (InitCategory.isLValue() &&
4183        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4184      // C++ [over.ics.ref]p1:
4185      //   When a parameter of reference type binds directly (8.5.3)
4186      //   to an argument expression, the implicit conversion sequence
4187      //   is the identity conversion, unless the argument expression
4188      //   has a type that is a derived class of the parameter type,
4189      //   in which case the implicit conversion sequence is a
4190      //   derived-to-base Conversion (13.3.3.1).
4191      ICS.setStandard();
4192      ICS.Standard.First = ICK_Identity;
4193      ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4194                         : ObjCConversion? ICK_Compatible_Conversion
4195                         : ICK_Identity;
4196      ICS.Standard.Third = ICK_Identity;
4197      ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4198      ICS.Standard.setToType(0, T2);
4199      ICS.Standard.setToType(1, T1);
4200      ICS.Standard.setToType(2, T1);
4201      ICS.Standard.ReferenceBinding = true;
4202      ICS.Standard.DirectBinding = true;
4203      ICS.Standard.IsLvalueReference = !isRValRef;
4204      ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4205      ICS.Standard.BindsToRvalue = false;
4206      ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4207      ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4208      ICS.Standard.CopyConstructor = 0;
4209
4210      // Nothing more to do: the inaccessibility/ambiguity check for
4211      // derived-to-base conversions is suppressed when we're
4212      // computing the implicit conversion sequence (C++
4213      // [over.best.ics]p2).
4214      return ICS;
4215    }
4216
4217    //       -- has a class type (i.e., T2 is a class type), where T1 is
4218    //          not reference-related to T2, and can be implicitly
4219    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4220    //          is reference-compatible with "cv3 T3" 92) (this
4221    //          conversion is selected by enumerating the applicable
4222    //          conversion functions (13.3.1.6) and choosing the best
4223    //          one through overload resolution (13.3)),
4224    if (!SuppressUserConversions && T2->isRecordType() &&
4225        !S.RequireCompleteType(DeclLoc, T2, 0) &&
4226        RefRelationship == Sema::Ref_Incompatible) {
4227      if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4228                                   Init, T2, /*AllowRvalues=*/false,
4229                                   AllowExplicit))
4230        return ICS;
4231    }
4232  }
4233
4234  //     -- Otherwise, the reference shall be an lvalue reference to a
4235  //        non-volatile const type (i.e., cv1 shall be const), or the reference
4236  //        shall be an rvalue reference.
4237  //
4238  // We actually handle one oddity of C++ [over.ics.ref] at this
4239  // point, which is that, due to p2 (which short-circuits reference
4240  // binding by only attempting a simple conversion for non-direct
4241  // bindings) and p3's strange wording, we allow a const volatile
4242  // reference to bind to an rvalue. Hence the check for the presence
4243  // of "const" rather than checking for "const" being the only
4244  // qualifier.
4245  // This is also the point where rvalue references and lvalue inits no longer
4246  // go together.
4247  if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4248    return ICS;
4249
4250  //       -- If the initializer expression
4251  //
4252  //            -- is an xvalue, class prvalue, array prvalue or function
4253  //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4254  if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4255      (InitCategory.isXValue() ||
4256      (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4257      (InitCategory.isLValue() && T2->isFunctionType()))) {
4258    ICS.setStandard();
4259    ICS.Standard.First = ICK_Identity;
4260    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4261                      : ObjCConversion? ICK_Compatible_Conversion
4262                      : ICK_Identity;
4263    ICS.Standard.Third = ICK_Identity;
4264    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4265    ICS.Standard.setToType(0, T2);
4266    ICS.Standard.setToType(1, T1);
4267    ICS.Standard.setToType(2, T1);
4268    ICS.Standard.ReferenceBinding = true;
4269    // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4270    // binding unless we're binding to a class prvalue.
4271    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4272    // allow the use of rvalue references in C++98/03 for the benefit of
4273    // standard library implementors; therefore, we need the xvalue check here.
4274    ICS.Standard.DirectBinding =
4275      S.getLangOpts().CPlusPlus11 ||
4276      (InitCategory.isPRValue() && !T2->isRecordType());
4277    ICS.Standard.IsLvalueReference = !isRValRef;
4278    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4279    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4280    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4281    ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4282    ICS.Standard.CopyConstructor = 0;
4283    return ICS;
4284  }
4285
4286  //            -- has a class type (i.e., T2 is a class type), where T1 is not
4287  //               reference-related to T2, and can be implicitly converted to
4288  //               an xvalue, class prvalue, or function lvalue of type
4289  //               "cv3 T3", where "cv1 T1" is reference-compatible with
4290  //               "cv3 T3",
4291  //
4292  //          then the reference is bound to the value of the initializer
4293  //          expression in the first case and to the result of the conversion
4294  //          in the second case (or, in either case, to an appropriate base
4295  //          class subobject).
4296  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4297      T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4298      FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4299                               Init, T2, /*AllowRvalues=*/true,
4300                               AllowExplicit)) {
4301    // In the second case, if the reference is an rvalue reference
4302    // and the second standard conversion sequence of the
4303    // user-defined conversion sequence includes an lvalue-to-rvalue
4304    // conversion, the program is ill-formed.
4305    if (ICS.isUserDefined() && isRValRef &&
4306        ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4307      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4308
4309    return ICS;
4310  }
4311
4312  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4313  //          initialized from the initializer expression using the
4314  //          rules for a non-reference copy initialization (8.5). The
4315  //          reference is then bound to the temporary. If T1 is
4316  //          reference-related to T2, cv1 must be the same
4317  //          cv-qualification as, or greater cv-qualification than,
4318  //          cv2; otherwise, the program is ill-formed.
4319  if (RefRelationship == Sema::Ref_Related) {
4320    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4321    // we would be reference-compatible or reference-compatible with
4322    // added qualification. But that wasn't the case, so the reference
4323    // initialization fails.
4324    //
4325    // Note that we only want to check address spaces and cvr-qualifiers here.
4326    // ObjC GC and lifetime qualifiers aren't important.
4327    Qualifiers T1Quals = T1.getQualifiers();
4328    Qualifiers T2Quals = T2.getQualifiers();
4329    T1Quals.removeObjCGCAttr();
4330    T1Quals.removeObjCLifetime();
4331    T2Quals.removeObjCGCAttr();
4332    T2Quals.removeObjCLifetime();
4333    if (!T1Quals.compatiblyIncludes(T2Quals))
4334      return ICS;
4335  }
4336
4337  // If at least one of the types is a class type, the types are not
4338  // related, and we aren't allowed any user conversions, the
4339  // reference binding fails. This case is important for breaking
4340  // recursion, since TryImplicitConversion below will attempt to
4341  // create a temporary through the use of a copy constructor.
4342  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4343      (T1->isRecordType() || T2->isRecordType()))
4344    return ICS;
4345
4346  // If T1 is reference-related to T2 and the reference is an rvalue
4347  // reference, the initializer expression shall not be an lvalue.
4348  if (RefRelationship >= Sema::Ref_Related &&
4349      isRValRef && Init->Classify(S.Context).isLValue())
4350    return ICS;
4351
4352  // C++ [over.ics.ref]p2:
4353  //   When a parameter of reference type is not bound directly to
4354  //   an argument expression, the conversion sequence is the one
4355  //   required to convert the argument expression to the
4356  //   underlying type of the reference according to
4357  //   13.3.3.1. Conceptually, this conversion sequence corresponds
4358  //   to copy-initializing a temporary of the underlying type with
4359  //   the argument expression. Any difference in top-level
4360  //   cv-qualification is subsumed by the initialization itself
4361  //   and does not constitute a conversion.
4362  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4363                              /*AllowExplicit=*/false,
4364                              /*InOverloadResolution=*/false,
4365                              /*CStyle=*/false,
4366                              /*AllowObjCWritebackConversion=*/false);
4367
4368  // Of course, that's still a reference binding.
4369  if (ICS.isStandard()) {
4370    ICS.Standard.ReferenceBinding = true;
4371    ICS.Standard.IsLvalueReference = !isRValRef;
4372    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4373    ICS.Standard.BindsToRvalue = true;
4374    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4375    ICS.Standard.ObjCLifetimeConversionBinding = false;
4376  } else if (ICS.isUserDefined()) {
4377    // Don't allow rvalue references to bind to lvalues.
4378    if (DeclType->isRValueReferenceType()) {
4379      if (const ReferenceType *RefType
4380            = ICS.UserDefined.ConversionFunction->getResultType()
4381                ->getAs<LValueReferenceType>()) {
4382        if (!RefType->getPointeeType()->isFunctionType()) {
4383          ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4384                     DeclType);
4385          return ICS;
4386        }
4387      }
4388    }
4389
4390    ICS.UserDefined.After.ReferenceBinding = true;
4391    ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4392    ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4393    ICS.UserDefined.After.BindsToRvalue = true;
4394    ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4395    ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4396  }
4397
4398  return ICS;
4399}
4400
4401static ImplicitConversionSequence
4402TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4403                      bool SuppressUserConversions,
4404                      bool InOverloadResolution,
4405                      bool AllowObjCWritebackConversion,
4406                      bool AllowExplicit = false);
4407
4408/// TryListConversion - Try to copy-initialize a value of type ToType from the
4409/// initializer list From.
4410static ImplicitConversionSequence
4411TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4412                  bool SuppressUserConversions,
4413                  bool InOverloadResolution,
4414                  bool AllowObjCWritebackConversion) {
4415  // C++11 [over.ics.list]p1:
4416  //   When an argument is an initializer list, it is not an expression and
4417  //   special rules apply for converting it to a parameter type.
4418
4419  ImplicitConversionSequence Result;
4420  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4421  Result.setListInitializationSequence();
4422
4423  // We need a complete type for what follows. Incomplete types can never be
4424  // initialized from init lists.
4425  if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4426    return Result;
4427
4428  // C++11 [over.ics.list]p2:
4429  //   If the parameter type is std::initializer_list<X> or "array of X" and
4430  //   all the elements can be implicitly converted to X, the implicit
4431  //   conversion sequence is the worst conversion necessary to convert an
4432  //   element of the list to X.
4433  bool toStdInitializerList = false;
4434  QualType X;
4435  if (ToType->isArrayType())
4436    X = S.Context.getAsArrayType(ToType)->getElementType();
4437  else
4438    toStdInitializerList = S.isStdInitializerList(ToType, &X);
4439  if (!X.isNull()) {
4440    for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4441      Expr *Init = From->getInit(i);
4442      ImplicitConversionSequence ICS =
4443          TryCopyInitialization(S, Init, X, SuppressUserConversions,
4444                                InOverloadResolution,
4445                                AllowObjCWritebackConversion);
4446      // If a single element isn't convertible, fail.
4447      if (ICS.isBad()) {
4448        Result = ICS;
4449        break;
4450      }
4451      // Otherwise, look for the worst conversion.
4452      if (Result.isBad() ||
4453          CompareImplicitConversionSequences(S, ICS, Result) ==
4454              ImplicitConversionSequence::Worse)
4455        Result = ICS;
4456    }
4457
4458    // For an empty list, we won't have computed any conversion sequence.
4459    // Introduce the identity conversion sequence.
4460    if (From->getNumInits() == 0) {
4461      Result.setStandard();
4462      Result.Standard.setAsIdentityConversion();
4463      Result.Standard.setFromType(ToType);
4464      Result.Standard.setAllToTypes(ToType);
4465    }
4466
4467    Result.setListInitializationSequence();
4468    Result.setStdInitializerListElement(toStdInitializerList);
4469    return Result;
4470  }
4471
4472  // C++11 [over.ics.list]p3:
4473  //   Otherwise, if the parameter is a non-aggregate class X and overload
4474  //   resolution chooses a single best constructor [...] the implicit
4475  //   conversion sequence is a user-defined conversion sequence. If multiple
4476  //   constructors are viable but none is better than the others, the
4477  //   implicit conversion sequence is a user-defined conversion sequence.
4478  if (ToType->isRecordType() && !ToType->isAggregateType()) {
4479    // This function can deal with initializer lists.
4480    Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4481                                      /*AllowExplicit=*/false,
4482                                      InOverloadResolution, /*CStyle=*/false,
4483                                      AllowObjCWritebackConversion);
4484    Result.setListInitializationSequence();
4485    return Result;
4486  }
4487
4488  // C++11 [over.ics.list]p4:
4489  //   Otherwise, if the parameter has an aggregate type which can be
4490  //   initialized from the initializer list [...] the implicit conversion
4491  //   sequence is a user-defined conversion sequence.
4492  if (ToType->isAggregateType()) {
4493    // Type is an aggregate, argument is an init list. At this point it comes
4494    // down to checking whether the initialization works.
4495    // FIXME: Find out whether this parameter is consumed or not.
4496    InitializedEntity Entity =
4497        InitializedEntity::InitializeParameter(S.Context, ToType,
4498                                               /*Consumed=*/false);
4499    if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4500      Result.setUserDefined();
4501      Result.UserDefined.Before.setAsIdentityConversion();
4502      // Initializer lists don't have a type.
4503      Result.UserDefined.Before.setFromType(QualType());
4504      Result.UserDefined.Before.setAllToTypes(QualType());
4505
4506      Result.UserDefined.After.setAsIdentityConversion();
4507      Result.UserDefined.After.setFromType(ToType);
4508      Result.UserDefined.After.setAllToTypes(ToType);
4509      Result.UserDefined.ConversionFunction = 0;
4510    }
4511    return Result;
4512  }
4513
4514  // C++11 [over.ics.list]p5:
4515  //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4516  if (ToType->isReferenceType()) {
4517    // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4518    // mention initializer lists in any way. So we go by what list-
4519    // initialization would do and try to extrapolate from that.
4520
4521    QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4522
4523    // If the initializer list has a single element that is reference-related
4524    // to the parameter type, we initialize the reference from that.
4525    if (From->getNumInits() == 1) {
4526      Expr *Init = From->getInit(0);
4527
4528      QualType T2 = Init->getType();
4529
4530      // If the initializer is the address of an overloaded function, try
4531      // to resolve the overloaded function. If all goes well, T2 is the
4532      // type of the resulting function.
4533      if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4534        DeclAccessPair Found;
4535        if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4536                                   Init, ToType, false, Found))
4537          T2 = Fn->getType();
4538      }
4539
4540      // Compute some basic properties of the types and the initializer.
4541      bool dummy1 = false;
4542      bool dummy2 = false;
4543      bool dummy3 = false;
4544      Sema::ReferenceCompareResult RefRelationship
4545        = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4546                                         dummy2, dummy3);
4547
4548      if (RefRelationship >= Sema::Ref_Related)
4549        return TryReferenceInit(S, Init, ToType,
4550                                /*FIXME:*/From->getLocStart(),
4551                                SuppressUserConversions,
4552                                /*AllowExplicit=*/false);
4553    }
4554
4555    // Otherwise, we bind the reference to a temporary created from the
4556    // initializer list.
4557    Result = TryListConversion(S, From, T1, SuppressUserConversions,
4558                               InOverloadResolution,
4559                               AllowObjCWritebackConversion);
4560    if (Result.isFailure())
4561      return Result;
4562    assert(!Result.isEllipsis() &&
4563           "Sub-initialization cannot result in ellipsis conversion.");
4564
4565    // Can we even bind to a temporary?
4566    if (ToType->isRValueReferenceType() ||
4567        (T1.isConstQualified() && !T1.isVolatileQualified())) {
4568      StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4569                                            Result.UserDefined.After;
4570      SCS.ReferenceBinding = true;
4571      SCS.IsLvalueReference = ToType->isLValueReferenceType();
4572      SCS.BindsToRvalue = true;
4573      SCS.BindsToFunctionLvalue = false;
4574      SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4575      SCS.ObjCLifetimeConversionBinding = false;
4576    } else
4577      Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4578                    From, ToType);
4579    return Result;
4580  }
4581
4582  // C++11 [over.ics.list]p6:
4583  //   Otherwise, if the parameter type is not a class:
4584  if (!ToType->isRecordType()) {
4585    //    - if the initializer list has one element, the implicit conversion
4586    //      sequence is the one required to convert the element to the
4587    //      parameter type.
4588    unsigned NumInits = From->getNumInits();
4589    if (NumInits == 1)
4590      Result = TryCopyInitialization(S, From->getInit(0), ToType,
4591                                     SuppressUserConversions,
4592                                     InOverloadResolution,
4593                                     AllowObjCWritebackConversion);
4594    //    - if the initializer list has no elements, the implicit conversion
4595    //      sequence is the identity conversion.
4596    else if (NumInits == 0) {
4597      Result.setStandard();
4598      Result.Standard.setAsIdentityConversion();
4599      Result.Standard.setFromType(ToType);
4600      Result.Standard.setAllToTypes(ToType);
4601    }
4602    Result.setListInitializationSequence();
4603    return Result;
4604  }
4605
4606  // C++11 [over.ics.list]p7:
4607  //   In all cases other than those enumerated above, no conversion is possible
4608  return Result;
4609}
4610
4611/// TryCopyInitialization - Try to copy-initialize a value of type
4612/// ToType from the expression From. Return the implicit conversion
4613/// sequence required to pass this argument, which may be a bad
4614/// conversion sequence (meaning that the argument cannot be passed to
4615/// a parameter of this type). If @p SuppressUserConversions, then we
4616/// do not permit any user-defined conversion sequences.
4617static ImplicitConversionSequence
4618TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4619                      bool SuppressUserConversions,
4620                      bool InOverloadResolution,
4621                      bool AllowObjCWritebackConversion,
4622                      bool AllowExplicit) {
4623  if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4624    return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4625                             InOverloadResolution,AllowObjCWritebackConversion);
4626
4627  if (ToType->isReferenceType())
4628    return TryReferenceInit(S, From, ToType,
4629                            /*FIXME:*/From->getLocStart(),
4630                            SuppressUserConversions,
4631                            AllowExplicit);
4632
4633  return TryImplicitConversion(S, From, ToType,
4634                               SuppressUserConversions,
4635                               /*AllowExplicit=*/false,
4636                               InOverloadResolution,
4637                               /*CStyle=*/false,
4638                               AllowObjCWritebackConversion);
4639}
4640
4641static bool TryCopyInitialization(const CanQualType FromQTy,
4642                                  const CanQualType ToQTy,
4643                                  Sema &S,
4644                                  SourceLocation Loc,
4645                                  ExprValueKind FromVK) {
4646  OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4647  ImplicitConversionSequence ICS =
4648    TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4649
4650  return !ICS.isBad();
4651}
4652
4653/// TryObjectArgumentInitialization - Try to initialize the object
4654/// parameter of the given member function (@c Method) from the
4655/// expression @p From.
4656static ImplicitConversionSequence
4657TryObjectArgumentInitialization(Sema &S, QualType FromType,
4658                                Expr::Classification FromClassification,
4659                                CXXMethodDecl *Method,
4660                                CXXRecordDecl *ActingContext) {
4661  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4662  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4663  //                 const volatile object.
4664  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4665    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4666  QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4667
4668  // Set up the conversion sequence as a "bad" conversion, to allow us
4669  // to exit early.
4670  ImplicitConversionSequence ICS;
4671
4672  // We need to have an object of class type.
4673  if (const PointerType *PT = FromType->getAs<PointerType>()) {
4674    FromType = PT->getPointeeType();
4675
4676    // When we had a pointer, it's implicitly dereferenced, so we
4677    // better have an lvalue.
4678    assert(FromClassification.isLValue());
4679  }
4680
4681  assert(FromType->isRecordType());
4682
4683  // C++0x [over.match.funcs]p4:
4684  //   For non-static member functions, the type of the implicit object
4685  //   parameter is
4686  //
4687  //     - "lvalue reference to cv X" for functions declared without a
4688  //        ref-qualifier or with the & ref-qualifier
4689  //     - "rvalue reference to cv X" for functions declared with the &&
4690  //        ref-qualifier
4691  //
4692  // where X is the class of which the function is a member and cv is the
4693  // cv-qualification on the member function declaration.
4694  //
4695  // However, when finding an implicit conversion sequence for the argument, we
4696  // are not allowed to create temporaries or perform user-defined conversions
4697  // (C++ [over.match.funcs]p5). We perform a simplified version of
4698  // reference binding here, that allows class rvalues to bind to
4699  // non-constant references.
4700
4701  // First check the qualifiers.
4702  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4703  if (ImplicitParamType.getCVRQualifiers()
4704                                    != FromTypeCanon.getLocalCVRQualifiers() &&
4705      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4706    ICS.setBad(BadConversionSequence::bad_qualifiers,
4707               FromType, ImplicitParamType);
4708    return ICS;
4709  }
4710
4711  // Check that we have either the same type or a derived type. It
4712  // affects the conversion rank.
4713  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4714  ImplicitConversionKind SecondKind;
4715  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4716    SecondKind = ICK_Identity;
4717  } else if (S.IsDerivedFrom(FromType, ClassType))
4718    SecondKind = ICK_Derived_To_Base;
4719  else {
4720    ICS.setBad(BadConversionSequence::unrelated_class,
4721               FromType, ImplicitParamType);
4722    return ICS;
4723  }
4724
4725  // Check the ref-qualifier.
4726  switch (Method->getRefQualifier()) {
4727  case RQ_None:
4728    // Do nothing; we don't care about lvalueness or rvalueness.
4729    break;
4730
4731  case RQ_LValue:
4732    if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4733      // non-const lvalue reference cannot bind to an rvalue
4734      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4735                 ImplicitParamType);
4736      return ICS;
4737    }
4738    break;
4739
4740  case RQ_RValue:
4741    if (!FromClassification.isRValue()) {
4742      // rvalue reference cannot bind to an lvalue
4743      ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4744                 ImplicitParamType);
4745      return ICS;
4746    }
4747    break;
4748  }
4749
4750  // Success. Mark this as a reference binding.
4751  ICS.setStandard();
4752  ICS.Standard.setAsIdentityConversion();
4753  ICS.Standard.Second = SecondKind;
4754  ICS.Standard.setFromType(FromType);
4755  ICS.Standard.setAllToTypes(ImplicitParamType);
4756  ICS.Standard.ReferenceBinding = true;
4757  ICS.Standard.DirectBinding = true;
4758  ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4759  ICS.Standard.BindsToFunctionLvalue = false;
4760  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4761  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4762    = (Method->getRefQualifier() == RQ_None);
4763  return ICS;
4764}
4765
4766/// PerformObjectArgumentInitialization - Perform initialization of
4767/// the implicit object parameter for the given Method with the given
4768/// expression.
4769ExprResult
4770Sema::PerformObjectArgumentInitialization(Expr *From,
4771                                          NestedNameSpecifier *Qualifier,
4772                                          NamedDecl *FoundDecl,
4773                                          CXXMethodDecl *Method) {
4774  QualType FromRecordType, DestType;
4775  QualType ImplicitParamRecordType  =
4776    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4777
4778  Expr::Classification FromClassification;
4779  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4780    FromRecordType = PT->getPointeeType();
4781    DestType = Method->getThisType(Context);
4782    FromClassification = Expr::Classification::makeSimpleLValue();
4783  } else {
4784    FromRecordType = From->getType();
4785    DestType = ImplicitParamRecordType;
4786    FromClassification = From->Classify(Context);
4787  }
4788
4789  // Note that we always use the true parent context when performing
4790  // the actual argument initialization.
4791  ImplicitConversionSequence ICS
4792    = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4793                                      Method, Method->getParent());
4794  if (ICS.isBad()) {
4795    if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4796      Qualifiers FromQs = FromRecordType.getQualifiers();
4797      Qualifiers ToQs = DestType.getQualifiers();
4798      unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4799      if (CVR) {
4800        Diag(From->getLocStart(),
4801             diag::err_member_function_call_bad_cvr)
4802          << Method->getDeclName() << FromRecordType << (CVR - 1)
4803          << From->getSourceRange();
4804        Diag(Method->getLocation(), diag::note_previous_decl)
4805          << Method->getDeclName();
4806        return ExprError();
4807      }
4808    }
4809
4810    return Diag(From->getLocStart(),
4811                diag::err_implicit_object_parameter_init)
4812       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4813  }
4814
4815  if (ICS.Standard.Second == ICK_Derived_To_Base) {
4816    ExprResult FromRes =
4817      PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4818    if (FromRes.isInvalid())
4819      return ExprError();
4820    From = FromRes.take();
4821  }
4822
4823  if (!Context.hasSameType(From->getType(), DestType))
4824    From = ImpCastExprToType(From, DestType, CK_NoOp,
4825                             From->getValueKind()).take();
4826  return Owned(From);
4827}
4828
4829/// TryContextuallyConvertToBool - Attempt to contextually convert the
4830/// expression From to bool (C++0x [conv]p3).
4831static ImplicitConversionSequence
4832TryContextuallyConvertToBool(Sema &S, Expr *From) {
4833  // FIXME: This is pretty broken.
4834  return TryImplicitConversion(S, From, S.Context.BoolTy,
4835                               // FIXME: Are these flags correct?
4836                               /*SuppressUserConversions=*/false,
4837                               /*AllowExplicit=*/true,
4838                               /*InOverloadResolution=*/false,
4839                               /*CStyle=*/false,
4840                               /*AllowObjCWritebackConversion=*/false);
4841}
4842
4843/// PerformContextuallyConvertToBool - Perform a contextual conversion
4844/// of the expression From to bool (C++0x [conv]p3).
4845ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4846  if (checkPlaceholderForOverload(*this, From))
4847    return ExprError();
4848
4849  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4850  if (!ICS.isBad())
4851    return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4852
4853  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4854    return Diag(From->getLocStart(),
4855                diag::err_typecheck_bool_condition)
4856                  << From->getType() << From->getSourceRange();
4857  return ExprError();
4858}
4859
4860/// Check that the specified conversion is permitted in a converted constant
4861/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4862/// is acceptable.
4863static bool CheckConvertedConstantConversions(Sema &S,
4864                                              StandardConversionSequence &SCS) {
4865  // Since we know that the target type is an integral or unscoped enumeration
4866  // type, most conversion kinds are impossible. All possible First and Third
4867  // conversions are fine.
4868  switch (SCS.Second) {
4869  case ICK_Identity:
4870  case ICK_Integral_Promotion:
4871  case ICK_Integral_Conversion:
4872    return true;
4873
4874  case ICK_Boolean_Conversion:
4875    // Conversion from an integral or unscoped enumeration type to bool is
4876    // classified as ICK_Boolean_Conversion, but it's also an integral
4877    // conversion, so it's permitted in a converted constant expression.
4878    return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4879           SCS.getToType(2)->isBooleanType();
4880
4881  case ICK_Floating_Integral:
4882  case ICK_Complex_Real:
4883    return false;
4884
4885  case ICK_Lvalue_To_Rvalue:
4886  case ICK_Array_To_Pointer:
4887  case ICK_Function_To_Pointer:
4888  case ICK_NoReturn_Adjustment:
4889  case ICK_Qualification:
4890  case ICK_Compatible_Conversion:
4891  case ICK_Vector_Conversion:
4892  case ICK_Vector_Splat:
4893  case ICK_Derived_To_Base:
4894  case ICK_Pointer_Conversion:
4895  case ICK_Pointer_Member:
4896  case ICK_Block_Pointer_Conversion:
4897  case ICK_Writeback_Conversion:
4898  case ICK_Floating_Promotion:
4899  case ICK_Complex_Promotion:
4900  case ICK_Complex_Conversion:
4901  case ICK_Floating_Conversion:
4902  case ICK_TransparentUnionConversion:
4903    llvm_unreachable("unexpected second conversion kind");
4904
4905  case ICK_Num_Conversion_Kinds:
4906    break;
4907  }
4908
4909  llvm_unreachable("unknown conversion kind");
4910}
4911
4912/// CheckConvertedConstantExpression - Check that the expression From is a
4913/// converted constant expression of type T, perform the conversion and produce
4914/// the converted expression, per C++11 [expr.const]p3.
4915ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4916                                                  llvm::APSInt &Value,
4917                                                  CCEKind CCE) {
4918  assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4919  assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4920
4921  if (checkPlaceholderForOverload(*this, From))
4922    return ExprError();
4923
4924  // C++11 [expr.const]p3 with proposed wording fixes:
4925  //  A converted constant expression of type T is a core constant expression,
4926  //  implicitly converted to a prvalue of type T, where the converted
4927  //  expression is a literal constant expression and the implicit conversion
4928  //  sequence contains only user-defined conversions, lvalue-to-rvalue
4929  //  conversions, integral promotions, and integral conversions other than
4930  //  narrowing conversions.
4931  ImplicitConversionSequence ICS =
4932    TryImplicitConversion(From, T,
4933                          /*SuppressUserConversions=*/false,
4934                          /*AllowExplicit=*/false,
4935                          /*InOverloadResolution=*/false,
4936                          /*CStyle=*/false,
4937                          /*AllowObjcWritebackConversion=*/false);
4938  StandardConversionSequence *SCS = 0;
4939  switch (ICS.getKind()) {
4940  case ImplicitConversionSequence::StandardConversion:
4941    if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4942      return Diag(From->getLocStart(),
4943                  diag::err_typecheck_converted_constant_expression_disallowed)
4944               << From->getType() << From->getSourceRange() << T;
4945    SCS = &ICS.Standard;
4946    break;
4947  case ImplicitConversionSequence::UserDefinedConversion:
4948    // We are converting from class type to an integral or enumeration type, so
4949    // the Before sequence must be trivial.
4950    if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4951      return Diag(From->getLocStart(),
4952                  diag::err_typecheck_converted_constant_expression_disallowed)
4953               << From->getType() << From->getSourceRange() << T;
4954    SCS = &ICS.UserDefined.After;
4955    break;
4956  case ImplicitConversionSequence::AmbiguousConversion:
4957  case ImplicitConversionSequence::BadConversion:
4958    if (!DiagnoseMultipleUserDefinedConversion(From, T))
4959      return Diag(From->getLocStart(),
4960                  diag::err_typecheck_converted_constant_expression)
4961                    << From->getType() << From->getSourceRange() << T;
4962    return ExprError();
4963
4964  case ImplicitConversionSequence::EllipsisConversion:
4965    llvm_unreachable("ellipsis conversion in converted constant expression");
4966  }
4967
4968  ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4969  if (Result.isInvalid())
4970    return Result;
4971
4972  // Check for a narrowing implicit conversion.
4973  APValue PreNarrowingValue;
4974  QualType PreNarrowingType;
4975  switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4976                                PreNarrowingType)) {
4977  case NK_Variable_Narrowing:
4978    // Implicit conversion to a narrower type, and the value is not a constant
4979    // expression. We'll diagnose this in a moment.
4980  case NK_Not_Narrowing:
4981    break;
4982
4983  case NK_Constant_Narrowing:
4984    Diag(From->getLocStart(),
4985         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4986                             diag::err_cce_narrowing)
4987      << CCE << /*Constant*/1
4988      << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
4989    break;
4990
4991  case NK_Type_Narrowing:
4992    Diag(From->getLocStart(),
4993         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4994                             diag::err_cce_narrowing)
4995      << CCE << /*Constant*/0 << From->getType() << T;
4996    break;
4997  }
4998
4999  // Check the expression is a constant expression.
5000  SmallVector<PartialDiagnosticAt, 8> Notes;
5001  Expr::EvalResult Eval;
5002  Eval.Diag = &Notes;
5003
5004  if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
5005    // The expression can't be folded, so we can't keep it at this position in
5006    // the AST.
5007    Result = ExprError();
5008  } else {
5009    Value = Eval.Val.getInt();
5010
5011    if (Notes.empty()) {
5012      // It's a constant expression.
5013      return Result;
5014    }
5015  }
5016
5017  // It's not a constant expression. Produce an appropriate diagnostic.
5018  if (Notes.size() == 1 &&
5019      Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5020    Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5021  else {
5022    Diag(From->getLocStart(), diag::err_expr_not_cce)
5023      << CCE << From->getSourceRange();
5024    for (unsigned I = 0; I < Notes.size(); ++I)
5025      Diag(Notes[I].first, Notes[I].second);
5026  }
5027  return Result;
5028}
5029
5030/// dropPointerConversions - If the given standard conversion sequence
5031/// involves any pointer conversions, remove them.  This may change
5032/// the result type of the conversion sequence.
5033static void dropPointerConversion(StandardConversionSequence &SCS) {
5034  if (SCS.Second == ICK_Pointer_Conversion) {
5035    SCS.Second = ICK_Identity;
5036    SCS.Third = ICK_Identity;
5037    SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5038  }
5039}
5040
5041/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5042/// convert the expression From to an Objective-C pointer type.
5043static ImplicitConversionSequence
5044TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5045  // Do an implicit conversion to 'id'.
5046  QualType Ty = S.Context.getObjCIdType();
5047  ImplicitConversionSequence ICS
5048    = TryImplicitConversion(S, From, Ty,
5049                            // FIXME: Are these flags correct?
5050                            /*SuppressUserConversions=*/false,
5051                            /*AllowExplicit=*/true,
5052                            /*InOverloadResolution=*/false,
5053                            /*CStyle=*/false,
5054                            /*AllowObjCWritebackConversion=*/false);
5055
5056  // Strip off any final conversions to 'id'.
5057  switch (ICS.getKind()) {
5058  case ImplicitConversionSequence::BadConversion:
5059  case ImplicitConversionSequence::AmbiguousConversion:
5060  case ImplicitConversionSequence::EllipsisConversion:
5061    break;
5062
5063  case ImplicitConversionSequence::UserDefinedConversion:
5064    dropPointerConversion(ICS.UserDefined.After);
5065    break;
5066
5067  case ImplicitConversionSequence::StandardConversion:
5068    dropPointerConversion(ICS.Standard);
5069    break;
5070  }
5071
5072  return ICS;
5073}
5074
5075/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5076/// conversion of the expression From to an Objective-C pointer type.
5077ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5078  if (checkPlaceholderForOverload(*this, From))
5079    return ExprError();
5080
5081  QualType Ty = Context.getObjCIdType();
5082  ImplicitConversionSequence ICS =
5083    TryContextuallyConvertToObjCPointer(*this, From);
5084  if (!ICS.isBad())
5085    return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5086  return ExprError();
5087}
5088
5089/// Determine whether the provided type is an integral type, or an enumeration
5090/// type of a permitted flavor.
5091static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5092  return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5093                         : T->isIntegralOrUnscopedEnumerationType();
5094}
5095
5096/// \brief Attempt to convert the given expression to an integral or
5097/// enumeration type.
5098///
5099/// This routine will attempt to convert an expression of class type to an
5100/// integral or enumeration type, if that class type only has a single
5101/// conversion to an integral or enumeration type.
5102///
5103/// \param Loc The source location of the construct that requires the
5104/// conversion.
5105///
5106/// \param From The expression we're converting from.
5107///
5108/// \param Diagnoser Used to output any diagnostics.
5109///
5110/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5111/// enumerations should be considered.
5112///
5113/// \returns The expression, converted to an integral or enumeration type if
5114/// successful.
5115ExprResult
5116Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
5117                                         ICEConvertDiagnoser &Diagnoser,
5118                                         bool AllowScopedEnumerations) {
5119  // We can't perform any more checking for type-dependent expressions.
5120  if (From->isTypeDependent())
5121    return Owned(From);
5122
5123  // Process placeholders immediately.
5124  if (From->hasPlaceholderType()) {
5125    ExprResult result = CheckPlaceholderExpr(From);
5126    if (result.isInvalid()) return result;
5127    From = result.take();
5128  }
5129
5130  // If the expression already has integral or enumeration type, we're golden.
5131  QualType T = From->getType();
5132  if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
5133    return DefaultLvalueConversion(From);
5134
5135  // FIXME: Check for missing '()' if T is a function type?
5136
5137  // If we don't have a class type in C++, there's no way we can get an
5138  // expression of integral or enumeration type.
5139  const RecordType *RecordTy = T->getAs<RecordType>();
5140  if (!RecordTy || !getLangOpts().CPlusPlus) {
5141    if (!Diagnoser.Suppress)
5142      Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
5143    return Owned(From);
5144  }
5145
5146  // We must have a complete class type.
5147  struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5148    ICEConvertDiagnoser &Diagnoser;
5149    Expr *From;
5150
5151    TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5152      : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
5153
5154    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5155      Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5156    }
5157  } IncompleteDiagnoser(Diagnoser, From);
5158
5159  if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5160    return Owned(From);
5161
5162  // Look for a conversion to an integral or enumeration type.
5163  UnresolvedSet<4> ViableConversions;
5164  UnresolvedSet<4> ExplicitConversions;
5165  std::pair<CXXRecordDecl::conversion_iterator,
5166            CXXRecordDecl::conversion_iterator> Conversions
5167    = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5168
5169  bool HadMultipleCandidates
5170    = (std::distance(Conversions.first, Conversions.second) > 1);
5171
5172  for (CXXRecordDecl::conversion_iterator
5173         I = Conversions.first, E = Conversions.second; I != E; ++I) {
5174    if (CXXConversionDecl *Conversion
5175          = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5176      if (isIntegralOrEnumerationType(
5177            Conversion->getConversionType().getNonReferenceType(),
5178            AllowScopedEnumerations)) {
5179        if (Conversion->isExplicit())
5180          ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5181        else
5182          ViableConversions.addDecl(I.getDecl(), I.getAccess());
5183      }
5184    }
5185  }
5186
5187  switch (ViableConversions.size()) {
5188  case 0:
5189    if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
5190      DeclAccessPair Found = ExplicitConversions[0];
5191      CXXConversionDecl *Conversion
5192        = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5193
5194      // The user probably meant to invoke the given explicit
5195      // conversion; use it.
5196      QualType ConvTy
5197        = Conversion->getConversionType().getNonReferenceType();
5198      std::string TypeStr;
5199      ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
5200
5201      Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
5202        << FixItHint::CreateInsertion(From->getLocStart(),
5203                                      "static_cast<" + TypeStr + ">(")
5204        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5205                                      ")");
5206      Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
5207
5208      // If we aren't in a SFINAE context, build a call to the
5209      // explicit conversion function.
5210      if (isSFINAEContext())
5211        return ExprError();
5212
5213      CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5214      ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5215                                                 HadMultipleCandidates);
5216      if (Result.isInvalid())
5217        return ExprError();
5218      // Record usage of conversion in an implicit cast.
5219      From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5220                                      CK_UserDefinedConversion,
5221                                      Result.get(), 0,
5222                                      Result.get()->getValueKind());
5223    }
5224
5225    // We'll complain below about a non-integral condition type.
5226    break;
5227
5228  case 1: {
5229    // Apply this conversion.
5230    DeclAccessPair Found = ViableConversions[0];
5231    CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5232
5233    CXXConversionDecl *Conversion
5234      = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5235    QualType ConvTy
5236      = Conversion->getConversionType().getNonReferenceType();
5237    if (!Diagnoser.SuppressConversion) {
5238      if (isSFINAEContext())
5239        return ExprError();
5240
5241      Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5242        << From->getSourceRange();
5243    }
5244
5245    ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5246                                               HadMultipleCandidates);
5247    if (Result.isInvalid())
5248      return ExprError();
5249    // Record usage of conversion in an implicit cast.
5250    From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5251                                    CK_UserDefinedConversion,
5252                                    Result.get(), 0,
5253                                    Result.get()->getValueKind());
5254    break;
5255  }
5256
5257  default:
5258    if (Diagnoser.Suppress)
5259      return ExprError();
5260
5261    Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
5262    for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5263      CXXConversionDecl *Conv
5264        = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5265      QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5266      Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
5267    }
5268    return Owned(From);
5269  }
5270
5271  if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5272      !Diagnoser.Suppress) {
5273    Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5274      << From->getSourceRange();
5275  }
5276
5277  return DefaultLvalueConversion(From);
5278}
5279
5280/// AddOverloadCandidate - Adds the given function to the set of
5281/// candidate functions, using the given function call arguments.  If
5282/// @p SuppressUserConversions, then don't allow user-defined
5283/// conversions via constructors or conversion operators.
5284///
5285/// \param PartialOverloading true if we are performing "partial" overloading
5286/// based on an incomplete set of function arguments. This feature is used by
5287/// code completion.
5288void
5289Sema::AddOverloadCandidate(FunctionDecl *Function,
5290                           DeclAccessPair FoundDecl,
5291                           ArrayRef<Expr *> Args,
5292                           OverloadCandidateSet& CandidateSet,
5293                           bool SuppressUserConversions,
5294                           bool PartialOverloading,
5295                           bool AllowExplicit) {
5296  const FunctionProtoType* Proto
5297    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5298  assert(Proto && "Functions without a prototype cannot be overloaded");
5299  assert(!Function->getDescribedFunctionTemplate() &&
5300         "Use AddTemplateOverloadCandidate for function templates");
5301
5302  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5303    if (!isa<CXXConstructorDecl>(Method)) {
5304      // If we get here, it's because we're calling a member function
5305      // that is named without a member access expression (e.g.,
5306      // "this->f") that was either written explicitly or created
5307      // implicitly. This can happen with a qualified call to a member
5308      // function, e.g., X::f(). We use an empty type for the implied
5309      // object argument (C++ [over.call.func]p3), and the acting context
5310      // is irrelevant.
5311      AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5312                         QualType(), Expr::Classification::makeSimpleLValue(),
5313                         Args, CandidateSet, SuppressUserConversions);
5314      return;
5315    }
5316    // We treat a constructor like a non-member function, since its object
5317    // argument doesn't participate in overload resolution.
5318  }
5319
5320  if (!CandidateSet.isNewCandidate(Function))
5321    return;
5322
5323  // Overload resolution is always an unevaluated context.
5324  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5325
5326  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5327    // C++ [class.copy]p3:
5328    //   A member function template is never instantiated to perform the copy
5329    //   of a class object to an object of its class type.
5330    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5331    if (Args.size() == 1 &&
5332        Constructor->isSpecializationCopyingObject() &&
5333        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5334         IsDerivedFrom(Args[0]->getType(), ClassType)))
5335      return;
5336  }
5337
5338  // Add this candidate
5339  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5340  Candidate.FoundDecl = FoundDecl;
5341  Candidate.Function = Function;
5342  Candidate.Viable = true;
5343  Candidate.IsSurrogate = false;
5344  Candidate.IgnoreObjectArgument = false;
5345  Candidate.ExplicitCallArguments = Args.size();
5346
5347  unsigned NumArgsInProto = Proto->getNumArgs();
5348
5349  // (C++ 13.3.2p2): A candidate function having fewer than m
5350  // parameters is viable only if it has an ellipsis in its parameter
5351  // list (8.3.5).
5352  if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5353      !Proto->isVariadic()) {
5354    Candidate.Viable = false;
5355    Candidate.FailureKind = ovl_fail_too_many_arguments;
5356    return;
5357  }
5358
5359  // (C++ 13.3.2p2): A candidate function having more than m parameters
5360  // is viable only if the (m+1)st parameter has a default argument
5361  // (8.3.6). For the purposes of overload resolution, the
5362  // parameter list is truncated on the right, so that there are
5363  // exactly m parameters.
5364  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5365  if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5366    // Not enough arguments.
5367    Candidate.Viable = false;
5368    Candidate.FailureKind = ovl_fail_too_few_arguments;
5369    return;
5370  }
5371
5372  // (CUDA B.1): Check for invalid calls between targets.
5373  if (getLangOpts().CUDA)
5374    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5375      if (CheckCUDATarget(Caller, Function)) {
5376        Candidate.Viable = false;
5377        Candidate.FailureKind = ovl_fail_bad_target;
5378        return;
5379      }
5380
5381  // Determine the implicit conversion sequences for each of the
5382  // arguments.
5383  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5384    if (ArgIdx < NumArgsInProto) {
5385      // (C++ 13.3.2p3): for F to be a viable function, there shall
5386      // exist for each argument an implicit conversion sequence
5387      // (13.3.3.1) that converts that argument to the corresponding
5388      // parameter of F.
5389      QualType ParamType = Proto->getArgType(ArgIdx);
5390      Candidate.Conversions[ArgIdx]
5391        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5392                                SuppressUserConversions,
5393                                /*InOverloadResolution=*/true,
5394                                /*AllowObjCWritebackConversion=*/
5395                                  getLangOpts().ObjCAutoRefCount,
5396                                AllowExplicit);
5397      if (Candidate.Conversions[ArgIdx].isBad()) {
5398        Candidate.Viable = false;
5399        Candidate.FailureKind = ovl_fail_bad_conversion;
5400        break;
5401      }
5402    } else {
5403      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5404      // argument for which there is no corresponding parameter is
5405      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5406      Candidate.Conversions[ArgIdx].setEllipsis();
5407    }
5408  }
5409}
5410
5411/// \brief Add all of the function declarations in the given function set to
5412/// the overload canddiate set.
5413void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5414                                 ArrayRef<Expr *> Args,
5415                                 OverloadCandidateSet& CandidateSet,
5416                                 bool SuppressUserConversions,
5417                               TemplateArgumentListInfo *ExplicitTemplateArgs) {
5418  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5419    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5420    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5421      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5422        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5423                           cast<CXXMethodDecl>(FD)->getParent(),
5424                           Args[0]->getType(), Args[0]->Classify(Context),
5425                           Args.slice(1), CandidateSet,
5426                           SuppressUserConversions);
5427      else
5428        AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5429                             SuppressUserConversions);
5430    } else {
5431      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5432      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5433          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5434        AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5435                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5436                                   ExplicitTemplateArgs,
5437                                   Args[0]->getType(),
5438                                   Args[0]->Classify(Context), Args.slice(1),
5439                                   CandidateSet, SuppressUserConversions);
5440      else
5441        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5442                                     ExplicitTemplateArgs, Args,
5443                                     CandidateSet, SuppressUserConversions);
5444    }
5445  }
5446}
5447
5448/// AddMethodCandidate - Adds a named decl (which is some kind of
5449/// method) as a method candidate to the given overload set.
5450void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5451                              QualType ObjectType,
5452                              Expr::Classification ObjectClassification,
5453                              Expr **Args, unsigned NumArgs,
5454                              OverloadCandidateSet& CandidateSet,
5455                              bool SuppressUserConversions) {
5456  NamedDecl *Decl = FoundDecl.getDecl();
5457  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5458
5459  if (isa<UsingShadowDecl>(Decl))
5460    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5461
5462  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5463    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5464           "Expected a member function template");
5465    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5466                               /*ExplicitArgs*/ 0,
5467                               ObjectType, ObjectClassification,
5468                               llvm::makeArrayRef(Args, NumArgs), CandidateSet,
5469                               SuppressUserConversions);
5470  } else {
5471    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5472                       ObjectType, ObjectClassification,
5473                       llvm::makeArrayRef(Args, NumArgs),
5474                       CandidateSet, SuppressUserConversions);
5475  }
5476}
5477
5478/// AddMethodCandidate - Adds the given C++ member function to the set
5479/// of candidate functions, using the given function call arguments
5480/// and the object argument (@c Object). For example, in a call
5481/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5482/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5483/// allow user-defined conversions via constructors or conversion
5484/// operators.
5485void
5486Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5487                         CXXRecordDecl *ActingContext, QualType ObjectType,
5488                         Expr::Classification ObjectClassification,
5489                         ArrayRef<Expr *> Args,
5490                         OverloadCandidateSet& CandidateSet,
5491                         bool SuppressUserConversions) {
5492  const FunctionProtoType* Proto
5493    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5494  assert(Proto && "Methods without a prototype cannot be overloaded");
5495  assert(!isa<CXXConstructorDecl>(Method) &&
5496         "Use AddOverloadCandidate for constructors");
5497
5498  if (!CandidateSet.isNewCandidate(Method))
5499    return;
5500
5501  // Overload resolution is always an unevaluated context.
5502  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5503
5504  // Add this candidate
5505  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5506  Candidate.FoundDecl = FoundDecl;
5507  Candidate.Function = Method;
5508  Candidate.IsSurrogate = false;
5509  Candidate.IgnoreObjectArgument = false;
5510  Candidate.ExplicitCallArguments = Args.size();
5511
5512  unsigned NumArgsInProto = Proto->getNumArgs();
5513
5514  // (C++ 13.3.2p2): A candidate function having fewer than m
5515  // parameters is viable only if it has an ellipsis in its parameter
5516  // list (8.3.5).
5517  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5518    Candidate.Viable = false;
5519    Candidate.FailureKind = ovl_fail_too_many_arguments;
5520    return;
5521  }
5522
5523  // (C++ 13.3.2p2): A candidate function having more than m parameters
5524  // is viable only if the (m+1)st parameter has a default argument
5525  // (8.3.6). For the purposes of overload resolution, the
5526  // parameter list is truncated on the right, so that there are
5527  // exactly m parameters.
5528  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5529  if (Args.size() < MinRequiredArgs) {
5530    // Not enough arguments.
5531    Candidate.Viable = false;
5532    Candidate.FailureKind = ovl_fail_too_few_arguments;
5533    return;
5534  }
5535
5536  Candidate.Viable = true;
5537
5538  if (Method->isStatic() || ObjectType.isNull())
5539    // The implicit object argument is ignored.
5540    Candidate.IgnoreObjectArgument = true;
5541  else {
5542    // Determine the implicit conversion sequence for the object
5543    // parameter.
5544    Candidate.Conversions[0]
5545      = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5546                                        Method, ActingContext);
5547    if (Candidate.Conversions[0].isBad()) {
5548      Candidate.Viable = false;
5549      Candidate.FailureKind = ovl_fail_bad_conversion;
5550      return;
5551    }
5552  }
5553
5554  // Determine the implicit conversion sequences for each of the
5555  // arguments.
5556  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5557    if (ArgIdx < NumArgsInProto) {
5558      // (C++ 13.3.2p3): for F to be a viable function, there shall
5559      // exist for each argument an implicit conversion sequence
5560      // (13.3.3.1) that converts that argument to the corresponding
5561      // parameter of F.
5562      QualType ParamType = Proto->getArgType(ArgIdx);
5563      Candidate.Conversions[ArgIdx + 1]
5564        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5565                                SuppressUserConversions,
5566                                /*InOverloadResolution=*/true,
5567                                /*AllowObjCWritebackConversion=*/
5568                                  getLangOpts().ObjCAutoRefCount);
5569      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5570        Candidate.Viable = false;
5571        Candidate.FailureKind = ovl_fail_bad_conversion;
5572        break;
5573      }
5574    } else {
5575      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5576      // argument for which there is no corresponding parameter is
5577      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5578      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5579    }
5580  }
5581}
5582
5583/// \brief Add a C++ member function template as a candidate to the candidate
5584/// set, using template argument deduction to produce an appropriate member
5585/// function template specialization.
5586void
5587Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5588                                 DeclAccessPair FoundDecl,
5589                                 CXXRecordDecl *ActingContext,
5590                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5591                                 QualType ObjectType,
5592                                 Expr::Classification ObjectClassification,
5593                                 ArrayRef<Expr *> Args,
5594                                 OverloadCandidateSet& CandidateSet,
5595                                 bool SuppressUserConversions) {
5596  if (!CandidateSet.isNewCandidate(MethodTmpl))
5597    return;
5598
5599  // C++ [over.match.funcs]p7:
5600  //   In each case where a candidate is a function template, candidate
5601  //   function template specializations are generated using template argument
5602  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5603  //   candidate functions in the usual way.113) A given name can refer to one
5604  //   or more function templates and also to a set of overloaded non-template
5605  //   functions. In such a case, the candidate functions generated from each
5606  //   function template are combined with the set of non-template candidate
5607  //   functions.
5608  TemplateDeductionInfo Info(CandidateSet.getLocation());
5609  FunctionDecl *Specialization = 0;
5610  if (TemplateDeductionResult Result
5611      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5612                                Specialization, Info)) {
5613    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5614    Candidate.FoundDecl = FoundDecl;
5615    Candidate.Function = MethodTmpl->getTemplatedDecl();
5616    Candidate.Viable = false;
5617    Candidate.FailureKind = ovl_fail_bad_deduction;
5618    Candidate.IsSurrogate = false;
5619    Candidate.IgnoreObjectArgument = false;
5620    Candidate.ExplicitCallArguments = Args.size();
5621    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5622                                                          Info);
5623    return;
5624  }
5625
5626  // Add the function template specialization produced by template argument
5627  // deduction as a candidate.
5628  assert(Specialization && "Missing member function template specialization?");
5629  assert(isa<CXXMethodDecl>(Specialization) &&
5630         "Specialization is not a member function?");
5631  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5632                     ActingContext, ObjectType, ObjectClassification, Args,
5633                     CandidateSet, SuppressUserConversions);
5634}
5635
5636/// \brief Add a C++ function template specialization as a candidate
5637/// in the candidate set, using template argument deduction to produce
5638/// an appropriate function template specialization.
5639void
5640Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5641                                   DeclAccessPair FoundDecl,
5642                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5643                                   ArrayRef<Expr *> Args,
5644                                   OverloadCandidateSet& CandidateSet,
5645                                   bool SuppressUserConversions) {
5646  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5647    return;
5648
5649  // C++ [over.match.funcs]p7:
5650  //   In each case where a candidate is a function template, candidate
5651  //   function template specializations are generated using template argument
5652  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5653  //   candidate functions in the usual way.113) A given name can refer to one
5654  //   or more function templates and also to a set of overloaded non-template
5655  //   functions. In such a case, the candidate functions generated from each
5656  //   function template are combined with the set of non-template candidate
5657  //   functions.
5658  TemplateDeductionInfo Info(CandidateSet.getLocation());
5659  FunctionDecl *Specialization = 0;
5660  if (TemplateDeductionResult Result
5661        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5662                                  Specialization, Info)) {
5663    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5664    Candidate.FoundDecl = FoundDecl;
5665    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5666    Candidate.Viable = false;
5667    Candidate.FailureKind = ovl_fail_bad_deduction;
5668    Candidate.IsSurrogate = false;
5669    Candidate.IgnoreObjectArgument = false;
5670    Candidate.ExplicitCallArguments = Args.size();
5671    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5672                                                          Info);
5673    return;
5674  }
5675
5676  // Add the function template specialization produced by template argument
5677  // deduction as a candidate.
5678  assert(Specialization && "Missing function template specialization?");
5679  AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5680                       SuppressUserConversions);
5681}
5682
5683/// AddConversionCandidate - Add a C++ conversion function as a
5684/// candidate in the candidate set (C++ [over.match.conv],
5685/// C++ [over.match.copy]). From is the expression we're converting from,
5686/// and ToType is the type that we're eventually trying to convert to
5687/// (which may or may not be the same type as the type that the
5688/// conversion function produces).
5689void
5690Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5691                             DeclAccessPair FoundDecl,
5692                             CXXRecordDecl *ActingContext,
5693                             Expr *From, QualType ToType,
5694                             OverloadCandidateSet& CandidateSet) {
5695  assert(!Conversion->getDescribedFunctionTemplate() &&
5696         "Conversion function templates use AddTemplateConversionCandidate");
5697  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5698  if (!CandidateSet.isNewCandidate(Conversion))
5699    return;
5700
5701  // Overload resolution is always an unevaluated context.
5702  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5703
5704  // Add this candidate
5705  OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5706  Candidate.FoundDecl = FoundDecl;
5707  Candidate.Function = Conversion;
5708  Candidate.IsSurrogate = false;
5709  Candidate.IgnoreObjectArgument = false;
5710  Candidate.FinalConversion.setAsIdentityConversion();
5711  Candidate.FinalConversion.setFromType(ConvType);
5712  Candidate.FinalConversion.setAllToTypes(ToType);
5713  Candidate.Viable = true;
5714  Candidate.ExplicitCallArguments = 1;
5715
5716  // C++ [over.match.funcs]p4:
5717  //   For conversion functions, the function is considered to be a member of
5718  //   the class of the implicit implied object argument for the purpose of
5719  //   defining the type of the implicit object parameter.
5720  //
5721  // Determine the implicit conversion sequence for the implicit
5722  // object parameter.
5723  QualType ImplicitParamType = From->getType();
5724  if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5725    ImplicitParamType = FromPtrType->getPointeeType();
5726  CXXRecordDecl *ConversionContext
5727    = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5728
5729  Candidate.Conversions[0]
5730    = TryObjectArgumentInitialization(*this, From->getType(),
5731                                      From->Classify(Context),
5732                                      Conversion, ConversionContext);
5733
5734  if (Candidate.Conversions[0].isBad()) {
5735    Candidate.Viable = false;
5736    Candidate.FailureKind = ovl_fail_bad_conversion;
5737    return;
5738  }
5739
5740  // We won't go through a user-define type conversion function to convert a
5741  // derived to base as such conversions are given Conversion Rank. They only
5742  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5743  QualType FromCanon
5744    = Context.getCanonicalType(From->getType().getUnqualifiedType());
5745  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5746  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5747    Candidate.Viable = false;
5748    Candidate.FailureKind = ovl_fail_trivial_conversion;
5749    return;
5750  }
5751
5752  // To determine what the conversion from the result of calling the
5753  // conversion function to the type we're eventually trying to
5754  // convert to (ToType), we need to synthesize a call to the
5755  // conversion function and attempt copy initialization from it. This
5756  // makes sure that we get the right semantics with respect to
5757  // lvalues/rvalues and the type. Fortunately, we can allocate this
5758  // call on the stack and we don't need its arguments to be
5759  // well-formed.
5760  DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5761                            VK_LValue, From->getLocStart());
5762  ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5763                                Context.getPointerType(Conversion->getType()),
5764                                CK_FunctionToPointerDecay,
5765                                &ConversionRef, VK_RValue);
5766
5767  QualType ConversionType = Conversion->getConversionType();
5768  if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5769    Candidate.Viable = false;
5770    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5771    return;
5772  }
5773
5774  ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5775
5776  // Note that it is safe to allocate CallExpr on the stack here because
5777  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5778  // allocator).
5779  QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5780  CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
5781                From->getLocStart());
5782  ImplicitConversionSequence ICS =
5783    TryCopyInitialization(*this, &Call, ToType,
5784                          /*SuppressUserConversions=*/true,
5785                          /*InOverloadResolution=*/false,
5786                          /*AllowObjCWritebackConversion=*/false);
5787
5788  switch (ICS.getKind()) {
5789  case ImplicitConversionSequence::StandardConversion:
5790    Candidate.FinalConversion = ICS.Standard;
5791
5792    // C++ [over.ics.user]p3:
5793    //   If the user-defined conversion is specified by a specialization of a
5794    //   conversion function template, the second standard conversion sequence
5795    //   shall have exact match rank.
5796    if (Conversion->getPrimaryTemplate() &&
5797        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5798      Candidate.Viable = false;
5799      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5800    }
5801
5802    // C++0x [dcl.init.ref]p5:
5803    //    In the second case, if the reference is an rvalue reference and
5804    //    the second standard conversion sequence of the user-defined
5805    //    conversion sequence includes an lvalue-to-rvalue conversion, the
5806    //    program is ill-formed.
5807    if (ToType->isRValueReferenceType() &&
5808        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5809      Candidate.Viable = false;
5810      Candidate.FailureKind = ovl_fail_bad_final_conversion;
5811    }
5812    break;
5813
5814  case ImplicitConversionSequence::BadConversion:
5815    Candidate.Viable = false;
5816    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5817    break;
5818
5819  default:
5820    llvm_unreachable(
5821           "Can only end up with a standard conversion sequence or failure");
5822  }
5823}
5824
5825/// \brief Adds a conversion function template specialization
5826/// candidate to the overload set, using template argument deduction
5827/// to deduce the template arguments of the conversion function
5828/// template from the type that we are converting to (C++
5829/// [temp.deduct.conv]).
5830void
5831Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
5832                                     DeclAccessPair FoundDecl,
5833                                     CXXRecordDecl *ActingDC,
5834                                     Expr *From, QualType ToType,
5835                                     OverloadCandidateSet &CandidateSet) {
5836  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5837         "Only conversion function templates permitted here");
5838
5839  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5840    return;
5841
5842  TemplateDeductionInfo Info(CandidateSet.getLocation());
5843  CXXConversionDecl *Specialization = 0;
5844  if (TemplateDeductionResult Result
5845        = DeduceTemplateArguments(FunctionTemplate, ToType,
5846                                  Specialization, Info)) {
5847    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5848    Candidate.FoundDecl = FoundDecl;
5849    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5850    Candidate.Viable = false;
5851    Candidate.FailureKind = ovl_fail_bad_deduction;
5852    Candidate.IsSurrogate = false;
5853    Candidate.IgnoreObjectArgument = false;
5854    Candidate.ExplicitCallArguments = 1;
5855    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5856                                                          Info);
5857    return;
5858  }
5859
5860  // Add the conversion function template specialization produced by
5861  // template argument deduction as a candidate.
5862  assert(Specialization && "Missing function template specialization?");
5863  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
5864                         CandidateSet);
5865}
5866
5867/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5868/// converts the given @c Object to a function pointer via the
5869/// conversion function @c Conversion, and then attempts to call it
5870/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5871/// the type of function that we'll eventually be calling.
5872void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
5873                                 DeclAccessPair FoundDecl,
5874                                 CXXRecordDecl *ActingContext,
5875                                 const FunctionProtoType *Proto,
5876                                 Expr *Object,
5877                                 ArrayRef<Expr *> Args,
5878                                 OverloadCandidateSet& CandidateSet) {
5879  if (!CandidateSet.isNewCandidate(Conversion))
5880    return;
5881
5882  // Overload resolution is always an unevaluated context.
5883  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5884
5885  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5886  Candidate.FoundDecl = FoundDecl;
5887  Candidate.Function = 0;
5888  Candidate.Surrogate = Conversion;
5889  Candidate.Viable = true;
5890  Candidate.IsSurrogate = true;
5891  Candidate.IgnoreObjectArgument = false;
5892  Candidate.ExplicitCallArguments = Args.size();
5893
5894  // Determine the implicit conversion sequence for the implicit
5895  // object parameter.
5896  ImplicitConversionSequence ObjectInit
5897    = TryObjectArgumentInitialization(*this, Object->getType(),
5898                                      Object->Classify(Context),
5899                                      Conversion, ActingContext);
5900  if (ObjectInit.isBad()) {
5901    Candidate.Viable = false;
5902    Candidate.FailureKind = ovl_fail_bad_conversion;
5903    Candidate.Conversions[0] = ObjectInit;
5904    return;
5905  }
5906
5907  // The first conversion is actually a user-defined conversion whose
5908  // first conversion is ObjectInit's standard conversion (which is
5909  // effectively a reference binding). Record it as such.
5910  Candidate.Conversions[0].setUserDefined();
5911  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
5912  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
5913  Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
5914  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
5915  Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
5916  Candidate.Conversions[0].UserDefined.After
5917    = Candidate.Conversions[0].UserDefined.Before;
5918  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5919
5920  // Find the
5921  unsigned NumArgsInProto = Proto->getNumArgs();
5922
5923  // (C++ 13.3.2p2): A candidate function having fewer than m
5924  // parameters is viable only if it has an ellipsis in its parameter
5925  // list (8.3.5).
5926  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5927    Candidate.Viable = false;
5928    Candidate.FailureKind = ovl_fail_too_many_arguments;
5929    return;
5930  }
5931
5932  // Function types don't have any default arguments, so just check if
5933  // we have enough arguments.
5934  if (Args.size() < NumArgsInProto) {
5935    // Not enough arguments.
5936    Candidate.Viable = false;
5937    Candidate.FailureKind = ovl_fail_too_few_arguments;
5938    return;
5939  }
5940
5941  // Determine the implicit conversion sequences for each of the
5942  // arguments.
5943  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5944    if (ArgIdx < NumArgsInProto) {
5945      // (C++ 13.3.2p3): for F to be a viable function, there shall
5946      // exist for each argument an implicit conversion sequence
5947      // (13.3.3.1) that converts that argument to the corresponding
5948      // parameter of F.
5949      QualType ParamType = Proto->getArgType(ArgIdx);
5950      Candidate.Conversions[ArgIdx + 1]
5951        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5952                                /*SuppressUserConversions=*/false,
5953                                /*InOverloadResolution=*/false,
5954                                /*AllowObjCWritebackConversion=*/
5955                                  getLangOpts().ObjCAutoRefCount);
5956      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5957        Candidate.Viable = false;
5958        Candidate.FailureKind = ovl_fail_bad_conversion;
5959        break;
5960      }
5961    } else {
5962      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5963      // argument for which there is no corresponding parameter is
5964      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5965      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5966    }
5967  }
5968}
5969
5970/// \brief Add overload candidates for overloaded operators that are
5971/// member functions.
5972///
5973/// Add the overloaded operator candidates that are member functions
5974/// for the operator Op that was used in an operator expression such
5975/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5976/// CandidateSet will store the added overload candidates. (C++
5977/// [over.match.oper]).
5978void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5979                                       SourceLocation OpLoc,
5980                                       Expr **Args, unsigned NumArgs,
5981                                       OverloadCandidateSet& CandidateSet,
5982                                       SourceRange OpRange) {
5983  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5984
5985  // C++ [over.match.oper]p3:
5986  //   For a unary operator @ with an operand of a type whose
5987  //   cv-unqualified version is T1, and for a binary operator @ with
5988  //   a left operand of a type whose cv-unqualified version is T1 and
5989  //   a right operand of a type whose cv-unqualified version is T2,
5990  //   three sets of candidate functions, designated member
5991  //   candidates, non-member candidates and built-in candidates, are
5992  //   constructed as follows:
5993  QualType T1 = Args[0]->getType();
5994
5995  //     -- If T1 is a class type, the set of member candidates is the
5996  //        result of the qualified lookup of T1::operator@
5997  //        (13.3.1.1.1); otherwise, the set of member candidates is
5998  //        empty.
5999  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6000    // Complete the type if it can be completed. Otherwise, we're done.
6001    if (RequireCompleteType(OpLoc, T1, 0))
6002      return;
6003
6004    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6005    LookupQualifiedName(Operators, T1Rec->getDecl());
6006    Operators.suppressDiagnostics();
6007
6008    for (LookupResult::iterator Oper = Operators.begin(),
6009                             OperEnd = Operators.end();
6010         Oper != OperEnd;
6011         ++Oper)
6012      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6013                         Args[0]->Classify(Context), Args + 1, NumArgs - 1,
6014                         CandidateSet,
6015                         /* SuppressUserConversions = */ false);
6016  }
6017}
6018
6019/// AddBuiltinCandidate - Add a candidate for a built-in
6020/// operator. ResultTy and ParamTys are the result and parameter types
6021/// of the built-in candidate, respectively. Args and NumArgs are the
6022/// arguments being passed to the candidate. IsAssignmentOperator
6023/// should be true when this built-in candidate is an assignment
6024/// operator. NumContextualBoolArguments is the number of arguments
6025/// (at the beginning of the argument list) that will be contextually
6026/// converted to bool.
6027void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6028                               Expr **Args, unsigned NumArgs,
6029                               OverloadCandidateSet& CandidateSet,
6030                               bool IsAssignmentOperator,
6031                               unsigned NumContextualBoolArguments) {
6032  // Overload resolution is always an unevaluated context.
6033  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6034
6035  // Add this candidate
6036  OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
6037  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
6038  Candidate.Function = 0;
6039  Candidate.IsSurrogate = false;
6040  Candidate.IgnoreObjectArgument = false;
6041  Candidate.BuiltinTypes.ResultTy = ResultTy;
6042  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6043    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6044
6045  // Determine the implicit conversion sequences for each of the
6046  // arguments.
6047  Candidate.Viable = true;
6048  Candidate.ExplicitCallArguments = NumArgs;
6049  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6050    // C++ [over.match.oper]p4:
6051    //   For the built-in assignment operators, conversions of the
6052    //   left operand are restricted as follows:
6053    //     -- no temporaries are introduced to hold the left operand, and
6054    //     -- no user-defined conversions are applied to the left
6055    //        operand to achieve a type match with the left-most
6056    //        parameter of a built-in candidate.
6057    //
6058    // We block these conversions by turning off user-defined
6059    // conversions, since that is the only way that initialization of
6060    // a reference to a non-class type can occur from something that
6061    // is not of the same type.
6062    if (ArgIdx < NumContextualBoolArguments) {
6063      assert(ParamTys[ArgIdx] == Context.BoolTy &&
6064             "Contextual conversion to bool requires bool type");
6065      Candidate.Conversions[ArgIdx]
6066        = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6067    } else {
6068      Candidate.Conversions[ArgIdx]
6069        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6070                                ArgIdx == 0 && IsAssignmentOperator,
6071                                /*InOverloadResolution=*/false,
6072                                /*AllowObjCWritebackConversion=*/
6073                                  getLangOpts().ObjCAutoRefCount);
6074    }
6075    if (Candidate.Conversions[ArgIdx].isBad()) {
6076      Candidate.Viable = false;
6077      Candidate.FailureKind = ovl_fail_bad_conversion;
6078      break;
6079    }
6080  }
6081}
6082
6083/// BuiltinCandidateTypeSet - A set of types that will be used for the
6084/// candidate operator functions for built-in operators (C++
6085/// [over.built]). The types are separated into pointer types and
6086/// enumeration types.
6087class BuiltinCandidateTypeSet  {
6088  /// TypeSet - A set of types.
6089  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6090
6091  /// PointerTypes - The set of pointer types that will be used in the
6092  /// built-in candidates.
6093  TypeSet PointerTypes;
6094
6095  /// MemberPointerTypes - The set of member pointer types that will be
6096  /// used in the built-in candidates.
6097  TypeSet MemberPointerTypes;
6098
6099  /// EnumerationTypes - The set of enumeration types that will be
6100  /// used in the built-in candidates.
6101  TypeSet EnumerationTypes;
6102
6103  /// \brief The set of vector types that will be used in the built-in
6104  /// candidates.
6105  TypeSet VectorTypes;
6106
6107  /// \brief A flag indicating non-record types are viable candidates
6108  bool HasNonRecordTypes;
6109
6110  /// \brief A flag indicating whether either arithmetic or enumeration types
6111  /// were present in the candidate set.
6112  bool HasArithmeticOrEnumeralTypes;
6113
6114  /// \brief A flag indicating whether the nullptr type was present in the
6115  /// candidate set.
6116  bool HasNullPtrType;
6117
6118  /// Sema - The semantic analysis instance where we are building the
6119  /// candidate type set.
6120  Sema &SemaRef;
6121
6122  /// Context - The AST context in which we will build the type sets.
6123  ASTContext &Context;
6124
6125  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6126                                               const Qualifiers &VisibleQuals);
6127  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6128
6129public:
6130  /// iterator - Iterates through the types that are part of the set.
6131  typedef TypeSet::iterator iterator;
6132
6133  BuiltinCandidateTypeSet(Sema &SemaRef)
6134    : HasNonRecordTypes(false),
6135      HasArithmeticOrEnumeralTypes(false),
6136      HasNullPtrType(false),
6137      SemaRef(SemaRef),
6138      Context(SemaRef.Context) { }
6139
6140  void AddTypesConvertedFrom(QualType Ty,
6141                             SourceLocation Loc,
6142                             bool AllowUserConversions,
6143                             bool AllowExplicitConversions,
6144                             const Qualifiers &VisibleTypeConversionsQuals);
6145
6146  /// pointer_begin - First pointer type found;
6147  iterator pointer_begin() { return PointerTypes.begin(); }
6148
6149  /// pointer_end - Past the last pointer type found;
6150  iterator pointer_end() { return PointerTypes.end(); }
6151
6152  /// member_pointer_begin - First member pointer type found;
6153  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6154
6155  /// member_pointer_end - Past the last member pointer type found;
6156  iterator member_pointer_end() { return MemberPointerTypes.end(); }
6157
6158  /// enumeration_begin - First enumeration type found;
6159  iterator enumeration_begin() { return EnumerationTypes.begin(); }
6160
6161  /// enumeration_end - Past the last enumeration type found;
6162  iterator enumeration_end() { return EnumerationTypes.end(); }
6163
6164  iterator vector_begin() { return VectorTypes.begin(); }
6165  iterator vector_end() { return VectorTypes.end(); }
6166
6167  bool hasNonRecordTypes() { return HasNonRecordTypes; }
6168  bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6169  bool hasNullPtrType() const { return HasNullPtrType; }
6170};
6171
6172/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6173/// the set of pointer types along with any more-qualified variants of
6174/// that type. For example, if @p Ty is "int const *", this routine
6175/// will add "int const *", "int const volatile *", "int const
6176/// restrict *", and "int const volatile restrict *" to the set of
6177/// pointer types. Returns true if the add of @p Ty itself succeeded,
6178/// false otherwise.
6179///
6180/// FIXME: what to do about extended qualifiers?
6181bool
6182BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6183                                             const Qualifiers &VisibleQuals) {
6184
6185  // Insert this type.
6186  if (!PointerTypes.insert(Ty))
6187    return false;
6188
6189  QualType PointeeTy;
6190  const PointerType *PointerTy = Ty->getAs<PointerType>();
6191  bool buildObjCPtr = false;
6192  if (!PointerTy) {
6193    const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6194    PointeeTy = PTy->getPointeeType();
6195    buildObjCPtr = true;
6196  } else {
6197    PointeeTy = PointerTy->getPointeeType();
6198  }
6199
6200  // Don't add qualified variants of arrays. For one, they're not allowed
6201  // (the qualifier would sink to the element type), and for another, the
6202  // only overload situation where it matters is subscript or pointer +- int,
6203  // and those shouldn't have qualifier variants anyway.
6204  if (PointeeTy->isArrayType())
6205    return true;
6206
6207  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6208  bool hasVolatile = VisibleQuals.hasVolatile();
6209  bool hasRestrict = VisibleQuals.hasRestrict();
6210
6211  // Iterate through all strict supersets of BaseCVR.
6212  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6213    if ((CVR | BaseCVR) != CVR) continue;
6214    // Skip over volatile if no volatile found anywhere in the types.
6215    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6216
6217    // Skip over restrict if no restrict found anywhere in the types, or if
6218    // the type cannot be restrict-qualified.
6219    if ((CVR & Qualifiers::Restrict) &&
6220        (!hasRestrict ||
6221         (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6222      continue;
6223
6224    // Build qualified pointee type.
6225    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6226
6227    // Build qualified pointer type.
6228    QualType QPointerTy;
6229    if (!buildObjCPtr)
6230      QPointerTy = Context.getPointerType(QPointeeTy);
6231    else
6232      QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6233
6234    // Insert qualified pointer type.
6235    PointerTypes.insert(QPointerTy);
6236  }
6237
6238  return true;
6239}
6240
6241/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6242/// to the set of pointer types along with any more-qualified variants of
6243/// that type. For example, if @p Ty is "int const *", this routine
6244/// will add "int const *", "int const volatile *", "int const
6245/// restrict *", and "int const volatile restrict *" to the set of
6246/// pointer types. Returns true if the add of @p Ty itself succeeded,
6247/// false otherwise.
6248///
6249/// FIXME: what to do about extended qualifiers?
6250bool
6251BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6252    QualType Ty) {
6253  // Insert this type.
6254  if (!MemberPointerTypes.insert(Ty))
6255    return false;
6256
6257  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6258  assert(PointerTy && "type was not a member pointer type!");
6259
6260  QualType PointeeTy = PointerTy->getPointeeType();
6261  // Don't add qualified variants of arrays. For one, they're not allowed
6262  // (the qualifier would sink to the element type), and for another, the
6263  // only overload situation where it matters is subscript or pointer +- int,
6264  // and those shouldn't have qualifier variants anyway.
6265  if (PointeeTy->isArrayType())
6266    return true;
6267  const Type *ClassTy = PointerTy->getClass();
6268
6269  // Iterate through all strict supersets of the pointee type's CVR
6270  // qualifiers.
6271  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6272  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6273    if ((CVR | BaseCVR) != CVR) continue;
6274
6275    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6276    MemberPointerTypes.insert(
6277      Context.getMemberPointerType(QPointeeTy, ClassTy));
6278  }
6279
6280  return true;
6281}
6282
6283/// AddTypesConvertedFrom - Add each of the types to which the type @p
6284/// Ty can be implicit converted to the given set of @p Types. We're
6285/// primarily interested in pointer types and enumeration types. We also
6286/// take member pointer types, for the conditional operator.
6287/// AllowUserConversions is true if we should look at the conversion
6288/// functions of a class type, and AllowExplicitConversions if we
6289/// should also include the explicit conversion functions of a class
6290/// type.
6291void
6292BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6293                                               SourceLocation Loc,
6294                                               bool AllowUserConversions,
6295                                               bool AllowExplicitConversions,
6296                                               const Qualifiers &VisibleQuals) {
6297  // Only deal with canonical types.
6298  Ty = Context.getCanonicalType(Ty);
6299
6300  // Look through reference types; they aren't part of the type of an
6301  // expression for the purposes of conversions.
6302  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6303    Ty = RefTy->getPointeeType();
6304
6305  // If we're dealing with an array type, decay to the pointer.
6306  if (Ty->isArrayType())
6307    Ty = SemaRef.Context.getArrayDecayedType(Ty);
6308
6309  // Otherwise, we don't care about qualifiers on the type.
6310  Ty = Ty.getLocalUnqualifiedType();
6311
6312  // Flag if we ever add a non-record type.
6313  const RecordType *TyRec = Ty->getAs<RecordType>();
6314  HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6315
6316  // Flag if we encounter an arithmetic type.
6317  HasArithmeticOrEnumeralTypes =
6318    HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6319
6320  if (Ty->isObjCIdType() || Ty->isObjCClassType())
6321    PointerTypes.insert(Ty);
6322  else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6323    // Insert our type, and its more-qualified variants, into the set
6324    // of types.
6325    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6326      return;
6327  } else if (Ty->isMemberPointerType()) {
6328    // Member pointers are far easier, since the pointee can't be converted.
6329    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6330      return;
6331  } else if (Ty->isEnumeralType()) {
6332    HasArithmeticOrEnumeralTypes = true;
6333    EnumerationTypes.insert(Ty);
6334  } else if (Ty->isVectorType()) {
6335    // We treat vector types as arithmetic types in many contexts as an
6336    // extension.
6337    HasArithmeticOrEnumeralTypes = true;
6338    VectorTypes.insert(Ty);
6339  } else if (Ty->isNullPtrType()) {
6340    HasNullPtrType = true;
6341  } else if (AllowUserConversions && TyRec) {
6342    // No conversion functions in incomplete types.
6343    if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6344      return;
6345
6346    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6347    std::pair<CXXRecordDecl::conversion_iterator,
6348              CXXRecordDecl::conversion_iterator>
6349      Conversions = ClassDecl->getVisibleConversionFunctions();
6350    for (CXXRecordDecl::conversion_iterator
6351           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6352      NamedDecl *D = I.getDecl();
6353      if (isa<UsingShadowDecl>(D))
6354        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6355
6356      // Skip conversion function templates; they don't tell us anything
6357      // about which builtin types we can convert to.
6358      if (isa<FunctionTemplateDecl>(D))
6359        continue;
6360
6361      CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6362      if (AllowExplicitConversions || !Conv->isExplicit()) {
6363        AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6364                              VisibleQuals);
6365      }
6366    }
6367  }
6368}
6369
6370/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6371/// the volatile- and non-volatile-qualified assignment operators for the
6372/// given type to the candidate set.
6373static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6374                                                   QualType T,
6375                                                   Expr **Args,
6376                                                   unsigned NumArgs,
6377                                    OverloadCandidateSet &CandidateSet) {
6378  QualType ParamTypes[2];
6379
6380  // T& operator=(T&, T)
6381  ParamTypes[0] = S.Context.getLValueReferenceType(T);
6382  ParamTypes[1] = T;
6383  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6384                        /*IsAssignmentOperator=*/true);
6385
6386  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6387    // volatile T& operator=(volatile T&, T)
6388    ParamTypes[0]
6389      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6390    ParamTypes[1] = T;
6391    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6392                          /*IsAssignmentOperator=*/true);
6393  }
6394}
6395
6396/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6397/// if any, found in visible type conversion functions found in ArgExpr's type.
6398static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6399    Qualifiers VRQuals;
6400    const RecordType *TyRec;
6401    if (const MemberPointerType *RHSMPType =
6402        ArgExpr->getType()->getAs<MemberPointerType>())
6403      TyRec = RHSMPType->getClass()->getAs<RecordType>();
6404    else
6405      TyRec = ArgExpr->getType()->getAs<RecordType>();
6406    if (!TyRec) {
6407      // Just to be safe, assume the worst case.
6408      VRQuals.addVolatile();
6409      VRQuals.addRestrict();
6410      return VRQuals;
6411    }
6412
6413    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6414    if (!ClassDecl->hasDefinition())
6415      return VRQuals;
6416
6417    std::pair<CXXRecordDecl::conversion_iterator,
6418              CXXRecordDecl::conversion_iterator>
6419      Conversions = ClassDecl->getVisibleConversionFunctions();
6420
6421    for (CXXRecordDecl::conversion_iterator
6422           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6423      NamedDecl *D = I.getDecl();
6424      if (isa<UsingShadowDecl>(D))
6425        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6426      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6427        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6428        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6429          CanTy = ResTypeRef->getPointeeType();
6430        // Need to go down the pointer/mempointer chain and add qualifiers
6431        // as see them.
6432        bool done = false;
6433        while (!done) {
6434          if (CanTy.isRestrictQualified())
6435            VRQuals.addRestrict();
6436          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6437            CanTy = ResTypePtr->getPointeeType();
6438          else if (const MemberPointerType *ResTypeMPtr =
6439                CanTy->getAs<MemberPointerType>())
6440            CanTy = ResTypeMPtr->getPointeeType();
6441          else
6442            done = true;
6443          if (CanTy.isVolatileQualified())
6444            VRQuals.addVolatile();
6445          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6446            return VRQuals;
6447        }
6448      }
6449    }
6450    return VRQuals;
6451}
6452
6453namespace {
6454
6455/// \brief Helper class to manage the addition of builtin operator overload
6456/// candidates. It provides shared state and utility methods used throughout
6457/// the process, as well as a helper method to add each group of builtin
6458/// operator overloads from the standard to a candidate set.
6459class BuiltinOperatorOverloadBuilder {
6460  // Common instance state available to all overload candidate addition methods.
6461  Sema &S;
6462  Expr **Args;
6463  unsigned NumArgs;
6464  Qualifiers VisibleTypeConversionsQuals;
6465  bool HasArithmeticOrEnumeralCandidateType;
6466  SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6467  OverloadCandidateSet &CandidateSet;
6468
6469  // Define some constants used to index and iterate over the arithemetic types
6470  // provided via the getArithmeticType() method below.
6471  // The "promoted arithmetic types" are the arithmetic
6472  // types are that preserved by promotion (C++ [over.built]p2).
6473  static const unsigned FirstIntegralType = 3;
6474  static const unsigned LastIntegralType = 20;
6475  static const unsigned FirstPromotedIntegralType = 3,
6476                        LastPromotedIntegralType = 11;
6477  static const unsigned FirstPromotedArithmeticType = 0,
6478                        LastPromotedArithmeticType = 11;
6479  static const unsigned NumArithmeticTypes = 20;
6480
6481  /// \brief Get the canonical type for a given arithmetic type index.
6482  CanQualType getArithmeticType(unsigned index) {
6483    assert(index < NumArithmeticTypes);
6484    static CanQualType ASTContext::* const
6485      ArithmeticTypes[NumArithmeticTypes] = {
6486      // Start of promoted types.
6487      &ASTContext::FloatTy,
6488      &ASTContext::DoubleTy,
6489      &ASTContext::LongDoubleTy,
6490
6491      // Start of integral types.
6492      &ASTContext::IntTy,
6493      &ASTContext::LongTy,
6494      &ASTContext::LongLongTy,
6495      &ASTContext::Int128Ty,
6496      &ASTContext::UnsignedIntTy,
6497      &ASTContext::UnsignedLongTy,
6498      &ASTContext::UnsignedLongLongTy,
6499      &ASTContext::UnsignedInt128Ty,
6500      // End of promoted types.
6501
6502      &ASTContext::BoolTy,
6503      &ASTContext::CharTy,
6504      &ASTContext::WCharTy,
6505      &ASTContext::Char16Ty,
6506      &ASTContext::Char32Ty,
6507      &ASTContext::SignedCharTy,
6508      &ASTContext::ShortTy,
6509      &ASTContext::UnsignedCharTy,
6510      &ASTContext::UnsignedShortTy,
6511      // End of integral types.
6512      // FIXME: What about complex? What about half?
6513    };
6514    return S.Context.*ArithmeticTypes[index];
6515  }
6516
6517  /// \brief Gets the canonical type resulting from the usual arithemetic
6518  /// converions for the given arithmetic types.
6519  CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6520    // Accelerator table for performing the usual arithmetic conversions.
6521    // The rules are basically:
6522    //   - if either is floating-point, use the wider floating-point
6523    //   - if same signedness, use the higher rank
6524    //   - if same size, use unsigned of the higher rank
6525    //   - use the larger type
6526    // These rules, together with the axiom that higher ranks are
6527    // never smaller, are sufficient to precompute all of these results
6528    // *except* when dealing with signed types of higher rank.
6529    // (we could precompute SLL x UI for all known platforms, but it's
6530    // better not to make any assumptions).
6531    // We assume that int128 has a higher rank than long long on all platforms.
6532    enum PromotedType {
6533            Dep=-1,
6534            Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6535    };
6536    static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6537                                        [LastPromotedArithmeticType] = {
6538/* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6539/* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6540/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6541/*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6542/*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6543/* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6544/*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6545/*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6546/*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6547/* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6548/*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6549    };
6550
6551    assert(L < LastPromotedArithmeticType);
6552    assert(R < LastPromotedArithmeticType);
6553    int Idx = ConversionsTable[L][R];
6554
6555    // Fast path: the table gives us a concrete answer.
6556    if (Idx != Dep) return getArithmeticType(Idx);
6557
6558    // Slow path: we need to compare widths.
6559    // An invariant is that the signed type has higher rank.
6560    CanQualType LT = getArithmeticType(L),
6561                RT = getArithmeticType(R);
6562    unsigned LW = S.Context.getIntWidth(LT),
6563             RW = S.Context.getIntWidth(RT);
6564
6565    // If they're different widths, use the signed type.
6566    if (LW > RW) return LT;
6567    else if (LW < RW) return RT;
6568
6569    // Otherwise, use the unsigned type of the signed type's rank.
6570    if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6571    assert(L == SLL || R == SLL);
6572    return S.Context.UnsignedLongLongTy;
6573  }
6574
6575  /// \brief Helper method to factor out the common pattern of adding overloads
6576  /// for '++' and '--' builtin operators.
6577  void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6578                                           bool HasVolatile,
6579                                           bool HasRestrict) {
6580    QualType ParamTypes[2] = {
6581      S.Context.getLValueReferenceType(CandidateTy),
6582      S.Context.IntTy
6583    };
6584
6585    // Non-volatile version.
6586    if (NumArgs == 1)
6587      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6588    else
6589      S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6590
6591    // Use a heuristic to reduce number of builtin candidates in the set:
6592    // add volatile version only if there are conversions to a volatile type.
6593    if (HasVolatile) {
6594      ParamTypes[0] =
6595        S.Context.getLValueReferenceType(
6596          S.Context.getVolatileType(CandidateTy));
6597      if (NumArgs == 1)
6598        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6599      else
6600        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6601    }
6602
6603    // Add restrict version only if there are conversions to a restrict type
6604    // and our candidate type is a non-restrict-qualified pointer.
6605    if (HasRestrict && CandidateTy->isAnyPointerType() &&
6606        !CandidateTy.isRestrictQualified()) {
6607      ParamTypes[0]
6608        = S.Context.getLValueReferenceType(
6609            S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6610      if (NumArgs == 1)
6611        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6612      else
6613        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6614
6615      if (HasVolatile) {
6616        ParamTypes[0]
6617          = S.Context.getLValueReferenceType(
6618              S.Context.getCVRQualifiedType(CandidateTy,
6619                                            (Qualifiers::Volatile |
6620                                             Qualifiers::Restrict)));
6621        if (NumArgs == 1)
6622          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6623                                CandidateSet);
6624        else
6625          S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6626      }
6627    }
6628
6629  }
6630
6631public:
6632  BuiltinOperatorOverloadBuilder(
6633    Sema &S, Expr **Args, unsigned NumArgs,
6634    Qualifiers VisibleTypeConversionsQuals,
6635    bool HasArithmeticOrEnumeralCandidateType,
6636    SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6637    OverloadCandidateSet &CandidateSet)
6638    : S(S), Args(Args), NumArgs(NumArgs),
6639      VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6640      HasArithmeticOrEnumeralCandidateType(
6641        HasArithmeticOrEnumeralCandidateType),
6642      CandidateTypes(CandidateTypes),
6643      CandidateSet(CandidateSet) {
6644    // Validate some of our static helper constants in debug builds.
6645    assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6646           "Invalid first promoted integral type");
6647    assert(getArithmeticType(LastPromotedIntegralType - 1)
6648             == S.Context.UnsignedInt128Ty &&
6649           "Invalid last promoted integral type");
6650    assert(getArithmeticType(FirstPromotedArithmeticType)
6651             == S.Context.FloatTy &&
6652           "Invalid first promoted arithmetic type");
6653    assert(getArithmeticType(LastPromotedArithmeticType - 1)
6654             == S.Context.UnsignedInt128Ty &&
6655           "Invalid last promoted arithmetic type");
6656  }
6657
6658  // C++ [over.built]p3:
6659  //
6660  //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6661  //   is either volatile or empty, there exist candidate operator
6662  //   functions of the form
6663  //
6664  //       VQ T&      operator++(VQ T&);
6665  //       T          operator++(VQ T&, int);
6666  //
6667  // C++ [over.built]p4:
6668  //
6669  //   For every pair (T, VQ), where T is an arithmetic type other
6670  //   than bool, and VQ is either volatile or empty, there exist
6671  //   candidate operator functions of the form
6672  //
6673  //       VQ T&      operator--(VQ T&);
6674  //       T          operator--(VQ T&, int);
6675  void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6676    if (!HasArithmeticOrEnumeralCandidateType)
6677      return;
6678
6679    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6680         Arith < NumArithmeticTypes; ++Arith) {
6681      addPlusPlusMinusMinusStyleOverloads(
6682        getArithmeticType(Arith),
6683        VisibleTypeConversionsQuals.hasVolatile(),
6684        VisibleTypeConversionsQuals.hasRestrict());
6685    }
6686  }
6687
6688  // C++ [over.built]p5:
6689  //
6690  //   For every pair (T, VQ), where T is a cv-qualified or
6691  //   cv-unqualified object type, and VQ is either volatile or
6692  //   empty, there exist candidate operator functions of the form
6693  //
6694  //       T*VQ&      operator++(T*VQ&);
6695  //       T*VQ&      operator--(T*VQ&);
6696  //       T*         operator++(T*VQ&, int);
6697  //       T*         operator--(T*VQ&, int);
6698  void addPlusPlusMinusMinusPointerOverloads() {
6699    for (BuiltinCandidateTypeSet::iterator
6700              Ptr = CandidateTypes[0].pointer_begin(),
6701           PtrEnd = CandidateTypes[0].pointer_end();
6702         Ptr != PtrEnd; ++Ptr) {
6703      // Skip pointer types that aren't pointers to object types.
6704      if (!(*Ptr)->getPointeeType()->isObjectType())
6705        continue;
6706
6707      addPlusPlusMinusMinusStyleOverloads(*Ptr,
6708        (!(*Ptr).isVolatileQualified() &&
6709         VisibleTypeConversionsQuals.hasVolatile()),
6710        (!(*Ptr).isRestrictQualified() &&
6711         VisibleTypeConversionsQuals.hasRestrict()));
6712    }
6713  }
6714
6715  // C++ [over.built]p6:
6716  //   For every cv-qualified or cv-unqualified object type T, there
6717  //   exist candidate operator functions of the form
6718  //
6719  //       T&         operator*(T*);
6720  //
6721  // C++ [over.built]p7:
6722  //   For every function type T that does not have cv-qualifiers or a
6723  //   ref-qualifier, there exist candidate operator functions of the form
6724  //       T&         operator*(T*);
6725  void addUnaryStarPointerOverloads() {
6726    for (BuiltinCandidateTypeSet::iterator
6727              Ptr = CandidateTypes[0].pointer_begin(),
6728           PtrEnd = CandidateTypes[0].pointer_end();
6729         Ptr != PtrEnd; ++Ptr) {
6730      QualType ParamTy = *Ptr;
6731      QualType PointeeTy = ParamTy->getPointeeType();
6732      if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6733        continue;
6734
6735      if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6736        if (Proto->getTypeQuals() || Proto->getRefQualifier())
6737          continue;
6738
6739      S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6740                            &ParamTy, Args, 1, CandidateSet);
6741    }
6742  }
6743
6744  // C++ [over.built]p9:
6745  //  For every promoted arithmetic type T, there exist candidate
6746  //  operator functions of the form
6747  //
6748  //       T         operator+(T);
6749  //       T         operator-(T);
6750  void addUnaryPlusOrMinusArithmeticOverloads() {
6751    if (!HasArithmeticOrEnumeralCandidateType)
6752      return;
6753
6754    for (unsigned Arith = FirstPromotedArithmeticType;
6755         Arith < LastPromotedArithmeticType; ++Arith) {
6756      QualType ArithTy = getArithmeticType(Arith);
6757      S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6758    }
6759
6760    // Extension: We also add these operators for vector types.
6761    for (BuiltinCandidateTypeSet::iterator
6762              Vec = CandidateTypes[0].vector_begin(),
6763           VecEnd = CandidateTypes[0].vector_end();
6764         Vec != VecEnd; ++Vec) {
6765      QualType VecTy = *Vec;
6766      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6767    }
6768  }
6769
6770  // C++ [over.built]p8:
6771  //   For every type T, there exist candidate operator functions of
6772  //   the form
6773  //
6774  //       T*         operator+(T*);
6775  void addUnaryPlusPointerOverloads() {
6776    for (BuiltinCandidateTypeSet::iterator
6777              Ptr = CandidateTypes[0].pointer_begin(),
6778           PtrEnd = CandidateTypes[0].pointer_end();
6779         Ptr != PtrEnd; ++Ptr) {
6780      QualType ParamTy = *Ptr;
6781      S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6782    }
6783  }
6784
6785  // C++ [over.built]p10:
6786  //   For every promoted integral type T, there exist candidate
6787  //   operator functions of the form
6788  //
6789  //        T         operator~(T);
6790  void addUnaryTildePromotedIntegralOverloads() {
6791    if (!HasArithmeticOrEnumeralCandidateType)
6792      return;
6793
6794    for (unsigned Int = FirstPromotedIntegralType;
6795         Int < LastPromotedIntegralType; ++Int) {
6796      QualType IntTy = getArithmeticType(Int);
6797      S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6798    }
6799
6800    // Extension: We also add this operator for vector types.
6801    for (BuiltinCandidateTypeSet::iterator
6802              Vec = CandidateTypes[0].vector_begin(),
6803           VecEnd = CandidateTypes[0].vector_end();
6804         Vec != VecEnd; ++Vec) {
6805      QualType VecTy = *Vec;
6806      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6807    }
6808  }
6809
6810  // C++ [over.match.oper]p16:
6811  //   For every pointer to member type T, there exist candidate operator
6812  //   functions of the form
6813  //
6814  //        bool operator==(T,T);
6815  //        bool operator!=(T,T);
6816  void addEqualEqualOrNotEqualMemberPointerOverloads() {
6817    /// Set of (canonical) types that we've already handled.
6818    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6819
6820    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6821      for (BuiltinCandidateTypeSet::iterator
6822                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6823             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6824           MemPtr != MemPtrEnd;
6825           ++MemPtr) {
6826        // Don't add the same builtin candidate twice.
6827        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6828          continue;
6829
6830        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6831        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6832                              CandidateSet);
6833      }
6834    }
6835  }
6836
6837  // C++ [over.built]p15:
6838  //
6839  //   For every T, where T is an enumeration type, a pointer type, or
6840  //   std::nullptr_t, there exist candidate operator functions of the form
6841  //
6842  //        bool       operator<(T, T);
6843  //        bool       operator>(T, T);
6844  //        bool       operator<=(T, T);
6845  //        bool       operator>=(T, T);
6846  //        bool       operator==(T, T);
6847  //        bool       operator!=(T, T);
6848  void addRelationalPointerOrEnumeralOverloads() {
6849    // C++ [over.match.oper]p3:
6850    //   [...]the built-in candidates include all of the candidate operator
6851    //   functions defined in 13.6 that, compared to the given operator, [...]
6852    //   do not have the same parameter-type-list as any non-template non-member
6853    //   candidate.
6854    //
6855    // Note that in practice, this only affects enumeration types because there
6856    // aren't any built-in candidates of record type, and a user-defined operator
6857    // must have an operand of record or enumeration type. Also, the only other
6858    // overloaded operator with enumeration arguments, operator=,
6859    // cannot be overloaded for enumeration types, so this is the only place
6860    // where we must suppress candidates like this.
6861    llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6862      UserDefinedBinaryOperators;
6863
6864    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6865      if (CandidateTypes[ArgIdx].enumeration_begin() !=
6866          CandidateTypes[ArgIdx].enumeration_end()) {
6867        for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6868                                         CEnd = CandidateSet.end();
6869             C != CEnd; ++C) {
6870          if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6871            continue;
6872
6873          if (C->Function->isFunctionTemplateSpecialization())
6874            continue;
6875
6876          QualType FirstParamType =
6877            C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6878          QualType SecondParamType =
6879            C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6880
6881          // Skip if either parameter isn't of enumeral type.
6882          if (!FirstParamType->isEnumeralType() ||
6883              !SecondParamType->isEnumeralType())
6884            continue;
6885
6886          // Add this operator to the set of known user-defined operators.
6887          UserDefinedBinaryOperators.insert(
6888            std::make_pair(S.Context.getCanonicalType(FirstParamType),
6889                           S.Context.getCanonicalType(SecondParamType)));
6890        }
6891      }
6892    }
6893
6894    /// Set of (canonical) types that we've already handled.
6895    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6896
6897    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6898      for (BuiltinCandidateTypeSet::iterator
6899                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6900             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6901           Ptr != PtrEnd; ++Ptr) {
6902        // Don't add the same builtin candidate twice.
6903        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6904          continue;
6905
6906        QualType ParamTypes[2] = { *Ptr, *Ptr };
6907        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6908                              CandidateSet);
6909      }
6910      for (BuiltinCandidateTypeSet::iterator
6911                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6912             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6913           Enum != EnumEnd; ++Enum) {
6914        CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6915
6916        // Don't add the same builtin candidate twice, or if a user defined
6917        // candidate exists.
6918        if (!AddedTypes.insert(CanonType) ||
6919            UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6920                                                            CanonType)))
6921          continue;
6922
6923        QualType ParamTypes[2] = { *Enum, *Enum };
6924        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6925                              CandidateSet);
6926      }
6927
6928      if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6929        CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6930        if (AddedTypes.insert(NullPtrTy) &&
6931            !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6932                                                             NullPtrTy))) {
6933          QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6934          S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6935                                CandidateSet);
6936        }
6937      }
6938    }
6939  }
6940
6941  // C++ [over.built]p13:
6942  //
6943  //   For every cv-qualified or cv-unqualified object type T
6944  //   there exist candidate operator functions of the form
6945  //
6946  //      T*         operator+(T*, ptrdiff_t);
6947  //      T&         operator[](T*, ptrdiff_t);    [BELOW]
6948  //      T*         operator-(T*, ptrdiff_t);
6949  //      T*         operator+(ptrdiff_t, T*);
6950  //      T&         operator[](ptrdiff_t, T*);    [BELOW]
6951  //
6952  // C++ [over.built]p14:
6953  //
6954  //   For every T, where T is a pointer to object type, there
6955  //   exist candidate operator functions of the form
6956  //
6957  //      ptrdiff_t  operator-(T, T);
6958  void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6959    /// Set of (canonical) types that we've already handled.
6960    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6961
6962    for (int Arg = 0; Arg < 2; ++Arg) {
6963      QualType AsymetricParamTypes[2] = {
6964        S.Context.getPointerDiffType(),
6965        S.Context.getPointerDiffType(),
6966      };
6967      for (BuiltinCandidateTypeSet::iterator
6968                Ptr = CandidateTypes[Arg].pointer_begin(),
6969             PtrEnd = CandidateTypes[Arg].pointer_end();
6970           Ptr != PtrEnd; ++Ptr) {
6971        QualType PointeeTy = (*Ptr)->getPointeeType();
6972        if (!PointeeTy->isObjectType())
6973          continue;
6974
6975        AsymetricParamTypes[Arg] = *Ptr;
6976        if (Arg == 0 || Op == OO_Plus) {
6977          // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6978          // T* operator+(ptrdiff_t, T*);
6979          S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6980                                CandidateSet);
6981        }
6982        if (Op == OO_Minus) {
6983          // ptrdiff_t operator-(T, T);
6984          if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6985            continue;
6986
6987          QualType ParamTypes[2] = { *Ptr, *Ptr };
6988          S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6989                                Args, 2, CandidateSet);
6990        }
6991      }
6992    }
6993  }
6994
6995  // C++ [over.built]p12:
6996  //
6997  //   For every pair of promoted arithmetic types L and R, there
6998  //   exist candidate operator functions of the form
6999  //
7000  //        LR         operator*(L, R);
7001  //        LR         operator/(L, R);
7002  //        LR         operator+(L, R);
7003  //        LR         operator-(L, R);
7004  //        bool       operator<(L, R);
7005  //        bool       operator>(L, R);
7006  //        bool       operator<=(L, R);
7007  //        bool       operator>=(L, R);
7008  //        bool       operator==(L, R);
7009  //        bool       operator!=(L, R);
7010  //
7011  //   where LR is the result of the usual arithmetic conversions
7012  //   between types L and R.
7013  //
7014  // C++ [over.built]p24:
7015  //
7016  //   For every pair of promoted arithmetic types L and R, there exist
7017  //   candidate operator functions of the form
7018  //
7019  //        LR       operator?(bool, L, R);
7020  //
7021  //   where LR is the result of the usual arithmetic conversions
7022  //   between types L and R.
7023  // Our candidates ignore the first parameter.
7024  void addGenericBinaryArithmeticOverloads(bool isComparison) {
7025    if (!HasArithmeticOrEnumeralCandidateType)
7026      return;
7027
7028    for (unsigned Left = FirstPromotedArithmeticType;
7029         Left < LastPromotedArithmeticType; ++Left) {
7030      for (unsigned Right = FirstPromotedArithmeticType;
7031           Right < LastPromotedArithmeticType; ++Right) {
7032        QualType LandR[2] = { getArithmeticType(Left),
7033                              getArithmeticType(Right) };
7034        QualType Result =
7035          isComparison ? S.Context.BoolTy
7036                       : getUsualArithmeticConversions(Left, Right);
7037        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7038      }
7039    }
7040
7041    // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7042    // conditional operator for vector types.
7043    for (BuiltinCandidateTypeSet::iterator
7044              Vec1 = CandidateTypes[0].vector_begin(),
7045           Vec1End = CandidateTypes[0].vector_end();
7046         Vec1 != Vec1End; ++Vec1) {
7047      for (BuiltinCandidateTypeSet::iterator
7048                Vec2 = CandidateTypes[1].vector_begin(),
7049             Vec2End = CandidateTypes[1].vector_end();
7050           Vec2 != Vec2End; ++Vec2) {
7051        QualType LandR[2] = { *Vec1, *Vec2 };
7052        QualType Result = S.Context.BoolTy;
7053        if (!isComparison) {
7054          if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7055            Result = *Vec1;
7056          else
7057            Result = *Vec2;
7058        }
7059
7060        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7061      }
7062    }
7063  }
7064
7065  // C++ [over.built]p17:
7066  //
7067  //   For every pair of promoted integral types L and R, there
7068  //   exist candidate operator functions of the form
7069  //
7070  //      LR         operator%(L, R);
7071  //      LR         operator&(L, R);
7072  //      LR         operator^(L, R);
7073  //      LR         operator|(L, R);
7074  //      L          operator<<(L, R);
7075  //      L          operator>>(L, R);
7076  //
7077  //   where LR is the result of the usual arithmetic conversions
7078  //   between types L and R.
7079  void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7080    if (!HasArithmeticOrEnumeralCandidateType)
7081      return;
7082
7083    for (unsigned Left = FirstPromotedIntegralType;
7084         Left < LastPromotedIntegralType; ++Left) {
7085      for (unsigned Right = FirstPromotedIntegralType;
7086           Right < LastPromotedIntegralType; ++Right) {
7087        QualType LandR[2] = { getArithmeticType(Left),
7088                              getArithmeticType(Right) };
7089        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7090            ? LandR[0]
7091            : getUsualArithmeticConversions(Left, Right);
7092        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7093      }
7094    }
7095  }
7096
7097  // C++ [over.built]p20:
7098  //
7099  //   For every pair (T, VQ), where T is an enumeration or
7100  //   pointer to member type and VQ is either volatile or
7101  //   empty, there exist candidate operator functions of the form
7102  //
7103  //        VQ T&      operator=(VQ T&, T);
7104  void addAssignmentMemberPointerOrEnumeralOverloads() {
7105    /// Set of (canonical) types that we've already handled.
7106    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7107
7108    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7109      for (BuiltinCandidateTypeSet::iterator
7110                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7111             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7112           Enum != EnumEnd; ++Enum) {
7113        if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7114          continue;
7115
7116        AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7117                                               CandidateSet);
7118      }
7119
7120      for (BuiltinCandidateTypeSet::iterator
7121                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7122             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7123           MemPtr != MemPtrEnd; ++MemPtr) {
7124        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7125          continue;
7126
7127        AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7128                                               CandidateSet);
7129      }
7130    }
7131  }
7132
7133  // C++ [over.built]p19:
7134  //
7135  //   For every pair (T, VQ), where T is any type and VQ is either
7136  //   volatile or empty, there exist candidate operator functions
7137  //   of the form
7138  //
7139  //        T*VQ&      operator=(T*VQ&, T*);
7140  //
7141  // C++ [over.built]p21:
7142  //
7143  //   For every pair (T, VQ), where T is a cv-qualified or
7144  //   cv-unqualified object type and VQ is either volatile or
7145  //   empty, there exist candidate operator functions of the form
7146  //
7147  //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7148  //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7149  void addAssignmentPointerOverloads(bool isEqualOp) {
7150    /// Set of (canonical) types that we've already handled.
7151    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7152
7153    for (BuiltinCandidateTypeSet::iterator
7154              Ptr = CandidateTypes[0].pointer_begin(),
7155           PtrEnd = CandidateTypes[0].pointer_end();
7156         Ptr != PtrEnd; ++Ptr) {
7157      // If this is operator=, keep track of the builtin candidates we added.
7158      if (isEqualOp)
7159        AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7160      else if (!(*Ptr)->getPointeeType()->isObjectType())
7161        continue;
7162
7163      // non-volatile version
7164      QualType ParamTypes[2] = {
7165        S.Context.getLValueReferenceType(*Ptr),
7166        isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7167      };
7168      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7169                            /*IsAssigmentOperator=*/ isEqualOp);
7170
7171      bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7172                          VisibleTypeConversionsQuals.hasVolatile();
7173      if (NeedVolatile) {
7174        // volatile version
7175        ParamTypes[0] =
7176          S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7177        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7178                              /*IsAssigmentOperator=*/isEqualOp);
7179      }
7180
7181      if (!(*Ptr).isRestrictQualified() &&
7182          VisibleTypeConversionsQuals.hasRestrict()) {
7183        // restrict version
7184        ParamTypes[0]
7185          = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7186        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7187                              /*IsAssigmentOperator=*/isEqualOp);
7188
7189        if (NeedVolatile) {
7190          // volatile restrict version
7191          ParamTypes[0]
7192            = S.Context.getLValueReferenceType(
7193                S.Context.getCVRQualifiedType(*Ptr,
7194                                              (Qualifiers::Volatile |
7195                                               Qualifiers::Restrict)));
7196          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7197                                CandidateSet,
7198                                /*IsAssigmentOperator=*/isEqualOp);
7199        }
7200      }
7201    }
7202
7203    if (isEqualOp) {
7204      for (BuiltinCandidateTypeSet::iterator
7205                Ptr = CandidateTypes[1].pointer_begin(),
7206             PtrEnd = CandidateTypes[1].pointer_end();
7207           Ptr != PtrEnd; ++Ptr) {
7208        // Make sure we don't add the same candidate twice.
7209        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7210          continue;
7211
7212        QualType ParamTypes[2] = {
7213          S.Context.getLValueReferenceType(*Ptr),
7214          *Ptr,
7215        };
7216
7217        // non-volatile version
7218        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7219                              /*IsAssigmentOperator=*/true);
7220
7221        bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7222                           VisibleTypeConversionsQuals.hasVolatile();
7223        if (NeedVolatile) {
7224          // volatile version
7225          ParamTypes[0] =
7226            S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7227          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7228                                CandidateSet, /*IsAssigmentOperator=*/true);
7229        }
7230
7231        if (!(*Ptr).isRestrictQualified() &&
7232            VisibleTypeConversionsQuals.hasRestrict()) {
7233          // restrict version
7234          ParamTypes[0]
7235            = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7236          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7237                                CandidateSet, /*IsAssigmentOperator=*/true);
7238
7239          if (NeedVolatile) {
7240            // volatile restrict version
7241            ParamTypes[0]
7242              = S.Context.getLValueReferenceType(
7243                  S.Context.getCVRQualifiedType(*Ptr,
7244                                                (Qualifiers::Volatile |
7245                                                 Qualifiers::Restrict)));
7246            S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7247                                  CandidateSet, /*IsAssigmentOperator=*/true);
7248
7249          }
7250        }
7251      }
7252    }
7253  }
7254
7255  // C++ [over.built]p18:
7256  //
7257  //   For every triple (L, VQ, R), where L is an arithmetic type,
7258  //   VQ is either volatile or empty, and R is a promoted
7259  //   arithmetic type, there exist candidate operator functions of
7260  //   the form
7261  //
7262  //        VQ L&      operator=(VQ L&, R);
7263  //        VQ L&      operator*=(VQ L&, R);
7264  //        VQ L&      operator/=(VQ L&, R);
7265  //        VQ L&      operator+=(VQ L&, R);
7266  //        VQ L&      operator-=(VQ L&, R);
7267  void addAssignmentArithmeticOverloads(bool isEqualOp) {
7268    if (!HasArithmeticOrEnumeralCandidateType)
7269      return;
7270
7271    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7272      for (unsigned Right = FirstPromotedArithmeticType;
7273           Right < LastPromotedArithmeticType; ++Right) {
7274        QualType ParamTypes[2];
7275        ParamTypes[1] = getArithmeticType(Right);
7276
7277        // Add this built-in operator as a candidate (VQ is empty).
7278        ParamTypes[0] =
7279          S.Context.getLValueReferenceType(getArithmeticType(Left));
7280        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7281                              /*IsAssigmentOperator=*/isEqualOp);
7282
7283        // Add this built-in operator as a candidate (VQ is 'volatile').
7284        if (VisibleTypeConversionsQuals.hasVolatile()) {
7285          ParamTypes[0] =
7286            S.Context.getVolatileType(getArithmeticType(Left));
7287          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7288          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7289                                CandidateSet,
7290                                /*IsAssigmentOperator=*/isEqualOp);
7291        }
7292      }
7293    }
7294
7295    // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7296    for (BuiltinCandidateTypeSet::iterator
7297              Vec1 = CandidateTypes[0].vector_begin(),
7298           Vec1End = CandidateTypes[0].vector_end();
7299         Vec1 != Vec1End; ++Vec1) {
7300      for (BuiltinCandidateTypeSet::iterator
7301                Vec2 = CandidateTypes[1].vector_begin(),
7302             Vec2End = CandidateTypes[1].vector_end();
7303           Vec2 != Vec2End; ++Vec2) {
7304        QualType ParamTypes[2];
7305        ParamTypes[1] = *Vec2;
7306        // Add this built-in operator as a candidate (VQ is empty).
7307        ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7308        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7309                              /*IsAssigmentOperator=*/isEqualOp);
7310
7311        // Add this built-in operator as a candidate (VQ is 'volatile').
7312        if (VisibleTypeConversionsQuals.hasVolatile()) {
7313          ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7314          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7315          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7316                                CandidateSet,
7317                                /*IsAssigmentOperator=*/isEqualOp);
7318        }
7319      }
7320    }
7321  }
7322
7323  // C++ [over.built]p22:
7324  //
7325  //   For every triple (L, VQ, R), where L is an integral type, VQ
7326  //   is either volatile or empty, and R is a promoted integral
7327  //   type, there exist candidate operator functions of the form
7328  //
7329  //        VQ L&       operator%=(VQ L&, R);
7330  //        VQ L&       operator<<=(VQ L&, R);
7331  //        VQ L&       operator>>=(VQ L&, R);
7332  //        VQ L&       operator&=(VQ L&, R);
7333  //        VQ L&       operator^=(VQ L&, R);
7334  //        VQ L&       operator|=(VQ L&, R);
7335  void addAssignmentIntegralOverloads() {
7336    if (!HasArithmeticOrEnumeralCandidateType)
7337      return;
7338
7339    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7340      for (unsigned Right = FirstPromotedIntegralType;
7341           Right < LastPromotedIntegralType; ++Right) {
7342        QualType ParamTypes[2];
7343        ParamTypes[1] = getArithmeticType(Right);
7344
7345        // Add this built-in operator as a candidate (VQ is empty).
7346        ParamTypes[0] =
7347          S.Context.getLValueReferenceType(getArithmeticType(Left));
7348        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7349        if (VisibleTypeConversionsQuals.hasVolatile()) {
7350          // Add this built-in operator as a candidate (VQ is 'volatile').
7351          ParamTypes[0] = getArithmeticType(Left);
7352          ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7353          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7354          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7355                                CandidateSet);
7356        }
7357      }
7358    }
7359  }
7360
7361  // C++ [over.operator]p23:
7362  //
7363  //   There also exist candidate operator functions of the form
7364  //
7365  //        bool        operator!(bool);
7366  //        bool        operator&&(bool, bool);
7367  //        bool        operator||(bool, bool);
7368  void addExclaimOverload() {
7369    QualType ParamTy = S.Context.BoolTy;
7370    S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7371                          /*IsAssignmentOperator=*/false,
7372                          /*NumContextualBoolArguments=*/1);
7373  }
7374  void addAmpAmpOrPipePipeOverload() {
7375    QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7376    S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7377                          /*IsAssignmentOperator=*/false,
7378                          /*NumContextualBoolArguments=*/2);
7379  }
7380
7381  // C++ [over.built]p13:
7382  //
7383  //   For every cv-qualified or cv-unqualified object type T there
7384  //   exist candidate operator functions of the form
7385  //
7386  //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7387  //        T&         operator[](T*, ptrdiff_t);
7388  //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7389  //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7390  //        T&         operator[](ptrdiff_t, T*);
7391  void addSubscriptOverloads() {
7392    for (BuiltinCandidateTypeSet::iterator
7393              Ptr = CandidateTypes[0].pointer_begin(),
7394           PtrEnd = CandidateTypes[0].pointer_end();
7395         Ptr != PtrEnd; ++Ptr) {
7396      QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7397      QualType PointeeType = (*Ptr)->getPointeeType();
7398      if (!PointeeType->isObjectType())
7399        continue;
7400
7401      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7402
7403      // T& operator[](T*, ptrdiff_t)
7404      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7405    }
7406
7407    for (BuiltinCandidateTypeSet::iterator
7408              Ptr = CandidateTypes[1].pointer_begin(),
7409           PtrEnd = CandidateTypes[1].pointer_end();
7410         Ptr != PtrEnd; ++Ptr) {
7411      QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7412      QualType PointeeType = (*Ptr)->getPointeeType();
7413      if (!PointeeType->isObjectType())
7414        continue;
7415
7416      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7417
7418      // T& operator[](ptrdiff_t, T*)
7419      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7420    }
7421  }
7422
7423  // C++ [over.built]p11:
7424  //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7425  //    C1 is the same type as C2 or is a derived class of C2, T is an object
7426  //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7427  //    there exist candidate operator functions of the form
7428  //
7429  //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7430  //
7431  //    where CV12 is the union of CV1 and CV2.
7432  void addArrowStarOverloads() {
7433    for (BuiltinCandidateTypeSet::iterator
7434             Ptr = CandidateTypes[0].pointer_begin(),
7435           PtrEnd = CandidateTypes[0].pointer_end();
7436         Ptr != PtrEnd; ++Ptr) {
7437      QualType C1Ty = (*Ptr);
7438      QualType C1;
7439      QualifierCollector Q1;
7440      C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7441      if (!isa<RecordType>(C1))
7442        continue;
7443      // heuristic to reduce number of builtin candidates in the set.
7444      // Add volatile/restrict version only if there are conversions to a
7445      // volatile/restrict type.
7446      if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7447        continue;
7448      if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7449        continue;
7450      for (BuiltinCandidateTypeSet::iterator
7451                MemPtr = CandidateTypes[1].member_pointer_begin(),
7452             MemPtrEnd = CandidateTypes[1].member_pointer_end();
7453           MemPtr != MemPtrEnd; ++MemPtr) {
7454        const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7455        QualType C2 = QualType(mptr->getClass(), 0);
7456        C2 = C2.getUnqualifiedType();
7457        if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7458          break;
7459        QualType ParamTypes[2] = { *Ptr, *MemPtr };
7460        // build CV12 T&
7461        QualType T = mptr->getPointeeType();
7462        if (!VisibleTypeConversionsQuals.hasVolatile() &&
7463            T.isVolatileQualified())
7464          continue;
7465        if (!VisibleTypeConversionsQuals.hasRestrict() &&
7466            T.isRestrictQualified())
7467          continue;
7468        T = Q1.apply(S.Context, T);
7469        QualType ResultTy = S.Context.getLValueReferenceType(T);
7470        S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7471      }
7472    }
7473  }
7474
7475  // Note that we don't consider the first argument, since it has been
7476  // contextually converted to bool long ago. The candidates below are
7477  // therefore added as binary.
7478  //
7479  // C++ [over.built]p25:
7480  //   For every type T, where T is a pointer, pointer-to-member, or scoped
7481  //   enumeration type, there exist candidate operator functions of the form
7482  //
7483  //        T        operator?(bool, T, T);
7484  //
7485  void addConditionalOperatorOverloads() {
7486    /// Set of (canonical) types that we've already handled.
7487    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7488
7489    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7490      for (BuiltinCandidateTypeSet::iterator
7491                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7492             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7493           Ptr != PtrEnd; ++Ptr) {
7494        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7495          continue;
7496
7497        QualType ParamTypes[2] = { *Ptr, *Ptr };
7498        S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7499      }
7500
7501      for (BuiltinCandidateTypeSet::iterator
7502                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7503             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7504           MemPtr != MemPtrEnd; ++MemPtr) {
7505        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7506          continue;
7507
7508        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7509        S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7510      }
7511
7512      if (S.getLangOpts().CPlusPlus11) {
7513        for (BuiltinCandidateTypeSet::iterator
7514                  Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7515               EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7516             Enum != EnumEnd; ++Enum) {
7517          if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7518            continue;
7519
7520          if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7521            continue;
7522
7523          QualType ParamTypes[2] = { *Enum, *Enum };
7524          S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7525        }
7526      }
7527    }
7528  }
7529};
7530
7531} // end anonymous namespace
7532
7533/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7534/// operator overloads to the candidate set (C++ [over.built]), based
7535/// on the operator @p Op and the arguments given. For example, if the
7536/// operator is a binary '+', this routine might add "int
7537/// operator+(int, int)" to cover integer addition.
7538void
7539Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7540                                   SourceLocation OpLoc,
7541                                   Expr **Args, unsigned NumArgs,
7542                                   OverloadCandidateSet& CandidateSet) {
7543  // Find all of the types that the arguments can convert to, but only
7544  // if the operator we're looking at has built-in operator candidates
7545  // that make use of these types. Also record whether we encounter non-record
7546  // candidate types or either arithmetic or enumeral candidate types.
7547  Qualifiers VisibleTypeConversionsQuals;
7548  VisibleTypeConversionsQuals.addConst();
7549  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7550    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7551
7552  bool HasNonRecordCandidateType = false;
7553  bool HasArithmeticOrEnumeralCandidateType = false;
7554  SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7555  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7556    CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7557    CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7558                                                 OpLoc,
7559                                                 true,
7560                                                 (Op == OO_Exclaim ||
7561                                                  Op == OO_AmpAmp ||
7562                                                  Op == OO_PipePipe),
7563                                                 VisibleTypeConversionsQuals);
7564    HasNonRecordCandidateType = HasNonRecordCandidateType ||
7565        CandidateTypes[ArgIdx].hasNonRecordTypes();
7566    HasArithmeticOrEnumeralCandidateType =
7567        HasArithmeticOrEnumeralCandidateType ||
7568        CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7569  }
7570
7571  // Exit early when no non-record types have been added to the candidate set
7572  // for any of the arguments to the operator.
7573  //
7574  // We can't exit early for !, ||, or &&, since there we have always have
7575  // 'bool' overloads.
7576  if (!HasNonRecordCandidateType &&
7577      !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7578    return;
7579
7580  // Setup an object to manage the common state for building overloads.
7581  BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7582                                           VisibleTypeConversionsQuals,
7583                                           HasArithmeticOrEnumeralCandidateType,
7584                                           CandidateTypes, CandidateSet);
7585
7586  // Dispatch over the operation to add in only those overloads which apply.
7587  switch (Op) {
7588  case OO_None:
7589  case NUM_OVERLOADED_OPERATORS:
7590    llvm_unreachable("Expected an overloaded operator");
7591
7592  case OO_New:
7593  case OO_Delete:
7594  case OO_Array_New:
7595  case OO_Array_Delete:
7596  case OO_Call:
7597    llvm_unreachable(
7598                    "Special operators don't use AddBuiltinOperatorCandidates");
7599
7600  case OO_Comma:
7601  case OO_Arrow:
7602    // C++ [over.match.oper]p3:
7603    //   -- For the operator ',', the unary operator '&', or the
7604    //      operator '->', the built-in candidates set is empty.
7605    break;
7606
7607  case OO_Plus: // '+' is either unary or binary
7608    if (NumArgs == 1)
7609      OpBuilder.addUnaryPlusPointerOverloads();
7610    // Fall through.
7611
7612  case OO_Minus: // '-' is either unary or binary
7613    if (NumArgs == 1) {
7614      OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7615    } else {
7616      OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7617      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7618    }
7619    break;
7620
7621  case OO_Star: // '*' is either unary or binary
7622    if (NumArgs == 1)
7623      OpBuilder.addUnaryStarPointerOverloads();
7624    else
7625      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7626    break;
7627
7628  case OO_Slash:
7629    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7630    break;
7631
7632  case OO_PlusPlus:
7633  case OO_MinusMinus:
7634    OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7635    OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7636    break;
7637
7638  case OO_EqualEqual:
7639  case OO_ExclaimEqual:
7640    OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7641    // Fall through.
7642
7643  case OO_Less:
7644  case OO_Greater:
7645  case OO_LessEqual:
7646  case OO_GreaterEqual:
7647    OpBuilder.addRelationalPointerOrEnumeralOverloads();
7648    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7649    break;
7650
7651  case OO_Percent:
7652  case OO_Caret:
7653  case OO_Pipe:
7654  case OO_LessLess:
7655  case OO_GreaterGreater:
7656    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7657    break;
7658
7659  case OO_Amp: // '&' is either unary or binary
7660    if (NumArgs == 1)
7661      // C++ [over.match.oper]p3:
7662      //   -- For the operator ',', the unary operator '&', or the
7663      //      operator '->', the built-in candidates set is empty.
7664      break;
7665
7666    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7667    break;
7668
7669  case OO_Tilde:
7670    OpBuilder.addUnaryTildePromotedIntegralOverloads();
7671    break;
7672
7673  case OO_Equal:
7674    OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7675    // Fall through.
7676
7677  case OO_PlusEqual:
7678  case OO_MinusEqual:
7679    OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7680    // Fall through.
7681
7682  case OO_StarEqual:
7683  case OO_SlashEqual:
7684    OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7685    break;
7686
7687  case OO_PercentEqual:
7688  case OO_LessLessEqual:
7689  case OO_GreaterGreaterEqual:
7690  case OO_AmpEqual:
7691  case OO_CaretEqual:
7692  case OO_PipeEqual:
7693    OpBuilder.addAssignmentIntegralOverloads();
7694    break;
7695
7696  case OO_Exclaim:
7697    OpBuilder.addExclaimOverload();
7698    break;
7699
7700  case OO_AmpAmp:
7701  case OO_PipePipe:
7702    OpBuilder.addAmpAmpOrPipePipeOverload();
7703    break;
7704
7705  case OO_Subscript:
7706    OpBuilder.addSubscriptOverloads();
7707    break;
7708
7709  case OO_ArrowStar:
7710    OpBuilder.addArrowStarOverloads();
7711    break;
7712
7713  case OO_Conditional:
7714    OpBuilder.addConditionalOperatorOverloads();
7715    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7716    break;
7717  }
7718}
7719
7720/// \brief Add function candidates found via argument-dependent lookup
7721/// to the set of overloading candidates.
7722///
7723/// This routine performs argument-dependent name lookup based on the
7724/// given function name (which may also be an operator name) and adds
7725/// all of the overload candidates found by ADL to the overload
7726/// candidate set (C++ [basic.lookup.argdep]).
7727void
7728Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7729                                           bool Operator, SourceLocation Loc,
7730                                           ArrayRef<Expr *> Args,
7731                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
7732                                           OverloadCandidateSet& CandidateSet,
7733                                           bool PartialOverloading) {
7734  ADLResult Fns;
7735
7736  // FIXME: This approach for uniquing ADL results (and removing
7737  // redundant candidates from the set) relies on pointer-equality,
7738  // which means we need to key off the canonical decl.  However,
7739  // always going back to the canonical decl might not get us the
7740  // right set of default arguments.  What default arguments are
7741  // we supposed to consider on ADL candidates, anyway?
7742
7743  // FIXME: Pass in the explicit template arguments?
7744  ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
7745
7746  // Erase all of the candidates we already knew about.
7747  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7748                                   CandEnd = CandidateSet.end();
7749       Cand != CandEnd; ++Cand)
7750    if (Cand->Function) {
7751      Fns.erase(Cand->Function);
7752      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7753        Fns.erase(FunTmpl);
7754    }
7755
7756  // For each of the ADL candidates we found, add it to the overload
7757  // set.
7758  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7759    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7760    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7761      if (ExplicitTemplateArgs)
7762        continue;
7763
7764      AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7765                           PartialOverloading);
7766    } else
7767      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7768                                   FoundDecl, ExplicitTemplateArgs,
7769                                   Args, CandidateSet);
7770  }
7771}
7772
7773/// isBetterOverloadCandidate - Determines whether the first overload
7774/// candidate is a better candidate than the second (C++ 13.3.3p1).
7775bool
7776isBetterOverloadCandidate(Sema &S,
7777                          const OverloadCandidate &Cand1,
7778                          const OverloadCandidate &Cand2,
7779                          SourceLocation Loc,
7780                          bool UserDefinedConversion) {
7781  // Define viable functions to be better candidates than non-viable
7782  // functions.
7783  if (!Cand2.Viable)
7784    return Cand1.Viable;
7785  else if (!Cand1.Viable)
7786    return false;
7787
7788  // C++ [over.match.best]p1:
7789  //
7790  //   -- if F is a static member function, ICS1(F) is defined such
7791  //      that ICS1(F) is neither better nor worse than ICS1(G) for
7792  //      any function G, and, symmetrically, ICS1(G) is neither
7793  //      better nor worse than ICS1(F).
7794  unsigned StartArg = 0;
7795  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7796    StartArg = 1;
7797
7798  // C++ [over.match.best]p1:
7799  //   A viable function F1 is defined to be a better function than another
7800  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
7801  //   conversion sequence than ICSi(F2), and then...
7802  unsigned NumArgs = Cand1.NumConversions;
7803  assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7804  bool HasBetterConversion = false;
7805  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7806    switch (CompareImplicitConversionSequences(S,
7807                                               Cand1.Conversions[ArgIdx],
7808                                               Cand2.Conversions[ArgIdx])) {
7809    case ImplicitConversionSequence::Better:
7810      // Cand1 has a better conversion sequence.
7811      HasBetterConversion = true;
7812      break;
7813
7814    case ImplicitConversionSequence::Worse:
7815      // Cand1 can't be better than Cand2.
7816      return false;
7817
7818    case ImplicitConversionSequence::Indistinguishable:
7819      // Do nothing.
7820      break;
7821    }
7822  }
7823
7824  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
7825  //       ICSj(F2), or, if not that,
7826  if (HasBetterConversion)
7827    return true;
7828
7829  //     - F1 is a non-template function and F2 is a function template
7830  //       specialization, or, if not that,
7831  if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
7832      Cand2.Function && Cand2.Function->getPrimaryTemplate())
7833    return true;
7834
7835  //   -- F1 and F2 are function template specializations, and the function
7836  //      template for F1 is more specialized than the template for F2
7837  //      according to the partial ordering rules described in 14.5.5.2, or,
7838  //      if not that,
7839  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
7840      Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
7841    if (FunctionTemplateDecl *BetterTemplate
7842          = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7843                                         Cand2.Function->getPrimaryTemplate(),
7844                                         Loc,
7845                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
7846                                                             : TPOC_Call,
7847                                         Cand1.ExplicitCallArguments))
7848      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
7849  }
7850
7851  //   -- the context is an initialization by user-defined conversion
7852  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
7853  //      from the return type of F1 to the destination type (i.e.,
7854  //      the type of the entity being initialized) is a better
7855  //      conversion sequence than the standard conversion sequence
7856  //      from the return type of F2 to the destination type.
7857  if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
7858      isa<CXXConversionDecl>(Cand1.Function) &&
7859      isa<CXXConversionDecl>(Cand2.Function)) {
7860    // First check whether we prefer one of the conversion functions over the
7861    // other. This only distinguishes the results in non-standard, extension
7862    // cases such as the conversion from a lambda closure type to a function
7863    // pointer or block.
7864    ImplicitConversionSequence::CompareKind FuncResult
7865      = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7866    if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7867      return FuncResult;
7868
7869    switch (CompareStandardConversionSequences(S,
7870                                               Cand1.FinalConversion,
7871                                               Cand2.FinalConversion)) {
7872    case ImplicitConversionSequence::Better:
7873      // Cand1 has a better conversion sequence.
7874      return true;
7875
7876    case ImplicitConversionSequence::Worse:
7877      // Cand1 can't be better than Cand2.
7878      return false;
7879
7880    case ImplicitConversionSequence::Indistinguishable:
7881      // Do nothing
7882      break;
7883    }
7884  }
7885
7886  return false;
7887}
7888
7889/// \brief Computes the best viable function (C++ 13.3.3)
7890/// within an overload candidate set.
7891///
7892/// \param Loc The location of the function name (or operator symbol) for
7893/// which overload resolution occurs.
7894///
7895/// \param Best If overload resolution was successful or found a deleted
7896/// function, \p Best points to the candidate function found.
7897///
7898/// \returns The result of overload resolution.
7899OverloadingResult
7900OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
7901                                         iterator &Best,
7902                                         bool UserDefinedConversion) {
7903  // Find the best viable function.
7904  Best = end();
7905  for (iterator Cand = begin(); Cand != end(); ++Cand) {
7906    if (Cand->Viable)
7907      if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
7908                                                     UserDefinedConversion))
7909        Best = Cand;
7910  }
7911
7912  // If we didn't find any viable functions, abort.
7913  if (Best == end())
7914    return OR_No_Viable_Function;
7915
7916  // Make sure that this function is better than every other viable
7917  // function. If not, we have an ambiguity.
7918  for (iterator Cand = begin(); Cand != end(); ++Cand) {
7919    if (Cand->Viable &&
7920        Cand != Best &&
7921        !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
7922                                   UserDefinedConversion)) {
7923      Best = end();
7924      return OR_Ambiguous;
7925    }
7926  }
7927
7928  // Best is the best viable function.
7929  if (Best->Function &&
7930      (Best->Function->isDeleted() ||
7931       S.isFunctionConsideredUnavailable(Best->Function)))
7932    return OR_Deleted;
7933
7934  return OR_Success;
7935}
7936
7937namespace {
7938
7939enum OverloadCandidateKind {
7940  oc_function,
7941  oc_method,
7942  oc_constructor,
7943  oc_function_template,
7944  oc_method_template,
7945  oc_constructor_template,
7946  oc_implicit_default_constructor,
7947  oc_implicit_copy_constructor,
7948  oc_implicit_move_constructor,
7949  oc_implicit_copy_assignment,
7950  oc_implicit_move_assignment,
7951  oc_implicit_inherited_constructor
7952};
7953
7954OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7955                                                FunctionDecl *Fn,
7956                                                std::string &Description) {
7957  bool isTemplate = false;
7958
7959  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7960    isTemplate = true;
7961    Description = S.getTemplateArgumentBindingsText(
7962      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7963  }
7964
7965  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
7966    if (!Ctor->isImplicit())
7967      return isTemplate ? oc_constructor_template : oc_constructor;
7968
7969    if (Ctor->getInheritedConstructor())
7970      return oc_implicit_inherited_constructor;
7971
7972    if (Ctor->isDefaultConstructor())
7973      return oc_implicit_default_constructor;
7974
7975    if (Ctor->isMoveConstructor())
7976      return oc_implicit_move_constructor;
7977
7978    assert(Ctor->isCopyConstructor() &&
7979           "unexpected sort of implicit constructor");
7980    return oc_implicit_copy_constructor;
7981  }
7982
7983  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7984    // This actually gets spelled 'candidate function' for now, but
7985    // it doesn't hurt to split it out.
7986    if (!Meth->isImplicit())
7987      return isTemplate ? oc_method_template : oc_method;
7988
7989    if (Meth->isMoveAssignmentOperator())
7990      return oc_implicit_move_assignment;
7991
7992    if (Meth->isCopyAssignmentOperator())
7993      return oc_implicit_copy_assignment;
7994
7995    assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7996    return oc_method;
7997  }
7998
7999  return isTemplate ? oc_function_template : oc_function;
8000}
8001
8002void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
8003  const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8004  if (!Ctor) return;
8005
8006  Ctor = Ctor->getInheritedConstructor();
8007  if (!Ctor) return;
8008
8009  S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8010}
8011
8012} // end anonymous namespace
8013
8014// Notes the location of an overload candidate.
8015void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8016  std::string FnDesc;
8017  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8018  PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8019                             << (unsigned) K << FnDesc;
8020  HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8021  Diag(Fn->getLocation(), PD);
8022  MaybeEmitInheritedConstructorNote(*this, Fn);
8023}
8024
8025//Notes the location of all overload candidates designated through
8026// OverloadedExpr
8027void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8028  assert(OverloadedExpr->getType() == Context.OverloadTy);
8029
8030  OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8031  OverloadExpr *OvlExpr = Ovl.Expression;
8032
8033  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8034                            IEnd = OvlExpr->decls_end();
8035       I != IEnd; ++I) {
8036    if (FunctionTemplateDecl *FunTmpl =
8037                dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8038      NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8039    } else if (FunctionDecl *Fun
8040                      = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8041      NoteOverloadCandidate(Fun, DestType);
8042    }
8043  }
8044}
8045
8046/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8047/// "lead" diagnostic; it will be given two arguments, the source and
8048/// target types of the conversion.
8049void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8050                                 Sema &S,
8051                                 SourceLocation CaretLoc,
8052                                 const PartialDiagnostic &PDiag) const {
8053  S.Diag(CaretLoc, PDiag)
8054    << Ambiguous.getFromType() << Ambiguous.getToType();
8055  // FIXME: The note limiting machinery is borrowed from
8056  // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8057  // refactoring here.
8058  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8059  unsigned CandsShown = 0;
8060  AmbiguousConversionSequence::const_iterator I, E;
8061  for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8062    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8063      break;
8064    ++CandsShown;
8065    S.NoteOverloadCandidate(*I);
8066  }
8067  if (I != E)
8068    S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8069}
8070
8071namespace {
8072
8073void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8074  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8075  assert(Conv.isBad());
8076  assert(Cand->Function && "for now, candidate must be a function");
8077  FunctionDecl *Fn = Cand->Function;
8078
8079  // There's a conversion slot for the object argument if this is a
8080  // non-constructor method.  Note that 'I' corresponds the
8081  // conversion-slot index.
8082  bool isObjectArgument = false;
8083  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8084    if (I == 0)
8085      isObjectArgument = true;
8086    else
8087      I--;
8088  }
8089
8090  std::string FnDesc;
8091  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8092
8093  Expr *FromExpr = Conv.Bad.FromExpr;
8094  QualType FromTy = Conv.Bad.getFromType();
8095  QualType ToTy = Conv.Bad.getToType();
8096
8097  if (FromTy == S.Context.OverloadTy) {
8098    assert(FromExpr && "overload set argument came from implicit argument?");
8099    Expr *E = FromExpr->IgnoreParens();
8100    if (isa<UnaryOperator>(E))
8101      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8102    DeclarationName Name = cast<OverloadExpr>(E)->getName();
8103
8104    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8105      << (unsigned) FnKind << FnDesc
8106      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8107      << ToTy << Name << I+1;
8108    MaybeEmitInheritedConstructorNote(S, Fn);
8109    return;
8110  }
8111
8112  // Do some hand-waving analysis to see if the non-viability is due
8113  // to a qualifier mismatch.
8114  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8115  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8116  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8117    CToTy = RT->getPointeeType();
8118  else {
8119    // TODO: detect and diagnose the full richness of const mismatches.
8120    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8121      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8122        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8123  }
8124
8125  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8126      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8127    Qualifiers FromQs = CFromTy.getQualifiers();
8128    Qualifiers ToQs = CToTy.getQualifiers();
8129
8130    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8131      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8132        << (unsigned) FnKind << FnDesc
8133        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8134        << FromTy
8135        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8136        << (unsigned) isObjectArgument << I+1;
8137      MaybeEmitInheritedConstructorNote(S, Fn);
8138      return;
8139    }
8140
8141    if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8142      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8143        << (unsigned) FnKind << FnDesc
8144        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8145        << FromTy
8146        << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8147        << (unsigned) isObjectArgument << I+1;
8148      MaybeEmitInheritedConstructorNote(S, Fn);
8149      return;
8150    }
8151
8152    if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8153      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8154      << (unsigned) FnKind << FnDesc
8155      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8156      << FromTy
8157      << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8158      << (unsigned) isObjectArgument << I+1;
8159      MaybeEmitInheritedConstructorNote(S, Fn);
8160      return;
8161    }
8162
8163    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8164    assert(CVR && "unexpected qualifiers mismatch");
8165
8166    if (isObjectArgument) {
8167      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8168        << (unsigned) FnKind << FnDesc
8169        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8170        << FromTy << (CVR - 1);
8171    } else {
8172      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8173        << (unsigned) FnKind << FnDesc
8174        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8175        << FromTy << (CVR - 1) << I+1;
8176    }
8177    MaybeEmitInheritedConstructorNote(S, Fn);
8178    return;
8179  }
8180
8181  // Special diagnostic for failure to convert an initializer list, since
8182  // telling the user that it has type void is not useful.
8183  if (FromExpr && isa<InitListExpr>(FromExpr)) {
8184    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8185      << (unsigned) FnKind << FnDesc
8186      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8187      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8188    MaybeEmitInheritedConstructorNote(S, Fn);
8189    return;
8190  }
8191
8192  // Diagnose references or pointers to incomplete types differently,
8193  // since it's far from impossible that the incompleteness triggered
8194  // the failure.
8195  QualType TempFromTy = FromTy.getNonReferenceType();
8196  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8197    TempFromTy = PTy->getPointeeType();
8198  if (TempFromTy->isIncompleteType()) {
8199    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8200      << (unsigned) FnKind << FnDesc
8201      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8202      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8203    MaybeEmitInheritedConstructorNote(S, Fn);
8204    return;
8205  }
8206
8207  // Diagnose base -> derived pointer conversions.
8208  unsigned BaseToDerivedConversion = 0;
8209  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8210    if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8211      if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8212                                               FromPtrTy->getPointeeType()) &&
8213          !FromPtrTy->getPointeeType()->isIncompleteType() &&
8214          !ToPtrTy->getPointeeType()->isIncompleteType() &&
8215          S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8216                          FromPtrTy->getPointeeType()))
8217        BaseToDerivedConversion = 1;
8218    }
8219  } else if (const ObjCObjectPointerType *FromPtrTy
8220                                    = FromTy->getAs<ObjCObjectPointerType>()) {
8221    if (const ObjCObjectPointerType *ToPtrTy
8222                                        = ToTy->getAs<ObjCObjectPointerType>())
8223      if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8224        if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8225          if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8226                                                FromPtrTy->getPointeeType()) &&
8227              FromIface->isSuperClassOf(ToIface))
8228            BaseToDerivedConversion = 2;
8229  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8230    if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8231        !FromTy->isIncompleteType() &&
8232        !ToRefTy->getPointeeType()->isIncompleteType() &&
8233        S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8234      BaseToDerivedConversion = 3;
8235    } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8236               ToTy.getNonReferenceType().getCanonicalType() ==
8237               FromTy.getNonReferenceType().getCanonicalType()) {
8238      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8239        << (unsigned) FnKind << FnDesc
8240        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8241        << (unsigned) isObjectArgument << I + 1;
8242      MaybeEmitInheritedConstructorNote(S, Fn);
8243      return;
8244    }
8245  }
8246
8247  if (BaseToDerivedConversion) {
8248    S.Diag(Fn->getLocation(),
8249           diag::note_ovl_candidate_bad_base_to_derived_conv)
8250      << (unsigned) FnKind << FnDesc
8251      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8252      << (BaseToDerivedConversion - 1)
8253      << FromTy << ToTy << I+1;
8254    MaybeEmitInheritedConstructorNote(S, Fn);
8255    return;
8256  }
8257
8258  if (isa<ObjCObjectPointerType>(CFromTy) &&
8259      isa<PointerType>(CToTy)) {
8260      Qualifiers FromQs = CFromTy.getQualifiers();
8261      Qualifiers ToQs = CToTy.getQualifiers();
8262      if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8263        S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8264        << (unsigned) FnKind << FnDesc
8265        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8266        << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8267        MaybeEmitInheritedConstructorNote(S, Fn);
8268        return;
8269      }
8270  }
8271
8272  // Emit the generic diagnostic and, optionally, add the hints to it.
8273  PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8274  FDiag << (unsigned) FnKind << FnDesc
8275    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8276    << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8277    << (unsigned) (Cand->Fix.Kind);
8278
8279  // If we can fix the conversion, suggest the FixIts.
8280  for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8281       HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8282    FDiag << *HI;
8283  S.Diag(Fn->getLocation(), FDiag);
8284
8285  MaybeEmitInheritedConstructorNote(S, Fn);
8286}
8287
8288void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8289                           unsigned NumFormalArgs) {
8290  // TODO: treat calls to a missing default constructor as a special case
8291
8292  FunctionDecl *Fn = Cand->Function;
8293  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8294
8295  unsigned MinParams = Fn->getMinRequiredArguments();
8296
8297  // With invalid overloaded operators, it's possible that we think we
8298  // have an arity mismatch when it fact it looks like we have the
8299  // right number of arguments, because only overloaded operators have
8300  // the weird behavior of overloading member and non-member functions.
8301  // Just don't report anything.
8302  if (Fn->isInvalidDecl() &&
8303      Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8304    return;
8305
8306  // at least / at most / exactly
8307  unsigned mode, modeCount;
8308  if (NumFormalArgs < MinParams) {
8309    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8310           (Cand->FailureKind == ovl_fail_bad_deduction &&
8311            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8312    if (MinParams != FnTy->getNumArgs() ||
8313        FnTy->isVariadic() || FnTy->isTemplateVariadic())
8314      mode = 0; // "at least"
8315    else
8316      mode = 2; // "exactly"
8317    modeCount = MinParams;
8318  } else {
8319    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8320           (Cand->FailureKind == ovl_fail_bad_deduction &&
8321            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8322    if (MinParams != FnTy->getNumArgs())
8323      mode = 1; // "at most"
8324    else
8325      mode = 2; // "exactly"
8326    modeCount = FnTy->getNumArgs();
8327  }
8328
8329  std::string Description;
8330  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8331
8332  if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8333    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8334      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8335      << Fn->getParamDecl(0) << NumFormalArgs;
8336  else
8337    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8338      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8339      << modeCount << NumFormalArgs;
8340  MaybeEmitInheritedConstructorNote(S, Fn);
8341}
8342
8343/// Diagnose a failed template-argument deduction.
8344void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
8345                          unsigned NumArgs) {
8346  FunctionDecl *Fn = Cand->Function; // pattern
8347
8348  TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
8349  NamedDecl *ParamD;
8350  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8351  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8352  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8353  switch (Cand->DeductionFailure.Result) {
8354  case Sema::TDK_Success:
8355    llvm_unreachable("TDK_success while diagnosing bad deduction");
8356
8357  case Sema::TDK_Incomplete: {
8358    assert(ParamD && "no parameter found for incomplete deduction result");
8359    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8360      << ParamD->getDeclName();
8361    MaybeEmitInheritedConstructorNote(S, Fn);
8362    return;
8363  }
8364
8365  case Sema::TDK_Underqualified: {
8366    assert(ParamD && "no parameter found for bad qualifiers deduction result");
8367    TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8368
8369    QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8370
8371    // Param will have been canonicalized, but it should just be a
8372    // qualified version of ParamD, so move the qualifiers to that.
8373    QualifierCollector Qs;
8374    Qs.strip(Param);
8375    QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8376    assert(S.Context.hasSameType(Param, NonCanonParam));
8377
8378    // Arg has also been canonicalized, but there's nothing we can do
8379    // about that.  It also doesn't matter as much, because it won't
8380    // have any template parameters in it (because deduction isn't
8381    // done on dependent types).
8382    QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8383
8384    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8385      << ParamD->getDeclName() << Arg << NonCanonParam;
8386    MaybeEmitInheritedConstructorNote(S, Fn);
8387    return;
8388  }
8389
8390  case Sema::TDK_Inconsistent: {
8391    assert(ParamD && "no parameter found for inconsistent deduction result");
8392    int which = 0;
8393    if (isa<TemplateTypeParmDecl>(ParamD))
8394      which = 0;
8395    else if (isa<NonTypeTemplateParmDecl>(ParamD))
8396      which = 1;
8397    else {
8398      which = 2;
8399    }
8400
8401    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
8402      << which << ParamD->getDeclName()
8403      << *Cand->DeductionFailure.getFirstArg()
8404      << *Cand->DeductionFailure.getSecondArg();
8405    MaybeEmitInheritedConstructorNote(S, Fn);
8406    return;
8407  }
8408
8409  case Sema::TDK_InvalidExplicitArguments:
8410    assert(ParamD && "no parameter found for invalid explicit arguments");
8411    if (ParamD->getDeclName())
8412      S.Diag(Fn->getLocation(),
8413             diag::note_ovl_candidate_explicit_arg_mismatch_named)
8414        << ParamD->getDeclName();
8415    else {
8416      int index = 0;
8417      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8418        index = TTP->getIndex();
8419      else if (NonTypeTemplateParmDecl *NTTP
8420                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8421        index = NTTP->getIndex();
8422      else
8423        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8424      S.Diag(Fn->getLocation(),
8425             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8426        << (index + 1);
8427    }
8428    MaybeEmitInheritedConstructorNote(S, Fn);
8429    return;
8430
8431  case Sema::TDK_TooManyArguments:
8432  case Sema::TDK_TooFewArguments:
8433    DiagnoseArityMismatch(S, Cand, NumArgs);
8434    return;
8435
8436  case Sema::TDK_InstantiationDepth:
8437    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
8438    MaybeEmitInheritedConstructorNote(S, Fn);
8439    return;
8440
8441  case Sema::TDK_SubstitutionFailure: {
8442    // Format the template argument list into the argument string.
8443    SmallString<128> TemplateArgString;
8444    if (TemplateArgumentList *Args =
8445          Cand->DeductionFailure.getTemplateArgumentList()) {
8446      TemplateArgString = " ";
8447      TemplateArgString += S.getTemplateArgumentBindingsText(
8448          Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8449    }
8450
8451    // If this candidate was disabled by enable_if, say so.
8452    PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8453    if (PDiag && PDiag->second.getDiagID() ==
8454          diag::err_typename_nested_not_found_enable_if) {
8455      // FIXME: Use the source range of the condition, and the fully-qualified
8456      //        name of the enable_if template. These are both present in PDiag.
8457      S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8458        << "'enable_if'" << TemplateArgString;
8459      return;
8460    }
8461
8462    // Format the SFINAE diagnostic into the argument string.
8463    // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8464    //        formatted message in another diagnostic.
8465    SmallString<128> SFINAEArgString;
8466    SourceRange R;
8467    if (PDiag) {
8468      SFINAEArgString = ": ";
8469      R = SourceRange(PDiag->first, PDiag->first);
8470      PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8471    }
8472
8473    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8474      << TemplateArgString << SFINAEArgString << R;
8475    MaybeEmitInheritedConstructorNote(S, Fn);
8476    return;
8477  }
8478
8479  case Sema::TDK_FailedOverloadResolution: {
8480    OverloadExpr::FindResult R =
8481        OverloadExpr::find(Cand->DeductionFailure.getExpr());
8482    S.Diag(Fn->getLocation(),
8483           diag::note_ovl_candidate_failed_overload_resolution)
8484      << R.Expression->getName();
8485    return;
8486  }
8487
8488  case Sema::TDK_NonDeducedMismatch:
8489    // FIXME: Provide a source location to indicate what we couldn't match.
8490    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
8491      << *Cand->DeductionFailure.getFirstArg()
8492      << *Cand->DeductionFailure.getSecondArg();
8493    return;
8494
8495  // TODO: diagnose these individually, then kill off
8496  // note_ovl_candidate_bad_deduction, which is uselessly vague.
8497  case Sema::TDK_MiscellaneousDeductionFailure:
8498    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
8499    MaybeEmitInheritedConstructorNote(S, Fn);
8500    return;
8501  }
8502}
8503
8504/// CUDA: diagnose an invalid call across targets.
8505void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8506  FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8507  FunctionDecl *Callee = Cand->Function;
8508
8509  Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8510                           CalleeTarget = S.IdentifyCUDATarget(Callee);
8511
8512  std::string FnDesc;
8513  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8514
8515  S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8516      << (unsigned) FnKind << CalleeTarget << CallerTarget;
8517}
8518
8519/// Generates a 'note' diagnostic for an overload candidate.  We've
8520/// already generated a primary error at the call site.
8521///
8522/// It really does need to be a single diagnostic with its caret
8523/// pointed at the candidate declaration.  Yes, this creates some
8524/// major challenges of technical writing.  Yes, this makes pointing
8525/// out problems with specific arguments quite awkward.  It's still
8526/// better than generating twenty screens of text for every failed
8527/// overload.
8528///
8529/// It would be great to be able to express per-candidate problems
8530/// more richly for those diagnostic clients that cared, but we'd
8531/// still have to be just as careful with the default diagnostics.
8532void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8533                           unsigned NumArgs) {
8534  FunctionDecl *Fn = Cand->Function;
8535
8536  // Note deleted candidates, but only if they're viable.
8537  if (Cand->Viable && (Fn->isDeleted() ||
8538      S.isFunctionConsideredUnavailable(Fn))) {
8539    std::string FnDesc;
8540    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8541
8542    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8543      << FnKind << FnDesc
8544      << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8545    MaybeEmitInheritedConstructorNote(S, Fn);
8546    return;
8547  }
8548
8549  // We don't really have anything else to say about viable candidates.
8550  if (Cand->Viable) {
8551    S.NoteOverloadCandidate(Fn);
8552    return;
8553  }
8554
8555  switch (Cand->FailureKind) {
8556  case ovl_fail_too_many_arguments:
8557  case ovl_fail_too_few_arguments:
8558    return DiagnoseArityMismatch(S, Cand, NumArgs);
8559
8560  case ovl_fail_bad_deduction:
8561    return DiagnoseBadDeduction(S, Cand, NumArgs);
8562
8563  case ovl_fail_trivial_conversion:
8564  case ovl_fail_bad_final_conversion:
8565  case ovl_fail_final_conversion_not_exact:
8566    return S.NoteOverloadCandidate(Fn);
8567
8568  case ovl_fail_bad_conversion: {
8569    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8570    for (unsigned N = Cand->NumConversions; I != N; ++I)
8571      if (Cand->Conversions[I].isBad())
8572        return DiagnoseBadConversion(S, Cand, I);
8573
8574    // FIXME: this currently happens when we're called from SemaInit
8575    // when user-conversion overload fails.  Figure out how to handle
8576    // those conditions and diagnose them well.
8577    return S.NoteOverloadCandidate(Fn);
8578  }
8579
8580  case ovl_fail_bad_target:
8581    return DiagnoseBadTarget(S, Cand);
8582  }
8583}
8584
8585void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8586  // Desugar the type of the surrogate down to a function type,
8587  // retaining as many typedefs as possible while still showing
8588  // the function type (and, therefore, its parameter types).
8589  QualType FnType = Cand->Surrogate->getConversionType();
8590  bool isLValueReference = false;
8591  bool isRValueReference = false;
8592  bool isPointer = false;
8593  if (const LValueReferenceType *FnTypeRef =
8594        FnType->getAs<LValueReferenceType>()) {
8595    FnType = FnTypeRef->getPointeeType();
8596    isLValueReference = true;
8597  } else if (const RValueReferenceType *FnTypeRef =
8598               FnType->getAs<RValueReferenceType>()) {
8599    FnType = FnTypeRef->getPointeeType();
8600    isRValueReference = true;
8601  }
8602  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8603    FnType = FnTypePtr->getPointeeType();
8604    isPointer = true;
8605  }
8606  // Desugar down to a function type.
8607  FnType = QualType(FnType->getAs<FunctionType>(), 0);
8608  // Reconstruct the pointer/reference as appropriate.
8609  if (isPointer) FnType = S.Context.getPointerType(FnType);
8610  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8611  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8612
8613  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8614    << FnType;
8615  MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8616}
8617
8618void NoteBuiltinOperatorCandidate(Sema &S,
8619                                  StringRef Opc,
8620                                  SourceLocation OpLoc,
8621                                  OverloadCandidate *Cand) {
8622  assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8623  std::string TypeStr("operator");
8624  TypeStr += Opc;
8625  TypeStr += "(";
8626  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8627  if (Cand->NumConversions == 1) {
8628    TypeStr += ")";
8629    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8630  } else {
8631    TypeStr += ", ";
8632    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8633    TypeStr += ")";
8634    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8635  }
8636}
8637
8638void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8639                                  OverloadCandidate *Cand) {
8640  unsigned NoOperands = Cand->NumConversions;
8641  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8642    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8643    if (ICS.isBad()) break; // all meaningless after first invalid
8644    if (!ICS.isAmbiguous()) continue;
8645
8646    ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8647                              S.PDiag(diag::note_ambiguous_type_conversion));
8648  }
8649}
8650
8651SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8652  if (Cand->Function)
8653    return Cand->Function->getLocation();
8654  if (Cand->IsSurrogate)
8655    return Cand->Surrogate->getLocation();
8656  return SourceLocation();
8657}
8658
8659static unsigned
8660RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
8661  switch ((Sema::TemplateDeductionResult)DFI.Result) {
8662  case Sema::TDK_Success:
8663    llvm_unreachable("TDK_success while diagnosing bad deduction");
8664
8665  case Sema::TDK_Invalid:
8666  case Sema::TDK_Incomplete:
8667    return 1;
8668
8669  case Sema::TDK_Underqualified:
8670  case Sema::TDK_Inconsistent:
8671    return 2;
8672
8673  case Sema::TDK_SubstitutionFailure:
8674  case Sema::TDK_NonDeducedMismatch:
8675  case Sema::TDK_MiscellaneousDeductionFailure:
8676    return 3;
8677
8678  case Sema::TDK_InstantiationDepth:
8679  case Sema::TDK_FailedOverloadResolution:
8680    return 4;
8681
8682  case Sema::TDK_InvalidExplicitArguments:
8683    return 5;
8684
8685  case Sema::TDK_TooManyArguments:
8686  case Sema::TDK_TooFewArguments:
8687    return 6;
8688  }
8689  llvm_unreachable("Unhandled deduction result");
8690}
8691
8692struct CompareOverloadCandidatesForDisplay {
8693  Sema &S;
8694  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8695
8696  bool operator()(const OverloadCandidate *L,
8697                  const OverloadCandidate *R) {
8698    // Fast-path this check.
8699    if (L == R) return false;
8700
8701    // Order first by viability.
8702    if (L->Viable) {
8703      if (!R->Viable) return true;
8704
8705      // TODO: introduce a tri-valued comparison for overload
8706      // candidates.  Would be more worthwhile if we had a sort
8707      // that could exploit it.
8708      if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8709      if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8710    } else if (R->Viable)
8711      return false;
8712
8713    assert(L->Viable == R->Viable);
8714
8715    // Criteria by which we can sort non-viable candidates:
8716    if (!L->Viable) {
8717      // 1. Arity mismatches come after other candidates.
8718      if (L->FailureKind == ovl_fail_too_many_arguments ||
8719          L->FailureKind == ovl_fail_too_few_arguments)
8720        return false;
8721      if (R->FailureKind == ovl_fail_too_many_arguments ||
8722          R->FailureKind == ovl_fail_too_few_arguments)
8723        return true;
8724
8725      // 2. Bad conversions come first and are ordered by the number
8726      // of bad conversions and quality of good conversions.
8727      if (L->FailureKind == ovl_fail_bad_conversion) {
8728        if (R->FailureKind != ovl_fail_bad_conversion)
8729          return true;
8730
8731        // The conversion that can be fixed with a smaller number of changes,
8732        // comes first.
8733        unsigned numLFixes = L->Fix.NumConversionsFixed;
8734        unsigned numRFixes = R->Fix.NumConversionsFixed;
8735        numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8736        numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8737        if (numLFixes != numRFixes) {
8738          if (numLFixes < numRFixes)
8739            return true;
8740          else
8741            return false;
8742        }
8743
8744        // If there's any ordering between the defined conversions...
8745        // FIXME: this might not be transitive.
8746        assert(L->NumConversions == R->NumConversions);
8747
8748        int leftBetter = 0;
8749        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8750        for (unsigned E = L->NumConversions; I != E; ++I) {
8751          switch (CompareImplicitConversionSequences(S,
8752                                                     L->Conversions[I],
8753                                                     R->Conversions[I])) {
8754          case ImplicitConversionSequence::Better:
8755            leftBetter++;
8756            break;
8757
8758          case ImplicitConversionSequence::Worse:
8759            leftBetter--;
8760            break;
8761
8762          case ImplicitConversionSequence::Indistinguishable:
8763            break;
8764          }
8765        }
8766        if (leftBetter > 0) return true;
8767        if (leftBetter < 0) return false;
8768
8769      } else if (R->FailureKind == ovl_fail_bad_conversion)
8770        return false;
8771
8772      if (L->FailureKind == ovl_fail_bad_deduction) {
8773        if (R->FailureKind != ovl_fail_bad_deduction)
8774          return true;
8775
8776        if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8777          return RankDeductionFailure(L->DeductionFailure)
8778               < RankDeductionFailure(R->DeductionFailure);
8779      } else if (R->FailureKind == ovl_fail_bad_deduction)
8780        return false;
8781
8782      // TODO: others?
8783    }
8784
8785    // Sort everything else by location.
8786    SourceLocation LLoc = GetLocationForCandidate(L);
8787    SourceLocation RLoc = GetLocationForCandidate(R);
8788
8789    // Put candidates without locations (e.g. builtins) at the end.
8790    if (LLoc.isInvalid()) return false;
8791    if (RLoc.isInvalid()) return true;
8792
8793    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8794  }
8795};
8796
8797/// CompleteNonViableCandidate - Normally, overload resolution only
8798/// computes up to the first. Produces the FixIt set if possible.
8799void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8800                                ArrayRef<Expr *> Args) {
8801  assert(!Cand->Viable);
8802
8803  // Don't do anything on failures other than bad conversion.
8804  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8805
8806  // We only want the FixIts if all the arguments can be corrected.
8807  bool Unfixable = false;
8808  // Use a implicit copy initialization to check conversion fixes.
8809  Cand->Fix.setConversionChecker(TryCopyInitialization);
8810
8811  // Skip forward to the first bad conversion.
8812  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
8813  unsigned ConvCount = Cand->NumConversions;
8814  while (true) {
8815    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8816    ConvIdx++;
8817    if (Cand->Conversions[ConvIdx - 1].isBad()) {
8818      Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
8819      break;
8820    }
8821  }
8822
8823  if (ConvIdx == ConvCount)
8824    return;
8825
8826  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8827         "remaining conversion is initialized?");
8828
8829  // FIXME: this should probably be preserved from the overload
8830  // operation somehow.
8831  bool SuppressUserConversions = false;
8832
8833  const FunctionProtoType* Proto;
8834  unsigned ArgIdx = ConvIdx;
8835
8836  if (Cand->IsSurrogate) {
8837    QualType ConvType
8838      = Cand->Surrogate->getConversionType().getNonReferenceType();
8839    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8840      ConvType = ConvPtrType->getPointeeType();
8841    Proto = ConvType->getAs<FunctionProtoType>();
8842    ArgIdx--;
8843  } else if (Cand->Function) {
8844    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8845    if (isa<CXXMethodDecl>(Cand->Function) &&
8846        !isa<CXXConstructorDecl>(Cand->Function))
8847      ArgIdx--;
8848  } else {
8849    // Builtin binary operator with a bad first conversion.
8850    assert(ConvCount <= 3);
8851    for (; ConvIdx != ConvCount; ++ConvIdx)
8852      Cand->Conversions[ConvIdx]
8853        = TryCopyInitialization(S, Args[ConvIdx],
8854                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
8855                                SuppressUserConversions,
8856                                /*InOverloadResolution*/ true,
8857                                /*AllowObjCWritebackConversion=*/
8858                                  S.getLangOpts().ObjCAutoRefCount);
8859    return;
8860  }
8861
8862  // Fill in the rest of the conversions.
8863  unsigned NumArgsInProto = Proto->getNumArgs();
8864  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
8865    if (ArgIdx < NumArgsInProto) {
8866      Cand->Conversions[ConvIdx]
8867        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
8868                                SuppressUserConversions,
8869                                /*InOverloadResolution=*/true,
8870                                /*AllowObjCWritebackConversion=*/
8871                                  S.getLangOpts().ObjCAutoRefCount);
8872      // Store the FixIt in the candidate if it exists.
8873      if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
8874        Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
8875    }
8876    else
8877      Cand->Conversions[ConvIdx].setEllipsis();
8878  }
8879}
8880
8881} // end anonymous namespace
8882
8883/// PrintOverloadCandidates - When overload resolution fails, prints
8884/// diagnostic messages containing the candidates in the candidate
8885/// set.
8886void OverloadCandidateSet::NoteCandidates(Sema &S,
8887                                          OverloadCandidateDisplayKind OCD,
8888                                          ArrayRef<Expr *> Args,
8889                                          StringRef Opc,
8890                                          SourceLocation OpLoc) {
8891  // Sort the candidates by viability and position.  Sorting directly would
8892  // be prohibitive, so we make a set of pointers and sort those.
8893  SmallVector<OverloadCandidate*, 32> Cands;
8894  if (OCD == OCD_AllCandidates) Cands.reserve(size());
8895  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
8896    if (Cand->Viable)
8897      Cands.push_back(Cand);
8898    else if (OCD == OCD_AllCandidates) {
8899      CompleteNonViableCandidate(S, Cand, Args);
8900      if (Cand->Function || Cand->IsSurrogate)
8901        Cands.push_back(Cand);
8902      // Otherwise, this a non-viable builtin candidate.  We do not, in general,
8903      // want to list every possible builtin candidate.
8904    }
8905  }
8906
8907  std::sort(Cands.begin(), Cands.end(),
8908            CompareOverloadCandidatesForDisplay(S));
8909
8910  bool ReportedAmbiguousConversions = false;
8911
8912  SmallVectorImpl<OverloadCandidate*>::iterator I, E;
8913  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8914  unsigned CandsShown = 0;
8915  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8916    OverloadCandidate *Cand = *I;
8917
8918    // Set an arbitrary limit on the number of candidate functions we'll spam
8919    // the user with.  FIXME: This limit should depend on details of the
8920    // candidate list.
8921    if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
8922      break;
8923    }
8924    ++CandsShown;
8925
8926    if (Cand->Function)
8927      NoteFunctionCandidate(S, Cand, Args.size());
8928    else if (Cand->IsSurrogate)
8929      NoteSurrogateCandidate(S, Cand);
8930    else {
8931      assert(Cand->Viable &&
8932             "Non-viable built-in candidates are not added to Cands.");
8933      // Generally we only see ambiguities including viable builtin
8934      // operators if overload resolution got screwed up by an
8935      // ambiguous user-defined conversion.
8936      //
8937      // FIXME: It's quite possible for different conversions to see
8938      // different ambiguities, though.
8939      if (!ReportedAmbiguousConversions) {
8940        NoteAmbiguousUserConversions(S, OpLoc, Cand);
8941        ReportedAmbiguousConversions = true;
8942      }
8943
8944      // If this is a viable builtin, print it.
8945      NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
8946    }
8947  }
8948
8949  if (I != E)
8950    S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
8951}
8952
8953// [PossiblyAFunctionType]  -->   [Return]
8954// NonFunctionType --> NonFunctionType
8955// R (A) --> R(A)
8956// R (*)(A) --> R (A)
8957// R (&)(A) --> R (A)
8958// R (S::*)(A) --> R (A)
8959QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8960  QualType Ret = PossiblyAFunctionType;
8961  if (const PointerType *ToTypePtr =
8962    PossiblyAFunctionType->getAs<PointerType>())
8963    Ret = ToTypePtr->getPointeeType();
8964  else if (const ReferenceType *ToTypeRef =
8965    PossiblyAFunctionType->getAs<ReferenceType>())
8966    Ret = ToTypeRef->getPointeeType();
8967  else if (const MemberPointerType *MemTypePtr =
8968    PossiblyAFunctionType->getAs<MemberPointerType>())
8969    Ret = MemTypePtr->getPointeeType();
8970  Ret =
8971    Context.getCanonicalType(Ret).getUnqualifiedType();
8972  return Ret;
8973}
8974
8975// A helper class to help with address of function resolution
8976// - allows us to avoid passing around all those ugly parameters
8977class AddressOfFunctionResolver
8978{
8979  Sema& S;
8980  Expr* SourceExpr;
8981  const QualType& TargetType;
8982  QualType TargetFunctionType; // Extracted function type from target type
8983
8984  bool Complain;
8985  //DeclAccessPair& ResultFunctionAccessPair;
8986  ASTContext& Context;
8987
8988  bool TargetTypeIsNonStaticMemberFunction;
8989  bool FoundNonTemplateFunction;
8990
8991  OverloadExpr::FindResult OvlExprInfo;
8992  OverloadExpr *OvlExpr;
8993  TemplateArgumentListInfo OvlExplicitTemplateArgs;
8994  SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
8995
8996public:
8997  AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8998                            const QualType& TargetType, bool Complain)
8999    : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9000      Complain(Complain), Context(S.getASTContext()),
9001      TargetTypeIsNonStaticMemberFunction(
9002                                    !!TargetType->getAs<MemberPointerType>()),
9003      FoundNonTemplateFunction(false),
9004      OvlExprInfo(OverloadExpr::find(SourceExpr)),
9005      OvlExpr(OvlExprInfo.Expression)
9006  {
9007    ExtractUnqualifiedFunctionTypeFromTargetType();
9008
9009    if (!TargetFunctionType->isFunctionType()) {
9010      if (OvlExpr->hasExplicitTemplateArgs()) {
9011        DeclAccessPair dap;
9012        if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
9013                                            OvlExpr, false, &dap) ) {
9014
9015          if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9016            if (!Method->isStatic()) {
9017              // If the target type is a non-function type and the function
9018              // found is a non-static member function, pretend as if that was
9019              // the target, it's the only possible type to end up with.
9020              TargetTypeIsNonStaticMemberFunction = true;
9021
9022              // And skip adding the function if its not in the proper form.
9023              // We'll diagnose this due to an empty set of functions.
9024              if (!OvlExprInfo.HasFormOfMemberPointer)
9025                return;
9026            }
9027          }
9028
9029          Matches.push_back(std::make_pair(dap,Fn));
9030        }
9031      }
9032      return;
9033    }
9034
9035    if (OvlExpr->hasExplicitTemplateArgs())
9036      OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9037
9038    if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9039      // C++ [over.over]p4:
9040      //   If more than one function is selected, [...]
9041      if (Matches.size() > 1) {
9042        if (FoundNonTemplateFunction)
9043          EliminateAllTemplateMatches();
9044        else
9045          EliminateAllExceptMostSpecializedTemplate();
9046      }
9047    }
9048  }
9049
9050private:
9051  bool isTargetTypeAFunction() const {
9052    return TargetFunctionType->isFunctionType();
9053  }
9054
9055  // [ToType]     [Return]
9056
9057  // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9058  // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9059  // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9060  void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9061    TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9062  }
9063
9064  // return true if any matching specializations were found
9065  bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9066                                   const DeclAccessPair& CurAccessFunPair) {
9067    if (CXXMethodDecl *Method
9068              = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9069      // Skip non-static function templates when converting to pointer, and
9070      // static when converting to member pointer.
9071      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9072        return false;
9073    }
9074    else if (TargetTypeIsNonStaticMemberFunction)
9075      return false;
9076
9077    // C++ [over.over]p2:
9078    //   If the name is a function template, template argument deduction is
9079    //   done (14.8.2.2), and if the argument deduction succeeds, the
9080    //   resulting template argument list is used to generate a single
9081    //   function template specialization, which is added to the set of
9082    //   overloaded functions considered.
9083    FunctionDecl *Specialization = 0;
9084    TemplateDeductionInfo Info(OvlExpr->getNameLoc());
9085    if (Sema::TemplateDeductionResult Result
9086          = S.DeduceTemplateArguments(FunctionTemplate,
9087                                      &OvlExplicitTemplateArgs,
9088                                      TargetFunctionType, Specialization,
9089                                      Info)) {
9090      // FIXME: make a note of the failed deduction for diagnostics.
9091      (void)Result;
9092      return false;
9093    }
9094
9095    // Template argument deduction ensures that we have an exact match.
9096    // This function template specicalization works.
9097    Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9098    assert(TargetFunctionType
9099                      == Context.getCanonicalType(Specialization->getType()));
9100    Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9101    return true;
9102  }
9103
9104  bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9105                                      const DeclAccessPair& CurAccessFunPair) {
9106    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9107      // Skip non-static functions when converting to pointer, and static
9108      // when converting to member pointer.
9109      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9110        return false;
9111    }
9112    else if (TargetTypeIsNonStaticMemberFunction)
9113      return false;
9114
9115    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9116      if (S.getLangOpts().CUDA)
9117        if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9118          if (S.CheckCUDATarget(Caller, FunDecl))
9119            return false;
9120
9121      QualType ResultTy;
9122      if (Context.hasSameUnqualifiedType(TargetFunctionType,
9123                                         FunDecl->getType()) ||
9124          S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9125                                 ResultTy)) {
9126        Matches.push_back(std::make_pair(CurAccessFunPair,
9127          cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9128        FoundNonTemplateFunction = true;
9129        return true;
9130      }
9131    }
9132
9133    return false;
9134  }
9135
9136  bool FindAllFunctionsThatMatchTargetTypeExactly() {
9137    bool Ret = false;
9138
9139    // If the overload expression doesn't have the form of a pointer to
9140    // member, don't try to convert it to a pointer-to-member type.
9141    if (IsInvalidFormOfPointerToMemberFunction())
9142      return false;
9143
9144    for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9145                               E = OvlExpr->decls_end();
9146         I != E; ++I) {
9147      // Look through any using declarations to find the underlying function.
9148      NamedDecl *Fn = (*I)->getUnderlyingDecl();
9149
9150      // C++ [over.over]p3:
9151      //   Non-member functions and static member functions match
9152      //   targets of type "pointer-to-function" or "reference-to-function."
9153      //   Nonstatic member functions match targets of
9154      //   type "pointer-to-member-function."
9155      // Note that according to DR 247, the containing class does not matter.
9156      if (FunctionTemplateDecl *FunctionTemplate
9157                                        = dyn_cast<FunctionTemplateDecl>(Fn)) {
9158        if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9159          Ret = true;
9160      }
9161      // If we have explicit template arguments supplied, skip non-templates.
9162      else if (!OvlExpr->hasExplicitTemplateArgs() &&
9163               AddMatchingNonTemplateFunction(Fn, I.getPair()))
9164        Ret = true;
9165    }
9166    assert(Ret || Matches.empty());
9167    return Ret;
9168  }
9169
9170  void EliminateAllExceptMostSpecializedTemplate() {
9171    //   [...] and any given function template specialization F1 is
9172    //   eliminated if the set contains a second function template
9173    //   specialization whose function template is more specialized
9174    //   than the function template of F1 according to the partial
9175    //   ordering rules of 14.5.5.2.
9176
9177    // The algorithm specified above is quadratic. We instead use a
9178    // two-pass algorithm (similar to the one used to identify the
9179    // best viable function in an overload set) that identifies the
9180    // best function template (if it exists).
9181
9182    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9183    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9184      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9185
9186    UnresolvedSetIterator Result =
9187      S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9188                           TPOC_Other, 0, SourceExpr->getLocStart(),
9189                           S.PDiag(),
9190                           S.PDiag(diag::err_addr_ovl_ambiguous)
9191                             << Matches[0].second->getDeclName(),
9192                           S.PDiag(diag::note_ovl_candidate)
9193                             << (unsigned) oc_function_template,
9194                           Complain, TargetFunctionType);
9195
9196    if (Result != MatchesCopy.end()) {
9197      // Make it the first and only element
9198      Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9199      Matches[0].second = cast<FunctionDecl>(*Result);
9200      Matches.resize(1);
9201    }
9202  }
9203
9204  void EliminateAllTemplateMatches() {
9205    //   [...] any function template specializations in the set are
9206    //   eliminated if the set also contains a non-template function, [...]
9207    for (unsigned I = 0, N = Matches.size(); I != N; ) {
9208      if (Matches[I].second->getPrimaryTemplate() == 0)
9209        ++I;
9210      else {
9211        Matches[I] = Matches[--N];
9212        Matches.set_size(N);
9213      }
9214    }
9215  }
9216
9217public:
9218  void ComplainNoMatchesFound() const {
9219    assert(Matches.empty());
9220    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9221        << OvlExpr->getName() << TargetFunctionType
9222        << OvlExpr->getSourceRange();
9223    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9224  }
9225
9226  bool IsInvalidFormOfPointerToMemberFunction() const {
9227    return TargetTypeIsNonStaticMemberFunction &&
9228      !OvlExprInfo.HasFormOfMemberPointer;
9229  }
9230
9231  void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9232      // TODO: Should we condition this on whether any functions might
9233      // have matched, or is it more appropriate to do that in callers?
9234      // TODO: a fixit wouldn't hurt.
9235      S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9236        << TargetType << OvlExpr->getSourceRange();
9237  }
9238
9239  void ComplainOfInvalidConversion() const {
9240    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9241      << OvlExpr->getName() << TargetType;
9242  }
9243
9244  void ComplainMultipleMatchesFound() const {
9245    assert(Matches.size() > 1);
9246    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9247      << OvlExpr->getName()
9248      << OvlExpr->getSourceRange();
9249    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9250  }
9251
9252  bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9253
9254  int getNumMatches() const { return Matches.size(); }
9255
9256  FunctionDecl* getMatchingFunctionDecl() const {
9257    if (Matches.size() != 1) return 0;
9258    return Matches[0].second;
9259  }
9260
9261  const DeclAccessPair* getMatchingFunctionAccessPair() const {
9262    if (Matches.size() != 1) return 0;
9263    return &Matches[0].first;
9264  }
9265};
9266
9267/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9268/// an overloaded function (C++ [over.over]), where @p From is an
9269/// expression with overloaded function type and @p ToType is the type
9270/// we're trying to resolve to. For example:
9271///
9272/// @code
9273/// int f(double);
9274/// int f(int);
9275///
9276/// int (*pfd)(double) = f; // selects f(double)
9277/// @endcode
9278///
9279/// This routine returns the resulting FunctionDecl if it could be
9280/// resolved, and NULL otherwise. When @p Complain is true, this
9281/// routine will emit diagnostics if there is an error.
9282FunctionDecl *
9283Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9284                                         QualType TargetType,
9285                                         bool Complain,
9286                                         DeclAccessPair &FoundResult,
9287                                         bool *pHadMultipleCandidates) {
9288  assert(AddressOfExpr->getType() == Context.OverloadTy);
9289
9290  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9291                                     Complain);
9292  int NumMatches = Resolver.getNumMatches();
9293  FunctionDecl* Fn = 0;
9294  if (NumMatches == 0 && Complain) {
9295    if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9296      Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9297    else
9298      Resolver.ComplainNoMatchesFound();
9299  }
9300  else if (NumMatches > 1 && Complain)
9301    Resolver.ComplainMultipleMatchesFound();
9302  else if (NumMatches == 1) {
9303    Fn = Resolver.getMatchingFunctionDecl();
9304    assert(Fn);
9305    FoundResult = *Resolver.getMatchingFunctionAccessPair();
9306    if (Complain)
9307      CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9308  }
9309
9310  if (pHadMultipleCandidates)
9311    *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9312  return Fn;
9313}
9314
9315/// \brief Given an expression that refers to an overloaded function, try to
9316/// resolve that overloaded function expression down to a single function.
9317///
9318/// This routine can only resolve template-ids that refer to a single function
9319/// template, where that template-id refers to a single template whose template
9320/// arguments are either provided by the template-id or have defaults,
9321/// as described in C++0x [temp.arg.explicit]p3.
9322FunctionDecl *
9323Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9324                                                  bool Complain,
9325                                                  DeclAccessPair *FoundResult) {
9326  // C++ [over.over]p1:
9327  //   [...] [Note: any redundant set of parentheses surrounding the
9328  //   overloaded function name is ignored (5.1). ]
9329  // C++ [over.over]p1:
9330  //   [...] The overloaded function name can be preceded by the &
9331  //   operator.
9332
9333  // If we didn't actually find any template-ids, we're done.
9334  if (!ovl->hasExplicitTemplateArgs())
9335    return 0;
9336
9337  TemplateArgumentListInfo ExplicitTemplateArgs;
9338  ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9339
9340  // Look through all of the overloaded functions, searching for one
9341  // whose type matches exactly.
9342  FunctionDecl *Matched = 0;
9343  for (UnresolvedSetIterator I = ovl->decls_begin(),
9344         E = ovl->decls_end(); I != E; ++I) {
9345    // C++0x [temp.arg.explicit]p3:
9346    //   [...] In contexts where deduction is done and fails, or in contexts
9347    //   where deduction is not done, if a template argument list is
9348    //   specified and it, along with any default template arguments,
9349    //   identifies a single function template specialization, then the
9350    //   template-id is an lvalue for the function template specialization.
9351    FunctionTemplateDecl *FunctionTemplate
9352      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9353
9354    // C++ [over.over]p2:
9355    //   If the name is a function template, template argument deduction is
9356    //   done (14.8.2.2), and if the argument deduction succeeds, the
9357    //   resulting template argument list is used to generate a single
9358    //   function template specialization, which is added to the set of
9359    //   overloaded functions considered.
9360    FunctionDecl *Specialization = 0;
9361    TemplateDeductionInfo Info(ovl->getNameLoc());
9362    if (TemplateDeductionResult Result
9363          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9364                                    Specialization, Info)) {
9365      // FIXME: make a note of the failed deduction for diagnostics.
9366      (void)Result;
9367      continue;
9368    }
9369
9370    assert(Specialization && "no specialization and no error?");
9371
9372    // Multiple matches; we can't resolve to a single declaration.
9373    if (Matched) {
9374      if (Complain) {
9375        Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9376          << ovl->getName();
9377        NoteAllOverloadCandidates(ovl);
9378      }
9379      return 0;
9380    }
9381
9382    Matched = Specialization;
9383    if (FoundResult) *FoundResult = I.getPair();
9384  }
9385
9386  return Matched;
9387}
9388
9389
9390
9391
9392// Resolve and fix an overloaded expression that can be resolved
9393// because it identifies a single function template specialization.
9394//
9395// Last three arguments should only be supplied if Complain = true
9396//
9397// Return true if it was logically possible to so resolve the
9398// expression, regardless of whether or not it succeeded.  Always
9399// returns true if 'complain' is set.
9400bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9401                      ExprResult &SrcExpr, bool doFunctionPointerConverion,
9402                   bool complain, const SourceRange& OpRangeForComplaining,
9403                                           QualType DestTypeForComplaining,
9404                                            unsigned DiagIDForComplaining) {
9405  assert(SrcExpr.get()->getType() == Context.OverloadTy);
9406
9407  OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9408
9409  DeclAccessPair found;
9410  ExprResult SingleFunctionExpression;
9411  if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9412                           ovl.Expression, /*complain*/ false, &found)) {
9413    if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9414      SrcExpr = ExprError();
9415      return true;
9416    }
9417
9418    // It is only correct to resolve to an instance method if we're
9419    // resolving a form that's permitted to be a pointer to member.
9420    // Otherwise we'll end up making a bound member expression, which
9421    // is illegal in all the contexts we resolve like this.
9422    if (!ovl.HasFormOfMemberPointer &&
9423        isa<CXXMethodDecl>(fn) &&
9424        cast<CXXMethodDecl>(fn)->isInstance()) {
9425      if (!complain) return false;
9426
9427      Diag(ovl.Expression->getExprLoc(),
9428           diag::err_bound_member_function)
9429        << 0 << ovl.Expression->getSourceRange();
9430
9431      // TODO: I believe we only end up here if there's a mix of
9432      // static and non-static candidates (otherwise the expression
9433      // would have 'bound member' type, not 'overload' type).
9434      // Ideally we would note which candidate was chosen and why
9435      // the static candidates were rejected.
9436      SrcExpr = ExprError();
9437      return true;
9438    }
9439
9440    // Fix the expression to refer to 'fn'.
9441    SingleFunctionExpression =
9442      Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9443
9444    // If desired, do function-to-pointer decay.
9445    if (doFunctionPointerConverion) {
9446      SingleFunctionExpression =
9447        DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9448      if (SingleFunctionExpression.isInvalid()) {
9449        SrcExpr = ExprError();
9450        return true;
9451      }
9452    }
9453  }
9454
9455  if (!SingleFunctionExpression.isUsable()) {
9456    if (complain) {
9457      Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9458        << ovl.Expression->getName()
9459        << DestTypeForComplaining
9460        << OpRangeForComplaining
9461        << ovl.Expression->getQualifierLoc().getSourceRange();
9462      NoteAllOverloadCandidates(SrcExpr.get());
9463
9464      SrcExpr = ExprError();
9465      return true;
9466    }
9467
9468    return false;
9469  }
9470
9471  SrcExpr = SingleFunctionExpression;
9472  return true;
9473}
9474
9475/// \brief Add a single candidate to the overload set.
9476static void AddOverloadedCallCandidate(Sema &S,
9477                                       DeclAccessPair FoundDecl,
9478                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
9479                                       ArrayRef<Expr *> Args,
9480                                       OverloadCandidateSet &CandidateSet,
9481                                       bool PartialOverloading,
9482                                       bool KnownValid) {
9483  NamedDecl *Callee = FoundDecl.getDecl();
9484  if (isa<UsingShadowDecl>(Callee))
9485    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9486
9487  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9488    if (ExplicitTemplateArgs) {
9489      assert(!KnownValid && "Explicit template arguments?");
9490      return;
9491    }
9492    S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9493                           PartialOverloading);
9494    return;
9495  }
9496
9497  if (FunctionTemplateDecl *FuncTemplate
9498      = dyn_cast<FunctionTemplateDecl>(Callee)) {
9499    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9500                                   ExplicitTemplateArgs, Args, CandidateSet);
9501    return;
9502  }
9503
9504  assert(!KnownValid && "unhandled case in overloaded call candidate");
9505}
9506
9507/// \brief Add the overload candidates named by callee and/or found by argument
9508/// dependent lookup to the given overload set.
9509void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9510                                       ArrayRef<Expr *> Args,
9511                                       OverloadCandidateSet &CandidateSet,
9512                                       bool PartialOverloading) {
9513
9514#ifndef NDEBUG
9515  // Verify that ArgumentDependentLookup is consistent with the rules
9516  // in C++0x [basic.lookup.argdep]p3:
9517  //
9518  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9519  //   and let Y be the lookup set produced by argument dependent
9520  //   lookup (defined as follows). If X contains
9521  //
9522  //     -- a declaration of a class member, or
9523  //
9524  //     -- a block-scope function declaration that is not a
9525  //        using-declaration, or
9526  //
9527  //     -- a declaration that is neither a function or a function
9528  //        template
9529  //
9530  //   then Y is empty.
9531
9532  if (ULE->requiresADL()) {
9533    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9534           E = ULE->decls_end(); I != E; ++I) {
9535      assert(!(*I)->getDeclContext()->isRecord());
9536      assert(isa<UsingShadowDecl>(*I) ||
9537             !(*I)->getDeclContext()->isFunctionOrMethod());
9538      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9539    }
9540  }
9541#endif
9542
9543  // It would be nice to avoid this copy.
9544  TemplateArgumentListInfo TABuffer;
9545  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9546  if (ULE->hasExplicitTemplateArgs()) {
9547    ULE->copyTemplateArgumentsInto(TABuffer);
9548    ExplicitTemplateArgs = &TABuffer;
9549  }
9550
9551  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9552         E = ULE->decls_end(); I != E; ++I)
9553    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9554                               CandidateSet, PartialOverloading,
9555                               /*KnownValid*/ true);
9556
9557  if (ULE->requiresADL())
9558    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9559                                         ULE->getExprLoc(),
9560                                         Args, ExplicitTemplateArgs,
9561                                         CandidateSet, PartialOverloading);
9562}
9563
9564/// Attempt to recover from an ill-formed use of a non-dependent name in a
9565/// template, where the non-dependent name was declared after the template
9566/// was defined. This is common in code written for a compilers which do not
9567/// correctly implement two-stage name lookup.
9568///
9569/// Returns true if a viable candidate was found and a diagnostic was issued.
9570static bool
9571DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9572                       const CXXScopeSpec &SS, LookupResult &R,
9573                       TemplateArgumentListInfo *ExplicitTemplateArgs,
9574                       ArrayRef<Expr *> Args) {
9575  if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9576    return false;
9577
9578  for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9579    if (DC->isTransparentContext())
9580      continue;
9581
9582    SemaRef.LookupQualifiedName(R, DC);
9583
9584    if (!R.empty()) {
9585      R.suppressDiagnostics();
9586
9587      if (isa<CXXRecordDecl>(DC)) {
9588        // Don't diagnose names we find in classes; we get much better
9589        // diagnostics for these from DiagnoseEmptyLookup.
9590        R.clear();
9591        return false;
9592      }
9593
9594      OverloadCandidateSet Candidates(FnLoc);
9595      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9596        AddOverloadedCallCandidate(SemaRef, I.getPair(),
9597                                   ExplicitTemplateArgs, Args,
9598                                   Candidates, false, /*KnownValid*/ false);
9599
9600      OverloadCandidateSet::iterator Best;
9601      if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9602        // No viable functions. Don't bother the user with notes for functions
9603        // which don't work and shouldn't be found anyway.
9604        R.clear();
9605        return false;
9606      }
9607
9608      // Find the namespaces where ADL would have looked, and suggest
9609      // declaring the function there instead.
9610      Sema::AssociatedNamespaceSet AssociatedNamespaces;
9611      Sema::AssociatedClassSet AssociatedClasses;
9612      SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
9613                                                 AssociatedNamespaces,
9614                                                 AssociatedClasses);
9615      Sema::AssociatedNamespaceSet SuggestedNamespaces;
9616      DeclContext *Std = SemaRef.getStdNamespace();
9617      for (Sema::AssociatedNamespaceSet::iterator
9618             it = AssociatedNamespaces.begin(),
9619             end = AssociatedNamespaces.end(); it != end; ++it) {
9620        // Never suggest declaring a function within namespace 'std'.
9621        if (Std && Std->Encloses(*it))
9622          continue;
9623
9624        // Never suggest declaring a function within a namespace with a reserved
9625        // name, like __gnu_cxx.
9626        NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9627        if (NS &&
9628            NS->getQualifiedNameAsString().find("__") != std::string::npos)
9629          continue;
9630
9631        SuggestedNamespaces.insert(*it);
9632      }
9633
9634      SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9635        << R.getLookupName();
9636      if (SuggestedNamespaces.empty()) {
9637        SemaRef.Diag(Best->Function->getLocation(),
9638                     diag::note_not_found_by_two_phase_lookup)
9639          << R.getLookupName() << 0;
9640      } else if (SuggestedNamespaces.size() == 1) {
9641        SemaRef.Diag(Best->Function->getLocation(),
9642                     diag::note_not_found_by_two_phase_lookup)
9643          << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
9644      } else {
9645        // FIXME: It would be useful to list the associated namespaces here,
9646        // but the diagnostics infrastructure doesn't provide a way to produce
9647        // a localized representation of a list of items.
9648        SemaRef.Diag(Best->Function->getLocation(),
9649                     diag::note_not_found_by_two_phase_lookup)
9650          << R.getLookupName() << 2;
9651      }
9652
9653      // Try to recover by calling this function.
9654      return true;
9655    }
9656
9657    R.clear();
9658  }
9659
9660  return false;
9661}
9662
9663/// Attempt to recover from ill-formed use of a non-dependent operator in a
9664/// template, where the non-dependent operator was declared after the template
9665/// was defined.
9666///
9667/// Returns true if a viable candidate was found and a diagnostic was issued.
9668static bool
9669DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9670                               SourceLocation OpLoc,
9671                               ArrayRef<Expr *> Args) {
9672  DeclarationName OpName =
9673    SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9674  LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9675  return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9676                                /*ExplicitTemplateArgs=*/0, Args);
9677}
9678
9679namespace {
9680// Callback to limit the allowed keywords and to only accept typo corrections
9681// that are keywords or whose decls refer to functions (or template functions)
9682// that accept the given number of arguments.
9683class RecoveryCallCCC : public CorrectionCandidateCallback {
9684 public:
9685  RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9686      : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9687    WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
9688    WantRemainingKeywords = false;
9689  }
9690
9691  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9692    if (!candidate.getCorrectionDecl())
9693      return candidate.isKeyword();
9694
9695    for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9696           DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9697      FunctionDecl *FD = 0;
9698      NamedDecl *ND = (*DI)->getUnderlyingDecl();
9699      if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9700        FD = FTD->getTemplatedDecl();
9701      if (!HasExplicitTemplateArgs && !FD) {
9702        if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9703          // If the Decl is neither a function nor a template function,
9704          // determine if it is a pointer or reference to a function. If so,
9705          // check against the number of arguments expected for the pointee.
9706          QualType ValType = cast<ValueDecl>(ND)->getType();
9707          if (ValType->isAnyPointerType() || ValType->isReferenceType())
9708            ValType = ValType->getPointeeType();
9709          if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9710            if (FPT->getNumArgs() == NumArgs)
9711              return true;
9712        }
9713      }
9714      if (FD && FD->getNumParams() >= NumArgs &&
9715          FD->getMinRequiredArguments() <= NumArgs)
9716        return true;
9717    }
9718    return false;
9719  }
9720
9721 private:
9722  unsigned NumArgs;
9723  bool HasExplicitTemplateArgs;
9724};
9725
9726// Callback that effectively disabled typo correction
9727class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9728 public:
9729  NoTypoCorrectionCCC() {
9730    WantTypeSpecifiers = false;
9731    WantExpressionKeywords = false;
9732    WantCXXNamedCasts = false;
9733    WantRemainingKeywords = false;
9734  }
9735
9736  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9737    return false;
9738  }
9739};
9740
9741class BuildRecoveryCallExprRAII {
9742  Sema &SemaRef;
9743public:
9744  BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9745    assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9746    SemaRef.IsBuildingRecoveryCallExpr = true;
9747  }
9748
9749  ~BuildRecoveryCallExprRAII() {
9750    SemaRef.IsBuildingRecoveryCallExpr = false;
9751  }
9752};
9753
9754}
9755
9756/// Attempts to recover from a call where no functions were found.
9757///
9758/// Returns true if new candidates were found.
9759static ExprResult
9760BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9761                      UnresolvedLookupExpr *ULE,
9762                      SourceLocation LParenLoc,
9763                      llvm::MutableArrayRef<Expr *> Args,
9764                      SourceLocation RParenLoc,
9765                      bool EmptyLookup, bool AllowTypoCorrection) {
9766  // Do not try to recover if it is already building a recovery call.
9767  // This stops infinite loops for template instantiations like
9768  //
9769  // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9770  // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9771  //
9772  if (SemaRef.IsBuildingRecoveryCallExpr)
9773    return ExprError();
9774  BuildRecoveryCallExprRAII RCE(SemaRef);
9775
9776  CXXScopeSpec SS;
9777  SS.Adopt(ULE->getQualifierLoc());
9778  SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
9779
9780  TemplateArgumentListInfo TABuffer;
9781  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9782  if (ULE->hasExplicitTemplateArgs()) {
9783    ULE->copyTemplateArgumentsInto(TABuffer);
9784    ExplicitTemplateArgs = &TABuffer;
9785  }
9786
9787  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9788                 Sema::LookupOrdinaryName);
9789  RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
9790  NoTypoCorrectionCCC RejectAll;
9791  CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9792      (CorrectionCandidateCallback*)&Validator :
9793      (CorrectionCandidateCallback*)&RejectAll;
9794  if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9795                              ExplicitTemplateArgs, Args) &&
9796      (!EmptyLookup ||
9797       SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
9798                                   ExplicitTemplateArgs, Args)))
9799    return ExprError();
9800
9801  assert(!R.empty() && "lookup results empty despite recovery");
9802
9803  // Build an implicit member call if appropriate.  Just drop the
9804  // casts and such from the call, we don't really care.
9805  ExprResult NewFn = ExprError();
9806  if ((*R.begin())->isCXXClassMember())
9807    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9808                                                    R, ExplicitTemplateArgs);
9809  else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
9810    NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
9811                                        ExplicitTemplateArgs);
9812  else
9813    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9814
9815  if (NewFn.isInvalid())
9816    return ExprError();
9817
9818  // This shouldn't cause an infinite loop because we're giving it
9819  // an expression with viable lookup results, which should never
9820  // end up here.
9821  return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
9822                               MultiExprArg(Args.data(), Args.size()),
9823                               RParenLoc);
9824}
9825
9826/// \brief Constructs and populates an OverloadedCandidateSet from
9827/// the given function.
9828/// \returns true when an the ExprResult output parameter has been set.
9829bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9830                                  UnresolvedLookupExpr *ULE,
9831                                  Expr **Args, unsigned NumArgs,
9832                                  SourceLocation RParenLoc,
9833                                  OverloadCandidateSet *CandidateSet,
9834                                  ExprResult *Result) {
9835#ifndef NDEBUG
9836  if (ULE->requiresADL()) {
9837    // To do ADL, we must have found an unqualified name.
9838    assert(!ULE->getQualifier() && "qualified name with ADL");
9839
9840    // We don't perform ADL for implicit declarations of builtins.
9841    // Verify that this was correctly set up.
9842    FunctionDecl *F;
9843    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9844        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9845        F->getBuiltinID() && F->isImplicit())
9846      llvm_unreachable("performing ADL for builtin");
9847
9848    // We don't perform ADL in C.
9849    assert(getLangOpts().CPlusPlus && "ADL enabled in C");
9850  }
9851#endif
9852
9853  UnbridgedCastsSet UnbridgedCasts;
9854  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9855    *Result = ExprError();
9856    return true;
9857  }
9858
9859  // Add the functions denoted by the callee to the set of candidate
9860  // functions, including those from argument-dependent lookup.
9861  AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9862                              *CandidateSet);
9863
9864  // If we found nothing, try to recover.
9865  // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9866  // out if it fails.
9867  if (CandidateSet->empty()) {
9868    // In Microsoft mode, if we are inside a template class member function then
9869    // create a type dependent CallExpr. The goal is to postpone name lookup
9870    // to instantiation time to be able to search into type dependent base
9871    // classes.
9872    if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
9873        (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
9874      CallExpr *CE = new (Context) CallExpr(Context, Fn,
9875                                            llvm::makeArrayRef(Args, NumArgs),
9876                                            Context.DependentTy, VK_RValue,
9877                                            RParenLoc);
9878      CE->setTypeDependent(true);
9879      *Result = Owned(CE);
9880      return true;
9881    }
9882    return false;
9883  }
9884
9885  UnbridgedCasts.restore();
9886  return false;
9887}
9888
9889/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9890/// the completed call expression. If overload resolution fails, emits
9891/// diagnostics and returns ExprError()
9892static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9893                                           UnresolvedLookupExpr *ULE,
9894                                           SourceLocation LParenLoc,
9895                                           Expr **Args, unsigned NumArgs,
9896                                           SourceLocation RParenLoc,
9897                                           Expr *ExecConfig,
9898                                           OverloadCandidateSet *CandidateSet,
9899                                           OverloadCandidateSet::iterator *Best,
9900                                           OverloadingResult OverloadResult,
9901                                           bool AllowTypoCorrection) {
9902  if (CandidateSet->empty())
9903    return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9904                                 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9905                                 RParenLoc, /*EmptyLookup=*/true,
9906                                 AllowTypoCorrection);
9907
9908  switch (OverloadResult) {
9909  case OR_Success: {
9910    FunctionDecl *FDecl = (*Best)->Function;
9911    SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9912    SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9913    SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9914    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9915    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9916                                         RParenLoc, ExecConfig);
9917  }
9918
9919  case OR_No_Viable_Function: {
9920    // Try to recover by looking for viable functions which the user might
9921    // have meant to call.
9922    ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9923                                  llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9924                                                RParenLoc,
9925                                                /*EmptyLookup=*/false,
9926                                                AllowTypoCorrection);
9927    if (!Recovery.isInvalid())
9928      return Recovery;
9929
9930    SemaRef.Diag(Fn->getLocStart(),
9931         diag::err_ovl_no_viable_function_in_call)
9932      << ULE->getName() << Fn->getSourceRange();
9933    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9934                                 llvm::makeArrayRef(Args, NumArgs));
9935    break;
9936  }
9937
9938  case OR_Ambiguous:
9939    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
9940      << ULE->getName() << Fn->getSourceRange();
9941    CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9942                                 llvm::makeArrayRef(Args, NumArgs));
9943    break;
9944
9945  case OR_Deleted: {
9946    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9947      << (*Best)->Function->isDeleted()
9948      << ULE->getName()
9949      << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9950      << Fn->getSourceRange();
9951    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9952                                 llvm::makeArrayRef(Args, NumArgs));
9953
9954    // We emitted an error for the unvailable/deleted function call but keep
9955    // the call in the AST.
9956    FunctionDecl *FDecl = (*Best)->Function;
9957    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9958    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9959                                 RParenLoc, ExecConfig);
9960  }
9961  }
9962
9963  // Overload resolution failed.
9964  return ExprError();
9965}
9966
9967/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9968/// (which eventually refers to the declaration Func) and the call
9969/// arguments Args/NumArgs, attempt to resolve the function call down
9970/// to a specific function. If overload resolution succeeds, returns
9971/// the call expression produced by overload resolution.
9972/// Otherwise, emits diagnostics and returns ExprError.
9973ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9974                                         UnresolvedLookupExpr *ULE,
9975                                         SourceLocation LParenLoc,
9976                                         Expr **Args, unsigned NumArgs,
9977                                         SourceLocation RParenLoc,
9978                                         Expr *ExecConfig,
9979                                         bool AllowTypoCorrection) {
9980  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9981  ExprResult result;
9982
9983  if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9984                             &CandidateSet, &result))
9985    return result;
9986
9987  OverloadCandidateSet::iterator Best;
9988  OverloadingResult OverloadResult =
9989      CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9990
9991  return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9992                                  RParenLoc, ExecConfig, &CandidateSet,
9993                                  &Best, OverloadResult,
9994                                  AllowTypoCorrection);
9995}
9996
9997static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
9998  return Functions.size() > 1 ||
9999    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10000}
10001
10002/// \brief Create a unary operation that may resolve to an overloaded
10003/// operator.
10004///
10005/// \param OpLoc The location of the operator itself (e.g., '*').
10006///
10007/// \param OpcIn The UnaryOperator::Opcode that describes this
10008/// operator.
10009///
10010/// \param Fns The set of non-member functions that will be
10011/// considered by overload resolution. The caller needs to build this
10012/// set based on the context using, e.g.,
10013/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10014/// set should not contain any member functions; those will be added
10015/// by CreateOverloadedUnaryOp().
10016///
10017/// \param Input The input argument.
10018ExprResult
10019Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10020                              const UnresolvedSetImpl &Fns,
10021                              Expr *Input) {
10022  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10023
10024  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10025  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10026  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10027  // TODO: provide better source location info.
10028  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10029
10030  if (checkPlaceholderForOverload(*this, Input))
10031    return ExprError();
10032
10033  Expr *Args[2] = { Input, 0 };
10034  unsigned NumArgs = 1;
10035
10036  // For post-increment and post-decrement, add the implicit '0' as
10037  // the second argument, so that we know this is a post-increment or
10038  // post-decrement.
10039  if (Opc == UO_PostInc || Opc == UO_PostDec) {
10040    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10041    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10042                                     SourceLocation());
10043    NumArgs = 2;
10044  }
10045
10046  if (Input->isTypeDependent()) {
10047    if (Fns.empty())
10048      return Owned(new (Context) UnaryOperator(Input,
10049                                               Opc,
10050                                               Context.DependentTy,
10051                                               VK_RValue, OK_Ordinary,
10052                                               OpLoc));
10053
10054    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10055    UnresolvedLookupExpr *Fn
10056      = UnresolvedLookupExpr::Create(Context, NamingClass,
10057                                     NestedNameSpecifierLoc(), OpNameInfo,
10058                                     /*ADL*/ true, IsOverloaded(Fns),
10059                                     Fns.begin(), Fns.end());
10060    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
10061                                              llvm::makeArrayRef(Args, NumArgs),
10062                                                   Context.DependentTy,
10063                                                   VK_RValue,
10064                                                   OpLoc, false));
10065  }
10066
10067  // Build an empty overload set.
10068  OverloadCandidateSet CandidateSet(OpLoc);
10069
10070  // Add the candidates from the given function set.
10071  AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10072                        false);
10073
10074  // Add operator candidates that are member functions.
10075  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10076
10077  // Add candidates from ADL.
10078  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10079                                       OpLoc, llvm::makeArrayRef(Args, NumArgs),
10080                                       /*ExplicitTemplateArgs*/ 0,
10081                                       CandidateSet);
10082
10083  // Add builtin operator candidates.
10084  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10085
10086  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10087
10088  // Perform overload resolution.
10089  OverloadCandidateSet::iterator Best;
10090  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10091  case OR_Success: {
10092    // We found a built-in operator or an overloaded operator.
10093    FunctionDecl *FnDecl = Best->Function;
10094
10095    if (FnDecl) {
10096      // We matched an overloaded operator. Build a call to that
10097      // operator.
10098
10099      // Convert the arguments.
10100      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10101        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
10102
10103        ExprResult InputRes =
10104          PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10105                                              Best->FoundDecl, Method);
10106        if (InputRes.isInvalid())
10107          return ExprError();
10108        Input = InputRes.take();
10109      } else {
10110        // Convert the arguments.
10111        ExprResult InputInit
10112          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10113                                                      Context,
10114                                                      FnDecl->getParamDecl(0)),
10115                                      SourceLocation(),
10116                                      Input);
10117        if (InputInit.isInvalid())
10118          return ExprError();
10119        Input = InputInit.take();
10120      }
10121
10122      // Determine the result type.
10123      QualType ResultTy = FnDecl->getResultType();
10124      ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10125      ResultTy = ResultTy.getNonLValueExprType(Context);
10126
10127      // Build the actual expression node.
10128      ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10129                                                HadMultipleCandidates, OpLoc);
10130      if (FnExpr.isInvalid())
10131        return ExprError();
10132
10133      Args[0] = Input;
10134      CallExpr *TheCall =
10135        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10136                                          llvm::makeArrayRef(Args, NumArgs),
10137                                          ResultTy, VK, OpLoc, false);
10138
10139      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10140                              FnDecl))
10141        return ExprError();
10142
10143      return MaybeBindToTemporary(TheCall);
10144    } else {
10145      // We matched a built-in operator. Convert the arguments, then
10146      // break out so that we will build the appropriate built-in
10147      // operator node.
10148      ExprResult InputRes =
10149        PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10150                                  Best->Conversions[0], AA_Passing);
10151      if (InputRes.isInvalid())
10152        return ExprError();
10153      Input = InputRes.take();
10154      break;
10155    }
10156  }
10157
10158  case OR_No_Viable_Function:
10159    // This is an erroneous use of an operator which can be overloaded by
10160    // a non-member function. Check for non-member operators which were
10161    // defined too late to be candidates.
10162    if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10163                                       llvm::makeArrayRef(Args, NumArgs)))
10164      // FIXME: Recover by calling the found function.
10165      return ExprError();
10166
10167    // No viable function; fall through to handling this as a
10168    // built-in operator, which will produce an error message for us.
10169    break;
10170
10171  case OR_Ambiguous:
10172    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10173        << UnaryOperator::getOpcodeStr(Opc)
10174        << Input->getType()
10175        << Input->getSourceRange();
10176    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10177                                llvm::makeArrayRef(Args, NumArgs),
10178                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10179    return ExprError();
10180
10181  case OR_Deleted:
10182    Diag(OpLoc, diag::err_ovl_deleted_oper)
10183      << Best->Function->isDeleted()
10184      << UnaryOperator::getOpcodeStr(Opc)
10185      << getDeletedOrUnavailableSuffix(Best->Function)
10186      << Input->getSourceRange();
10187    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10188                                llvm::makeArrayRef(Args, NumArgs),
10189                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10190    return ExprError();
10191  }
10192
10193  // Either we found no viable overloaded operator or we matched a
10194  // built-in operator. In either case, fall through to trying to
10195  // build a built-in operation.
10196  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10197}
10198
10199/// \brief Create a binary operation that may resolve to an overloaded
10200/// operator.
10201///
10202/// \param OpLoc The location of the operator itself (e.g., '+').
10203///
10204/// \param OpcIn The BinaryOperator::Opcode that describes this
10205/// operator.
10206///
10207/// \param Fns The set of non-member functions that will be
10208/// considered by overload resolution. The caller needs to build this
10209/// set based on the context using, e.g.,
10210/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10211/// set should not contain any member functions; those will be added
10212/// by CreateOverloadedBinOp().
10213///
10214/// \param LHS Left-hand argument.
10215/// \param RHS Right-hand argument.
10216ExprResult
10217Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10218                            unsigned OpcIn,
10219                            const UnresolvedSetImpl &Fns,
10220                            Expr *LHS, Expr *RHS) {
10221  Expr *Args[2] = { LHS, RHS };
10222  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
10223
10224  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10225  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10226  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10227
10228  // If either side is type-dependent, create an appropriate dependent
10229  // expression.
10230  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10231    if (Fns.empty()) {
10232      // If there are no functions to store, just build a dependent
10233      // BinaryOperator or CompoundAssignment.
10234      if (Opc <= BO_Assign || Opc > BO_OrAssign)
10235        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
10236                                                  Context.DependentTy,
10237                                                  VK_RValue, OK_Ordinary,
10238                                                  OpLoc,
10239                                                  FPFeatures.fp_contract));
10240
10241      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10242                                                        Context.DependentTy,
10243                                                        VK_LValue,
10244                                                        OK_Ordinary,
10245                                                        Context.DependentTy,
10246                                                        Context.DependentTy,
10247                                                        OpLoc,
10248                                                        FPFeatures.fp_contract));
10249    }
10250
10251    // FIXME: save results of ADL from here?
10252    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10253    // TODO: provide better source location info in DNLoc component.
10254    DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10255    UnresolvedLookupExpr *Fn
10256      = UnresolvedLookupExpr::Create(Context, NamingClass,
10257                                     NestedNameSpecifierLoc(), OpNameInfo,
10258                                     /*ADL*/ true, IsOverloaded(Fns),
10259                                     Fns.begin(), Fns.end());
10260    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10261                                                Context.DependentTy, VK_RValue,
10262                                                OpLoc, FPFeatures.fp_contract));
10263  }
10264
10265  // Always do placeholder-like conversions on the RHS.
10266  if (checkPlaceholderForOverload(*this, Args[1]))
10267    return ExprError();
10268
10269  // Do placeholder-like conversion on the LHS; note that we should
10270  // not get here with a PseudoObject LHS.
10271  assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10272  if (checkPlaceholderForOverload(*this, Args[0]))
10273    return ExprError();
10274
10275  // If this is the assignment operator, we only perform overload resolution
10276  // if the left-hand side is a class or enumeration type. This is actually
10277  // a hack. The standard requires that we do overload resolution between the
10278  // various built-in candidates, but as DR507 points out, this can lead to
10279  // problems. So we do it this way, which pretty much follows what GCC does.
10280  // Note that we go the traditional code path for compound assignment forms.
10281  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10282    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10283
10284  // If this is the .* operator, which is not overloadable, just
10285  // create a built-in binary operator.
10286  if (Opc == BO_PtrMemD)
10287    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10288
10289  // Build an empty overload set.
10290  OverloadCandidateSet CandidateSet(OpLoc);
10291
10292  // Add the candidates from the given function set.
10293  AddFunctionCandidates(Fns, Args, CandidateSet, false);
10294
10295  // Add operator candidates that are member functions.
10296  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10297
10298  // Add candidates from ADL.
10299  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10300                                       OpLoc, Args,
10301                                       /*ExplicitTemplateArgs*/ 0,
10302                                       CandidateSet);
10303
10304  // Add builtin operator candidates.
10305  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10306
10307  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10308
10309  // Perform overload resolution.
10310  OverloadCandidateSet::iterator Best;
10311  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10312    case OR_Success: {
10313      // We found a built-in operator or an overloaded operator.
10314      FunctionDecl *FnDecl = Best->Function;
10315
10316      if (FnDecl) {
10317        // We matched an overloaded operator. Build a call to that
10318        // operator.
10319
10320        // Convert the arguments.
10321        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10322          // Best->Access is only meaningful for class members.
10323          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10324
10325          ExprResult Arg1 =
10326            PerformCopyInitialization(
10327              InitializedEntity::InitializeParameter(Context,
10328                                                     FnDecl->getParamDecl(0)),
10329              SourceLocation(), Owned(Args[1]));
10330          if (Arg1.isInvalid())
10331            return ExprError();
10332
10333          ExprResult Arg0 =
10334            PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10335                                                Best->FoundDecl, Method);
10336          if (Arg0.isInvalid())
10337            return ExprError();
10338          Args[0] = Arg0.takeAs<Expr>();
10339          Args[1] = RHS = Arg1.takeAs<Expr>();
10340        } else {
10341          // Convert the arguments.
10342          ExprResult Arg0 = PerformCopyInitialization(
10343            InitializedEntity::InitializeParameter(Context,
10344                                                   FnDecl->getParamDecl(0)),
10345            SourceLocation(), Owned(Args[0]));
10346          if (Arg0.isInvalid())
10347            return ExprError();
10348
10349          ExprResult Arg1 =
10350            PerformCopyInitialization(
10351              InitializedEntity::InitializeParameter(Context,
10352                                                     FnDecl->getParamDecl(1)),
10353              SourceLocation(), Owned(Args[1]));
10354          if (Arg1.isInvalid())
10355            return ExprError();
10356          Args[0] = LHS = Arg0.takeAs<Expr>();
10357          Args[1] = RHS = Arg1.takeAs<Expr>();
10358        }
10359
10360        // Determine the result type.
10361        QualType ResultTy = FnDecl->getResultType();
10362        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10363        ResultTy = ResultTy.getNonLValueExprType(Context);
10364
10365        // Build the actual expression node.
10366        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10367                                                  Best->FoundDecl,
10368                                                  HadMultipleCandidates, OpLoc);
10369        if (FnExpr.isInvalid())
10370          return ExprError();
10371
10372        CXXOperatorCallExpr *TheCall =
10373          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10374                                            Args, ResultTy, VK, OpLoc,
10375                                            FPFeatures.fp_contract);
10376
10377        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10378                                FnDecl))
10379          return ExprError();
10380
10381        ArrayRef<const Expr *> ArgsArray(Args, 2);
10382        // Cut off the implicit 'this'.
10383        if (isa<CXXMethodDecl>(FnDecl))
10384          ArgsArray = ArgsArray.slice(1);
10385        checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10386                  TheCall->getSourceRange(), VariadicDoesNotApply);
10387
10388        return MaybeBindToTemporary(TheCall);
10389      } else {
10390        // We matched a built-in operator. Convert the arguments, then
10391        // break out so that we will build the appropriate built-in
10392        // operator node.
10393        ExprResult ArgsRes0 =
10394          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10395                                    Best->Conversions[0], AA_Passing);
10396        if (ArgsRes0.isInvalid())
10397          return ExprError();
10398        Args[0] = ArgsRes0.take();
10399
10400        ExprResult ArgsRes1 =
10401          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10402                                    Best->Conversions[1], AA_Passing);
10403        if (ArgsRes1.isInvalid())
10404          return ExprError();
10405        Args[1] = ArgsRes1.take();
10406        break;
10407      }
10408    }
10409
10410    case OR_No_Viable_Function: {
10411      // C++ [over.match.oper]p9:
10412      //   If the operator is the operator , [...] and there are no
10413      //   viable functions, then the operator is assumed to be the
10414      //   built-in operator and interpreted according to clause 5.
10415      if (Opc == BO_Comma)
10416        break;
10417
10418      // For class as left operand for assignment or compound assigment
10419      // operator do not fall through to handling in built-in, but report that
10420      // no overloaded assignment operator found
10421      ExprResult Result = ExprError();
10422      if (Args[0]->getType()->isRecordType() &&
10423          Opc >= BO_Assign && Opc <= BO_OrAssign) {
10424        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10425             << BinaryOperator::getOpcodeStr(Opc)
10426             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10427      } else {
10428        // This is an erroneous use of an operator which can be overloaded by
10429        // a non-member function. Check for non-member operators which were
10430        // defined too late to be candidates.
10431        if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10432          // FIXME: Recover by calling the found function.
10433          return ExprError();
10434
10435        // No viable function; try to create a built-in operation, which will
10436        // produce an error. Then, show the non-viable candidates.
10437        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10438      }
10439      assert(Result.isInvalid() &&
10440             "C++ binary operator overloading is missing candidates!");
10441      if (Result.isInvalid())
10442        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10443                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
10444      return Result;
10445    }
10446
10447    case OR_Ambiguous:
10448      Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10449          << BinaryOperator::getOpcodeStr(Opc)
10450          << Args[0]->getType() << Args[1]->getType()
10451          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10452      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10453                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10454      return ExprError();
10455
10456    case OR_Deleted:
10457      if (isImplicitlyDeleted(Best->Function)) {
10458        CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10459        Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10460          << Context.getRecordType(Method->getParent())
10461          << getSpecialMember(Method);
10462
10463        // The user probably meant to call this special member. Just
10464        // explain why it's deleted.
10465        NoteDeletedFunction(Method);
10466        return ExprError();
10467      } else {
10468        Diag(OpLoc, diag::err_ovl_deleted_oper)
10469          << Best->Function->isDeleted()
10470          << BinaryOperator::getOpcodeStr(Opc)
10471          << getDeletedOrUnavailableSuffix(Best->Function)
10472          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10473      }
10474      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10475                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10476      return ExprError();
10477  }
10478
10479  // We matched a built-in operator; build it.
10480  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10481}
10482
10483ExprResult
10484Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10485                                         SourceLocation RLoc,
10486                                         Expr *Base, Expr *Idx) {
10487  Expr *Args[2] = { Base, Idx };
10488  DeclarationName OpName =
10489      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10490
10491  // If either side is type-dependent, create an appropriate dependent
10492  // expression.
10493  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10494
10495    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10496    // CHECKME: no 'operator' keyword?
10497    DeclarationNameInfo OpNameInfo(OpName, LLoc);
10498    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10499    UnresolvedLookupExpr *Fn
10500      = UnresolvedLookupExpr::Create(Context, NamingClass,
10501                                     NestedNameSpecifierLoc(), OpNameInfo,
10502                                     /*ADL*/ true, /*Overloaded*/ false,
10503                                     UnresolvedSetIterator(),
10504                                     UnresolvedSetIterator());
10505    // Can't add any actual overloads yet
10506
10507    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10508                                                   Args,
10509                                                   Context.DependentTy,
10510                                                   VK_RValue,
10511                                                   RLoc, false));
10512  }
10513
10514  // Handle placeholders on both operands.
10515  if (checkPlaceholderForOverload(*this, Args[0]))
10516    return ExprError();
10517  if (checkPlaceholderForOverload(*this, Args[1]))
10518    return ExprError();
10519
10520  // Build an empty overload set.
10521  OverloadCandidateSet CandidateSet(LLoc);
10522
10523  // Subscript can only be overloaded as a member function.
10524
10525  // Add operator candidates that are member functions.
10526  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10527
10528  // Add builtin operator candidates.
10529  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10530
10531  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10532
10533  // Perform overload resolution.
10534  OverloadCandidateSet::iterator Best;
10535  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10536    case OR_Success: {
10537      // We found a built-in operator or an overloaded operator.
10538      FunctionDecl *FnDecl = Best->Function;
10539
10540      if (FnDecl) {
10541        // We matched an overloaded operator. Build a call to that
10542        // operator.
10543
10544        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10545
10546        // Convert the arguments.
10547        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10548        ExprResult Arg0 =
10549          PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10550                                              Best->FoundDecl, Method);
10551        if (Arg0.isInvalid())
10552          return ExprError();
10553        Args[0] = Arg0.take();
10554
10555        // Convert the arguments.
10556        ExprResult InputInit
10557          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10558                                                      Context,
10559                                                      FnDecl->getParamDecl(0)),
10560                                      SourceLocation(),
10561                                      Owned(Args[1]));
10562        if (InputInit.isInvalid())
10563          return ExprError();
10564
10565        Args[1] = InputInit.takeAs<Expr>();
10566
10567        // Determine the result type
10568        QualType ResultTy = FnDecl->getResultType();
10569        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10570        ResultTy = ResultTy.getNonLValueExprType(Context);
10571
10572        // Build the actual expression node.
10573        DeclarationNameInfo OpLocInfo(OpName, LLoc);
10574        OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10575        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10576                                                  Best->FoundDecl,
10577                                                  HadMultipleCandidates,
10578                                                  OpLocInfo.getLoc(),
10579                                                  OpLocInfo.getInfo());
10580        if (FnExpr.isInvalid())
10581          return ExprError();
10582
10583        CXXOperatorCallExpr *TheCall =
10584          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10585                                            FnExpr.take(), Args,
10586                                            ResultTy, VK, RLoc,
10587                                            false);
10588
10589        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10590                                FnDecl))
10591          return ExprError();
10592
10593        return MaybeBindToTemporary(TheCall);
10594      } else {
10595        // We matched a built-in operator. Convert the arguments, then
10596        // break out so that we will build the appropriate built-in
10597        // operator node.
10598        ExprResult ArgsRes0 =
10599          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10600                                    Best->Conversions[0], AA_Passing);
10601        if (ArgsRes0.isInvalid())
10602          return ExprError();
10603        Args[0] = ArgsRes0.take();
10604
10605        ExprResult ArgsRes1 =
10606          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10607                                    Best->Conversions[1], AA_Passing);
10608        if (ArgsRes1.isInvalid())
10609          return ExprError();
10610        Args[1] = ArgsRes1.take();
10611
10612        break;
10613      }
10614    }
10615
10616    case OR_No_Viable_Function: {
10617      if (CandidateSet.empty())
10618        Diag(LLoc, diag::err_ovl_no_oper)
10619          << Args[0]->getType() << /*subscript*/ 0
10620          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10621      else
10622        Diag(LLoc, diag::err_ovl_no_viable_subscript)
10623          << Args[0]->getType()
10624          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10625      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10626                                  "[]", LLoc);
10627      return ExprError();
10628    }
10629
10630    case OR_Ambiguous:
10631      Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10632          << "[]"
10633          << Args[0]->getType() << Args[1]->getType()
10634          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10635      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10636                                  "[]", LLoc);
10637      return ExprError();
10638
10639    case OR_Deleted:
10640      Diag(LLoc, diag::err_ovl_deleted_oper)
10641        << Best->Function->isDeleted() << "[]"
10642        << getDeletedOrUnavailableSuffix(Best->Function)
10643        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10644      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10645                                  "[]", LLoc);
10646      return ExprError();
10647    }
10648
10649  // We matched a built-in operator; build it.
10650  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10651}
10652
10653/// BuildCallToMemberFunction - Build a call to a member
10654/// function. MemExpr is the expression that refers to the member
10655/// function (and includes the object parameter), Args/NumArgs are the
10656/// arguments to the function call (not including the object
10657/// parameter). The caller needs to validate that the member
10658/// expression refers to a non-static member function or an overloaded
10659/// member function.
10660ExprResult
10661Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10662                                SourceLocation LParenLoc, Expr **Args,
10663                                unsigned NumArgs, SourceLocation RParenLoc) {
10664  assert(MemExprE->getType() == Context.BoundMemberTy ||
10665         MemExprE->getType() == Context.OverloadTy);
10666
10667  // Dig out the member expression. This holds both the object
10668  // argument and the member function we're referring to.
10669  Expr *NakedMemExpr = MemExprE->IgnoreParens();
10670
10671  // Determine whether this is a call to a pointer-to-member function.
10672  if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10673    assert(op->getType() == Context.BoundMemberTy);
10674    assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10675
10676    QualType fnType =
10677      op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10678
10679    const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10680    QualType resultType = proto->getCallResultType(Context);
10681    ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10682
10683    // Check that the object type isn't more qualified than the
10684    // member function we're calling.
10685    Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10686
10687    QualType objectType = op->getLHS()->getType();
10688    if (op->getOpcode() == BO_PtrMemI)
10689      objectType = objectType->castAs<PointerType>()->getPointeeType();
10690    Qualifiers objectQuals = objectType.getQualifiers();
10691
10692    Qualifiers difference = objectQuals - funcQuals;
10693    difference.removeObjCGCAttr();
10694    difference.removeAddressSpace();
10695    if (difference) {
10696      std::string qualsString = difference.getAsString();
10697      Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10698        << fnType.getUnqualifiedType()
10699        << qualsString
10700        << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10701    }
10702
10703    CXXMemberCallExpr *call
10704      = new (Context) CXXMemberCallExpr(Context, MemExprE,
10705                                        llvm::makeArrayRef(Args, NumArgs),
10706                                        resultType, valueKind, RParenLoc);
10707
10708    if (CheckCallReturnType(proto->getResultType(),
10709                            op->getRHS()->getLocStart(),
10710                            call, 0))
10711      return ExprError();
10712
10713    if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10714      return ExprError();
10715
10716    return MaybeBindToTemporary(call);
10717  }
10718
10719  UnbridgedCastsSet UnbridgedCasts;
10720  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10721    return ExprError();
10722
10723  MemberExpr *MemExpr;
10724  CXXMethodDecl *Method = 0;
10725  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
10726  NestedNameSpecifier *Qualifier = 0;
10727  if (isa<MemberExpr>(NakedMemExpr)) {
10728    MemExpr = cast<MemberExpr>(NakedMemExpr);
10729    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
10730    FoundDecl = MemExpr->getFoundDecl();
10731    Qualifier = MemExpr->getQualifier();
10732    UnbridgedCasts.restore();
10733  } else {
10734    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
10735    Qualifier = UnresExpr->getQualifier();
10736
10737    QualType ObjectType = UnresExpr->getBaseType();
10738    Expr::Classification ObjectClassification
10739      = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10740                            : UnresExpr->getBase()->Classify(Context);
10741
10742    // Add overload candidates
10743    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
10744
10745    // FIXME: avoid copy.
10746    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10747    if (UnresExpr->hasExplicitTemplateArgs()) {
10748      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10749      TemplateArgs = &TemplateArgsBuffer;
10750    }
10751
10752    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10753           E = UnresExpr->decls_end(); I != E; ++I) {
10754
10755      NamedDecl *Func = *I;
10756      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10757      if (isa<UsingShadowDecl>(Func))
10758        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10759
10760
10761      // Microsoft supports direct constructor calls.
10762      if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
10763        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10764                             llvm::makeArrayRef(Args, NumArgs), CandidateSet);
10765      } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
10766        // If explicit template arguments were provided, we can't call a
10767        // non-template member function.
10768        if (TemplateArgs)
10769          continue;
10770
10771        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
10772                           ObjectClassification,
10773                           llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10774                           /*SuppressUserConversions=*/false);
10775      } else {
10776        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
10777                                   I.getPair(), ActingDC, TemplateArgs,
10778                                   ObjectType,  ObjectClassification,
10779                                   llvm::makeArrayRef(Args, NumArgs),
10780                                   CandidateSet,
10781                                   /*SuppressUsedConversions=*/false);
10782      }
10783    }
10784
10785    DeclarationName DeclName = UnresExpr->getMemberName();
10786
10787    UnbridgedCasts.restore();
10788
10789    OverloadCandidateSet::iterator Best;
10790    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
10791                                            Best)) {
10792    case OR_Success:
10793      Method = cast<CXXMethodDecl>(Best->Function);
10794      MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
10795      FoundDecl = Best->FoundDecl;
10796      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
10797      DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
10798      break;
10799
10800    case OR_No_Viable_Function:
10801      Diag(UnresExpr->getMemberLoc(),
10802           diag::err_ovl_no_viable_member_function_in_call)
10803        << DeclName << MemExprE->getSourceRange();
10804      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10805                                  llvm::makeArrayRef(Args, NumArgs));
10806      // FIXME: Leaking incoming expressions!
10807      return ExprError();
10808
10809    case OR_Ambiguous:
10810      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
10811        << DeclName << MemExprE->getSourceRange();
10812      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10813                                  llvm::makeArrayRef(Args, NumArgs));
10814      // FIXME: Leaking incoming expressions!
10815      return ExprError();
10816
10817    case OR_Deleted:
10818      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
10819        << Best->Function->isDeleted()
10820        << DeclName
10821        << getDeletedOrUnavailableSuffix(Best->Function)
10822        << MemExprE->getSourceRange();
10823      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10824                                  llvm::makeArrayRef(Args, NumArgs));
10825      // FIXME: Leaking incoming expressions!
10826      return ExprError();
10827    }
10828
10829    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
10830
10831    // If overload resolution picked a static member, build a
10832    // non-member call based on that function.
10833    if (Method->isStatic()) {
10834      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10835                                   Args, NumArgs, RParenLoc);
10836    }
10837
10838    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
10839  }
10840
10841  QualType ResultType = Method->getResultType();
10842  ExprValueKind VK = Expr::getValueKindForType(ResultType);
10843  ResultType = ResultType.getNonLValueExprType(Context);
10844
10845  assert(Method && "Member call to something that isn't a method?");
10846  CXXMemberCallExpr *TheCall =
10847    new (Context) CXXMemberCallExpr(Context, MemExprE,
10848                                    llvm::makeArrayRef(Args, NumArgs),
10849                                    ResultType, VK, RParenLoc);
10850
10851  // Check for a valid return type.
10852  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
10853                          TheCall, Method))
10854    return ExprError();
10855
10856  // Convert the object argument (for a non-static member function call).
10857  // We only need to do this if there was actually an overload; otherwise
10858  // it was done at lookup.
10859  if (!Method->isStatic()) {
10860    ExprResult ObjectArg =
10861      PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10862                                          FoundDecl, Method);
10863    if (ObjectArg.isInvalid())
10864      return ExprError();
10865    MemExpr->setBase(ObjectArg.take());
10866  }
10867
10868  // Convert the rest of the arguments
10869  const FunctionProtoType *Proto =
10870    Method->getType()->getAs<FunctionProtoType>();
10871  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
10872                              RParenLoc))
10873    return ExprError();
10874
10875  DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10876
10877  if (CheckFunctionCall(Method, TheCall, Proto))
10878    return ExprError();
10879
10880  if ((isa<CXXConstructorDecl>(CurContext) ||
10881       isa<CXXDestructorDecl>(CurContext)) &&
10882      TheCall->getMethodDecl()->isPure()) {
10883    const CXXMethodDecl *MD = TheCall->getMethodDecl();
10884
10885    if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
10886      Diag(MemExpr->getLocStart(),
10887           diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10888        << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10889        << MD->getParent()->getDeclName();
10890
10891      Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
10892    }
10893  }
10894  return MaybeBindToTemporary(TheCall);
10895}
10896
10897/// BuildCallToObjectOfClassType - Build a call to an object of class
10898/// type (C++ [over.call.object]), which can end up invoking an
10899/// overloaded function call operator (@c operator()) or performing a
10900/// user-defined conversion on the object argument.
10901ExprResult
10902Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
10903                                   SourceLocation LParenLoc,
10904                                   Expr **Args, unsigned NumArgs,
10905                                   SourceLocation RParenLoc) {
10906  if (checkPlaceholderForOverload(*this, Obj))
10907    return ExprError();
10908  ExprResult Object = Owned(Obj);
10909
10910  UnbridgedCastsSet UnbridgedCasts;
10911  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10912    return ExprError();
10913
10914  assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10915  const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
10916
10917  // C++ [over.call.object]p1:
10918  //  If the primary-expression E in the function call syntax
10919  //  evaluates to a class object of type "cv T", then the set of
10920  //  candidate functions includes at least the function call
10921  //  operators of T. The function call operators of T are obtained by
10922  //  ordinary lookup of the name operator() in the context of
10923  //  (E).operator().
10924  OverloadCandidateSet CandidateSet(LParenLoc);
10925  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
10926
10927  if (RequireCompleteType(LParenLoc, Object.get()->getType(),
10928                          diag::err_incomplete_object_call, Object.get()))
10929    return true;
10930
10931  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10932  LookupQualifiedName(R, Record->getDecl());
10933  R.suppressDiagnostics();
10934
10935  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10936       Oper != OperEnd; ++Oper) {
10937    AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10938                       Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
10939                       /*SuppressUserConversions=*/ false);
10940  }
10941
10942  // C++ [over.call.object]p2:
10943  //   In addition, for each (non-explicit in C++0x) conversion function
10944  //   declared in T of the form
10945  //
10946  //        operator conversion-type-id () cv-qualifier;
10947  //
10948  //   where cv-qualifier is the same cv-qualification as, or a
10949  //   greater cv-qualification than, cv, and where conversion-type-id
10950  //   denotes the type "pointer to function of (P1,...,Pn) returning
10951  //   R", or the type "reference to pointer to function of
10952  //   (P1,...,Pn) returning R", or the type "reference to function
10953  //   of (P1,...,Pn) returning R", a surrogate call function [...]
10954  //   is also considered as a candidate function. Similarly,
10955  //   surrogate call functions are added to the set of candidate
10956  //   functions for each conversion function declared in an
10957  //   accessible base class provided the function is not hidden
10958  //   within T by another intervening declaration.
10959  std::pair<CXXRecordDecl::conversion_iterator,
10960            CXXRecordDecl::conversion_iterator> Conversions
10961    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
10962  for (CXXRecordDecl::conversion_iterator
10963         I = Conversions.first, E = Conversions.second; I != E; ++I) {
10964    NamedDecl *D = *I;
10965    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10966    if (isa<UsingShadowDecl>(D))
10967      D = cast<UsingShadowDecl>(D)->getTargetDecl();
10968
10969    // Skip over templated conversion functions; they aren't
10970    // surrogates.
10971    if (isa<FunctionTemplateDecl>(D))
10972      continue;
10973
10974    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
10975    if (!Conv->isExplicit()) {
10976      // Strip the reference type (if any) and then the pointer type (if
10977      // any) to get down to what might be a function type.
10978      QualType ConvType = Conv->getConversionType().getNonReferenceType();
10979      if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10980        ConvType = ConvPtrType->getPointeeType();
10981
10982      if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10983      {
10984        AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10985                              Object.get(), llvm::makeArrayRef(Args, NumArgs),
10986                              CandidateSet);
10987      }
10988    }
10989  }
10990
10991  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10992
10993  // Perform overload resolution.
10994  OverloadCandidateSet::iterator Best;
10995  switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
10996                             Best)) {
10997  case OR_Success:
10998    // Overload resolution succeeded; we'll build the appropriate call
10999    // below.
11000    break;
11001
11002  case OR_No_Viable_Function:
11003    if (CandidateSet.empty())
11004      Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11005        << Object.get()->getType() << /*call*/ 1
11006        << Object.get()->getSourceRange();
11007    else
11008      Diag(Object.get()->getLocStart(),
11009           diag::err_ovl_no_viable_object_call)
11010        << Object.get()->getType() << Object.get()->getSourceRange();
11011    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11012                                llvm::makeArrayRef(Args, NumArgs));
11013    break;
11014
11015  case OR_Ambiguous:
11016    Diag(Object.get()->getLocStart(),
11017         diag::err_ovl_ambiguous_object_call)
11018      << Object.get()->getType() << Object.get()->getSourceRange();
11019    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
11020                                llvm::makeArrayRef(Args, NumArgs));
11021    break;
11022
11023  case OR_Deleted:
11024    Diag(Object.get()->getLocStart(),
11025         diag::err_ovl_deleted_object_call)
11026      << Best->Function->isDeleted()
11027      << Object.get()->getType()
11028      << getDeletedOrUnavailableSuffix(Best->Function)
11029      << Object.get()->getSourceRange();
11030    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11031                                llvm::makeArrayRef(Args, NumArgs));
11032    break;
11033  }
11034
11035  if (Best == CandidateSet.end())
11036    return true;
11037
11038  UnbridgedCasts.restore();
11039
11040  if (Best->Function == 0) {
11041    // Since there is no function declaration, this is one of the
11042    // surrogate candidates. Dig out the conversion function.
11043    CXXConversionDecl *Conv
11044      = cast<CXXConversionDecl>(
11045                         Best->Conversions[0].UserDefined.ConversionFunction);
11046
11047    CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11048    DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
11049
11050    // We selected one of the surrogate functions that converts the
11051    // object parameter to a function pointer. Perform the conversion
11052    // on the object argument, then let ActOnCallExpr finish the job.
11053
11054    // Create an implicit member expr to refer to the conversion operator.
11055    // and then call it.
11056    ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11057                                             Conv, HadMultipleCandidates);
11058    if (Call.isInvalid())
11059      return ExprError();
11060    // Record usage of conversion in an implicit cast.
11061    Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11062                                          CK_UserDefinedConversion,
11063                                          Call.get(), 0, VK_RValue));
11064
11065    return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
11066                         RParenLoc);
11067  }
11068
11069  CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11070
11071  // We found an overloaded operator(). Build a CXXOperatorCallExpr
11072  // that calls this method, using Object for the implicit object
11073  // parameter and passing along the remaining arguments.
11074  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11075
11076  // An error diagnostic has already been printed when parsing the declaration.
11077  if (Method->isInvalidDecl())
11078    return ExprError();
11079
11080  const FunctionProtoType *Proto =
11081    Method->getType()->getAs<FunctionProtoType>();
11082
11083  unsigned NumArgsInProto = Proto->getNumArgs();
11084  unsigned NumArgsToCheck = NumArgs;
11085
11086  // Build the full argument list for the method call (the
11087  // implicit object parameter is placed at the beginning of the
11088  // list).
11089  Expr **MethodArgs;
11090  if (NumArgs < NumArgsInProto) {
11091    NumArgsToCheck = NumArgsInProto;
11092    MethodArgs = new Expr*[NumArgsInProto + 1];
11093  } else {
11094    MethodArgs = new Expr*[NumArgs + 1];
11095  }
11096  MethodArgs[0] = Object.get();
11097  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11098    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
11099
11100  DeclarationNameInfo OpLocInfo(
11101               Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11102  OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11103  ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11104                                           HadMultipleCandidates,
11105                                           OpLocInfo.getLoc(),
11106                                           OpLocInfo.getInfo());
11107  if (NewFn.isInvalid())
11108    return true;
11109
11110  // Once we've built TheCall, all of the expressions are properly
11111  // owned.
11112  QualType ResultTy = Method->getResultType();
11113  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11114  ResultTy = ResultTy.getNonLValueExprType(Context);
11115
11116  CXXOperatorCallExpr *TheCall =
11117    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11118                                      llvm::makeArrayRef(MethodArgs, NumArgs+1),
11119                                      ResultTy, VK, RParenLoc, false);
11120  delete [] MethodArgs;
11121
11122  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
11123                          Method))
11124    return true;
11125
11126  // We may have default arguments. If so, we need to allocate more
11127  // slots in the call for them.
11128  if (NumArgs < NumArgsInProto)
11129    TheCall->setNumArgs(Context, NumArgsInProto + 1);
11130  else if (NumArgs > NumArgsInProto)
11131    NumArgsToCheck = NumArgsInProto;
11132
11133  bool IsError = false;
11134
11135  // Initialize the implicit object parameter.
11136  ExprResult ObjRes =
11137    PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11138                                        Best->FoundDecl, Method);
11139  if (ObjRes.isInvalid())
11140    IsError = true;
11141  else
11142    Object = ObjRes;
11143  TheCall->setArg(0, Object.take());
11144
11145  // Check the argument types.
11146  for (unsigned i = 0; i != NumArgsToCheck; i++) {
11147    Expr *Arg;
11148    if (i < NumArgs) {
11149      Arg = Args[i];
11150
11151      // Pass the argument.
11152
11153      ExprResult InputInit
11154        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11155                                                    Context,
11156                                                    Method->getParamDecl(i)),
11157                                    SourceLocation(), Arg);
11158
11159      IsError |= InputInit.isInvalid();
11160      Arg = InputInit.takeAs<Expr>();
11161    } else {
11162      ExprResult DefArg
11163        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11164      if (DefArg.isInvalid()) {
11165        IsError = true;
11166        break;
11167      }
11168
11169      Arg = DefArg.takeAs<Expr>();
11170    }
11171
11172    TheCall->setArg(i + 1, Arg);
11173  }
11174
11175  // If this is a variadic call, handle args passed through "...".
11176  if (Proto->isVariadic()) {
11177    // Promote the arguments (C99 6.5.2.2p7).
11178    for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
11179      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11180      IsError |= Arg.isInvalid();
11181      TheCall->setArg(i + 1, Arg.take());
11182    }
11183  }
11184
11185  if (IsError) return true;
11186
11187  DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11188
11189  if (CheckFunctionCall(Method, TheCall, Proto))
11190    return true;
11191
11192  return MaybeBindToTemporary(TheCall);
11193}
11194
11195/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11196///  (if one exists), where @c Base is an expression of class type and
11197/// @c Member is the name of the member we're trying to find.
11198ExprResult
11199Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
11200  assert(Base->getType()->isRecordType() &&
11201         "left-hand side must have class type");
11202
11203  if (checkPlaceholderForOverload(*this, Base))
11204    return ExprError();
11205
11206  SourceLocation Loc = Base->getExprLoc();
11207
11208  // C++ [over.ref]p1:
11209  //
11210  //   [...] An expression x->m is interpreted as (x.operator->())->m
11211  //   for a class object x of type T if T::operator->() exists and if
11212  //   the operator is selected as the best match function by the
11213  //   overload resolution mechanism (13.3).
11214  DeclarationName OpName =
11215    Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11216  OverloadCandidateSet CandidateSet(Loc);
11217  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11218
11219  if (RequireCompleteType(Loc, Base->getType(),
11220                          diag::err_typecheck_incomplete_tag, Base))
11221    return ExprError();
11222
11223  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11224  LookupQualifiedName(R, BaseRecord->getDecl());
11225  R.suppressDiagnostics();
11226
11227  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11228       Oper != OperEnd; ++Oper) {
11229    AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11230                       0, 0, CandidateSet, /*SuppressUserConversions=*/false);
11231  }
11232
11233  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11234
11235  // Perform overload resolution.
11236  OverloadCandidateSet::iterator Best;
11237  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11238  case OR_Success:
11239    // Overload resolution succeeded; we'll build the call below.
11240    break;
11241
11242  case OR_No_Viable_Function:
11243    if (CandidateSet.empty())
11244      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11245        << Base->getType() << Base->getSourceRange();
11246    else
11247      Diag(OpLoc, diag::err_ovl_no_viable_oper)
11248        << "operator->" << Base->getSourceRange();
11249    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11250    return ExprError();
11251
11252  case OR_Ambiguous:
11253    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11254      << "->" << Base->getType() << Base->getSourceRange();
11255    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11256    return ExprError();
11257
11258  case OR_Deleted:
11259    Diag(OpLoc,  diag::err_ovl_deleted_oper)
11260      << Best->Function->isDeleted()
11261      << "->"
11262      << getDeletedOrUnavailableSuffix(Best->Function)
11263      << Base->getSourceRange();
11264    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11265    return ExprError();
11266  }
11267
11268  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11269
11270  // Convert the object parameter.
11271  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11272  ExprResult BaseResult =
11273    PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11274                                        Best->FoundDecl, Method);
11275  if (BaseResult.isInvalid())
11276    return ExprError();
11277  Base = BaseResult.take();
11278
11279  // Build the operator call.
11280  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11281                                            HadMultipleCandidates, OpLoc);
11282  if (FnExpr.isInvalid())
11283    return ExprError();
11284
11285  QualType ResultTy = Method->getResultType();
11286  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11287  ResultTy = ResultTy.getNonLValueExprType(Context);
11288  CXXOperatorCallExpr *TheCall =
11289    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11290                                      Base, ResultTy, VK, OpLoc, false);
11291
11292  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11293                          Method))
11294          return ExprError();
11295
11296  return MaybeBindToTemporary(TheCall);
11297}
11298
11299/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11300/// a literal operator described by the provided lookup results.
11301ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11302                                          DeclarationNameInfo &SuffixInfo,
11303                                          ArrayRef<Expr*> Args,
11304                                          SourceLocation LitEndLoc,
11305                                       TemplateArgumentListInfo *TemplateArgs) {
11306  SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11307
11308  OverloadCandidateSet CandidateSet(UDSuffixLoc);
11309  AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11310                        TemplateArgs);
11311
11312  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11313
11314  // Perform overload resolution. This will usually be trivial, but might need
11315  // to perform substitutions for a literal operator template.
11316  OverloadCandidateSet::iterator Best;
11317  switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11318  case OR_Success:
11319  case OR_Deleted:
11320    break;
11321
11322  case OR_No_Viable_Function:
11323    Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11324      << R.getLookupName();
11325    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11326    return ExprError();
11327
11328  case OR_Ambiguous:
11329    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11330    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11331    return ExprError();
11332  }
11333
11334  FunctionDecl *FD = Best->Function;
11335  ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11336                                        HadMultipleCandidates,
11337                                        SuffixInfo.getLoc(),
11338                                        SuffixInfo.getInfo());
11339  if (Fn.isInvalid())
11340    return true;
11341
11342  // Check the argument types. This should almost always be a no-op, except
11343  // that array-to-pointer decay is applied to string literals.
11344  Expr *ConvArgs[2];
11345  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11346    ExprResult InputInit = PerformCopyInitialization(
11347      InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11348      SourceLocation(), Args[ArgIdx]);
11349    if (InputInit.isInvalid())
11350      return true;
11351    ConvArgs[ArgIdx] = InputInit.take();
11352  }
11353
11354  QualType ResultTy = FD->getResultType();
11355  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11356  ResultTy = ResultTy.getNonLValueExprType(Context);
11357
11358  UserDefinedLiteral *UDL =
11359    new (Context) UserDefinedLiteral(Context, Fn.take(),
11360                                     llvm::makeArrayRef(ConvArgs, Args.size()),
11361                                     ResultTy, VK, LitEndLoc, UDSuffixLoc);
11362
11363  if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11364    return ExprError();
11365
11366  if (CheckFunctionCall(FD, UDL, NULL))
11367    return ExprError();
11368
11369  return MaybeBindToTemporary(UDL);
11370}
11371
11372/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11373/// given LookupResult is non-empty, it is assumed to describe a member which
11374/// will be invoked. Otherwise, the function will be found via argument
11375/// dependent lookup.
11376/// CallExpr is set to a valid expression and FRS_Success returned on success,
11377/// otherwise CallExpr is set to ExprError() and some non-success value
11378/// is returned.
11379Sema::ForRangeStatus
11380Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11381                                SourceLocation RangeLoc, VarDecl *Decl,
11382                                BeginEndFunction BEF,
11383                                const DeclarationNameInfo &NameInfo,
11384                                LookupResult &MemberLookup,
11385                                OverloadCandidateSet *CandidateSet,
11386                                Expr *Range, ExprResult *CallExpr) {
11387  CandidateSet->clear();
11388  if (!MemberLookup.empty()) {
11389    ExprResult MemberRef =
11390        BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11391                                 /*IsPtr=*/false, CXXScopeSpec(),
11392                                 /*TemplateKWLoc=*/SourceLocation(),
11393                                 /*FirstQualifierInScope=*/0,
11394                                 MemberLookup,
11395                                 /*TemplateArgs=*/0);
11396    if (MemberRef.isInvalid()) {
11397      *CallExpr = ExprError();
11398      Diag(Range->getLocStart(), diag::note_in_for_range)
11399          << RangeLoc << BEF << Range->getType();
11400      return FRS_DiagnosticIssued;
11401    }
11402    *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11403    if (CallExpr->isInvalid()) {
11404      *CallExpr = ExprError();
11405      Diag(Range->getLocStart(), diag::note_in_for_range)
11406          << RangeLoc << BEF << Range->getType();
11407      return FRS_DiagnosticIssued;
11408    }
11409  } else {
11410    UnresolvedSet<0> FoundNames;
11411    UnresolvedLookupExpr *Fn =
11412      UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11413                                   NestedNameSpecifierLoc(), NameInfo,
11414                                   /*NeedsADL=*/true, /*Overloaded=*/false,
11415                                   FoundNames.begin(), FoundNames.end());
11416
11417    bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11418                                                    CandidateSet, CallExpr);
11419    if (CandidateSet->empty() || CandidateSetError) {
11420      *CallExpr = ExprError();
11421      return FRS_NoViableFunction;
11422    }
11423    OverloadCandidateSet::iterator Best;
11424    OverloadingResult OverloadResult =
11425        CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11426
11427    if (OverloadResult == OR_No_Viable_Function) {
11428      *CallExpr = ExprError();
11429      return FRS_NoViableFunction;
11430    }
11431    *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11432                                         Loc, 0, CandidateSet, &Best,
11433                                         OverloadResult,
11434                                         /*AllowTypoCorrection=*/false);
11435    if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11436      *CallExpr = ExprError();
11437      Diag(Range->getLocStart(), diag::note_in_for_range)
11438          << RangeLoc << BEF << Range->getType();
11439      return FRS_DiagnosticIssued;
11440    }
11441  }
11442  return FRS_Success;
11443}
11444
11445
11446/// FixOverloadedFunctionReference - E is an expression that refers to
11447/// a C++ overloaded function (possibly with some parentheses and
11448/// perhaps a '&' around it). We have resolved the overloaded function
11449/// to the function declaration Fn, so patch up the expression E to
11450/// refer (possibly indirectly) to Fn. Returns the new expr.
11451Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11452                                           FunctionDecl *Fn) {
11453  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11454    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11455                                                   Found, Fn);
11456    if (SubExpr == PE->getSubExpr())
11457      return PE;
11458
11459    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11460  }
11461
11462  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11463    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11464                                                   Found, Fn);
11465    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11466                               SubExpr->getType()) &&
11467           "Implicit cast type cannot be determined from overload");
11468    assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11469    if (SubExpr == ICE->getSubExpr())
11470      return ICE;
11471
11472    return ImplicitCastExpr::Create(Context, ICE->getType(),
11473                                    ICE->getCastKind(),
11474                                    SubExpr, 0,
11475                                    ICE->getValueKind());
11476  }
11477
11478  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11479    assert(UnOp->getOpcode() == UO_AddrOf &&
11480           "Can only take the address of an overloaded function");
11481    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11482      if (Method->isStatic()) {
11483        // Do nothing: static member functions aren't any different
11484        // from non-member functions.
11485      } else {
11486        // Fix the sub expression, which really has to be an
11487        // UnresolvedLookupExpr holding an overloaded member function
11488        // or template.
11489        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11490                                                       Found, Fn);
11491        if (SubExpr == UnOp->getSubExpr())
11492          return UnOp;
11493
11494        assert(isa<DeclRefExpr>(SubExpr)
11495               && "fixed to something other than a decl ref");
11496        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11497               && "fixed to a member ref with no nested name qualifier");
11498
11499        // We have taken the address of a pointer to member
11500        // function. Perform the computation here so that we get the
11501        // appropriate pointer to member type.
11502        QualType ClassType
11503          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11504        QualType MemPtrType
11505          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11506
11507        return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11508                                           VK_RValue, OK_Ordinary,
11509                                           UnOp->getOperatorLoc());
11510      }
11511    }
11512    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11513                                                   Found, Fn);
11514    if (SubExpr == UnOp->getSubExpr())
11515      return UnOp;
11516
11517    return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11518                                     Context.getPointerType(SubExpr->getType()),
11519                                       VK_RValue, OK_Ordinary,
11520                                       UnOp->getOperatorLoc());
11521  }
11522
11523  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11524    // FIXME: avoid copy.
11525    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11526    if (ULE->hasExplicitTemplateArgs()) {
11527      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11528      TemplateArgs = &TemplateArgsBuffer;
11529    }
11530
11531    DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11532                                           ULE->getQualifierLoc(),
11533                                           ULE->getTemplateKeywordLoc(),
11534                                           Fn,
11535                                           /*enclosing*/ false, // FIXME?
11536                                           ULE->getNameLoc(),
11537                                           Fn->getType(),
11538                                           VK_LValue,
11539                                           Found.getDecl(),
11540                                           TemplateArgs);
11541    MarkDeclRefReferenced(DRE);
11542    DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11543    return DRE;
11544  }
11545
11546  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11547    // FIXME: avoid copy.
11548    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11549    if (MemExpr->hasExplicitTemplateArgs()) {
11550      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11551      TemplateArgs = &TemplateArgsBuffer;
11552    }
11553
11554    Expr *Base;
11555
11556    // If we're filling in a static method where we used to have an
11557    // implicit member access, rewrite to a simple decl ref.
11558    if (MemExpr->isImplicitAccess()) {
11559      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11560        DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11561                                               MemExpr->getQualifierLoc(),
11562                                               MemExpr->getTemplateKeywordLoc(),
11563                                               Fn,
11564                                               /*enclosing*/ false,
11565                                               MemExpr->getMemberLoc(),
11566                                               Fn->getType(),
11567                                               VK_LValue,
11568                                               Found.getDecl(),
11569                                               TemplateArgs);
11570        MarkDeclRefReferenced(DRE);
11571        DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11572        return DRE;
11573      } else {
11574        SourceLocation Loc = MemExpr->getMemberLoc();
11575        if (MemExpr->getQualifier())
11576          Loc = MemExpr->getQualifierLoc().getBeginLoc();
11577        CheckCXXThisCapture(Loc);
11578        Base = new (Context) CXXThisExpr(Loc,
11579                                         MemExpr->getBaseType(),
11580                                         /*isImplicit=*/true);
11581      }
11582    } else
11583      Base = MemExpr->getBase();
11584
11585    ExprValueKind valueKind;
11586    QualType type;
11587    if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11588      valueKind = VK_LValue;
11589      type = Fn->getType();
11590    } else {
11591      valueKind = VK_RValue;
11592      type = Context.BoundMemberTy;
11593    }
11594
11595    MemberExpr *ME = MemberExpr::Create(Context, Base,
11596                                        MemExpr->isArrow(),
11597                                        MemExpr->getQualifierLoc(),
11598                                        MemExpr->getTemplateKeywordLoc(),
11599                                        Fn,
11600                                        Found,
11601                                        MemExpr->getMemberNameInfo(),
11602                                        TemplateArgs,
11603                                        type, valueKind, OK_Ordinary);
11604    ME->setHadMultipleCandidates(true);
11605    MarkMemberReferenced(ME);
11606    return ME;
11607  }
11608
11609  llvm_unreachable("Invalid reference to overloaded function");
11610}
11611
11612ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11613                                                DeclAccessPair Found,
11614                                                FunctionDecl *Fn) {
11615  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11616}
11617
11618} // end namespace clang
11619