SemaOverload.cpp revision 7acc5a64822093ec746748efcdabb162bd1b8560
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/Overload.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/AST/TypeOrdering.h"
22#include "clang/Basic/Diagnostic.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
30#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallString.h"
34#include <algorithm>
35
36namespace clang {
37using namespace sema;
38
39/// A convenience routine for creating a decayed reference to a function.
40static ExprResult
41CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
42                      bool HadMultipleCandidates,
43                      SourceLocation Loc = SourceLocation(),
44                      const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
45  if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
46    return ExprError();
47
48  DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
49                                                 VK_LValue, Loc, LocInfo);
50  if (HadMultipleCandidates)
51    DRE->setHadMultipleCandidates(true);
52
53  S.MarkDeclRefReferenced(DRE);
54
55  ExprResult E = S.Owned(DRE);
56  E = S.DefaultFunctionArrayConversion(E.take());
57  if (E.isInvalid())
58    return ExprError();
59  return E;
60}
61
62static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
63                                 bool InOverloadResolution,
64                                 StandardConversionSequence &SCS,
65                                 bool CStyle,
66                                 bool AllowObjCWritebackConversion);
67
68static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
69                                                 QualType &ToType,
70                                                 bool InOverloadResolution,
71                                                 StandardConversionSequence &SCS,
72                                                 bool CStyle);
73static OverloadingResult
74IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
75                        UserDefinedConversionSequence& User,
76                        OverloadCandidateSet& Conversions,
77                        bool AllowExplicit);
78
79
80static ImplicitConversionSequence::CompareKind
81CompareStandardConversionSequences(Sema &S,
82                                   const StandardConversionSequence& SCS1,
83                                   const StandardConversionSequence& SCS2);
84
85static ImplicitConversionSequence::CompareKind
86CompareQualificationConversions(Sema &S,
87                                const StandardConversionSequence& SCS1,
88                                const StandardConversionSequence& SCS2);
89
90static ImplicitConversionSequence::CompareKind
91CompareDerivedToBaseConversions(Sema &S,
92                                const StandardConversionSequence& SCS1,
93                                const StandardConversionSequence& SCS2);
94
95
96
97/// GetConversionCategory - Retrieve the implicit conversion
98/// category corresponding to the given implicit conversion kind.
99ImplicitConversionCategory
100GetConversionCategory(ImplicitConversionKind Kind) {
101  static const ImplicitConversionCategory
102    Category[(int)ICK_Num_Conversion_Kinds] = {
103    ICC_Identity,
104    ICC_Lvalue_Transformation,
105    ICC_Lvalue_Transformation,
106    ICC_Lvalue_Transformation,
107    ICC_Identity,
108    ICC_Qualification_Adjustment,
109    ICC_Promotion,
110    ICC_Promotion,
111    ICC_Promotion,
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    ICC_Conversion,
124    ICC_Conversion
125  };
126  return Category[(int)Kind];
127}
128
129/// GetConversionRank - Retrieve the implicit conversion rank
130/// corresponding to the given implicit conversion kind.
131ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
132  static const ImplicitConversionRank
133    Rank[(int)ICK_Num_Conversion_Kinds] = {
134    ICR_Exact_Match,
135    ICR_Exact_Match,
136    ICR_Exact_Match,
137    ICR_Exact_Match,
138    ICR_Exact_Match,
139    ICR_Exact_Match,
140    ICR_Promotion,
141    ICR_Promotion,
142    ICR_Promotion,
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_Conversion,
153    ICR_Conversion,
154    ICR_Complex_Real_Conversion,
155    ICR_Conversion,
156    ICR_Conversion,
157    ICR_Writeback_Conversion
158  };
159  return Rank[(int)Kind];
160}
161
162/// GetImplicitConversionName - Return the name of this kind of
163/// implicit conversion.
164const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
165  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
166    "No conversion",
167    "Lvalue-to-rvalue",
168    "Array-to-pointer",
169    "Function-to-pointer",
170    "Noreturn adjustment",
171    "Qualification",
172    "Integral promotion",
173    "Floating point promotion",
174    "Complex promotion",
175    "Integral conversion",
176    "Floating conversion",
177    "Complex conversion",
178    "Floating-integral conversion",
179    "Pointer conversion",
180    "Pointer-to-member conversion",
181    "Boolean conversion",
182    "Compatible-types conversion",
183    "Derived-to-base conversion",
184    "Vector conversion",
185    "Vector splat",
186    "Complex-real conversion",
187    "Block Pointer conversion",
188    "Transparent Union Conversion"
189    "Writeback conversion"
190  };
191  return Name[Kind];
192}
193
194/// StandardConversionSequence - Set the standard conversion
195/// sequence to the identity conversion.
196void StandardConversionSequence::setAsIdentityConversion() {
197  First = ICK_Identity;
198  Second = ICK_Identity;
199  Third = ICK_Identity;
200  DeprecatedStringLiteralToCharPtr = false;
201  QualificationIncludesObjCLifetime = false;
202  ReferenceBinding = false;
203  DirectBinding = false;
204  IsLvalueReference = true;
205  BindsToFunctionLvalue = false;
206  BindsToRvalue = false;
207  BindsImplicitObjectArgumentWithoutRefQualifier = false;
208  ObjCLifetimeConversionBinding = false;
209  CopyConstructor = 0;
210}
211
212/// getRank - Retrieve the rank of this standard conversion sequence
213/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
214/// implicit conversions.
215ImplicitConversionRank StandardConversionSequence::getRank() const {
216  ImplicitConversionRank Rank = ICR_Exact_Match;
217  if  (GetConversionRank(First) > Rank)
218    Rank = GetConversionRank(First);
219  if  (GetConversionRank(Second) > Rank)
220    Rank = GetConversionRank(Second);
221  if  (GetConversionRank(Third) > Rank)
222    Rank = GetConversionRank(Third);
223  return Rank;
224}
225
226/// isPointerConversionToBool - Determines whether this conversion is
227/// a conversion of a pointer or pointer-to-member to bool. This is
228/// used as part of the ranking of standard conversion sequences
229/// (C++ 13.3.3.2p4).
230bool StandardConversionSequence::isPointerConversionToBool() const {
231  // Note that FromType has not necessarily been transformed by the
232  // array-to-pointer or function-to-pointer implicit conversions, so
233  // check for their presence as well as checking whether FromType is
234  // a pointer.
235  if (getToType(1)->isBooleanType() &&
236      (getFromType()->isPointerType() ||
237       getFromType()->isObjCObjectPointerType() ||
238       getFromType()->isBlockPointerType() ||
239       getFromType()->isNullPtrType() ||
240       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
241    return true;
242
243  return false;
244}
245
246/// isPointerConversionToVoidPointer - Determines whether this
247/// conversion is a conversion of a pointer to a void pointer. This is
248/// used as part of the ranking of standard conversion sequences (C++
249/// 13.3.3.2p4).
250bool
251StandardConversionSequence::
252isPointerConversionToVoidPointer(ASTContext& Context) const {
253  QualType FromType = getFromType();
254  QualType ToType = getToType(1);
255
256  // Note that FromType has not necessarily been transformed by the
257  // array-to-pointer implicit conversion, so check for its presence
258  // and redo the conversion to get a pointer.
259  if (First == ICK_Array_To_Pointer)
260    FromType = Context.getArrayDecayedType(FromType);
261
262  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
263    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
264      return ToPtrType->getPointeeType()->isVoidType();
265
266  return false;
267}
268
269/// Skip any implicit casts which could be either part of a narrowing conversion
270/// or after one in an implicit conversion.
271static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
272  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
273    switch (ICE->getCastKind()) {
274    case CK_NoOp:
275    case CK_IntegralCast:
276    case CK_IntegralToBoolean:
277    case CK_IntegralToFloating:
278    case CK_FloatingToIntegral:
279    case CK_FloatingToBoolean:
280    case CK_FloatingCast:
281      Converted = ICE->getSubExpr();
282      continue;
283
284    default:
285      return Converted;
286    }
287  }
288
289  return Converted;
290}
291
292/// Check if this standard conversion sequence represents a narrowing
293/// conversion, according to C++11 [dcl.init.list]p7.
294///
295/// \param Ctx  The AST context.
296/// \param Converted  The result of applying this standard conversion sequence.
297/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
298///        value of the expression prior to the narrowing conversion.
299/// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
300///        type of the expression prior to the narrowing conversion.
301NarrowingKind
302StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
303                                             const Expr *Converted,
304                                             APValue &ConstantValue,
305                                             QualType &ConstantType) const {
306  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
307
308  // C++11 [dcl.init.list]p7:
309  //   A narrowing conversion is an implicit conversion ...
310  QualType FromType = getToType(0);
311  QualType ToType = getToType(1);
312  switch (Second) {
313  // -- from a floating-point type to an integer type, or
314  //
315  // -- from an integer type or unscoped enumeration type to a floating-point
316  //    type, except where the source is a constant expression and the actual
317  //    value after conversion will fit into the target type and will produce
318  //    the original value when converted back to the original type, or
319  case ICK_Floating_Integral:
320    if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
321      return NK_Type_Narrowing;
322    } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
323      llvm::APSInt IntConstantValue;
324      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
325      if (Initializer &&
326          Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
327        // Convert the integer to the floating type.
328        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
329        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
330                                llvm::APFloat::rmNearestTiesToEven);
331        // And back.
332        llvm::APSInt ConvertedValue = IntConstantValue;
333        bool ignored;
334        Result.convertToInteger(ConvertedValue,
335                                llvm::APFloat::rmTowardZero, &ignored);
336        // If the resulting value is different, this was a narrowing conversion.
337        if (IntConstantValue != ConvertedValue) {
338          ConstantValue = APValue(IntConstantValue);
339          ConstantType = Initializer->getType();
340          return NK_Constant_Narrowing;
341        }
342      } else {
343        // Variables are always narrowings.
344        return NK_Variable_Narrowing;
345      }
346    }
347    return NK_Not_Narrowing;
348
349  // -- from long double to double or float, or from double to float, except
350  //    where the source is a constant expression and the actual value after
351  //    conversion is within the range of values that can be represented (even
352  //    if it cannot be represented exactly), or
353  case ICK_Floating_Conversion:
354    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
355        Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
356      // FromType is larger than ToType.
357      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
358      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
359        // Constant!
360        assert(ConstantValue.isFloat());
361        llvm::APFloat FloatVal = ConstantValue.getFloat();
362        // Convert the source value into the target type.
363        bool ignored;
364        llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
365          Ctx.getFloatTypeSemantics(ToType),
366          llvm::APFloat::rmNearestTiesToEven, &ignored);
367        // If there was no overflow, the source value is within the range of
368        // values that can be represented.
369        if (ConvertStatus & llvm::APFloat::opOverflow) {
370          ConstantType = Initializer->getType();
371          return NK_Constant_Narrowing;
372        }
373      } else {
374        return NK_Variable_Narrowing;
375      }
376    }
377    return NK_Not_Narrowing;
378
379  // -- from an integer type or unscoped enumeration type to an integer type
380  //    that cannot represent all the values of the original type, except where
381  //    the source is a constant expression and the actual value after
382  //    conversion will fit into the target type and will produce the original
383  //    value when converted back to the original type.
384  case ICK_Boolean_Conversion:  // Bools are integers too.
385    if (!FromType->isIntegralOrUnscopedEnumerationType()) {
386      // Boolean conversions can be from pointers and pointers to members
387      // [conv.bool], and those aren't considered narrowing conversions.
388      return NK_Not_Narrowing;
389    }  // Otherwise, fall through to the integral case.
390  case ICK_Integral_Conversion: {
391    assert(FromType->isIntegralOrUnscopedEnumerationType());
392    assert(ToType->isIntegralOrUnscopedEnumerationType());
393    const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
394    const unsigned FromWidth = Ctx.getIntWidth(FromType);
395    const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
396    const unsigned ToWidth = Ctx.getIntWidth(ToType);
397
398    if (FromWidth > ToWidth ||
399        (FromWidth == ToWidth && FromSigned != ToSigned) ||
400        (FromSigned && !ToSigned)) {
401      // Not all values of FromType can be represented in ToType.
402      llvm::APSInt InitializerValue;
403      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
404      if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
405        // Such conversions on variables are always narrowing.
406        return NK_Variable_Narrowing;
407      }
408      bool Narrowing = false;
409      if (FromWidth < ToWidth) {
410        // Negative -> unsigned is narrowing. Otherwise, more bits is never
411        // narrowing.
412        if (InitializerValue.isSigned() && InitializerValue.isNegative())
413          Narrowing = true;
414      } else {
415        // Add a bit to the InitializerValue so we don't have to worry about
416        // signed vs. unsigned comparisons.
417        InitializerValue = InitializerValue.extend(
418          InitializerValue.getBitWidth() + 1);
419        // Convert the initializer to and from the target width and signed-ness.
420        llvm::APSInt ConvertedValue = InitializerValue;
421        ConvertedValue = ConvertedValue.trunc(ToWidth);
422        ConvertedValue.setIsSigned(ToSigned);
423        ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
424        ConvertedValue.setIsSigned(InitializerValue.isSigned());
425        // If the result is different, this was a narrowing conversion.
426        if (ConvertedValue != InitializerValue)
427          Narrowing = true;
428      }
429      if (Narrowing) {
430        ConstantType = Initializer->getType();
431        ConstantValue = APValue(InitializerValue);
432        return NK_Constant_Narrowing;
433      }
434    }
435    return NK_Not_Narrowing;
436  }
437
438  default:
439    // Other kinds of conversions are not narrowings.
440    return NK_Not_Narrowing;
441  }
442}
443
444/// DebugPrint - Print this standard conversion sequence to standard
445/// error. Useful for debugging overloading issues.
446void StandardConversionSequence::DebugPrint() const {
447  raw_ostream &OS = llvm::errs();
448  bool PrintedSomething = false;
449  if (First != ICK_Identity) {
450    OS << GetImplicitConversionName(First);
451    PrintedSomething = true;
452  }
453
454  if (Second != ICK_Identity) {
455    if (PrintedSomething) {
456      OS << " -> ";
457    }
458    OS << GetImplicitConversionName(Second);
459
460    if (CopyConstructor) {
461      OS << " (by copy constructor)";
462    } else if (DirectBinding) {
463      OS << " (direct reference binding)";
464    } else if (ReferenceBinding) {
465      OS << " (reference binding)";
466    }
467    PrintedSomething = true;
468  }
469
470  if (Third != ICK_Identity) {
471    if (PrintedSomething) {
472      OS << " -> ";
473    }
474    OS << GetImplicitConversionName(Third);
475    PrintedSomething = true;
476  }
477
478  if (!PrintedSomething) {
479    OS << "No conversions required";
480  }
481}
482
483/// DebugPrint - Print this user-defined conversion sequence to standard
484/// error. Useful for debugging overloading issues.
485void UserDefinedConversionSequence::DebugPrint() const {
486  raw_ostream &OS = llvm::errs();
487  if (Before.First || Before.Second || Before.Third) {
488    Before.DebugPrint();
489    OS << " -> ";
490  }
491  if (ConversionFunction)
492    OS << '\'' << *ConversionFunction << '\'';
493  else
494    OS << "aggregate initialization";
495  if (After.First || After.Second || After.Third) {
496    OS << " -> ";
497    After.DebugPrint();
498  }
499}
500
501/// DebugPrint - Print this implicit conversion sequence to standard
502/// error. Useful for debugging overloading issues.
503void ImplicitConversionSequence::DebugPrint() const {
504  raw_ostream &OS = llvm::errs();
505  switch (ConversionKind) {
506  case StandardConversion:
507    OS << "Standard conversion: ";
508    Standard.DebugPrint();
509    break;
510  case UserDefinedConversion:
511    OS << "User-defined conversion: ";
512    UserDefined.DebugPrint();
513    break;
514  case EllipsisConversion:
515    OS << "Ellipsis conversion";
516    break;
517  case AmbiguousConversion:
518    OS << "Ambiguous conversion";
519    break;
520  case BadConversion:
521    OS << "Bad conversion";
522    break;
523  }
524
525  OS << "\n";
526}
527
528void AmbiguousConversionSequence::construct() {
529  new (&conversions()) ConversionSet();
530}
531
532void AmbiguousConversionSequence::destruct() {
533  conversions().~ConversionSet();
534}
535
536void
537AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
538  FromTypePtr = O.FromTypePtr;
539  ToTypePtr = O.ToTypePtr;
540  new (&conversions()) ConversionSet(O.conversions());
541}
542
543namespace {
544  // Structure used by OverloadCandidate::DeductionFailureInfo to store
545  // template argument information.
546  struct DFIArguments {
547    TemplateArgument FirstArg;
548    TemplateArgument SecondArg;
549  };
550  // Structure used by OverloadCandidate::DeductionFailureInfo to store
551  // template parameter and template argument information.
552  struct DFIParamWithArguments : DFIArguments {
553    TemplateParameter Param;
554  };
555}
556
557/// \brief Convert from Sema's representation of template deduction information
558/// to the form used in overload-candidate information.
559OverloadCandidate::DeductionFailureInfo
560static MakeDeductionFailureInfo(ASTContext &Context,
561                                Sema::TemplateDeductionResult TDK,
562                                TemplateDeductionInfo &Info) {
563  OverloadCandidate::DeductionFailureInfo Result;
564  Result.Result = static_cast<unsigned>(TDK);
565  Result.HasDiagnostic = false;
566  Result.Data = 0;
567  switch (TDK) {
568  case Sema::TDK_Success:
569  case Sema::TDK_Invalid:
570  case Sema::TDK_InstantiationDepth:
571  case Sema::TDK_TooManyArguments:
572  case Sema::TDK_TooFewArguments:
573    break;
574
575  case Sema::TDK_Incomplete:
576  case Sema::TDK_InvalidExplicitArguments:
577    Result.Data = Info.Param.getOpaqueValue();
578    break;
579
580  case Sema::TDK_NonDeducedMismatch: {
581    // FIXME: Should allocate from normal heap so that we can free this later.
582    DFIArguments *Saved = new (Context) DFIArguments;
583    Saved->FirstArg = Info.FirstArg;
584    Saved->SecondArg = Info.SecondArg;
585    Result.Data = Saved;
586    break;
587  }
588
589  case Sema::TDK_Inconsistent:
590  case Sema::TDK_Underqualified: {
591    // FIXME: Should allocate from normal heap so that we can free this later.
592    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
593    Saved->Param = Info.Param;
594    Saved->FirstArg = Info.FirstArg;
595    Saved->SecondArg = Info.SecondArg;
596    Result.Data = Saved;
597    break;
598  }
599
600  case Sema::TDK_SubstitutionFailure:
601    Result.Data = Info.take();
602    if (Info.hasSFINAEDiagnostic()) {
603      PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
604          SourceLocation(), PartialDiagnostic::NullDiagnostic());
605      Info.takeSFINAEDiagnostic(*Diag);
606      Result.HasDiagnostic = true;
607    }
608    break;
609
610  case Sema::TDK_FailedOverloadResolution:
611    Result.Data = Info.Expression;
612    break;
613
614  case Sema::TDK_MiscellaneousDeductionFailure:
615    break;
616  }
617
618  return Result;
619}
620
621void OverloadCandidate::DeductionFailureInfo::Destroy() {
622  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
623  case Sema::TDK_Success:
624  case Sema::TDK_Invalid:
625  case Sema::TDK_InstantiationDepth:
626  case Sema::TDK_Incomplete:
627  case Sema::TDK_TooManyArguments:
628  case Sema::TDK_TooFewArguments:
629  case Sema::TDK_InvalidExplicitArguments:
630  case Sema::TDK_FailedOverloadResolution:
631    break;
632
633  case Sema::TDK_Inconsistent:
634  case Sema::TDK_Underqualified:
635  case Sema::TDK_NonDeducedMismatch:
636    // FIXME: Destroy the data?
637    Data = 0;
638    break;
639
640  case Sema::TDK_SubstitutionFailure:
641    // FIXME: Destroy the template argument list?
642    Data = 0;
643    if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
644      Diag->~PartialDiagnosticAt();
645      HasDiagnostic = false;
646    }
647    break;
648
649  // Unhandled
650  case Sema::TDK_MiscellaneousDeductionFailure:
651    break;
652  }
653}
654
655PartialDiagnosticAt *
656OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
657  if (HasDiagnostic)
658    return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
659  return 0;
660}
661
662TemplateParameter
663OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
664  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
665  case Sema::TDK_Success:
666  case Sema::TDK_Invalid:
667  case Sema::TDK_InstantiationDepth:
668  case Sema::TDK_TooManyArguments:
669  case Sema::TDK_TooFewArguments:
670  case Sema::TDK_SubstitutionFailure:
671  case Sema::TDK_NonDeducedMismatch:
672  case Sema::TDK_FailedOverloadResolution:
673    return TemplateParameter();
674
675  case Sema::TDK_Incomplete:
676  case Sema::TDK_InvalidExplicitArguments:
677    return TemplateParameter::getFromOpaqueValue(Data);
678
679  case Sema::TDK_Inconsistent:
680  case Sema::TDK_Underqualified:
681    return static_cast<DFIParamWithArguments*>(Data)->Param;
682
683  // Unhandled
684  case Sema::TDK_MiscellaneousDeductionFailure:
685    break;
686  }
687
688  return TemplateParameter();
689}
690
691TemplateArgumentList *
692OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
693  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
694  case Sema::TDK_Success:
695  case Sema::TDK_Invalid:
696  case Sema::TDK_InstantiationDepth:
697  case Sema::TDK_TooManyArguments:
698  case Sema::TDK_TooFewArguments:
699  case Sema::TDK_Incomplete:
700  case Sema::TDK_InvalidExplicitArguments:
701  case Sema::TDK_Inconsistent:
702  case Sema::TDK_Underqualified:
703  case Sema::TDK_NonDeducedMismatch:
704  case Sema::TDK_FailedOverloadResolution:
705    return 0;
706
707  case Sema::TDK_SubstitutionFailure:
708    return static_cast<TemplateArgumentList*>(Data);
709
710  // Unhandled
711  case Sema::TDK_MiscellaneousDeductionFailure:
712    break;
713  }
714
715  return 0;
716}
717
718const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
719  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
720  case Sema::TDK_Success:
721  case Sema::TDK_Invalid:
722  case Sema::TDK_InstantiationDepth:
723  case Sema::TDK_Incomplete:
724  case Sema::TDK_TooManyArguments:
725  case Sema::TDK_TooFewArguments:
726  case Sema::TDK_InvalidExplicitArguments:
727  case Sema::TDK_SubstitutionFailure:
728  case Sema::TDK_FailedOverloadResolution:
729    return 0;
730
731  case Sema::TDK_Inconsistent:
732  case Sema::TDK_Underqualified:
733  case Sema::TDK_NonDeducedMismatch:
734    return &static_cast<DFIArguments*>(Data)->FirstArg;
735
736  // Unhandled
737  case Sema::TDK_MiscellaneousDeductionFailure:
738    break;
739  }
740
741  return 0;
742}
743
744const TemplateArgument *
745OverloadCandidate::DeductionFailureInfo::getSecondArg() {
746  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
747  case Sema::TDK_Success:
748  case Sema::TDK_Invalid:
749  case Sema::TDK_InstantiationDepth:
750  case Sema::TDK_Incomplete:
751  case Sema::TDK_TooManyArguments:
752  case Sema::TDK_TooFewArguments:
753  case Sema::TDK_InvalidExplicitArguments:
754  case Sema::TDK_SubstitutionFailure:
755  case Sema::TDK_FailedOverloadResolution:
756    return 0;
757
758  case Sema::TDK_Inconsistent:
759  case Sema::TDK_Underqualified:
760  case Sema::TDK_NonDeducedMismatch:
761    return &static_cast<DFIArguments*>(Data)->SecondArg;
762
763  // Unhandled
764  case Sema::TDK_MiscellaneousDeductionFailure:
765    break;
766  }
767
768  return 0;
769}
770
771Expr *
772OverloadCandidate::DeductionFailureInfo::getExpr() {
773  if (static_cast<Sema::TemplateDeductionResult>(Result) ==
774        Sema::TDK_FailedOverloadResolution)
775    return static_cast<Expr*>(Data);
776
777  return 0;
778}
779
780void OverloadCandidateSet::destroyCandidates() {
781  for (iterator i = begin(), e = end(); i != e; ++i) {
782    for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
783      i->Conversions[ii].~ImplicitConversionSequence();
784    if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
785      i->DeductionFailure.Destroy();
786  }
787}
788
789void OverloadCandidateSet::clear() {
790  destroyCandidates();
791  NumInlineSequences = 0;
792  Candidates.clear();
793  Functions.clear();
794}
795
796namespace {
797  class UnbridgedCastsSet {
798    struct Entry {
799      Expr **Addr;
800      Expr *Saved;
801    };
802    SmallVector<Entry, 2> Entries;
803
804  public:
805    void save(Sema &S, Expr *&E) {
806      assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
807      Entry entry = { &E, E };
808      Entries.push_back(entry);
809      E = S.stripARCUnbridgedCast(E);
810    }
811
812    void restore() {
813      for (SmallVectorImpl<Entry>::iterator
814             i = Entries.begin(), e = Entries.end(); i != e; ++i)
815        *i->Addr = i->Saved;
816    }
817  };
818}
819
820/// checkPlaceholderForOverload - Do any interesting placeholder-like
821/// preprocessing on the given expression.
822///
823/// \param unbridgedCasts a collection to which to add unbridged casts;
824///   without this, they will be immediately diagnosed as errors
825///
826/// Return true on unrecoverable error.
827static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
828                                        UnbridgedCastsSet *unbridgedCasts = 0) {
829  if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
830    // We can't handle overloaded expressions here because overload
831    // resolution might reasonably tweak them.
832    if (placeholder->getKind() == BuiltinType::Overload) return false;
833
834    // If the context potentially accepts unbridged ARC casts, strip
835    // the unbridged cast and add it to the collection for later restoration.
836    if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
837        unbridgedCasts) {
838      unbridgedCasts->save(S, E);
839      return false;
840    }
841
842    // Go ahead and check everything else.
843    ExprResult result = S.CheckPlaceholderExpr(E);
844    if (result.isInvalid())
845      return true;
846
847    E = result.take();
848    return false;
849  }
850
851  // Nothing to do.
852  return false;
853}
854
855/// checkArgPlaceholdersForOverload - Check a set of call operands for
856/// placeholders.
857static bool checkArgPlaceholdersForOverload(Sema &S,
858                                            MultiExprArg Args,
859                                            UnbridgedCastsSet &unbridged) {
860  for (unsigned i = 0, e = Args.size(); i != e; ++i)
861    if (checkPlaceholderForOverload(S, Args[i], &unbridged))
862      return true;
863
864  return false;
865}
866
867// IsOverload - Determine whether the given New declaration is an
868// overload of the declarations in Old. This routine returns false if
869// New and Old cannot be overloaded, e.g., if New has the same
870// signature as some function in Old (C++ 1.3.10) or if the Old
871// declarations aren't functions (or function templates) at all. When
872// it does return false, MatchedDecl will point to the decl that New
873// cannot be overloaded with.  This decl may be a UsingShadowDecl on
874// top of the underlying declaration.
875//
876// Example: Given the following input:
877//
878//   void f(int, float); // #1
879//   void f(int, int); // #2
880//   int f(int, int); // #3
881//
882// When we process #1, there is no previous declaration of "f",
883// so IsOverload will not be used.
884//
885// When we process #2, Old contains only the FunctionDecl for #1.  By
886// comparing the parameter types, we see that #1 and #2 are overloaded
887// (since they have different signatures), so this routine returns
888// false; MatchedDecl is unchanged.
889//
890// When we process #3, Old is an overload set containing #1 and #2. We
891// compare the signatures of #3 to #1 (they're overloaded, so we do
892// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
893// identical (return types of functions are not part of the
894// signature), IsOverload returns false and MatchedDecl will be set to
895// point to the FunctionDecl for #2.
896//
897// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
898// into a class by a using declaration.  The rules for whether to hide
899// shadow declarations ignore some properties which otherwise figure
900// into a function template's signature.
901Sema::OverloadKind
902Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
903                    NamedDecl *&Match, bool NewIsUsingDecl) {
904  for (LookupResult::iterator I = Old.begin(), E = Old.end();
905         I != E; ++I) {
906    NamedDecl *OldD = *I;
907
908    bool OldIsUsingDecl = false;
909    if (isa<UsingShadowDecl>(OldD)) {
910      OldIsUsingDecl = true;
911
912      // We can always introduce two using declarations into the same
913      // context, even if they have identical signatures.
914      if (NewIsUsingDecl) continue;
915
916      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
917    }
918
919    // If either declaration was introduced by a using declaration,
920    // we'll need to use slightly different rules for matching.
921    // Essentially, these rules are the normal rules, except that
922    // function templates hide function templates with different
923    // return types or template parameter lists.
924    bool UseMemberUsingDeclRules =
925      (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
926      !New->getFriendObjectKind();
927
928    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
929      if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
930        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
931          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
932          continue;
933        }
934
935        Match = *I;
936        return Ovl_Match;
937      }
938    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
939      if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
940        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
941          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
942          continue;
943        }
944
945        if (!shouldLinkPossiblyHiddenDecl(*I, New))
946          continue;
947
948        Match = *I;
949        return Ovl_Match;
950      }
951    } else if (isa<UsingDecl>(OldD)) {
952      // We can overload with these, which can show up when doing
953      // redeclaration checks for UsingDecls.
954      assert(Old.getLookupKind() == LookupUsingDeclName);
955    } else if (isa<TagDecl>(OldD)) {
956      // We can always overload with tags by hiding them.
957    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
958      // Optimistically assume that an unresolved using decl will
959      // overload; if it doesn't, we'll have to diagnose during
960      // template instantiation.
961    } else {
962      // (C++ 13p1):
963      //   Only function declarations can be overloaded; object and type
964      //   declarations cannot be overloaded.
965      Match = *I;
966      return Ovl_NonFunction;
967    }
968  }
969
970  return Ovl_Overload;
971}
972
973static bool canBeOverloaded(const FunctionDecl &D) {
974  if (D.getAttr<OverloadableAttr>())
975    return true;
976  if (D.isExternC())
977    return false;
978
979  // Main cannot be overloaded (basic.start.main).
980  if (D.isMain())
981    return false;
982
983  return true;
984}
985
986static bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old,
987                                bool UseUsingDeclRules) {
988  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
989  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
990
991  // C++ [temp.fct]p2:
992  //   A function template can be overloaded with other function templates
993  //   and with normal (non-template) functions.
994  if ((OldTemplate == 0) != (NewTemplate == 0))
995    return true;
996
997  // Is the function New an overload of the function Old?
998  QualType OldQType = S.Context.getCanonicalType(Old->getType());
999  QualType NewQType = S.Context.getCanonicalType(New->getType());
1000
1001  // Compare the signatures (C++ 1.3.10) of the two functions to
1002  // determine whether they are overloads. If we find any mismatch
1003  // in the signature, they are overloads.
1004
1005  // If either of these functions is a K&R-style function (no
1006  // prototype), then we consider them to have matching signatures.
1007  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1008      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1009    return false;
1010
1011  const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1012  const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
1013
1014  // The signature of a function includes the types of its
1015  // parameters (C++ 1.3.10), which includes the presence or absence
1016  // of the ellipsis; see C++ DR 357).
1017  if (OldQType != NewQType &&
1018      (OldType->getNumArgs() != NewType->getNumArgs() ||
1019       OldType->isVariadic() != NewType->isVariadic() ||
1020       !S.FunctionArgTypesAreEqual(OldType, NewType)))
1021    return true;
1022
1023  // C++ [temp.over.link]p4:
1024  //   The signature of a function template consists of its function
1025  //   signature, its return type and its template parameter list. The names
1026  //   of the template parameters are significant only for establishing the
1027  //   relationship between the template parameters and the rest of the
1028  //   signature.
1029  //
1030  // We check the return type and template parameter lists for function
1031  // templates first; the remaining checks follow.
1032  //
1033  // However, we don't consider either of these when deciding whether
1034  // a member introduced by a shadow declaration is hidden.
1035  if (!UseUsingDeclRules && NewTemplate &&
1036      (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1037                                         OldTemplate->getTemplateParameters(),
1038                                         false, S.TPL_TemplateMatch) ||
1039       OldType->getResultType() != NewType->getResultType()))
1040    return true;
1041
1042  // If the function is a class member, its signature includes the
1043  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1044  //
1045  // As part of this, also check whether one of the member functions
1046  // is static, in which case they are not overloads (C++
1047  // 13.1p2). While not part of the definition of the signature,
1048  // this check is important to determine whether these functions
1049  // can be overloaded.
1050  CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1051  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1052  if (OldMethod && NewMethod &&
1053      !OldMethod->isStatic() && !NewMethod->isStatic()) {
1054    if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1055      if (!UseUsingDeclRules &&
1056          (OldMethod->getRefQualifier() == RQ_None ||
1057           NewMethod->getRefQualifier() == RQ_None)) {
1058        // C++0x [over.load]p2:
1059        //   - Member function declarations with the same name and the same
1060        //     parameter-type-list as well as member function template
1061        //     declarations with the same name, the same parameter-type-list, and
1062        //     the same template parameter lists cannot be overloaded if any of
1063        //     them, but not all, have a ref-qualifier (8.3.5).
1064        S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1065          << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1066        S.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1067      }
1068      return true;
1069    }
1070
1071    // We may not have applied the implicit const for a constexpr member
1072    // function yet (because we haven't yet resolved whether this is a static
1073    // or non-static member function). Add it now, on the assumption that this
1074    // is a redeclaration of OldMethod.
1075    unsigned NewQuals = NewMethod->getTypeQualifiers();
1076    if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod))
1077      NewQuals |= Qualifiers::Const;
1078    if (OldMethod->getTypeQualifiers() != NewQuals)
1079      return true;
1080  }
1081
1082  // The signatures match; this is not an overload.
1083  return false;
1084}
1085
1086bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1087                      bool UseUsingDeclRules) {
1088  if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules))
1089    return false;
1090
1091  // If both of the functions are extern "C", then they are not
1092  // overloads.
1093  if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
1094    return false;
1095
1096  return true;
1097}
1098
1099/// \brief Checks availability of the function depending on the current
1100/// function context. Inside an unavailable function, unavailability is ignored.
1101///
1102/// \returns true if \arg FD is unavailable and current context is inside
1103/// an available function, false otherwise.
1104bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1105  return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1106}
1107
1108/// \brief Tries a user-defined conversion from From to ToType.
1109///
1110/// Produces an implicit conversion sequence for when a standard conversion
1111/// is not an option. See TryImplicitConversion for more information.
1112static ImplicitConversionSequence
1113TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1114                         bool SuppressUserConversions,
1115                         bool AllowExplicit,
1116                         bool InOverloadResolution,
1117                         bool CStyle,
1118                         bool AllowObjCWritebackConversion) {
1119  ImplicitConversionSequence ICS;
1120
1121  if (SuppressUserConversions) {
1122    // We're not in the case above, so there is no conversion that
1123    // we can perform.
1124    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1125    return ICS;
1126  }
1127
1128  // Attempt user-defined conversion.
1129  OverloadCandidateSet Conversions(From->getExprLoc());
1130  OverloadingResult UserDefResult
1131    = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1132                              AllowExplicit);
1133
1134  if (UserDefResult == OR_Success) {
1135    ICS.setUserDefined();
1136    // C++ [over.ics.user]p4:
1137    //   A conversion of an expression of class type to the same class
1138    //   type is given Exact Match rank, and a conversion of an
1139    //   expression of class type to a base class of that type is
1140    //   given Conversion rank, in spite of the fact that a copy
1141    //   constructor (i.e., a user-defined conversion function) is
1142    //   called for those cases.
1143    if (CXXConstructorDecl *Constructor
1144          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1145      QualType FromCanon
1146        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1147      QualType ToCanon
1148        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1149      if (Constructor->isCopyConstructor() &&
1150          (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1151        // Turn this into a "standard" conversion sequence, so that it
1152        // gets ranked with standard conversion sequences.
1153        ICS.setStandard();
1154        ICS.Standard.setAsIdentityConversion();
1155        ICS.Standard.setFromType(From->getType());
1156        ICS.Standard.setAllToTypes(ToType);
1157        ICS.Standard.CopyConstructor = Constructor;
1158        if (ToCanon != FromCanon)
1159          ICS.Standard.Second = ICK_Derived_To_Base;
1160      }
1161    }
1162
1163    // C++ [over.best.ics]p4:
1164    //   However, when considering the argument of a user-defined
1165    //   conversion function that is a candidate by 13.3.1.3 when
1166    //   invoked for the copying of the temporary in the second step
1167    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1168    //   13.3.1.6 in all cases, only standard conversion sequences and
1169    //   ellipsis conversion sequences are allowed.
1170    if (SuppressUserConversions && ICS.isUserDefined()) {
1171      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1172    }
1173  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1174    ICS.setAmbiguous();
1175    ICS.Ambiguous.setFromType(From->getType());
1176    ICS.Ambiguous.setToType(ToType);
1177    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1178         Cand != Conversions.end(); ++Cand)
1179      if (Cand->Viable)
1180        ICS.Ambiguous.addConversion(Cand->Function);
1181  } else {
1182    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1183  }
1184
1185  return ICS;
1186}
1187
1188/// TryImplicitConversion - Attempt to perform an implicit conversion
1189/// from the given expression (Expr) to the given type (ToType). This
1190/// function returns an implicit conversion sequence that can be used
1191/// to perform the initialization. Given
1192///
1193///   void f(float f);
1194///   void g(int i) { f(i); }
1195///
1196/// this routine would produce an implicit conversion sequence to
1197/// describe the initialization of f from i, which will be a standard
1198/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1199/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1200//
1201/// Note that this routine only determines how the conversion can be
1202/// performed; it does not actually perform the conversion. As such,
1203/// it will not produce any diagnostics if no conversion is available,
1204/// but will instead return an implicit conversion sequence of kind
1205/// "BadConversion".
1206///
1207/// If @p SuppressUserConversions, then user-defined conversions are
1208/// not permitted.
1209/// If @p AllowExplicit, then explicit user-defined conversions are
1210/// permitted.
1211///
1212/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1213/// writeback conversion, which allows __autoreleasing id* parameters to
1214/// be initialized with __strong id* or __weak id* arguments.
1215static ImplicitConversionSequence
1216TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1217                      bool SuppressUserConversions,
1218                      bool AllowExplicit,
1219                      bool InOverloadResolution,
1220                      bool CStyle,
1221                      bool AllowObjCWritebackConversion) {
1222  ImplicitConversionSequence ICS;
1223  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1224                           ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1225    ICS.setStandard();
1226    return ICS;
1227  }
1228
1229  if (!S.getLangOpts().CPlusPlus) {
1230    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1231    return ICS;
1232  }
1233
1234  // C++ [over.ics.user]p4:
1235  //   A conversion of an expression of class type to the same class
1236  //   type is given Exact Match rank, and a conversion of an
1237  //   expression of class type to a base class of that type is
1238  //   given Conversion rank, in spite of the fact that a copy/move
1239  //   constructor (i.e., a user-defined conversion function) is
1240  //   called for those cases.
1241  QualType FromType = From->getType();
1242  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1243      (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1244       S.IsDerivedFrom(FromType, ToType))) {
1245    ICS.setStandard();
1246    ICS.Standard.setAsIdentityConversion();
1247    ICS.Standard.setFromType(FromType);
1248    ICS.Standard.setAllToTypes(ToType);
1249
1250    // We don't actually check at this point whether there is a valid
1251    // copy/move constructor, since overloading just assumes that it
1252    // exists. When we actually perform initialization, we'll find the
1253    // appropriate constructor to copy the returned object, if needed.
1254    ICS.Standard.CopyConstructor = 0;
1255
1256    // Determine whether this is considered a derived-to-base conversion.
1257    if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1258      ICS.Standard.Second = ICK_Derived_To_Base;
1259
1260    return ICS;
1261  }
1262
1263  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1264                                  AllowExplicit, InOverloadResolution, CStyle,
1265                                  AllowObjCWritebackConversion);
1266}
1267
1268ImplicitConversionSequence
1269Sema::TryImplicitConversion(Expr *From, QualType ToType,
1270                            bool SuppressUserConversions,
1271                            bool AllowExplicit,
1272                            bool InOverloadResolution,
1273                            bool CStyle,
1274                            bool AllowObjCWritebackConversion) {
1275  return clang::TryImplicitConversion(*this, From, ToType,
1276                                      SuppressUserConversions, AllowExplicit,
1277                                      InOverloadResolution, CStyle,
1278                                      AllowObjCWritebackConversion);
1279}
1280
1281/// PerformImplicitConversion - Perform an implicit conversion of the
1282/// expression From to the type ToType. Returns the
1283/// converted expression. Flavor is the kind of conversion we're
1284/// performing, used in the error message. If @p AllowExplicit,
1285/// explicit user-defined conversions are permitted.
1286ExprResult
1287Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1288                                AssignmentAction Action, bool AllowExplicit) {
1289  ImplicitConversionSequence ICS;
1290  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1291}
1292
1293ExprResult
1294Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1295                                AssignmentAction Action, bool AllowExplicit,
1296                                ImplicitConversionSequence& ICS) {
1297  if (checkPlaceholderForOverload(*this, From))
1298    return ExprError();
1299
1300  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1301  bool AllowObjCWritebackConversion
1302    = getLangOpts().ObjCAutoRefCount &&
1303      (Action == AA_Passing || Action == AA_Sending);
1304
1305  ICS = clang::TryImplicitConversion(*this, From, ToType,
1306                                     /*SuppressUserConversions=*/false,
1307                                     AllowExplicit,
1308                                     /*InOverloadResolution=*/false,
1309                                     /*CStyle=*/false,
1310                                     AllowObjCWritebackConversion);
1311  return PerformImplicitConversion(From, ToType, ICS, Action);
1312}
1313
1314/// \brief Determine whether the conversion from FromType to ToType is a valid
1315/// conversion that strips "noreturn" off the nested function type.
1316bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1317                                QualType &ResultTy) {
1318  if (Context.hasSameUnqualifiedType(FromType, ToType))
1319    return false;
1320
1321  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1322  // where F adds one of the following at most once:
1323  //   - a pointer
1324  //   - a member pointer
1325  //   - a block pointer
1326  CanQualType CanTo = Context.getCanonicalType(ToType);
1327  CanQualType CanFrom = Context.getCanonicalType(FromType);
1328  Type::TypeClass TyClass = CanTo->getTypeClass();
1329  if (TyClass != CanFrom->getTypeClass()) return false;
1330  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1331    if (TyClass == Type::Pointer) {
1332      CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1333      CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1334    } else if (TyClass == Type::BlockPointer) {
1335      CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1336      CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1337    } else if (TyClass == Type::MemberPointer) {
1338      CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1339      CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1340    } else {
1341      return false;
1342    }
1343
1344    TyClass = CanTo->getTypeClass();
1345    if (TyClass != CanFrom->getTypeClass()) return false;
1346    if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1347      return false;
1348  }
1349
1350  const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1351  FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1352  if (!EInfo.getNoReturn()) return false;
1353
1354  FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1355  assert(QualType(FromFn, 0).isCanonical());
1356  if (QualType(FromFn, 0) != CanTo) return false;
1357
1358  ResultTy = ToType;
1359  return true;
1360}
1361
1362/// \brief Determine whether the conversion from FromType to ToType is a valid
1363/// vector conversion.
1364///
1365/// \param ICK Will be set to the vector conversion kind, if this is a vector
1366/// conversion.
1367static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1368                               QualType ToType, ImplicitConversionKind &ICK) {
1369  // We need at least one of these types to be a vector type to have a vector
1370  // conversion.
1371  if (!ToType->isVectorType() && !FromType->isVectorType())
1372    return false;
1373
1374  // Identical types require no conversions.
1375  if (Context.hasSameUnqualifiedType(FromType, ToType))
1376    return false;
1377
1378  // There are no conversions between extended vector types, only identity.
1379  if (ToType->isExtVectorType()) {
1380    // There are no conversions between extended vector types other than the
1381    // identity conversion.
1382    if (FromType->isExtVectorType())
1383      return false;
1384
1385    // Vector splat from any arithmetic type to a vector.
1386    if (FromType->isArithmeticType()) {
1387      ICK = ICK_Vector_Splat;
1388      return true;
1389    }
1390  }
1391
1392  // We can perform the conversion between vector types in the following cases:
1393  // 1)vector types are equivalent AltiVec and GCC vector types
1394  // 2)lax vector conversions are permitted and the vector types are of the
1395  //   same size
1396  if (ToType->isVectorType() && FromType->isVectorType()) {
1397    if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1398        (Context.getLangOpts().LaxVectorConversions &&
1399         (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1400      ICK = ICK_Vector_Conversion;
1401      return true;
1402    }
1403  }
1404
1405  return false;
1406}
1407
1408static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1409                                bool InOverloadResolution,
1410                                StandardConversionSequence &SCS,
1411                                bool CStyle);
1412
1413/// IsStandardConversion - Determines whether there is a standard
1414/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1415/// expression From to the type ToType. Standard conversion sequences
1416/// only consider non-class types; for conversions that involve class
1417/// types, use TryImplicitConversion. If a conversion exists, SCS will
1418/// contain the standard conversion sequence required to perform this
1419/// conversion and this routine will return true. Otherwise, this
1420/// routine will return false and the value of SCS is unspecified.
1421static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1422                                 bool InOverloadResolution,
1423                                 StandardConversionSequence &SCS,
1424                                 bool CStyle,
1425                                 bool AllowObjCWritebackConversion) {
1426  QualType FromType = From->getType();
1427
1428  // Standard conversions (C++ [conv])
1429  SCS.setAsIdentityConversion();
1430  SCS.DeprecatedStringLiteralToCharPtr = false;
1431  SCS.IncompatibleObjC = false;
1432  SCS.setFromType(FromType);
1433  SCS.CopyConstructor = 0;
1434
1435  // There are no standard conversions for class types in C++, so
1436  // abort early. When overloading in C, however, we do permit
1437  if (FromType->isRecordType() || ToType->isRecordType()) {
1438    if (S.getLangOpts().CPlusPlus)
1439      return false;
1440
1441    // When we're overloading in C, we allow, as standard conversions,
1442  }
1443
1444  // The first conversion can be an lvalue-to-rvalue conversion,
1445  // array-to-pointer conversion, or function-to-pointer conversion
1446  // (C++ 4p1).
1447
1448  if (FromType == S.Context.OverloadTy) {
1449    DeclAccessPair AccessPair;
1450    if (FunctionDecl *Fn
1451          = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1452                                                 AccessPair)) {
1453      // We were able to resolve the address of the overloaded function,
1454      // so we can convert to the type of that function.
1455      FromType = Fn->getType();
1456
1457      // we can sometimes resolve &foo<int> regardless of ToType, so check
1458      // if the type matches (identity) or we are converting to bool
1459      if (!S.Context.hasSameUnqualifiedType(
1460                      S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1461        QualType resultTy;
1462        // if the function type matches except for [[noreturn]], it's ok
1463        if (!S.IsNoReturnConversion(FromType,
1464              S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1465          // otherwise, only a boolean conversion is standard
1466          if (!ToType->isBooleanType())
1467            return false;
1468      }
1469
1470      // Check if the "from" expression is taking the address of an overloaded
1471      // function and recompute the FromType accordingly. Take advantage of the
1472      // fact that non-static member functions *must* have such an address-of
1473      // expression.
1474      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1475      if (Method && !Method->isStatic()) {
1476        assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1477               "Non-unary operator on non-static member address");
1478        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1479               == UO_AddrOf &&
1480               "Non-address-of operator on non-static member address");
1481        const Type *ClassType
1482          = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1483        FromType = S.Context.getMemberPointerType(FromType, ClassType);
1484      } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1485        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1486               UO_AddrOf &&
1487               "Non-address-of operator for overloaded function expression");
1488        FromType = S.Context.getPointerType(FromType);
1489      }
1490
1491      // Check that we've computed the proper type after overload resolution.
1492      assert(S.Context.hasSameType(
1493        FromType,
1494        S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1495    } else {
1496      return false;
1497    }
1498  }
1499  // Lvalue-to-rvalue conversion (C++11 4.1):
1500  //   A glvalue (3.10) of a non-function, non-array type T can
1501  //   be converted to a prvalue.
1502  bool argIsLValue = From->isGLValue();
1503  if (argIsLValue &&
1504      !FromType->isFunctionType() && !FromType->isArrayType() &&
1505      S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1506    SCS.First = ICK_Lvalue_To_Rvalue;
1507
1508    // C11 6.3.2.1p2:
1509    //   ... if the lvalue has atomic type, the value has the non-atomic version
1510    //   of the type of the lvalue ...
1511    if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1512      FromType = Atomic->getValueType();
1513
1514    // If T is a non-class type, the type of the rvalue is the
1515    // cv-unqualified version of T. Otherwise, the type of the rvalue
1516    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1517    // just strip the qualifiers because they don't matter.
1518    FromType = FromType.getUnqualifiedType();
1519  } else if (FromType->isArrayType()) {
1520    // Array-to-pointer conversion (C++ 4.2)
1521    SCS.First = ICK_Array_To_Pointer;
1522
1523    // An lvalue or rvalue of type "array of N T" or "array of unknown
1524    // bound of T" can be converted to an rvalue of type "pointer to
1525    // T" (C++ 4.2p1).
1526    FromType = S.Context.getArrayDecayedType(FromType);
1527
1528    if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1529      // This conversion is deprecated. (C++ D.4).
1530      SCS.DeprecatedStringLiteralToCharPtr = true;
1531
1532      // For the purpose of ranking in overload resolution
1533      // (13.3.3.1.1), this conversion is considered an
1534      // array-to-pointer conversion followed by a qualification
1535      // conversion (4.4). (C++ 4.2p2)
1536      SCS.Second = ICK_Identity;
1537      SCS.Third = ICK_Qualification;
1538      SCS.QualificationIncludesObjCLifetime = false;
1539      SCS.setAllToTypes(FromType);
1540      return true;
1541    }
1542  } else if (FromType->isFunctionType() && argIsLValue) {
1543    // Function-to-pointer conversion (C++ 4.3).
1544    SCS.First = ICK_Function_To_Pointer;
1545
1546    // An lvalue of function type T can be converted to an rvalue of
1547    // type "pointer to T." The result is a pointer to the
1548    // function. (C++ 4.3p1).
1549    FromType = S.Context.getPointerType(FromType);
1550  } else {
1551    // We don't require any conversions for the first step.
1552    SCS.First = ICK_Identity;
1553  }
1554  SCS.setToType(0, FromType);
1555
1556  // The second conversion can be an integral promotion, floating
1557  // point promotion, integral conversion, floating point conversion,
1558  // floating-integral conversion, pointer conversion,
1559  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1560  // For overloading in C, this can also be a "compatible-type"
1561  // conversion.
1562  bool IncompatibleObjC = false;
1563  ImplicitConversionKind SecondICK = ICK_Identity;
1564  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1565    // The unqualified versions of the types are the same: there's no
1566    // conversion to do.
1567    SCS.Second = ICK_Identity;
1568  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1569    // Integral promotion (C++ 4.5).
1570    SCS.Second = ICK_Integral_Promotion;
1571    FromType = ToType.getUnqualifiedType();
1572  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1573    // Floating point promotion (C++ 4.6).
1574    SCS.Second = ICK_Floating_Promotion;
1575    FromType = ToType.getUnqualifiedType();
1576  } else if (S.IsComplexPromotion(FromType, ToType)) {
1577    // Complex promotion (Clang extension)
1578    SCS.Second = ICK_Complex_Promotion;
1579    FromType = ToType.getUnqualifiedType();
1580  } else if (ToType->isBooleanType() &&
1581             (FromType->isArithmeticType() ||
1582              FromType->isAnyPointerType() ||
1583              FromType->isBlockPointerType() ||
1584              FromType->isMemberPointerType() ||
1585              FromType->isNullPtrType())) {
1586    // Boolean conversions (C++ 4.12).
1587    SCS.Second = ICK_Boolean_Conversion;
1588    FromType = S.Context.BoolTy;
1589  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1590             ToType->isIntegralType(S.Context)) {
1591    // Integral conversions (C++ 4.7).
1592    SCS.Second = ICK_Integral_Conversion;
1593    FromType = ToType.getUnqualifiedType();
1594  } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1595    // Complex conversions (C99 6.3.1.6)
1596    SCS.Second = ICK_Complex_Conversion;
1597    FromType = ToType.getUnqualifiedType();
1598  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1599             (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1600    // Complex-real conversions (C99 6.3.1.7)
1601    SCS.Second = ICK_Complex_Real;
1602    FromType = ToType.getUnqualifiedType();
1603  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1604    // Floating point conversions (C++ 4.8).
1605    SCS.Second = ICK_Floating_Conversion;
1606    FromType = ToType.getUnqualifiedType();
1607  } else if ((FromType->isRealFloatingType() &&
1608              ToType->isIntegralType(S.Context)) ||
1609             (FromType->isIntegralOrUnscopedEnumerationType() &&
1610              ToType->isRealFloatingType())) {
1611    // Floating-integral conversions (C++ 4.9).
1612    SCS.Second = ICK_Floating_Integral;
1613    FromType = ToType.getUnqualifiedType();
1614  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1615    SCS.Second = ICK_Block_Pointer_Conversion;
1616  } else if (AllowObjCWritebackConversion &&
1617             S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1618    SCS.Second = ICK_Writeback_Conversion;
1619  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1620                                   FromType, IncompatibleObjC)) {
1621    // Pointer conversions (C++ 4.10).
1622    SCS.Second = ICK_Pointer_Conversion;
1623    SCS.IncompatibleObjC = IncompatibleObjC;
1624    FromType = FromType.getUnqualifiedType();
1625  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1626                                         InOverloadResolution, FromType)) {
1627    // Pointer to member conversions (4.11).
1628    SCS.Second = ICK_Pointer_Member;
1629  } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1630    SCS.Second = SecondICK;
1631    FromType = ToType.getUnqualifiedType();
1632  } else if (!S.getLangOpts().CPlusPlus &&
1633             S.Context.typesAreCompatible(ToType, FromType)) {
1634    // Compatible conversions (Clang extension for C function overloading)
1635    SCS.Second = ICK_Compatible_Conversion;
1636    FromType = ToType.getUnqualifiedType();
1637  } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1638    // Treat a conversion that strips "noreturn" as an identity conversion.
1639    SCS.Second = ICK_NoReturn_Adjustment;
1640  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1641                                             InOverloadResolution,
1642                                             SCS, CStyle)) {
1643    SCS.Second = ICK_TransparentUnionConversion;
1644    FromType = ToType;
1645  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1646                                 CStyle)) {
1647    // tryAtomicConversion has updated the standard conversion sequence
1648    // appropriately.
1649    return true;
1650  } else if (ToType->isEventT() &&
1651             From->isIntegerConstantExpr(S.getASTContext()) &&
1652             (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1653    SCS.Second = ICK_Zero_Event_Conversion;
1654    FromType = ToType;
1655  } else {
1656    // No second conversion required.
1657    SCS.Second = ICK_Identity;
1658  }
1659  SCS.setToType(1, FromType);
1660
1661  QualType CanonFrom;
1662  QualType CanonTo;
1663  // The third conversion can be a qualification conversion (C++ 4p1).
1664  bool ObjCLifetimeConversion;
1665  if (S.IsQualificationConversion(FromType, ToType, CStyle,
1666                                  ObjCLifetimeConversion)) {
1667    SCS.Third = ICK_Qualification;
1668    SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1669    FromType = ToType;
1670    CanonFrom = S.Context.getCanonicalType(FromType);
1671    CanonTo = S.Context.getCanonicalType(ToType);
1672  } else {
1673    // No conversion required
1674    SCS.Third = ICK_Identity;
1675
1676    // C++ [over.best.ics]p6:
1677    //   [...] Any difference in top-level cv-qualification is
1678    //   subsumed by the initialization itself and does not constitute
1679    //   a conversion. [...]
1680    CanonFrom = S.Context.getCanonicalType(FromType);
1681    CanonTo = S.Context.getCanonicalType(ToType);
1682    if (CanonFrom.getLocalUnqualifiedType()
1683                                       == CanonTo.getLocalUnqualifiedType() &&
1684        CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1685      FromType = ToType;
1686      CanonFrom = CanonTo;
1687    }
1688  }
1689  SCS.setToType(2, FromType);
1690
1691  // If we have not converted the argument type to the parameter type,
1692  // this is a bad conversion sequence.
1693  if (CanonFrom != CanonTo)
1694    return false;
1695
1696  return true;
1697}
1698
1699static bool
1700IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1701                                     QualType &ToType,
1702                                     bool InOverloadResolution,
1703                                     StandardConversionSequence &SCS,
1704                                     bool CStyle) {
1705
1706  const RecordType *UT = ToType->getAsUnionType();
1707  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1708    return false;
1709  // The field to initialize within the transparent union.
1710  RecordDecl *UD = UT->getDecl();
1711  // It's compatible if the expression matches any of the fields.
1712  for (RecordDecl::field_iterator it = UD->field_begin(),
1713       itend = UD->field_end();
1714       it != itend; ++it) {
1715    if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1716                             CStyle, /*ObjCWritebackConversion=*/false)) {
1717      ToType = it->getType();
1718      return true;
1719    }
1720  }
1721  return false;
1722}
1723
1724/// IsIntegralPromotion - Determines whether the conversion from the
1725/// expression From (whose potentially-adjusted type is FromType) to
1726/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1727/// sets PromotedType to the promoted type.
1728bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1729  const BuiltinType *To = ToType->getAs<BuiltinType>();
1730  // All integers are built-in.
1731  if (!To) {
1732    return false;
1733  }
1734
1735  // An rvalue of type char, signed char, unsigned char, short int, or
1736  // unsigned short int can be converted to an rvalue of type int if
1737  // int can represent all the values of the source type; otherwise,
1738  // the source rvalue can be converted to an rvalue of type unsigned
1739  // int (C++ 4.5p1).
1740  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1741      !FromType->isEnumeralType()) {
1742    if (// We can promote any signed, promotable integer type to an int
1743        (FromType->isSignedIntegerType() ||
1744         // We can promote any unsigned integer type whose size is
1745         // less than int to an int.
1746         (!FromType->isSignedIntegerType() &&
1747          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1748      return To->getKind() == BuiltinType::Int;
1749    }
1750
1751    return To->getKind() == BuiltinType::UInt;
1752  }
1753
1754  // C++11 [conv.prom]p3:
1755  //   A prvalue of an unscoped enumeration type whose underlying type is not
1756  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1757  //   following types that can represent all the values of the enumeration
1758  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1759  //   unsigned int, long int, unsigned long int, long long int, or unsigned
1760  //   long long int. If none of the types in that list can represent all the
1761  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1762  //   type can be converted to an rvalue a prvalue of the extended integer type
1763  //   with lowest integer conversion rank (4.13) greater than the rank of long
1764  //   long in which all the values of the enumeration can be represented. If
1765  //   there are two such extended types, the signed one is chosen.
1766  // C++11 [conv.prom]p4:
1767  //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1768  //   can be converted to a prvalue of its underlying type. Moreover, if
1769  //   integral promotion can be applied to its underlying type, a prvalue of an
1770  //   unscoped enumeration type whose underlying type is fixed can also be
1771  //   converted to a prvalue of the promoted underlying type.
1772  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1773    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1774    // provided for a scoped enumeration.
1775    if (FromEnumType->getDecl()->isScoped())
1776      return false;
1777
1778    // We can perform an integral promotion to the underlying type of the enum,
1779    // even if that's not the promoted type.
1780    if (FromEnumType->getDecl()->isFixed()) {
1781      QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1782      return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1783             IsIntegralPromotion(From, Underlying, ToType);
1784    }
1785
1786    // We have already pre-calculated the promotion type, so this is trivial.
1787    if (ToType->isIntegerType() &&
1788        !RequireCompleteType(From->getLocStart(), FromType, 0))
1789      return Context.hasSameUnqualifiedType(ToType,
1790                                FromEnumType->getDecl()->getPromotionType());
1791  }
1792
1793  // C++0x [conv.prom]p2:
1794  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1795  //   to an rvalue a prvalue of the first of the following types that can
1796  //   represent all the values of its underlying type: int, unsigned int,
1797  //   long int, unsigned long int, long long int, or unsigned long long int.
1798  //   If none of the types in that list can represent all the values of its
1799  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1800  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1801  //   type.
1802  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1803      ToType->isIntegerType()) {
1804    // Determine whether the type we're converting from is signed or
1805    // unsigned.
1806    bool FromIsSigned = FromType->isSignedIntegerType();
1807    uint64_t FromSize = Context.getTypeSize(FromType);
1808
1809    // The types we'll try to promote to, in the appropriate
1810    // order. Try each of these types.
1811    QualType PromoteTypes[6] = {
1812      Context.IntTy, Context.UnsignedIntTy,
1813      Context.LongTy, Context.UnsignedLongTy ,
1814      Context.LongLongTy, Context.UnsignedLongLongTy
1815    };
1816    for (int Idx = 0; Idx < 6; ++Idx) {
1817      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1818      if (FromSize < ToSize ||
1819          (FromSize == ToSize &&
1820           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1821        // We found the type that we can promote to. If this is the
1822        // type we wanted, we have a promotion. Otherwise, no
1823        // promotion.
1824        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1825      }
1826    }
1827  }
1828
1829  // An rvalue for an integral bit-field (9.6) can be converted to an
1830  // rvalue of type int if int can represent all the values of the
1831  // bit-field; otherwise, it can be converted to unsigned int if
1832  // unsigned int can represent all the values of the bit-field. If
1833  // the bit-field is larger yet, no integral promotion applies to
1834  // it. If the bit-field has an enumerated type, it is treated as any
1835  // other value of that type for promotion purposes (C++ 4.5p3).
1836  // FIXME: We should delay checking of bit-fields until we actually perform the
1837  // conversion.
1838  using llvm::APSInt;
1839  if (From)
1840    if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1841      APSInt BitWidth;
1842      if (FromType->isIntegralType(Context) &&
1843          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1844        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1845        ToSize = Context.getTypeSize(ToType);
1846
1847        // Are we promoting to an int from a bitfield that fits in an int?
1848        if (BitWidth < ToSize ||
1849            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1850          return To->getKind() == BuiltinType::Int;
1851        }
1852
1853        // Are we promoting to an unsigned int from an unsigned bitfield
1854        // that fits into an unsigned int?
1855        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1856          return To->getKind() == BuiltinType::UInt;
1857        }
1858
1859        return false;
1860      }
1861    }
1862
1863  // An rvalue of type bool can be converted to an rvalue of type int,
1864  // with false becoming zero and true becoming one (C++ 4.5p4).
1865  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1866    return true;
1867  }
1868
1869  return false;
1870}
1871
1872/// IsFloatingPointPromotion - Determines whether the conversion from
1873/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1874/// returns true and sets PromotedType to the promoted type.
1875bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1876  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1877    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1878      /// An rvalue of type float can be converted to an rvalue of type
1879      /// double. (C++ 4.6p1).
1880      if (FromBuiltin->getKind() == BuiltinType::Float &&
1881          ToBuiltin->getKind() == BuiltinType::Double)
1882        return true;
1883
1884      // C99 6.3.1.5p1:
1885      //   When a float is promoted to double or long double, or a
1886      //   double is promoted to long double [...].
1887      if (!getLangOpts().CPlusPlus &&
1888          (FromBuiltin->getKind() == BuiltinType::Float ||
1889           FromBuiltin->getKind() == BuiltinType::Double) &&
1890          (ToBuiltin->getKind() == BuiltinType::LongDouble))
1891        return true;
1892
1893      // Half can be promoted to float.
1894      if (!getLangOpts().NativeHalfType &&
1895           FromBuiltin->getKind() == BuiltinType::Half &&
1896          ToBuiltin->getKind() == BuiltinType::Float)
1897        return true;
1898    }
1899
1900  return false;
1901}
1902
1903/// \brief Determine if a conversion is a complex promotion.
1904///
1905/// A complex promotion is defined as a complex -> complex conversion
1906/// where the conversion between the underlying real types is a
1907/// floating-point or integral promotion.
1908bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1909  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1910  if (!FromComplex)
1911    return false;
1912
1913  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1914  if (!ToComplex)
1915    return false;
1916
1917  return IsFloatingPointPromotion(FromComplex->getElementType(),
1918                                  ToComplex->getElementType()) ||
1919    IsIntegralPromotion(0, FromComplex->getElementType(),
1920                        ToComplex->getElementType());
1921}
1922
1923/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1924/// the pointer type FromPtr to a pointer to type ToPointee, with the
1925/// same type qualifiers as FromPtr has on its pointee type. ToType,
1926/// if non-empty, will be a pointer to ToType that may or may not have
1927/// the right set of qualifiers on its pointee.
1928///
1929static QualType
1930BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1931                                   QualType ToPointee, QualType ToType,
1932                                   ASTContext &Context,
1933                                   bool StripObjCLifetime = false) {
1934  assert((FromPtr->getTypeClass() == Type::Pointer ||
1935          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1936         "Invalid similarly-qualified pointer type");
1937
1938  /// Conversions to 'id' subsume cv-qualifier conversions.
1939  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1940    return ToType.getUnqualifiedType();
1941
1942  QualType CanonFromPointee
1943    = Context.getCanonicalType(FromPtr->getPointeeType());
1944  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1945  Qualifiers Quals = CanonFromPointee.getQualifiers();
1946
1947  if (StripObjCLifetime)
1948    Quals.removeObjCLifetime();
1949
1950  // Exact qualifier match -> return the pointer type we're converting to.
1951  if (CanonToPointee.getLocalQualifiers() == Quals) {
1952    // ToType is exactly what we need. Return it.
1953    if (!ToType.isNull())
1954      return ToType.getUnqualifiedType();
1955
1956    // Build a pointer to ToPointee. It has the right qualifiers
1957    // already.
1958    if (isa<ObjCObjectPointerType>(ToType))
1959      return Context.getObjCObjectPointerType(ToPointee);
1960    return Context.getPointerType(ToPointee);
1961  }
1962
1963  // Just build a canonical type that has the right qualifiers.
1964  QualType QualifiedCanonToPointee
1965    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1966
1967  if (isa<ObjCObjectPointerType>(ToType))
1968    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1969  return Context.getPointerType(QualifiedCanonToPointee);
1970}
1971
1972static bool isNullPointerConstantForConversion(Expr *Expr,
1973                                               bool InOverloadResolution,
1974                                               ASTContext &Context) {
1975  // Handle value-dependent integral null pointer constants correctly.
1976  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1977  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1978      Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1979    return !InOverloadResolution;
1980
1981  return Expr->isNullPointerConstant(Context,
1982                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1983                                        : Expr::NPC_ValueDependentIsNull);
1984}
1985
1986/// IsPointerConversion - Determines whether the conversion of the
1987/// expression From, which has the (possibly adjusted) type FromType,
1988/// can be converted to the type ToType via a pointer conversion (C++
1989/// 4.10). If so, returns true and places the converted type (that
1990/// might differ from ToType in its cv-qualifiers at some level) into
1991/// ConvertedType.
1992///
1993/// This routine also supports conversions to and from block pointers
1994/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1995/// pointers to interfaces. FIXME: Once we've determined the
1996/// appropriate overloading rules for Objective-C, we may want to
1997/// split the Objective-C checks into a different routine; however,
1998/// GCC seems to consider all of these conversions to be pointer
1999/// conversions, so for now they live here. IncompatibleObjC will be
2000/// set if the conversion is an allowed Objective-C conversion that
2001/// should result in a warning.
2002bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2003                               bool InOverloadResolution,
2004                               QualType& ConvertedType,
2005                               bool &IncompatibleObjC) {
2006  IncompatibleObjC = false;
2007  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2008                              IncompatibleObjC))
2009    return true;
2010
2011  // Conversion from a null pointer constant to any Objective-C pointer type.
2012  if (ToType->isObjCObjectPointerType() &&
2013      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2014    ConvertedType = ToType;
2015    return true;
2016  }
2017
2018  // Blocks: Block pointers can be converted to void*.
2019  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2020      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2021    ConvertedType = ToType;
2022    return true;
2023  }
2024  // Blocks: A null pointer constant can be converted to a block
2025  // pointer type.
2026  if (ToType->isBlockPointerType() &&
2027      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2028    ConvertedType = ToType;
2029    return true;
2030  }
2031
2032  // If the left-hand-side is nullptr_t, the right side can be a null
2033  // pointer constant.
2034  if (ToType->isNullPtrType() &&
2035      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2036    ConvertedType = ToType;
2037    return true;
2038  }
2039
2040  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2041  if (!ToTypePtr)
2042    return false;
2043
2044  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2045  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2046    ConvertedType = ToType;
2047    return true;
2048  }
2049
2050  // Beyond this point, both types need to be pointers
2051  // , including objective-c pointers.
2052  QualType ToPointeeType = ToTypePtr->getPointeeType();
2053  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2054      !getLangOpts().ObjCAutoRefCount) {
2055    ConvertedType = BuildSimilarlyQualifiedPointerType(
2056                                      FromType->getAs<ObjCObjectPointerType>(),
2057                                                       ToPointeeType,
2058                                                       ToType, Context);
2059    return true;
2060  }
2061  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2062  if (!FromTypePtr)
2063    return false;
2064
2065  QualType FromPointeeType = FromTypePtr->getPointeeType();
2066
2067  // If the unqualified pointee types are the same, this can't be a
2068  // pointer conversion, so don't do all of the work below.
2069  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2070    return false;
2071
2072  // An rvalue of type "pointer to cv T," where T is an object type,
2073  // can be converted to an rvalue of type "pointer to cv void" (C++
2074  // 4.10p2).
2075  if (FromPointeeType->isIncompleteOrObjectType() &&
2076      ToPointeeType->isVoidType()) {
2077    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2078                                                       ToPointeeType,
2079                                                       ToType, Context,
2080                                                   /*StripObjCLifetime=*/true);
2081    return true;
2082  }
2083
2084  // MSVC allows implicit function to void* type conversion.
2085  if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2086      ToPointeeType->isVoidType()) {
2087    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2088                                                       ToPointeeType,
2089                                                       ToType, Context);
2090    return true;
2091  }
2092
2093  // When we're overloading in C, we allow a special kind of pointer
2094  // conversion for compatible-but-not-identical pointee types.
2095  if (!getLangOpts().CPlusPlus &&
2096      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2097    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2098                                                       ToPointeeType,
2099                                                       ToType, Context);
2100    return true;
2101  }
2102
2103  // C++ [conv.ptr]p3:
2104  //
2105  //   An rvalue of type "pointer to cv D," where D is a class type,
2106  //   can be converted to an rvalue of type "pointer to cv B," where
2107  //   B is a base class (clause 10) of D. If B is an inaccessible
2108  //   (clause 11) or ambiguous (10.2) base class of D, a program that
2109  //   necessitates this conversion is ill-formed. The result of the
2110  //   conversion is a pointer to the base class sub-object of the
2111  //   derived class object. The null pointer value is converted to
2112  //   the null pointer value of the destination type.
2113  //
2114  // Note that we do not check for ambiguity or inaccessibility
2115  // here. That is handled by CheckPointerConversion.
2116  if (getLangOpts().CPlusPlus &&
2117      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2118      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2119      !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2120      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2121    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2122                                                       ToPointeeType,
2123                                                       ToType, Context);
2124    return true;
2125  }
2126
2127  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2128      Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2129    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2130                                                       ToPointeeType,
2131                                                       ToType, Context);
2132    return true;
2133  }
2134
2135  return false;
2136}
2137
2138/// \brief Adopt the given qualifiers for the given type.
2139static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2140  Qualifiers TQs = T.getQualifiers();
2141
2142  // Check whether qualifiers already match.
2143  if (TQs == Qs)
2144    return T;
2145
2146  if (Qs.compatiblyIncludes(TQs))
2147    return Context.getQualifiedType(T, Qs);
2148
2149  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2150}
2151
2152/// isObjCPointerConversion - Determines whether this is an
2153/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2154/// with the same arguments and return values.
2155bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2156                                   QualType& ConvertedType,
2157                                   bool &IncompatibleObjC) {
2158  if (!getLangOpts().ObjC1)
2159    return false;
2160
2161  // The set of qualifiers on the type we're converting from.
2162  Qualifiers FromQualifiers = FromType.getQualifiers();
2163
2164  // First, we handle all conversions on ObjC object pointer types.
2165  const ObjCObjectPointerType* ToObjCPtr =
2166    ToType->getAs<ObjCObjectPointerType>();
2167  const ObjCObjectPointerType *FromObjCPtr =
2168    FromType->getAs<ObjCObjectPointerType>();
2169
2170  if (ToObjCPtr && FromObjCPtr) {
2171    // If the pointee types are the same (ignoring qualifications),
2172    // then this is not a pointer conversion.
2173    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2174                                       FromObjCPtr->getPointeeType()))
2175      return false;
2176
2177    // Check for compatible
2178    // Objective C++: We're able to convert between "id" or "Class" and a
2179    // pointer to any interface (in both directions).
2180    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2181      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2182      return true;
2183    }
2184    // Conversions with Objective-C's id<...>.
2185    if ((FromObjCPtr->isObjCQualifiedIdType() ||
2186         ToObjCPtr->isObjCQualifiedIdType()) &&
2187        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2188                                                  /*compare=*/false)) {
2189      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2190      return true;
2191    }
2192    // Objective C++: We're able to convert from a pointer to an
2193    // interface to a pointer to a different interface.
2194    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2195      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2196      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2197      if (getLangOpts().CPlusPlus && LHS && RHS &&
2198          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2199                                                FromObjCPtr->getPointeeType()))
2200        return false;
2201      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2202                                                   ToObjCPtr->getPointeeType(),
2203                                                         ToType, Context);
2204      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2205      return true;
2206    }
2207
2208    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2209      // Okay: this is some kind of implicit downcast of Objective-C
2210      // interfaces, which is permitted. However, we're going to
2211      // complain about it.
2212      IncompatibleObjC = true;
2213      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2214                                                   ToObjCPtr->getPointeeType(),
2215                                                         ToType, Context);
2216      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2217      return true;
2218    }
2219  }
2220  // Beyond this point, both types need to be C pointers or block pointers.
2221  QualType ToPointeeType;
2222  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2223    ToPointeeType = ToCPtr->getPointeeType();
2224  else if (const BlockPointerType *ToBlockPtr =
2225            ToType->getAs<BlockPointerType>()) {
2226    // Objective C++: We're able to convert from a pointer to any object
2227    // to a block pointer type.
2228    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2229      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2230      return true;
2231    }
2232    ToPointeeType = ToBlockPtr->getPointeeType();
2233  }
2234  else if (FromType->getAs<BlockPointerType>() &&
2235           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2236    // Objective C++: We're able to convert from a block pointer type to a
2237    // pointer to any object.
2238    ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2239    return true;
2240  }
2241  else
2242    return false;
2243
2244  QualType FromPointeeType;
2245  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2246    FromPointeeType = FromCPtr->getPointeeType();
2247  else if (const BlockPointerType *FromBlockPtr =
2248           FromType->getAs<BlockPointerType>())
2249    FromPointeeType = FromBlockPtr->getPointeeType();
2250  else
2251    return false;
2252
2253  // If we have pointers to pointers, recursively check whether this
2254  // is an Objective-C conversion.
2255  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2256      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2257                              IncompatibleObjC)) {
2258    // We always complain about this conversion.
2259    IncompatibleObjC = true;
2260    ConvertedType = Context.getPointerType(ConvertedType);
2261    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2262    return true;
2263  }
2264  // Allow conversion of pointee being objective-c pointer to another one;
2265  // as in I* to id.
2266  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2267      ToPointeeType->getAs<ObjCObjectPointerType>() &&
2268      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2269                              IncompatibleObjC)) {
2270
2271    ConvertedType = Context.getPointerType(ConvertedType);
2272    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2273    return true;
2274  }
2275
2276  // If we have pointers to functions or blocks, check whether the only
2277  // differences in the argument and result types are in Objective-C
2278  // pointer conversions. If so, we permit the conversion (but
2279  // complain about it).
2280  const FunctionProtoType *FromFunctionType
2281    = FromPointeeType->getAs<FunctionProtoType>();
2282  const FunctionProtoType *ToFunctionType
2283    = ToPointeeType->getAs<FunctionProtoType>();
2284  if (FromFunctionType && ToFunctionType) {
2285    // If the function types are exactly the same, this isn't an
2286    // Objective-C pointer conversion.
2287    if (Context.getCanonicalType(FromPointeeType)
2288          == Context.getCanonicalType(ToPointeeType))
2289      return false;
2290
2291    // Perform the quick checks that will tell us whether these
2292    // function types are obviously different.
2293    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2294        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2295        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2296      return false;
2297
2298    bool HasObjCConversion = false;
2299    if (Context.getCanonicalType(FromFunctionType->getResultType())
2300          == Context.getCanonicalType(ToFunctionType->getResultType())) {
2301      // Okay, the types match exactly. Nothing to do.
2302    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2303                                       ToFunctionType->getResultType(),
2304                                       ConvertedType, IncompatibleObjC)) {
2305      // Okay, we have an Objective-C pointer conversion.
2306      HasObjCConversion = true;
2307    } else {
2308      // Function types are too different. Abort.
2309      return false;
2310    }
2311
2312    // Check argument types.
2313    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2314         ArgIdx != NumArgs; ++ArgIdx) {
2315      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2316      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2317      if (Context.getCanonicalType(FromArgType)
2318            == Context.getCanonicalType(ToArgType)) {
2319        // Okay, the types match exactly. Nothing to do.
2320      } else if (isObjCPointerConversion(FromArgType, ToArgType,
2321                                         ConvertedType, IncompatibleObjC)) {
2322        // Okay, we have an Objective-C pointer conversion.
2323        HasObjCConversion = true;
2324      } else {
2325        // Argument types are too different. Abort.
2326        return false;
2327      }
2328    }
2329
2330    if (HasObjCConversion) {
2331      // We had an Objective-C conversion. Allow this pointer
2332      // conversion, but complain about it.
2333      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2334      IncompatibleObjC = true;
2335      return true;
2336    }
2337  }
2338
2339  return false;
2340}
2341
2342/// \brief Determine whether this is an Objective-C writeback conversion,
2343/// used for parameter passing when performing automatic reference counting.
2344///
2345/// \param FromType The type we're converting form.
2346///
2347/// \param ToType The type we're converting to.
2348///
2349/// \param ConvertedType The type that will be produced after applying
2350/// this conversion.
2351bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2352                                     QualType &ConvertedType) {
2353  if (!getLangOpts().ObjCAutoRefCount ||
2354      Context.hasSameUnqualifiedType(FromType, ToType))
2355    return false;
2356
2357  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2358  QualType ToPointee;
2359  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2360    ToPointee = ToPointer->getPointeeType();
2361  else
2362    return false;
2363
2364  Qualifiers ToQuals = ToPointee.getQualifiers();
2365  if (!ToPointee->isObjCLifetimeType() ||
2366      ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2367      !ToQuals.withoutObjCLifetime().empty())
2368    return false;
2369
2370  // Argument must be a pointer to __strong to __weak.
2371  QualType FromPointee;
2372  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2373    FromPointee = FromPointer->getPointeeType();
2374  else
2375    return false;
2376
2377  Qualifiers FromQuals = FromPointee.getQualifiers();
2378  if (!FromPointee->isObjCLifetimeType() ||
2379      (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2380       FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2381    return false;
2382
2383  // Make sure that we have compatible qualifiers.
2384  FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2385  if (!ToQuals.compatiblyIncludes(FromQuals))
2386    return false;
2387
2388  // Remove qualifiers from the pointee type we're converting from; they
2389  // aren't used in the compatibility check belong, and we'll be adding back
2390  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2391  FromPointee = FromPointee.getUnqualifiedType();
2392
2393  // The unqualified form of the pointee types must be compatible.
2394  ToPointee = ToPointee.getUnqualifiedType();
2395  bool IncompatibleObjC;
2396  if (Context.typesAreCompatible(FromPointee, ToPointee))
2397    FromPointee = ToPointee;
2398  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2399                                    IncompatibleObjC))
2400    return false;
2401
2402  /// \brief Construct the type we're converting to, which is a pointer to
2403  /// __autoreleasing pointee.
2404  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2405  ConvertedType = Context.getPointerType(FromPointee);
2406  return true;
2407}
2408
2409bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2410                                    QualType& ConvertedType) {
2411  QualType ToPointeeType;
2412  if (const BlockPointerType *ToBlockPtr =
2413        ToType->getAs<BlockPointerType>())
2414    ToPointeeType = ToBlockPtr->getPointeeType();
2415  else
2416    return false;
2417
2418  QualType FromPointeeType;
2419  if (const BlockPointerType *FromBlockPtr =
2420      FromType->getAs<BlockPointerType>())
2421    FromPointeeType = FromBlockPtr->getPointeeType();
2422  else
2423    return false;
2424  // We have pointer to blocks, check whether the only
2425  // differences in the argument and result types are in Objective-C
2426  // pointer conversions. If so, we permit the conversion.
2427
2428  const FunctionProtoType *FromFunctionType
2429    = FromPointeeType->getAs<FunctionProtoType>();
2430  const FunctionProtoType *ToFunctionType
2431    = ToPointeeType->getAs<FunctionProtoType>();
2432
2433  if (!FromFunctionType || !ToFunctionType)
2434    return false;
2435
2436  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2437    return true;
2438
2439  // Perform the quick checks that will tell us whether these
2440  // function types are obviously different.
2441  if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2442      FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2443    return false;
2444
2445  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2446  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2447  if (FromEInfo != ToEInfo)
2448    return false;
2449
2450  bool IncompatibleObjC = false;
2451  if (Context.hasSameType(FromFunctionType->getResultType(),
2452                          ToFunctionType->getResultType())) {
2453    // Okay, the types match exactly. Nothing to do.
2454  } else {
2455    QualType RHS = FromFunctionType->getResultType();
2456    QualType LHS = ToFunctionType->getResultType();
2457    if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2458        !RHS.hasQualifiers() && LHS.hasQualifiers())
2459       LHS = LHS.getUnqualifiedType();
2460
2461     if (Context.hasSameType(RHS,LHS)) {
2462       // OK exact match.
2463     } else if (isObjCPointerConversion(RHS, LHS,
2464                                        ConvertedType, IncompatibleObjC)) {
2465     if (IncompatibleObjC)
2466       return false;
2467     // Okay, we have an Objective-C pointer conversion.
2468     }
2469     else
2470       return false;
2471   }
2472
2473   // Check argument types.
2474   for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2475        ArgIdx != NumArgs; ++ArgIdx) {
2476     IncompatibleObjC = false;
2477     QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2478     QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2479     if (Context.hasSameType(FromArgType, ToArgType)) {
2480       // Okay, the types match exactly. Nothing to do.
2481     } else if (isObjCPointerConversion(ToArgType, FromArgType,
2482                                        ConvertedType, IncompatibleObjC)) {
2483       if (IncompatibleObjC)
2484         return false;
2485       // Okay, we have an Objective-C pointer conversion.
2486     } else
2487       // Argument types are too different. Abort.
2488       return false;
2489   }
2490   if (LangOpts.ObjCAutoRefCount &&
2491       !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2492                                                    ToFunctionType))
2493     return false;
2494
2495   ConvertedType = ToType;
2496   return true;
2497}
2498
2499enum {
2500  ft_default,
2501  ft_different_class,
2502  ft_parameter_arity,
2503  ft_parameter_mismatch,
2504  ft_return_type,
2505  ft_qualifer_mismatch
2506};
2507
2508/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2509/// function types.  Catches different number of parameter, mismatch in
2510/// parameter types, and different return types.
2511void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2512                                      QualType FromType, QualType ToType) {
2513  // If either type is not valid, include no extra info.
2514  if (FromType.isNull() || ToType.isNull()) {
2515    PDiag << ft_default;
2516    return;
2517  }
2518
2519  // Get the function type from the pointers.
2520  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2521    const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2522                            *ToMember = ToType->getAs<MemberPointerType>();
2523    if (FromMember->getClass() != ToMember->getClass()) {
2524      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2525            << QualType(FromMember->getClass(), 0);
2526      return;
2527    }
2528    FromType = FromMember->getPointeeType();
2529    ToType = ToMember->getPointeeType();
2530  }
2531
2532  if (FromType->isPointerType())
2533    FromType = FromType->getPointeeType();
2534  if (ToType->isPointerType())
2535    ToType = ToType->getPointeeType();
2536
2537  // Remove references.
2538  FromType = FromType.getNonReferenceType();
2539  ToType = ToType.getNonReferenceType();
2540
2541  // Don't print extra info for non-specialized template functions.
2542  if (FromType->isInstantiationDependentType() &&
2543      !FromType->getAs<TemplateSpecializationType>()) {
2544    PDiag << ft_default;
2545    return;
2546  }
2547
2548  // No extra info for same types.
2549  if (Context.hasSameType(FromType, ToType)) {
2550    PDiag << ft_default;
2551    return;
2552  }
2553
2554  const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2555                          *ToFunction = ToType->getAs<FunctionProtoType>();
2556
2557  // Both types need to be function types.
2558  if (!FromFunction || !ToFunction) {
2559    PDiag << ft_default;
2560    return;
2561  }
2562
2563  if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2564    PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2565          << FromFunction->getNumArgs();
2566    return;
2567  }
2568
2569  // Handle different parameter types.
2570  unsigned ArgPos;
2571  if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2572    PDiag << ft_parameter_mismatch << ArgPos + 1
2573          << ToFunction->getArgType(ArgPos)
2574          << FromFunction->getArgType(ArgPos);
2575    return;
2576  }
2577
2578  // Handle different return type.
2579  if (!Context.hasSameType(FromFunction->getResultType(),
2580                           ToFunction->getResultType())) {
2581    PDiag << ft_return_type << ToFunction->getResultType()
2582          << FromFunction->getResultType();
2583    return;
2584  }
2585
2586  unsigned FromQuals = FromFunction->getTypeQuals(),
2587           ToQuals = ToFunction->getTypeQuals();
2588  if (FromQuals != ToQuals) {
2589    PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2590    return;
2591  }
2592
2593  // Unable to find a difference, so add no extra info.
2594  PDiag << ft_default;
2595}
2596
2597/// FunctionArgTypesAreEqual - This routine checks two function proto types
2598/// for equality of their argument types. Caller has already checked that
2599/// they have same number of arguments. This routine assumes that Objective-C
2600/// pointer types which only differ in their protocol qualifiers are equal.
2601/// If the parameters are different, ArgPos will have the parameter index
2602/// of the first different parameter.
2603bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2604                                    const FunctionProtoType *NewType,
2605                                    unsigned *ArgPos) {
2606  if (!getLangOpts().ObjC1) {
2607    for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2608         N = NewType->arg_type_begin(),
2609         E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2610      if (!Context.hasSameType(*O, *N)) {
2611        if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2612        return false;
2613      }
2614    }
2615    return true;
2616  }
2617
2618  for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2619       N = NewType->arg_type_begin(),
2620       E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2621    QualType ToType = (*O);
2622    QualType FromType = (*N);
2623    if (!Context.hasSameType(ToType, FromType)) {
2624      if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2625        if (const PointerType *PTFr = FromType->getAs<PointerType>())
2626          if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2627               PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2628              (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2629               PTFr->getPointeeType()->isObjCQualifiedClassType()))
2630            continue;
2631      }
2632      else if (const ObjCObjectPointerType *PTTo =
2633                 ToType->getAs<ObjCObjectPointerType>()) {
2634        if (const ObjCObjectPointerType *PTFr =
2635              FromType->getAs<ObjCObjectPointerType>())
2636          if (Context.hasSameUnqualifiedType(
2637                PTTo->getObjectType()->getBaseType(),
2638                PTFr->getObjectType()->getBaseType()))
2639            continue;
2640      }
2641      if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2642      return false;
2643    }
2644  }
2645  return true;
2646}
2647
2648/// CheckPointerConversion - Check the pointer conversion from the
2649/// expression From to the type ToType. This routine checks for
2650/// ambiguous or inaccessible derived-to-base pointer
2651/// conversions for which IsPointerConversion has already returned
2652/// true. It returns true and produces a diagnostic if there was an
2653/// error, or returns false otherwise.
2654bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2655                                  CastKind &Kind,
2656                                  CXXCastPath& BasePath,
2657                                  bool IgnoreBaseAccess) {
2658  QualType FromType = From->getType();
2659  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2660
2661  Kind = CK_BitCast;
2662
2663  if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2664      From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2665      Expr::NPCK_ZeroExpression) {
2666    if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2667      DiagRuntimeBehavior(From->getExprLoc(), From,
2668                          PDiag(diag::warn_impcast_bool_to_null_pointer)
2669                            << ToType << From->getSourceRange());
2670    else if (!isUnevaluatedContext())
2671      Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2672        << ToType << From->getSourceRange();
2673  }
2674  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2675    if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2676      QualType FromPointeeType = FromPtrType->getPointeeType(),
2677               ToPointeeType   = ToPtrType->getPointeeType();
2678
2679      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2680          !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2681        // We must have a derived-to-base conversion. Check an
2682        // ambiguous or inaccessible conversion.
2683        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2684                                         From->getExprLoc(),
2685                                         From->getSourceRange(), &BasePath,
2686                                         IgnoreBaseAccess))
2687          return true;
2688
2689        // The conversion was successful.
2690        Kind = CK_DerivedToBase;
2691      }
2692    }
2693  } else if (const ObjCObjectPointerType *ToPtrType =
2694               ToType->getAs<ObjCObjectPointerType>()) {
2695    if (const ObjCObjectPointerType *FromPtrType =
2696          FromType->getAs<ObjCObjectPointerType>()) {
2697      // Objective-C++ conversions are always okay.
2698      // FIXME: We should have a different class of conversions for the
2699      // Objective-C++ implicit conversions.
2700      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2701        return false;
2702    } else if (FromType->isBlockPointerType()) {
2703      Kind = CK_BlockPointerToObjCPointerCast;
2704    } else {
2705      Kind = CK_CPointerToObjCPointerCast;
2706    }
2707  } else if (ToType->isBlockPointerType()) {
2708    if (!FromType->isBlockPointerType())
2709      Kind = CK_AnyPointerToBlockPointerCast;
2710  }
2711
2712  // We shouldn't fall into this case unless it's valid for other
2713  // reasons.
2714  if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2715    Kind = CK_NullToPointer;
2716
2717  return false;
2718}
2719
2720/// IsMemberPointerConversion - Determines whether the conversion of the
2721/// expression From, which has the (possibly adjusted) type FromType, can be
2722/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2723/// If so, returns true and places the converted type (that might differ from
2724/// ToType in its cv-qualifiers at some level) into ConvertedType.
2725bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2726                                     QualType ToType,
2727                                     bool InOverloadResolution,
2728                                     QualType &ConvertedType) {
2729  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2730  if (!ToTypePtr)
2731    return false;
2732
2733  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2734  if (From->isNullPointerConstant(Context,
2735                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2736                                        : Expr::NPC_ValueDependentIsNull)) {
2737    ConvertedType = ToType;
2738    return true;
2739  }
2740
2741  // Otherwise, both types have to be member pointers.
2742  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2743  if (!FromTypePtr)
2744    return false;
2745
2746  // A pointer to member of B can be converted to a pointer to member of D,
2747  // where D is derived from B (C++ 4.11p2).
2748  QualType FromClass(FromTypePtr->getClass(), 0);
2749  QualType ToClass(ToTypePtr->getClass(), 0);
2750
2751  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2752      !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2753      IsDerivedFrom(ToClass, FromClass)) {
2754    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2755                                                 ToClass.getTypePtr());
2756    return true;
2757  }
2758
2759  return false;
2760}
2761
2762/// CheckMemberPointerConversion - Check the member pointer conversion from the
2763/// expression From to the type ToType. This routine checks for ambiguous or
2764/// virtual or inaccessible base-to-derived member pointer conversions
2765/// for which IsMemberPointerConversion has already returned true. It returns
2766/// true and produces a diagnostic if there was an error, or returns false
2767/// otherwise.
2768bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2769                                        CastKind &Kind,
2770                                        CXXCastPath &BasePath,
2771                                        bool IgnoreBaseAccess) {
2772  QualType FromType = From->getType();
2773  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2774  if (!FromPtrType) {
2775    // This must be a null pointer to member pointer conversion
2776    assert(From->isNullPointerConstant(Context,
2777                                       Expr::NPC_ValueDependentIsNull) &&
2778           "Expr must be null pointer constant!");
2779    Kind = CK_NullToMemberPointer;
2780    return false;
2781  }
2782
2783  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2784  assert(ToPtrType && "No member pointer cast has a target type "
2785                      "that is not a member pointer.");
2786
2787  QualType FromClass = QualType(FromPtrType->getClass(), 0);
2788  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2789
2790  // FIXME: What about dependent types?
2791  assert(FromClass->isRecordType() && "Pointer into non-class.");
2792  assert(ToClass->isRecordType() && "Pointer into non-class.");
2793
2794  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2795                     /*DetectVirtual=*/true);
2796  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2797  assert(DerivationOkay &&
2798         "Should not have been called if derivation isn't OK.");
2799  (void)DerivationOkay;
2800
2801  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2802                                  getUnqualifiedType())) {
2803    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2804    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2805      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2806    return true;
2807  }
2808
2809  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2810    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2811      << FromClass << ToClass << QualType(VBase, 0)
2812      << From->getSourceRange();
2813    return true;
2814  }
2815
2816  if (!IgnoreBaseAccess)
2817    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2818                         Paths.front(),
2819                         diag::err_downcast_from_inaccessible_base);
2820
2821  // Must be a base to derived member conversion.
2822  BuildBasePathArray(Paths, BasePath);
2823  Kind = CK_BaseToDerivedMemberPointer;
2824  return false;
2825}
2826
2827/// IsQualificationConversion - Determines whether the conversion from
2828/// an rvalue of type FromType to ToType is a qualification conversion
2829/// (C++ 4.4).
2830///
2831/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2832/// when the qualification conversion involves a change in the Objective-C
2833/// object lifetime.
2834bool
2835Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2836                                bool CStyle, bool &ObjCLifetimeConversion) {
2837  FromType = Context.getCanonicalType(FromType);
2838  ToType = Context.getCanonicalType(ToType);
2839  ObjCLifetimeConversion = false;
2840
2841  // If FromType and ToType are the same type, this is not a
2842  // qualification conversion.
2843  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2844    return false;
2845
2846  // (C++ 4.4p4):
2847  //   A conversion can add cv-qualifiers at levels other than the first
2848  //   in multi-level pointers, subject to the following rules: [...]
2849  bool PreviousToQualsIncludeConst = true;
2850  bool UnwrappedAnyPointer = false;
2851  while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2852    // Within each iteration of the loop, we check the qualifiers to
2853    // determine if this still looks like a qualification
2854    // conversion. Then, if all is well, we unwrap one more level of
2855    // pointers or pointers-to-members and do it all again
2856    // until there are no more pointers or pointers-to-members left to
2857    // unwrap.
2858    UnwrappedAnyPointer = true;
2859
2860    Qualifiers FromQuals = FromType.getQualifiers();
2861    Qualifiers ToQuals = ToType.getQualifiers();
2862
2863    // Objective-C ARC:
2864    //   Check Objective-C lifetime conversions.
2865    if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2866        UnwrappedAnyPointer) {
2867      if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2868        ObjCLifetimeConversion = true;
2869        FromQuals.removeObjCLifetime();
2870        ToQuals.removeObjCLifetime();
2871      } else {
2872        // Qualification conversions cannot cast between different
2873        // Objective-C lifetime qualifiers.
2874        return false;
2875      }
2876    }
2877
2878    // Allow addition/removal of GC attributes but not changing GC attributes.
2879    if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2880        (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2881      FromQuals.removeObjCGCAttr();
2882      ToQuals.removeObjCGCAttr();
2883    }
2884
2885    //   -- for every j > 0, if const is in cv 1,j then const is in cv
2886    //      2,j, and similarly for volatile.
2887    if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2888      return false;
2889
2890    //   -- if the cv 1,j and cv 2,j are different, then const is in
2891    //      every cv for 0 < k < j.
2892    if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2893        && !PreviousToQualsIncludeConst)
2894      return false;
2895
2896    // Keep track of whether all prior cv-qualifiers in the "to" type
2897    // include const.
2898    PreviousToQualsIncludeConst
2899      = PreviousToQualsIncludeConst && ToQuals.hasConst();
2900  }
2901
2902  // We are left with FromType and ToType being the pointee types
2903  // after unwrapping the original FromType and ToType the same number
2904  // of types. If we unwrapped any pointers, and if FromType and
2905  // ToType have the same unqualified type (since we checked
2906  // qualifiers above), then this is a qualification conversion.
2907  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2908}
2909
2910/// \brief - Determine whether this is a conversion from a scalar type to an
2911/// atomic type.
2912///
2913/// If successful, updates \c SCS's second and third steps in the conversion
2914/// sequence to finish the conversion.
2915static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2916                                bool InOverloadResolution,
2917                                StandardConversionSequence &SCS,
2918                                bool CStyle) {
2919  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2920  if (!ToAtomic)
2921    return false;
2922
2923  StandardConversionSequence InnerSCS;
2924  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2925                            InOverloadResolution, InnerSCS,
2926                            CStyle, /*AllowObjCWritebackConversion=*/false))
2927    return false;
2928
2929  SCS.Second = InnerSCS.Second;
2930  SCS.setToType(1, InnerSCS.getToType(1));
2931  SCS.Third = InnerSCS.Third;
2932  SCS.QualificationIncludesObjCLifetime
2933    = InnerSCS.QualificationIncludesObjCLifetime;
2934  SCS.setToType(2, InnerSCS.getToType(2));
2935  return true;
2936}
2937
2938static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2939                                              CXXConstructorDecl *Constructor,
2940                                              QualType Type) {
2941  const FunctionProtoType *CtorType =
2942      Constructor->getType()->getAs<FunctionProtoType>();
2943  if (CtorType->getNumArgs() > 0) {
2944    QualType FirstArg = CtorType->getArgType(0);
2945    if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2946      return true;
2947  }
2948  return false;
2949}
2950
2951static OverloadingResult
2952IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2953                                       CXXRecordDecl *To,
2954                                       UserDefinedConversionSequence &User,
2955                                       OverloadCandidateSet &CandidateSet,
2956                                       bool AllowExplicit) {
2957  DeclContext::lookup_result R = S.LookupConstructors(To);
2958  for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2959       Con != ConEnd; ++Con) {
2960    NamedDecl *D = *Con;
2961    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2962
2963    // Find the constructor (which may be a template).
2964    CXXConstructorDecl *Constructor = 0;
2965    FunctionTemplateDecl *ConstructorTmpl
2966      = dyn_cast<FunctionTemplateDecl>(D);
2967    if (ConstructorTmpl)
2968      Constructor
2969        = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2970    else
2971      Constructor = cast<CXXConstructorDecl>(D);
2972
2973    bool Usable = !Constructor->isInvalidDecl() &&
2974                  S.isInitListConstructor(Constructor) &&
2975                  (AllowExplicit || !Constructor->isExplicit());
2976    if (Usable) {
2977      // If the first argument is (a reference to) the target type,
2978      // suppress conversions.
2979      bool SuppressUserConversions =
2980          isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2981      if (ConstructorTmpl)
2982        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2983                                       /*ExplicitArgs*/ 0,
2984                                       From, CandidateSet,
2985                                       SuppressUserConversions);
2986      else
2987        S.AddOverloadCandidate(Constructor, FoundDecl,
2988                               From, CandidateSet,
2989                               SuppressUserConversions);
2990    }
2991  }
2992
2993  bool HadMultipleCandidates = (CandidateSet.size() > 1);
2994
2995  OverloadCandidateSet::iterator Best;
2996  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2997  case OR_Success: {
2998    // Record the standard conversion we used and the conversion function.
2999    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3000    QualType ThisType = Constructor->getThisType(S.Context);
3001    // Initializer lists don't have conversions as such.
3002    User.Before.setAsIdentityConversion();
3003    User.HadMultipleCandidates = HadMultipleCandidates;
3004    User.ConversionFunction = Constructor;
3005    User.FoundConversionFunction = Best->FoundDecl;
3006    User.After.setAsIdentityConversion();
3007    User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3008    User.After.setAllToTypes(ToType);
3009    return OR_Success;
3010  }
3011
3012  case OR_No_Viable_Function:
3013    return OR_No_Viable_Function;
3014  case OR_Deleted:
3015    return OR_Deleted;
3016  case OR_Ambiguous:
3017    return OR_Ambiguous;
3018  }
3019
3020  llvm_unreachable("Invalid OverloadResult!");
3021}
3022
3023/// Determines whether there is a user-defined conversion sequence
3024/// (C++ [over.ics.user]) that converts expression From to the type
3025/// ToType. If such a conversion exists, User will contain the
3026/// user-defined conversion sequence that performs such a conversion
3027/// and this routine will return true. Otherwise, this routine returns
3028/// false and User is unspecified.
3029///
3030/// \param AllowExplicit  true if the conversion should consider C++0x
3031/// "explicit" conversion functions as well as non-explicit conversion
3032/// functions (C++0x [class.conv.fct]p2).
3033static OverloadingResult
3034IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3035                        UserDefinedConversionSequence &User,
3036                        OverloadCandidateSet &CandidateSet,
3037                        bool AllowExplicit) {
3038  // Whether we will only visit constructors.
3039  bool ConstructorsOnly = false;
3040
3041  // If the type we are conversion to is a class type, enumerate its
3042  // constructors.
3043  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3044    // C++ [over.match.ctor]p1:
3045    //   When objects of class type are direct-initialized (8.5), or
3046    //   copy-initialized from an expression of the same or a
3047    //   derived class type (8.5), overload resolution selects the
3048    //   constructor. [...] For copy-initialization, the candidate
3049    //   functions are all the converting constructors (12.3.1) of
3050    //   that class. The argument list is the expression-list within
3051    //   the parentheses of the initializer.
3052    if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3053        (From->getType()->getAs<RecordType>() &&
3054         S.IsDerivedFrom(From->getType(), ToType)))
3055      ConstructorsOnly = true;
3056
3057    S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3058    // RequireCompleteType may have returned true due to some invalid decl
3059    // during template instantiation, but ToType may be complete enough now
3060    // to try to recover.
3061    if (ToType->isIncompleteType()) {
3062      // We're not going to find any constructors.
3063    } else if (CXXRecordDecl *ToRecordDecl
3064                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3065
3066      Expr **Args = &From;
3067      unsigned NumArgs = 1;
3068      bool ListInitializing = false;
3069      if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3070        // But first, see if there is an init-list-contructor that will work.
3071        OverloadingResult Result = IsInitializerListConstructorConversion(
3072            S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3073        if (Result != OR_No_Viable_Function)
3074          return Result;
3075        // Never mind.
3076        CandidateSet.clear();
3077
3078        // If we're list-initializing, we pass the individual elements as
3079        // arguments, not the entire list.
3080        Args = InitList->getInits();
3081        NumArgs = InitList->getNumInits();
3082        ListInitializing = true;
3083      }
3084
3085      DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3086      for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3087           Con != ConEnd; ++Con) {
3088        NamedDecl *D = *Con;
3089        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3090
3091        // Find the constructor (which may be a template).
3092        CXXConstructorDecl *Constructor = 0;
3093        FunctionTemplateDecl *ConstructorTmpl
3094          = dyn_cast<FunctionTemplateDecl>(D);
3095        if (ConstructorTmpl)
3096          Constructor
3097            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3098        else
3099          Constructor = cast<CXXConstructorDecl>(D);
3100
3101        bool Usable = !Constructor->isInvalidDecl();
3102        if (ListInitializing)
3103          Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3104        else
3105          Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3106        if (Usable) {
3107          bool SuppressUserConversions = !ConstructorsOnly;
3108          if (SuppressUserConversions && ListInitializing) {
3109            SuppressUserConversions = false;
3110            if (NumArgs == 1) {
3111              // If the first argument is (a reference to) the target type,
3112              // suppress conversions.
3113              SuppressUserConversions = isFirstArgumentCompatibleWithType(
3114                                                S.Context, Constructor, ToType);
3115            }
3116          }
3117          if (ConstructorTmpl)
3118            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3119                                           /*ExplicitArgs*/ 0,
3120                                           llvm::makeArrayRef(Args, NumArgs),
3121                                           CandidateSet, SuppressUserConversions);
3122          else
3123            // Allow one user-defined conversion when user specifies a
3124            // From->ToType conversion via an static cast (c-style, etc).
3125            S.AddOverloadCandidate(Constructor, FoundDecl,
3126                                   llvm::makeArrayRef(Args, NumArgs),
3127                                   CandidateSet, SuppressUserConversions);
3128        }
3129      }
3130    }
3131  }
3132
3133  // Enumerate conversion functions, if we're allowed to.
3134  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3135  } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3136    // No conversion functions from incomplete types.
3137  } else if (const RecordType *FromRecordType
3138                                   = From->getType()->getAs<RecordType>()) {
3139    if (CXXRecordDecl *FromRecordDecl
3140         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3141      // Add all of the conversion functions as candidates.
3142      std::pair<CXXRecordDecl::conversion_iterator,
3143                CXXRecordDecl::conversion_iterator>
3144        Conversions = FromRecordDecl->getVisibleConversionFunctions();
3145      for (CXXRecordDecl::conversion_iterator
3146             I = Conversions.first, E = Conversions.second; I != E; ++I) {
3147        DeclAccessPair FoundDecl = I.getPair();
3148        NamedDecl *D = FoundDecl.getDecl();
3149        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3150        if (isa<UsingShadowDecl>(D))
3151          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3152
3153        CXXConversionDecl *Conv;
3154        FunctionTemplateDecl *ConvTemplate;
3155        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3156          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3157        else
3158          Conv = cast<CXXConversionDecl>(D);
3159
3160        if (AllowExplicit || !Conv->isExplicit()) {
3161          if (ConvTemplate)
3162            S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3163                                             ActingContext, From, ToType,
3164                                             CandidateSet);
3165          else
3166            S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3167                                     From, ToType, CandidateSet);
3168        }
3169      }
3170    }
3171  }
3172
3173  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3174
3175  OverloadCandidateSet::iterator Best;
3176  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3177  case OR_Success:
3178    // Record the standard conversion we used and the conversion function.
3179    if (CXXConstructorDecl *Constructor
3180          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3181      // C++ [over.ics.user]p1:
3182      //   If the user-defined conversion is specified by a
3183      //   constructor (12.3.1), the initial standard conversion
3184      //   sequence converts the source type to the type required by
3185      //   the argument of the constructor.
3186      //
3187      QualType ThisType = Constructor->getThisType(S.Context);
3188      if (isa<InitListExpr>(From)) {
3189        // Initializer lists don't have conversions as such.
3190        User.Before.setAsIdentityConversion();
3191      } else {
3192        if (Best->Conversions[0].isEllipsis())
3193          User.EllipsisConversion = true;
3194        else {
3195          User.Before = Best->Conversions[0].Standard;
3196          User.EllipsisConversion = false;
3197        }
3198      }
3199      User.HadMultipleCandidates = HadMultipleCandidates;
3200      User.ConversionFunction = Constructor;
3201      User.FoundConversionFunction = Best->FoundDecl;
3202      User.After.setAsIdentityConversion();
3203      User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3204      User.After.setAllToTypes(ToType);
3205      return OR_Success;
3206    }
3207    if (CXXConversionDecl *Conversion
3208                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3209      // C++ [over.ics.user]p1:
3210      //
3211      //   [...] If the user-defined conversion is specified by a
3212      //   conversion function (12.3.2), the initial standard
3213      //   conversion sequence converts the source type to the
3214      //   implicit object parameter of the conversion function.
3215      User.Before = Best->Conversions[0].Standard;
3216      User.HadMultipleCandidates = HadMultipleCandidates;
3217      User.ConversionFunction = Conversion;
3218      User.FoundConversionFunction = Best->FoundDecl;
3219      User.EllipsisConversion = false;
3220
3221      // C++ [over.ics.user]p2:
3222      //   The second standard conversion sequence converts the
3223      //   result of the user-defined conversion to the target type
3224      //   for the sequence. Since an implicit conversion sequence
3225      //   is an initialization, the special rules for
3226      //   initialization by user-defined conversion apply when
3227      //   selecting the best user-defined conversion for a
3228      //   user-defined conversion sequence (see 13.3.3 and
3229      //   13.3.3.1).
3230      User.After = Best->FinalConversion;
3231      return OR_Success;
3232    }
3233    llvm_unreachable("Not a constructor or conversion function?");
3234
3235  case OR_No_Viable_Function:
3236    return OR_No_Viable_Function;
3237  case OR_Deleted:
3238    // No conversion here! We're done.
3239    return OR_Deleted;
3240
3241  case OR_Ambiguous:
3242    return OR_Ambiguous;
3243  }
3244
3245  llvm_unreachable("Invalid OverloadResult!");
3246}
3247
3248bool
3249Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3250  ImplicitConversionSequence ICS;
3251  OverloadCandidateSet CandidateSet(From->getExprLoc());
3252  OverloadingResult OvResult =
3253    IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3254                            CandidateSet, false);
3255  if (OvResult == OR_Ambiguous)
3256    Diag(From->getLocStart(),
3257         diag::err_typecheck_ambiguous_condition)
3258          << From->getType() << ToType << From->getSourceRange();
3259  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3260    Diag(From->getLocStart(),
3261         diag::err_typecheck_nonviable_condition)
3262    << From->getType() << ToType << From->getSourceRange();
3263  else
3264    return false;
3265  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3266  return true;
3267}
3268
3269/// \brief Compare the user-defined conversion functions or constructors
3270/// of two user-defined conversion sequences to determine whether any ordering
3271/// is possible.
3272static ImplicitConversionSequence::CompareKind
3273compareConversionFunctions(Sema &S,
3274                           FunctionDecl *Function1,
3275                           FunctionDecl *Function2) {
3276  if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3277    return ImplicitConversionSequence::Indistinguishable;
3278
3279  // Objective-C++:
3280  //   If both conversion functions are implicitly-declared conversions from
3281  //   a lambda closure type to a function pointer and a block pointer,
3282  //   respectively, always prefer the conversion to a function pointer,
3283  //   because the function pointer is more lightweight and is more likely
3284  //   to keep code working.
3285  CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3286  if (!Conv1)
3287    return ImplicitConversionSequence::Indistinguishable;
3288
3289  CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3290  if (!Conv2)
3291    return ImplicitConversionSequence::Indistinguishable;
3292
3293  if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3294    bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3295    bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3296    if (Block1 != Block2)
3297      return Block1? ImplicitConversionSequence::Worse
3298                   : ImplicitConversionSequence::Better;
3299  }
3300
3301  return ImplicitConversionSequence::Indistinguishable;
3302}
3303
3304/// CompareImplicitConversionSequences - Compare two implicit
3305/// conversion sequences to determine whether one is better than the
3306/// other or if they are indistinguishable (C++ 13.3.3.2).
3307static ImplicitConversionSequence::CompareKind
3308CompareImplicitConversionSequences(Sema &S,
3309                                   const ImplicitConversionSequence& ICS1,
3310                                   const ImplicitConversionSequence& ICS2)
3311{
3312  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3313  // conversion sequences (as defined in 13.3.3.1)
3314  //   -- a standard conversion sequence (13.3.3.1.1) is a better
3315  //      conversion sequence than a user-defined conversion sequence or
3316  //      an ellipsis conversion sequence, and
3317  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3318  //      conversion sequence than an ellipsis conversion sequence
3319  //      (13.3.3.1.3).
3320  //
3321  // C++0x [over.best.ics]p10:
3322  //   For the purpose of ranking implicit conversion sequences as
3323  //   described in 13.3.3.2, the ambiguous conversion sequence is
3324  //   treated as a user-defined sequence that is indistinguishable
3325  //   from any other user-defined conversion sequence.
3326  if (ICS1.getKindRank() < ICS2.getKindRank())
3327    return ImplicitConversionSequence::Better;
3328  if (ICS2.getKindRank() < ICS1.getKindRank())
3329    return ImplicitConversionSequence::Worse;
3330
3331  // The following checks require both conversion sequences to be of
3332  // the same kind.
3333  if (ICS1.getKind() != ICS2.getKind())
3334    return ImplicitConversionSequence::Indistinguishable;
3335
3336  ImplicitConversionSequence::CompareKind Result =
3337      ImplicitConversionSequence::Indistinguishable;
3338
3339  // Two implicit conversion sequences of the same form are
3340  // indistinguishable conversion sequences unless one of the
3341  // following rules apply: (C++ 13.3.3.2p3):
3342  if (ICS1.isStandard())
3343    Result = CompareStandardConversionSequences(S,
3344                                                ICS1.Standard, ICS2.Standard);
3345  else if (ICS1.isUserDefined()) {
3346    // User-defined conversion sequence U1 is a better conversion
3347    // sequence than another user-defined conversion sequence U2 if
3348    // they contain the same user-defined conversion function or
3349    // constructor and if the second standard conversion sequence of
3350    // U1 is better than the second standard conversion sequence of
3351    // U2 (C++ 13.3.3.2p3).
3352    if (ICS1.UserDefined.ConversionFunction ==
3353          ICS2.UserDefined.ConversionFunction)
3354      Result = CompareStandardConversionSequences(S,
3355                                                  ICS1.UserDefined.After,
3356                                                  ICS2.UserDefined.After);
3357    else
3358      Result = compareConversionFunctions(S,
3359                                          ICS1.UserDefined.ConversionFunction,
3360                                          ICS2.UserDefined.ConversionFunction);
3361  }
3362
3363  // List-initialization sequence L1 is a better conversion sequence than
3364  // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3365  // for some X and L2 does not.
3366  if (Result == ImplicitConversionSequence::Indistinguishable &&
3367      !ICS1.isBad() &&
3368      ICS1.isListInitializationSequence() &&
3369      ICS2.isListInitializationSequence()) {
3370    if (ICS1.isStdInitializerListElement() &&
3371        !ICS2.isStdInitializerListElement())
3372      return ImplicitConversionSequence::Better;
3373    if (!ICS1.isStdInitializerListElement() &&
3374        ICS2.isStdInitializerListElement())
3375      return ImplicitConversionSequence::Worse;
3376  }
3377
3378  return Result;
3379}
3380
3381static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3382  while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3383    Qualifiers Quals;
3384    T1 = Context.getUnqualifiedArrayType(T1, Quals);
3385    T2 = Context.getUnqualifiedArrayType(T2, Quals);
3386  }
3387
3388  return Context.hasSameUnqualifiedType(T1, T2);
3389}
3390
3391// Per 13.3.3.2p3, compare the given standard conversion sequences to
3392// determine if one is a proper subset of the other.
3393static ImplicitConversionSequence::CompareKind
3394compareStandardConversionSubsets(ASTContext &Context,
3395                                 const StandardConversionSequence& SCS1,
3396                                 const StandardConversionSequence& SCS2) {
3397  ImplicitConversionSequence::CompareKind Result
3398    = ImplicitConversionSequence::Indistinguishable;
3399
3400  // the identity conversion sequence is considered to be a subsequence of
3401  // any non-identity conversion sequence
3402  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3403    return ImplicitConversionSequence::Better;
3404  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3405    return ImplicitConversionSequence::Worse;
3406
3407  if (SCS1.Second != SCS2.Second) {
3408    if (SCS1.Second == ICK_Identity)
3409      Result = ImplicitConversionSequence::Better;
3410    else if (SCS2.Second == ICK_Identity)
3411      Result = ImplicitConversionSequence::Worse;
3412    else
3413      return ImplicitConversionSequence::Indistinguishable;
3414  } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3415    return ImplicitConversionSequence::Indistinguishable;
3416
3417  if (SCS1.Third == SCS2.Third) {
3418    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3419                             : ImplicitConversionSequence::Indistinguishable;
3420  }
3421
3422  if (SCS1.Third == ICK_Identity)
3423    return Result == ImplicitConversionSequence::Worse
3424             ? ImplicitConversionSequence::Indistinguishable
3425             : ImplicitConversionSequence::Better;
3426
3427  if (SCS2.Third == ICK_Identity)
3428    return Result == ImplicitConversionSequence::Better
3429             ? ImplicitConversionSequence::Indistinguishable
3430             : ImplicitConversionSequence::Worse;
3431
3432  return ImplicitConversionSequence::Indistinguishable;
3433}
3434
3435/// \brief Determine whether one of the given reference bindings is better
3436/// than the other based on what kind of bindings they are.
3437static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3438                                       const StandardConversionSequence &SCS2) {
3439  // C++0x [over.ics.rank]p3b4:
3440  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3441  //      implicit object parameter of a non-static member function declared
3442  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3443  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3444  //      lvalue reference to a function lvalue and S2 binds an rvalue
3445  //      reference*.
3446  //
3447  // FIXME: Rvalue references. We're going rogue with the above edits,
3448  // because the semantics in the current C++0x working paper (N3225 at the
3449  // time of this writing) break the standard definition of std::forward
3450  // and std::reference_wrapper when dealing with references to functions.
3451  // Proposed wording changes submitted to CWG for consideration.
3452  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3453      SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3454    return false;
3455
3456  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3457          SCS2.IsLvalueReference) ||
3458         (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3459          !SCS2.IsLvalueReference);
3460}
3461
3462/// CompareStandardConversionSequences - Compare two standard
3463/// conversion sequences to determine whether one is better than the
3464/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3465static ImplicitConversionSequence::CompareKind
3466CompareStandardConversionSequences(Sema &S,
3467                                   const StandardConversionSequence& SCS1,
3468                                   const StandardConversionSequence& SCS2)
3469{
3470  // Standard conversion sequence S1 is a better conversion sequence
3471  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3472
3473  //  -- S1 is a proper subsequence of S2 (comparing the conversion
3474  //     sequences in the canonical form defined by 13.3.3.1.1,
3475  //     excluding any Lvalue Transformation; the identity conversion
3476  //     sequence is considered to be a subsequence of any
3477  //     non-identity conversion sequence) or, if not that,
3478  if (ImplicitConversionSequence::CompareKind CK
3479        = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3480    return CK;
3481
3482  //  -- the rank of S1 is better than the rank of S2 (by the rules
3483  //     defined below), or, if not that,
3484  ImplicitConversionRank Rank1 = SCS1.getRank();
3485  ImplicitConversionRank Rank2 = SCS2.getRank();
3486  if (Rank1 < Rank2)
3487    return ImplicitConversionSequence::Better;
3488  else if (Rank2 < Rank1)
3489    return ImplicitConversionSequence::Worse;
3490
3491  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3492  // are indistinguishable unless one of the following rules
3493  // applies:
3494
3495  //   A conversion that is not a conversion of a pointer, or
3496  //   pointer to member, to bool is better than another conversion
3497  //   that is such a conversion.
3498  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3499    return SCS2.isPointerConversionToBool()
3500             ? ImplicitConversionSequence::Better
3501             : ImplicitConversionSequence::Worse;
3502
3503  // C++ [over.ics.rank]p4b2:
3504  //
3505  //   If class B is derived directly or indirectly from class A,
3506  //   conversion of B* to A* is better than conversion of B* to
3507  //   void*, and conversion of A* to void* is better than conversion
3508  //   of B* to void*.
3509  bool SCS1ConvertsToVoid
3510    = SCS1.isPointerConversionToVoidPointer(S.Context);
3511  bool SCS2ConvertsToVoid
3512    = SCS2.isPointerConversionToVoidPointer(S.Context);
3513  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3514    // Exactly one of the conversion sequences is a conversion to
3515    // a void pointer; it's the worse conversion.
3516    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3517                              : ImplicitConversionSequence::Worse;
3518  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3519    // Neither conversion sequence converts to a void pointer; compare
3520    // their derived-to-base conversions.
3521    if (ImplicitConversionSequence::CompareKind DerivedCK
3522          = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3523      return DerivedCK;
3524  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3525             !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3526    // Both conversion sequences are conversions to void
3527    // pointers. Compare the source types to determine if there's an
3528    // inheritance relationship in their sources.
3529    QualType FromType1 = SCS1.getFromType();
3530    QualType FromType2 = SCS2.getFromType();
3531
3532    // Adjust the types we're converting from via the array-to-pointer
3533    // conversion, if we need to.
3534    if (SCS1.First == ICK_Array_To_Pointer)
3535      FromType1 = S.Context.getArrayDecayedType(FromType1);
3536    if (SCS2.First == ICK_Array_To_Pointer)
3537      FromType2 = S.Context.getArrayDecayedType(FromType2);
3538
3539    QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3540    QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3541
3542    if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3543      return ImplicitConversionSequence::Better;
3544    else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3545      return ImplicitConversionSequence::Worse;
3546
3547    // Objective-C++: If one interface is more specific than the
3548    // other, it is the better one.
3549    const ObjCObjectPointerType* FromObjCPtr1
3550      = FromType1->getAs<ObjCObjectPointerType>();
3551    const ObjCObjectPointerType* FromObjCPtr2
3552      = FromType2->getAs<ObjCObjectPointerType>();
3553    if (FromObjCPtr1 && FromObjCPtr2) {
3554      bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3555                                                          FromObjCPtr2);
3556      bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3557                                                           FromObjCPtr1);
3558      if (AssignLeft != AssignRight) {
3559        return AssignLeft? ImplicitConversionSequence::Better
3560                         : ImplicitConversionSequence::Worse;
3561      }
3562    }
3563  }
3564
3565  // Compare based on qualification conversions (C++ 13.3.3.2p3,
3566  // bullet 3).
3567  if (ImplicitConversionSequence::CompareKind QualCK
3568        = CompareQualificationConversions(S, SCS1, SCS2))
3569    return QualCK;
3570
3571  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3572    // Check for a better reference binding based on the kind of bindings.
3573    if (isBetterReferenceBindingKind(SCS1, SCS2))
3574      return ImplicitConversionSequence::Better;
3575    else if (isBetterReferenceBindingKind(SCS2, SCS1))
3576      return ImplicitConversionSequence::Worse;
3577
3578    // C++ [over.ics.rank]p3b4:
3579    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3580    //      which the references refer are the same type except for
3581    //      top-level cv-qualifiers, and the type to which the reference
3582    //      initialized by S2 refers is more cv-qualified than the type
3583    //      to which the reference initialized by S1 refers.
3584    QualType T1 = SCS1.getToType(2);
3585    QualType T2 = SCS2.getToType(2);
3586    T1 = S.Context.getCanonicalType(T1);
3587    T2 = S.Context.getCanonicalType(T2);
3588    Qualifiers T1Quals, T2Quals;
3589    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3590    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3591    if (UnqualT1 == UnqualT2) {
3592      // Objective-C++ ARC: If the references refer to objects with different
3593      // lifetimes, prefer bindings that don't change lifetime.
3594      if (SCS1.ObjCLifetimeConversionBinding !=
3595                                          SCS2.ObjCLifetimeConversionBinding) {
3596        return SCS1.ObjCLifetimeConversionBinding
3597                                           ? ImplicitConversionSequence::Worse
3598                                           : ImplicitConversionSequence::Better;
3599      }
3600
3601      // If the type is an array type, promote the element qualifiers to the
3602      // type for comparison.
3603      if (isa<ArrayType>(T1) && T1Quals)
3604        T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3605      if (isa<ArrayType>(T2) && T2Quals)
3606        T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3607      if (T2.isMoreQualifiedThan(T1))
3608        return ImplicitConversionSequence::Better;
3609      else if (T1.isMoreQualifiedThan(T2))
3610        return ImplicitConversionSequence::Worse;
3611    }
3612  }
3613
3614  // In Microsoft mode, prefer an integral conversion to a
3615  // floating-to-integral conversion if the integral conversion
3616  // is between types of the same size.
3617  // For example:
3618  // void f(float);
3619  // void f(int);
3620  // int main {
3621  //    long a;
3622  //    f(a);
3623  // }
3624  // Here, MSVC will call f(int) instead of generating a compile error
3625  // as clang will do in standard mode.
3626  if (S.getLangOpts().MicrosoftMode &&
3627      SCS1.Second == ICK_Integral_Conversion &&
3628      SCS2.Second == ICK_Floating_Integral &&
3629      S.Context.getTypeSize(SCS1.getFromType()) ==
3630      S.Context.getTypeSize(SCS1.getToType(2)))
3631    return ImplicitConversionSequence::Better;
3632
3633  return ImplicitConversionSequence::Indistinguishable;
3634}
3635
3636/// CompareQualificationConversions - Compares two standard conversion
3637/// sequences to determine whether they can be ranked based on their
3638/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3639ImplicitConversionSequence::CompareKind
3640CompareQualificationConversions(Sema &S,
3641                                const StandardConversionSequence& SCS1,
3642                                const StandardConversionSequence& SCS2) {
3643  // C++ 13.3.3.2p3:
3644  //  -- S1 and S2 differ only in their qualification conversion and
3645  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3646  //     cv-qualification signature of type T1 is a proper subset of
3647  //     the cv-qualification signature of type T2, and S1 is not the
3648  //     deprecated string literal array-to-pointer conversion (4.2).
3649  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3650      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3651    return ImplicitConversionSequence::Indistinguishable;
3652
3653  // FIXME: the example in the standard doesn't use a qualification
3654  // conversion (!)
3655  QualType T1 = SCS1.getToType(2);
3656  QualType T2 = SCS2.getToType(2);
3657  T1 = S.Context.getCanonicalType(T1);
3658  T2 = S.Context.getCanonicalType(T2);
3659  Qualifiers T1Quals, T2Quals;
3660  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3661  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3662
3663  // If the types are the same, we won't learn anything by unwrapped
3664  // them.
3665  if (UnqualT1 == UnqualT2)
3666    return ImplicitConversionSequence::Indistinguishable;
3667
3668  // If the type is an array type, promote the element qualifiers to the type
3669  // for comparison.
3670  if (isa<ArrayType>(T1) && T1Quals)
3671    T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3672  if (isa<ArrayType>(T2) && T2Quals)
3673    T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3674
3675  ImplicitConversionSequence::CompareKind Result
3676    = ImplicitConversionSequence::Indistinguishable;
3677
3678  // Objective-C++ ARC:
3679  //   Prefer qualification conversions not involving a change in lifetime
3680  //   to qualification conversions that do not change lifetime.
3681  if (SCS1.QualificationIncludesObjCLifetime !=
3682                                      SCS2.QualificationIncludesObjCLifetime) {
3683    Result = SCS1.QualificationIncludesObjCLifetime
3684               ? ImplicitConversionSequence::Worse
3685               : ImplicitConversionSequence::Better;
3686  }
3687
3688  while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3689    // Within each iteration of the loop, we check the qualifiers to
3690    // determine if this still looks like a qualification
3691    // conversion. Then, if all is well, we unwrap one more level of
3692    // pointers or pointers-to-members and do it all again
3693    // until there are no more pointers or pointers-to-members left
3694    // to unwrap. This essentially mimics what
3695    // IsQualificationConversion does, but here we're checking for a
3696    // strict subset of qualifiers.
3697    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3698      // The qualifiers are the same, so this doesn't tell us anything
3699      // about how the sequences rank.
3700      ;
3701    else if (T2.isMoreQualifiedThan(T1)) {
3702      // T1 has fewer qualifiers, so it could be the better sequence.
3703      if (Result == ImplicitConversionSequence::Worse)
3704        // Neither has qualifiers that are a subset of the other's
3705        // qualifiers.
3706        return ImplicitConversionSequence::Indistinguishable;
3707
3708      Result = ImplicitConversionSequence::Better;
3709    } else if (T1.isMoreQualifiedThan(T2)) {
3710      // T2 has fewer qualifiers, so it could be the better sequence.
3711      if (Result == ImplicitConversionSequence::Better)
3712        // Neither has qualifiers that are a subset of the other's
3713        // qualifiers.
3714        return ImplicitConversionSequence::Indistinguishable;
3715
3716      Result = ImplicitConversionSequence::Worse;
3717    } else {
3718      // Qualifiers are disjoint.
3719      return ImplicitConversionSequence::Indistinguishable;
3720    }
3721
3722    // If the types after this point are equivalent, we're done.
3723    if (S.Context.hasSameUnqualifiedType(T1, T2))
3724      break;
3725  }
3726
3727  // Check that the winning standard conversion sequence isn't using
3728  // the deprecated string literal array to pointer conversion.
3729  switch (Result) {
3730  case ImplicitConversionSequence::Better:
3731    if (SCS1.DeprecatedStringLiteralToCharPtr)
3732      Result = ImplicitConversionSequence::Indistinguishable;
3733    break;
3734
3735  case ImplicitConversionSequence::Indistinguishable:
3736    break;
3737
3738  case ImplicitConversionSequence::Worse:
3739    if (SCS2.DeprecatedStringLiteralToCharPtr)
3740      Result = ImplicitConversionSequence::Indistinguishable;
3741    break;
3742  }
3743
3744  return Result;
3745}
3746
3747/// CompareDerivedToBaseConversions - Compares two standard conversion
3748/// sequences to determine whether they can be ranked based on their
3749/// various kinds of derived-to-base conversions (C++
3750/// [over.ics.rank]p4b3).  As part of these checks, we also look at
3751/// conversions between Objective-C interface types.
3752ImplicitConversionSequence::CompareKind
3753CompareDerivedToBaseConversions(Sema &S,
3754                                const StandardConversionSequence& SCS1,
3755                                const StandardConversionSequence& SCS2) {
3756  QualType FromType1 = SCS1.getFromType();
3757  QualType ToType1 = SCS1.getToType(1);
3758  QualType FromType2 = SCS2.getFromType();
3759  QualType ToType2 = SCS2.getToType(1);
3760
3761  // Adjust the types we're converting from via the array-to-pointer
3762  // conversion, if we need to.
3763  if (SCS1.First == ICK_Array_To_Pointer)
3764    FromType1 = S.Context.getArrayDecayedType(FromType1);
3765  if (SCS2.First == ICK_Array_To_Pointer)
3766    FromType2 = S.Context.getArrayDecayedType(FromType2);
3767
3768  // Canonicalize all of the types.
3769  FromType1 = S.Context.getCanonicalType(FromType1);
3770  ToType1 = S.Context.getCanonicalType(ToType1);
3771  FromType2 = S.Context.getCanonicalType(FromType2);
3772  ToType2 = S.Context.getCanonicalType(ToType2);
3773
3774  // C++ [over.ics.rank]p4b3:
3775  //
3776  //   If class B is derived directly or indirectly from class A and
3777  //   class C is derived directly or indirectly from B,
3778  //
3779  // Compare based on pointer conversions.
3780  if (SCS1.Second == ICK_Pointer_Conversion &&
3781      SCS2.Second == ICK_Pointer_Conversion &&
3782      /*FIXME: Remove if Objective-C id conversions get their own rank*/
3783      FromType1->isPointerType() && FromType2->isPointerType() &&
3784      ToType1->isPointerType() && ToType2->isPointerType()) {
3785    QualType FromPointee1
3786      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3787    QualType ToPointee1
3788      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3789    QualType FromPointee2
3790      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3791    QualType ToPointee2
3792      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3793
3794    //   -- conversion of C* to B* is better than conversion of C* to A*,
3795    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3796      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3797        return ImplicitConversionSequence::Better;
3798      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3799        return ImplicitConversionSequence::Worse;
3800    }
3801
3802    //   -- conversion of B* to A* is better than conversion of C* to A*,
3803    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3804      if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3805        return ImplicitConversionSequence::Better;
3806      else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3807        return ImplicitConversionSequence::Worse;
3808    }
3809  } else if (SCS1.Second == ICK_Pointer_Conversion &&
3810             SCS2.Second == ICK_Pointer_Conversion) {
3811    const ObjCObjectPointerType *FromPtr1
3812      = FromType1->getAs<ObjCObjectPointerType>();
3813    const ObjCObjectPointerType *FromPtr2
3814      = FromType2->getAs<ObjCObjectPointerType>();
3815    const ObjCObjectPointerType *ToPtr1
3816      = ToType1->getAs<ObjCObjectPointerType>();
3817    const ObjCObjectPointerType *ToPtr2
3818      = ToType2->getAs<ObjCObjectPointerType>();
3819
3820    if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3821      // Apply the same conversion ranking rules for Objective-C pointer types
3822      // that we do for C++ pointers to class types. However, we employ the
3823      // Objective-C pseudo-subtyping relationship used for assignment of
3824      // Objective-C pointer types.
3825      bool FromAssignLeft
3826        = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3827      bool FromAssignRight
3828        = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3829      bool ToAssignLeft
3830        = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3831      bool ToAssignRight
3832        = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3833
3834      // A conversion to an a non-id object pointer type or qualified 'id'
3835      // type is better than a conversion to 'id'.
3836      if (ToPtr1->isObjCIdType() &&
3837          (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3838        return ImplicitConversionSequence::Worse;
3839      if (ToPtr2->isObjCIdType() &&
3840          (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3841        return ImplicitConversionSequence::Better;
3842
3843      // A conversion to a non-id object pointer type is better than a
3844      // conversion to a qualified 'id' type
3845      if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3846        return ImplicitConversionSequence::Worse;
3847      if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3848        return ImplicitConversionSequence::Better;
3849
3850      // A conversion to an a non-Class object pointer type or qualified 'Class'
3851      // type is better than a conversion to 'Class'.
3852      if (ToPtr1->isObjCClassType() &&
3853          (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3854        return ImplicitConversionSequence::Worse;
3855      if (ToPtr2->isObjCClassType() &&
3856          (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3857        return ImplicitConversionSequence::Better;
3858
3859      // A conversion to a non-Class object pointer type is better than a
3860      // conversion to a qualified 'Class' type.
3861      if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3862        return ImplicitConversionSequence::Worse;
3863      if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3864        return ImplicitConversionSequence::Better;
3865
3866      //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3867      if (S.Context.hasSameType(FromType1, FromType2) &&
3868          !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3869          (ToAssignLeft != ToAssignRight))
3870        return ToAssignLeft? ImplicitConversionSequence::Worse
3871                           : ImplicitConversionSequence::Better;
3872
3873      //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3874      if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3875          (FromAssignLeft != FromAssignRight))
3876        return FromAssignLeft? ImplicitConversionSequence::Better
3877        : ImplicitConversionSequence::Worse;
3878    }
3879  }
3880
3881  // Ranking of member-pointer types.
3882  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3883      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3884      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3885    const MemberPointerType * FromMemPointer1 =
3886                                        FromType1->getAs<MemberPointerType>();
3887    const MemberPointerType * ToMemPointer1 =
3888                                          ToType1->getAs<MemberPointerType>();
3889    const MemberPointerType * FromMemPointer2 =
3890                                          FromType2->getAs<MemberPointerType>();
3891    const MemberPointerType * ToMemPointer2 =
3892                                          ToType2->getAs<MemberPointerType>();
3893    const Type *FromPointeeType1 = FromMemPointer1->getClass();
3894    const Type *ToPointeeType1 = ToMemPointer1->getClass();
3895    const Type *FromPointeeType2 = FromMemPointer2->getClass();
3896    const Type *ToPointeeType2 = ToMemPointer2->getClass();
3897    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3898    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3899    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3900    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3901    // conversion of A::* to B::* is better than conversion of A::* to C::*,
3902    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3903      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3904        return ImplicitConversionSequence::Worse;
3905      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3906        return ImplicitConversionSequence::Better;
3907    }
3908    // conversion of B::* to C::* is better than conversion of A::* to C::*
3909    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3910      if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3911        return ImplicitConversionSequence::Better;
3912      else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3913        return ImplicitConversionSequence::Worse;
3914    }
3915  }
3916
3917  if (SCS1.Second == ICK_Derived_To_Base) {
3918    //   -- conversion of C to B is better than conversion of C to A,
3919    //   -- binding of an expression of type C to a reference of type
3920    //      B& is better than binding an expression of type C to a
3921    //      reference of type A&,
3922    if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3923        !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3924      if (S.IsDerivedFrom(ToType1, ToType2))
3925        return ImplicitConversionSequence::Better;
3926      else if (S.IsDerivedFrom(ToType2, ToType1))
3927        return ImplicitConversionSequence::Worse;
3928    }
3929
3930    //   -- conversion of B to A is better than conversion of C to A.
3931    //   -- binding of an expression of type B to a reference of type
3932    //      A& is better than binding an expression of type C to a
3933    //      reference of type A&,
3934    if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3935        S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3936      if (S.IsDerivedFrom(FromType2, FromType1))
3937        return ImplicitConversionSequence::Better;
3938      else if (S.IsDerivedFrom(FromType1, FromType2))
3939        return ImplicitConversionSequence::Worse;
3940    }
3941  }
3942
3943  return ImplicitConversionSequence::Indistinguishable;
3944}
3945
3946/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3947/// C++ class.
3948static bool isTypeValid(QualType T) {
3949  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3950    return !Record->isInvalidDecl();
3951
3952  return true;
3953}
3954
3955/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3956/// determine whether they are reference-related,
3957/// reference-compatible, reference-compatible with added
3958/// qualification, or incompatible, for use in C++ initialization by
3959/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3960/// type, and the first type (T1) is the pointee type of the reference
3961/// type being initialized.
3962Sema::ReferenceCompareResult
3963Sema::CompareReferenceRelationship(SourceLocation Loc,
3964                                   QualType OrigT1, QualType OrigT2,
3965                                   bool &DerivedToBase,
3966                                   bool &ObjCConversion,
3967                                   bool &ObjCLifetimeConversion) {
3968  assert(!OrigT1->isReferenceType() &&
3969    "T1 must be the pointee type of the reference type");
3970  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3971
3972  QualType T1 = Context.getCanonicalType(OrigT1);
3973  QualType T2 = Context.getCanonicalType(OrigT2);
3974  Qualifiers T1Quals, T2Quals;
3975  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3976  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3977
3978  // C++ [dcl.init.ref]p4:
3979  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3980  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3981  //   T1 is a base class of T2.
3982  DerivedToBase = false;
3983  ObjCConversion = false;
3984  ObjCLifetimeConversion = false;
3985  if (UnqualT1 == UnqualT2) {
3986    // Nothing to do.
3987  } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3988             isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3989             IsDerivedFrom(UnqualT2, UnqualT1))
3990    DerivedToBase = true;
3991  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3992           UnqualT2->isObjCObjectOrInterfaceType() &&
3993           Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3994    ObjCConversion = true;
3995  else
3996    return Ref_Incompatible;
3997
3998  // At this point, we know that T1 and T2 are reference-related (at
3999  // least).
4000
4001  // If the type is an array type, promote the element qualifiers to the type
4002  // for comparison.
4003  if (isa<ArrayType>(T1) && T1Quals)
4004    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4005  if (isa<ArrayType>(T2) && T2Quals)
4006    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4007
4008  // C++ [dcl.init.ref]p4:
4009  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4010  //   reference-related to T2 and cv1 is the same cv-qualification
4011  //   as, or greater cv-qualification than, cv2. For purposes of
4012  //   overload resolution, cases for which cv1 is greater
4013  //   cv-qualification than cv2 are identified as
4014  //   reference-compatible with added qualification (see 13.3.3.2).
4015  //
4016  // Note that we also require equivalence of Objective-C GC and address-space
4017  // qualifiers when performing these computations, so that e.g., an int in
4018  // address space 1 is not reference-compatible with an int in address
4019  // space 2.
4020  if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4021      T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4022    T1Quals.removeObjCLifetime();
4023    T2Quals.removeObjCLifetime();
4024    ObjCLifetimeConversion = true;
4025  }
4026
4027  if (T1Quals == T2Quals)
4028    return Ref_Compatible;
4029  else if (T1Quals.compatiblyIncludes(T2Quals))
4030    return Ref_Compatible_With_Added_Qualification;
4031  else
4032    return Ref_Related;
4033}
4034
4035/// \brief Look for a user-defined conversion to an value reference-compatible
4036///        with DeclType. Return true if something definite is found.
4037static bool
4038FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4039                         QualType DeclType, SourceLocation DeclLoc,
4040                         Expr *Init, QualType T2, bool AllowRvalues,
4041                         bool AllowExplicit) {
4042  assert(T2->isRecordType() && "Can only find conversions of record types.");
4043  CXXRecordDecl *T2RecordDecl
4044    = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4045
4046  OverloadCandidateSet CandidateSet(DeclLoc);
4047  std::pair<CXXRecordDecl::conversion_iterator,
4048            CXXRecordDecl::conversion_iterator>
4049    Conversions = T2RecordDecl->getVisibleConversionFunctions();
4050  for (CXXRecordDecl::conversion_iterator
4051         I = Conversions.first, E = Conversions.second; I != E; ++I) {
4052    NamedDecl *D = *I;
4053    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4054    if (isa<UsingShadowDecl>(D))
4055      D = cast<UsingShadowDecl>(D)->getTargetDecl();
4056
4057    FunctionTemplateDecl *ConvTemplate
4058      = dyn_cast<FunctionTemplateDecl>(D);
4059    CXXConversionDecl *Conv;
4060    if (ConvTemplate)
4061      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4062    else
4063      Conv = cast<CXXConversionDecl>(D);
4064
4065    // If this is an explicit conversion, and we're not allowed to consider
4066    // explicit conversions, skip it.
4067    if (!AllowExplicit && Conv->isExplicit())
4068      continue;
4069
4070    if (AllowRvalues) {
4071      bool DerivedToBase = false;
4072      bool ObjCConversion = false;
4073      bool ObjCLifetimeConversion = false;
4074
4075      // If we are initializing an rvalue reference, don't permit conversion
4076      // functions that return lvalues.
4077      if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4078        const ReferenceType *RefType
4079          = Conv->getConversionType()->getAs<LValueReferenceType>();
4080        if (RefType && !RefType->getPointeeType()->isFunctionType())
4081          continue;
4082      }
4083
4084      if (!ConvTemplate &&
4085          S.CompareReferenceRelationship(
4086            DeclLoc,
4087            Conv->getConversionType().getNonReferenceType()
4088              .getUnqualifiedType(),
4089            DeclType.getNonReferenceType().getUnqualifiedType(),
4090            DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4091          Sema::Ref_Incompatible)
4092        continue;
4093    } else {
4094      // If the conversion function doesn't return a reference type,
4095      // it can't be considered for this conversion. An rvalue reference
4096      // is only acceptable if its referencee is a function type.
4097
4098      const ReferenceType *RefType =
4099        Conv->getConversionType()->getAs<ReferenceType>();
4100      if (!RefType ||
4101          (!RefType->isLValueReferenceType() &&
4102           !RefType->getPointeeType()->isFunctionType()))
4103        continue;
4104    }
4105
4106    if (ConvTemplate)
4107      S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4108                                       Init, DeclType, CandidateSet);
4109    else
4110      S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4111                               DeclType, CandidateSet);
4112  }
4113
4114  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4115
4116  OverloadCandidateSet::iterator Best;
4117  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4118  case OR_Success:
4119    // C++ [over.ics.ref]p1:
4120    //
4121    //   [...] If the parameter binds directly to the result of
4122    //   applying a conversion function to the argument
4123    //   expression, the implicit conversion sequence is a
4124    //   user-defined conversion sequence (13.3.3.1.2), with the
4125    //   second standard conversion sequence either an identity
4126    //   conversion or, if the conversion function returns an
4127    //   entity of a type that is a derived class of the parameter
4128    //   type, a derived-to-base Conversion.
4129    if (!Best->FinalConversion.DirectBinding)
4130      return false;
4131
4132    ICS.setUserDefined();
4133    ICS.UserDefined.Before = Best->Conversions[0].Standard;
4134    ICS.UserDefined.After = Best->FinalConversion;
4135    ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4136    ICS.UserDefined.ConversionFunction = Best->Function;
4137    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4138    ICS.UserDefined.EllipsisConversion = false;
4139    assert(ICS.UserDefined.After.ReferenceBinding &&
4140           ICS.UserDefined.After.DirectBinding &&
4141           "Expected a direct reference binding!");
4142    return true;
4143
4144  case OR_Ambiguous:
4145    ICS.setAmbiguous();
4146    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4147         Cand != CandidateSet.end(); ++Cand)
4148      if (Cand->Viable)
4149        ICS.Ambiguous.addConversion(Cand->Function);
4150    return true;
4151
4152  case OR_No_Viable_Function:
4153  case OR_Deleted:
4154    // There was no suitable conversion, or we found a deleted
4155    // conversion; continue with other checks.
4156    return false;
4157  }
4158
4159  llvm_unreachable("Invalid OverloadResult!");
4160}
4161
4162/// \brief Compute an implicit conversion sequence for reference
4163/// initialization.
4164static ImplicitConversionSequence
4165TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4166                 SourceLocation DeclLoc,
4167                 bool SuppressUserConversions,
4168                 bool AllowExplicit) {
4169  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4170
4171  // Most paths end in a failed conversion.
4172  ImplicitConversionSequence ICS;
4173  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4174
4175  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4176  QualType T2 = Init->getType();
4177
4178  // If the initializer is the address of an overloaded function, try
4179  // to resolve the overloaded function. If all goes well, T2 is the
4180  // type of the resulting function.
4181  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4182    DeclAccessPair Found;
4183    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4184                                                                false, Found))
4185      T2 = Fn->getType();
4186  }
4187
4188  // Compute some basic properties of the types and the initializer.
4189  bool isRValRef = DeclType->isRValueReferenceType();
4190  bool DerivedToBase = false;
4191  bool ObjCConversion = false;
4192  bool ObjCLifetimeConversion = false;
4193  Expr::Classification InitCategory = Init->Classify(S.Context);
4194  Sema::ReferenceCompareResult RefRelationship
4195    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4196                                     ObjCConversion, ObjCLifetimeConversion);
4197
4198
4199  // C++0x [dcl.init.ref]p5:
4200  //   A reference to type "cv1 T1" is initialized by an expression
4201  //   of type "cv2 T2" as follows:
4202
4203  //     -- If reference is an lvalue reference and the initializer expression
4204  if (!isRValRef) {
4205    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4206    //        reference-compatible with "cv2 T2," or
4207    //
4208    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4209    if (InitCategory.isLValue() &&
4210        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4211      // C++ [over.ics.ref]p1:
4212      //   When a parameter of reference type binds directly (8.5.3)
4213      //   to an argument expression, the implicit conversion sequence
4214      //   is the identity conversion, unless the argument expression
4215      //   has a type that is a derived class of the parameter type,
4216      //   in which case the implicit conversion sequence is a
4217      //   derived-to-base Conversion (13.3.3.1).
4218      ICS.setStandard();
4219      ICS.Standard.First = ICK_Identity;
4220      ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4221                         : ObjCConversion? ICK_Compatible_Conversion
4222                         : ICK_Identity;
4223      ICS.Standard.Third = ICK_Identity;
4224      ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4225      ICS.Standard.setToType(0, T2);
4226      ICS.Standard.setToType(1, T1);
4227      ICS.Standard.setToType(2, T1);
4228      ICS.Standard.ReferenceBinding = true;
4229      ICS.Standard.DirectBinding = true;
4230      ICS.Standard.IsLvalueReference = !isRValRef;
4231      ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4232      ICS.Standard.BindsToRvalue = false;
4233      ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4234      ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4235      ICS.Standard.CopyConstructor = 0;
4236
4237      // Nothing more to do: the inaccessibility/ambiguity check for
4238      // derived-to-base conversions is suppressed when we're
4239      // computing the implicit conversion sequence (C++
4240      // [over.best.ics]p2).
4241      return ICS;
4242    }
4243
4244    //       -- has a class type (i.e., T2 is a class type), where T1 is
4245    //          not reference-related to T2, and can be implicitly
4246    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4247    //          is reference-compatible with "cv3 T3" 92) (this
4248    //          conversion is selected by enumerating the applicable
4249    //          conversion functions (13.3.1.6) and choosing the best
4250    //          one through overload resolution (13.3)),
4251    if (!SuppressUserConversions && T2->isRecordType() &&
4252        !S.RequireCompleteType(DeclLoc, T2, 0) &&
4253        RefRelationship == Sema::Ref_Incompatible) {
4254      if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4255                                   Init, T2, /*AllowRvalues=*/false,
4256                                   AllowExplicit))
4257        return ICS;
4258    }
4259  }
4260
4261  //     -- Otherwise, the reference shall be an lvalue reference to a
4262  //        non-volatile const type (i.e., cv1 shall be const), or the reference
4263  //        shall be an rvalue reference.
4264  //
4265  // We actually handle one oddity of C++ [over.ics.ref] at this
4266  // point, which is that, due to p2 (which short-circuits reference
4267  // binding by only attempting a simple conversion for non-direct
4268  // bindings) and p3's strange wording, we allow a const volatile
4269  // reference to bind to an rvalue. Hence the check for the presence
4270  // of "const" rather than checking for "const" being the only
4271  // qualifier.
4272  // This is also the point where rvalue references and lvalue inits no longer
4273  // go together.
4274  if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4275    return ICS;
4276
4277  //       -- If the initializer expression
4278  //
4279  //            -- is an xvalue, class prvalue, array prvalue or function
4280  //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4281  if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4282      (InitCategory.isXValue() ||
4283      (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4284      (InitCategory.isLValue() && T2->isFunctionType()))) {
4285    ICS.setStandard();
4286    ICS.Standard.First = ICK_Identity;
4287    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4288                      : ObjCConversion? ICK_Compatible_Conversion
4289                      : ICK_Identity;
4290    ICS.Standard.Third = ICK_Identity;
4291    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4292    ICS.Standard.setToType(0, T2);
4293    ICS.Standard.setToType(1, T1);
4294    ICS.Standard.setToType(2, T1);
4295    ICS.Standard.ReferenceBinding = true;
4296    // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4297    // binding unless we're binding to a class prvalue.
4298    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4299    // allow the use of rvalue references in C++98/03 for the benefit of
4300    // standard library implementors; therefore, we need the xvalue check here.
4301    ICS.Standard.DirectBinding =
4302      S.getLangOpts().CPlusPlus11 ||
4303      (InitCategory.isPRValue() && !T2->isRecordType());
4304    ICS.Standard.IsLvalueReference = !isRValRef;
4305    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4306    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4307    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4308    ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4309    ICS.Standard.CopyConstructor = 0;
4310    return ICS;
4311  }
4312
4313  //            -- has a class type (i.e., T2 is a class type), where T1 is not
4314  //               reference-related to T2, and can be implicitly converted to
4315  //               an xvalue, class prvalue, or function lvalue of type
4316  //               "cv3 T3", where "cv1 T1" is reference-compatible with
4317  //               "cv3 T3",
4318  //
4319  //          then the reference is bound to the value of the initializer
4320  //          expression in the first case and to the result of the conversion
4321  //          in the second case (or, in either case, to an appropriate base
4322  //          class subobject).
4323  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4324      T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4325      FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4326                               Init, T2, /*AllowRvalues=*/true,
4327                               AllowExplicit)) {
4328    // In the second case, if the reference is an rvalue reference
4329    // and the second standard conversion sequence of the
4330    // user-defined conversion sequence includes an lvalue-to-rvalue
4331    // conversion, the program is ill-formed.
4332    if (ICS.isUserDefined() && isRValRef &&
4333        ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4334      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4335
4336    return ICS;
4337  }
4338
4339  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4340  //          initialized from the initializer expression using the
4341  //          rules for a non-reference copy initialization (8.5). The
4342  //          reference is then bound to the temporary. If T1 is
4343  //          reference-related to T2, cv1 must be the same
4344  //          cv-qualification as, or greater cv-qualification than,
4345  //          cv2; otherwise, the program is ill-formed.
4346  if (RefRelationship == Sema::Ref_Related) {
4347    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4348    // we would be reference-compatible or reference-compatible with
4349    // added qualification. But that wasn't the case, so the reference
4350    // initialization fails.
4351    //
4352    // Note that we only want to check address spaces and cvr-qualifiers here.
4353    // ObjC GC and lifetime qualifiers aren't important.
4354    Qualifiers T1Quals = T1.getQualifiers();
4355    Qualifiers T2Quals = T2.getQualifiers();
4356    T1Quals.removeObjCGCAttr();
4357    T1Quals.removeObjCLifetime();
4358    T2Quals.removeObjCGCAttr();
4359    T2Quals.removeObjCLifetime();
4360    if (!T1Quals.compatiblyIncludes(T2Quals))
4361      return ICS;
4362  }
4363
4364  // If at least one of the types is a class type, the types are not
4365  // related, and we aren't allowed any user conversions, the
4366  // reference binding fails. This case is important for breaking
4367  // recursion, since TryImplicitConversion below will attempt to
4368  // create a temporary through the use of a copy constructor.
4369  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4370      (T1->isRecordType() || T2->isRecordType()))
4371    return ICS;
4372
4373  // If T1 is reference-related to T2 and the reference is an rvalue
4374  // reference, the initializer expression shall not be an lvalue.
4375  if (RefRelationship >= Sema::Ref_Related &&
4376      isRValRef && Init->Classify(S.Context).isLValue())
4377    return ICS;
4378
4379  // C++ [over.ics.ref]p2:
4380  //   When a parameter of reference type is not bound directly to
4381  //   an argument expression, the conversion sequence is the one
4382  //   required to convert the argument expression to the
4383  //   underlying type of the reference according to
4384  //   13.3.3.1. Conceptually, this conversion sequence corresponds
4385  //   to copy-initializing a temporary of the underlying type with
4386  //   the argument expression. Any difference in top-level
4387  //   cv-qualification is subsumed by the initialization itself
4388  //   and does not constitute a conversion.
4389  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4390                              /*AllowExplicit=*/false,
4391                              /*InOverloadResolution=*/false,
4392                              /*CStyle=*/false,
4393                              /*AllowObjCWritebackConversion=*/false);
4394
4395  // Of course, that's still a reference binding.
4396  if (ICS.isStandard()) {
4397    ICS.Standard.ReferenceBinding = true;
4398    ICS.Standard.IsLvalueReference = !isRValRef;
4399    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4400    ICS.Standard.BindsToRvalue = true;
4401    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4402    ICS.Standard.ObjCLifetimeConversionBinding = false;
4403  } else if (ICS.isUserDefined()) {
4404    // Don't allow rvalue references to bind to lvalues.
4405    if (DeclType->isRValueReferenceType()) {
4406      if (const ReferenceType *RefType
4407            = ICS.UserDefined.ConversionFunction->getResultType()
4408                ->getAs<LValueReferenceType>()) {
4409        if (!RefType->getPointeeType()->isFunctionType()) {
4410          ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4411                     DeclType);
4412          return ICS;
4413        }
4414      }
4415    }
4416
4417    ICS.UserDefined.After.ReferenceBinding = true;
4418    ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4419    ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4420    ICS.UserDefined.After.BindsToRvalue = true;
4421    ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4422    ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4423  }
4424
4425  return ICS;
4426}
4427
4428static ImplicitConversionSequence
4429TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4430                      bool SuppressUserConversions,
4431                      bool InOverloadResolution,
4432                      bool AllowObjCWritebackConversion,
4433                      bool AllowExplicit = false);
4434
4435/// TryListConversion - Try to copy-initialize a value of type ToType from the
4436/// initializer list From.
4437static ImplicitConversionSequence
4438TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4439                  bool SuppressUserConversions,
4440                  bool InOverloadResolution,
4441                  bool AllowObjCWritebackConversion) {
4442  // C++11 [over.ics.list]p1:
4443  //   When an argument is an initializer list, it is not an expression and
4444  //   special rules apply for converting it to a parameter type.
4445
4446  ImplicitConversionSequence Result;
4447  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4448  Result.setListInitializationSequence();
4449
4450  // We need a complete type for what follows. Incomplete types can never be
4451  // initialized from init lists.
4452  if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4453    return Result;
4454
4455  // C++11 [over.ics.list]p2:
4456  //   If the parameter type is std::initializer_list<X> or "array of X" and
4457  //   all the elements can be implicitly converted to X, the implicit
4458  //   conversion sequence is the worst conversion necessary to convert an
4459  //   element of the list to X.
4460  bool toStdInitializerList = false;
4461  QualType X;
4462  if (ToType->isArrayType())
4463    X = S.Context.getAsArrayType(ToType)->getElementType();
4464  else
4465    toStdInitializerList = S.isStdInitializerList(ToType, &X);
4466  if (!X.isNull()) {
4467    for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4468      Expr *Init = From->getInit(i);
4469      ImplicitConversionSequence ICS =
4470          TryCopyInitialization(S, Init, X, SuppressUserConversions,
4471                                InOverloadResolution,
4472                                AllowObjCWritebackConversion);
4473      // If a single element isn't convertible, fail.
4474      if (ICS.isBad()) {
4475        Result = ICS;
4476        break;
4477      }
4478      // Otherwise, look for the worst conversion.
4479      if (Result.isBad() ||
4480          CompareImplicitConversionSequences(S, ICS, Result) ==
4481              ImplicitConversionSequence::Worse)
4482        Result = ICS;
4483    }
4484
4485    // For an empty list, we won't have computed any conversion sequence.
4486    // Introduce the identity conversion sequence.
4487    if (From->getNumInits() == 0) {
4488      Result.setStandard();
4489      Result.Standard.setAsIdentityConversion();
4490      Result.Standard.setFromType(ToType);
4491      Result.Standard.setAllToTypes(ToType);
4492    }
4493
4494    Result.setListInitializationSequence();
4495    Result.setStdInitializerListElement(toStdInitializerList);
4496    return Result;
4497  }
4498
4499  // C++11 [over.ics.list]p3:
4500  //   Otherwise, if the parameter is a non-aggregate class X and overload
4501  //   resolution chooses a single best constructor [...] the implicit
4502  //   conversion sequence is a user-defined conversion sequence. If multiple
4503  //   constructors are viable but none is better than the others, the
4504  //   implicit conversion sequence is a user-defined conversion sequence.
4505  if (ToType->isRecordType() && !ToType->isAggregateType()) {
4506    // This function can deal with initializer lists.
4507    Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4508                                      /*AllowExplicit=*/false,
4509                                      InOverloadResolution, /*CStyle=*/false,
4510                                      AllowObjCWritebackConversion);
4511    Result.setListInitializationSequence();
4512    return Result;
4513  }
4514
4515  // C++11 [over.ics.list]p4:
4516  //   Otherwise, if the parameter has an aggregate type which can be
4517  //   initialized from the initializer list [...] the implicit conversion
4518  //   sequence is a user-defined conversion sequence.
4519  if (ToType->isAggregateType()) {
4520    // Type is an aggregate, argument is an init list. At this point it comes
4521    // down to checking whether the initialization works.
4522    // FIXME: Find out whether this parameter is consumed or not.
4523    InitializedEntity Entity =
4524        InitializedEntity::InitializeParameter(S.Context, ToType,
4525                                               /*Consumed=*/false);
4526    if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4527      Result.setUserDefined();
4528      Result.UserDefined.Before.setAsIdentityConversion();
4529      // Initializer lists don't have a type.
4530      Result.UserDefined.Before.setFromType(QualType());
4531      Result.UserDefined.Before.setAllToTypes(QualType());
4532
4533      Result.UserDefined.After.setAsIdentityConversion();
4534      Result.UserDefined.After.setFromType(ToType);
4535      Result.UserDefined.After.setAllToTypes(ToType);
4536      Result.UserDefined.ConversionFunction = 0;
4537    }
4538    return Result;
4539  }
4540
4541  // C++11 [over.ics.list]p5:
4542  //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4543  if (ToType->isReferenceType()) {
4544    // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4545    // mention initializer lists in any way. So we go by what list-
4546    // initialization would do and try to extrapolate from that.
4547
4548    QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4549
4550    // If the initializer list has a single element that is reference-related
4551    // to the parameter type, we initialize the reference from that.
4552    if (From->getNumInits() == 1) {
4553      Expr *Init = From->getInit(0);
4554
4555      QualType T2 = Init->getType();
4556
4557      // If the initializer is the address of an overloaded function, try
4558      // to resolve the overloaded function. If all goes well, T2 is the
4559      // type of the resulting function.
4560      if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4561        DeclAccessPair Found;
4562        if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4563                                   Init, ToType, false, Found))
4564          T2 = Fn->getType();
4565      }
4566
4567      // Compute some basic properties of the types and the initializer.
4568      bool dummy1 = false;
4569      bool dummy2 = false;
4570      bool dummy3 = false;
4571      Sema::ReferenceCompareResult RefRelationship
4572        = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4573                                         dummy2, dummy3);
4574
4575      if (RefRelationship >= Sema::Ref_Related)
4576        return TryReferenceInit(S, Init, ToType,
4577                                /*FIXME:*/From->getLocStart(),
4578                                SuppressUserConversions,
4579                                /*AllowExplicit=*/false);
4580    }
4581
4582    // Otherwise, we bind the reference to a temporary created from the
4583    // initializer list.
4584    Result = TryListConversion(S, From, T1, SuppressUserConversions,
4585                               InOverloadResolution,
4586                               AllowObjCWritebackConversion);
4587    if (Result.isFailure())
4588      return Result;
4589    assert(!Result.isEllipsis() &&
4590           "Sub-initialization cannot result in ellipsis conversion.");
4591
4592    // Can we even bind to a temporary?
4593    if (ToType->isRValueReferenceType() ||
4594        (T1.isConstQualified() && !T1.isVolatileQualified())) {
4595      StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4596                                            Result.UserDefined.After;
4597      SCS.ReferenceBinding = true;
4598      SCS.IsLvalueReference = ToType->isLValueReferenceType();
4599      SCS.BindsToRvalue = true;
4600      SCS.BindsToFunctionLvalue = false;
4601      SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4602      SCS.ObjCLifetimeConversionBinding = false;
4603    } else
4604      Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4605                    From, ToType);
4606    return Result;
4607  }
4608
4609  // C++11 [over.ics.list]p6:
4610  //   Otherwise, if the parameter type is not a class:
4611  if (!ToType->isRecordType()) {
4612    //    - if the initializer list has one element, the implicit conversion
4613    //      sequence is the one required to convert the element to the
4614    //      parameter type.
4615    unsigned NumInits = From->getNumInits();
4616    if (NumInits == 1)
4617      Result = TryCopyInitialization(S, From->getInit(0), ToType,
4618                                     SuppressUserConversions,
4619                                     InOverloadResolution,
4620                                     AllowObjCWritebackConversion);
4621    //    - if the initializer list has no elements, the implicit conversion
4622    //      sequence is the identity conversion.
4623    else if (NumInits == 0) {
4624      Result.setStandard();
4625      Result.Standard.setAsIdentityConversion();
4626      Result.Standard.setFromType(ToType);
4627      Result.Standard.setAllToTypes(ToType);
4628    }
4629    Result.setListInitializationSequence();
4630    return Result;
4631  }
4632
4633  // C++11 [over.ics.list]p7:
4634  //   In all cases other than those enumerated above, no conversion is possible
4635  return Result;
4636}
4637
4638/// TryCopyInitialization - Try to copy-initialize a value of type
4639/// ToType from the expression From. Return the implicit conversion
4640/// sequence required to pass this argument, which may be a bad
4641/// conversion sequence (meaning that the argument cannot be passed to
4642/// a parameter of this type). If @p SuppressUserConversions, then we
4643/// do not permit any user-defined conversion sequences.
4644static ImplicitConversionSequence
4645TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4646                      bool SuppressUserConversions,
4647                      bool InOverloadResolution,
4648                      bool AllowObjCWritebackConversion,
4649                      bool AllowExplicit) {
4650  if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4651    return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4652                             InOverloadResolution,AllowObjCWritebackConversion);
4653
4654  if (ToType->isReferenceType())
4655    return TryReferenceInit(S, From, ToType,
4656                            /*FIXME:*/From->getLocStart(),
4657                            SuppressUserConversions,
4658                            AllowExplicit);
4659
4660  return TryImplicitConversion(S, From, ToType,
4661                               SuppressUserConversions,
4662                               /*AllowExplicit=*/false,
4663                               InOverloadResolution,
4664                               /*CStyle=*/false,
4665                               AllowObjCWritebackConversion);
4666}
4667
4668static bool TryCopyInitialization(const CanQualType FromQTy,
4669                                  const CanQualType ToQTy,
4670                                  Sema &S,
4671                                  SourceLocation Loc,
4672                                  ExprValueKind FromVK) {
4673  OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4674  ImplicitConversionSequence ICS =
4675    TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4676
4677  return !ICS.isBad();
4678}
4679
4680/// TryObjectArgumentInitialization - Try to initialize the object
4681/// parameter of the given member function (@c Method) from the
4682/// expression @p From.
4683static ImplicitConversionSequence
4684TryObjectArgumentInitialization(Sema &S, QualType FromType,
4685                                Expr::Classification FromClassification,
4686                                CXXMethodDecl *Method,
4687                                CXXRecordDecl *ActingContext) {
4688  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4689  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4690  //                 const volatile object.
4691  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4692    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4693  QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4694
4695  // Set up the conversion sequence as a "bad" conversion, to allow us
4696  // to exit early.
4697  ImplicitConversionSequence ICS;
4698
4699  // We need to have an object of class type.
4700  if (const PointerType *PT = FromType->getAs<PointerType>()) {
4701    FromType = PT->getPointeeType();
4702
4703    // When we had a pointer, it's implicitly dereferenced, so we
4704    // better have an lvalue.
4705    assert(FromClassification.isLValue());
4706  }
4707
4708  assert(FromType->isRecordType());
4709
4710  // C++0x [over.match.funcs]p4:
4711  //   For non-static member functions, the type of the implicit object
4712  //   parameter is
4713  //
4714  //     - "lvalue reference to cv X" for functions declared without a
4715  //        ref-qualifier or with the & ref-qualifier
4716  //     - "rvalue reference to cv X" for functions declared with the &&
4717  //        ref-qualifier
4718  //
4719  // where X is the class of which the function is a member and cv is the
4720  // cv-qualification on the member function declaration.
4721  //
4722  // However, when finding an implicit conversion sequence for the argument, we
4723  // are not allowed to create temporaries or perform user-defined conversions
4724  // (C++ [over.match.funcs]p5). We perform a simplified version of
4725  // reference binding here, that allows class rvalues to bind to
4726  // non-constant references.
4727
4728  // First check the qualifiers.
4729  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4730  if (ImplicitParamType.getCVRQualifiers()
4731                                    != FromTypeCanon.getLocalCVRQualifiers() &&
4732      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4733    ICS.setBad(BadConversionSequence::bad_qualifiers,
4734               FromType, ImplicitParamType);
4735    return ICS;
4736  }
4737
4738  // Check that we have either the same type or a derived type. It
4739  // affects the conversion rank.
4740  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4741  ImplicitConversionKind SecondKind;
4742  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4743    SecondKind = ICK_Identity;
4744  } else if (S.IsDerivedFrom(FromType, ClassType))
4745    SecondKind = ICK_Derived_To_Base;
4746  else {
4747    ICS.setBad(BadConversionSequence::unrelated_class,
4748               FromType, ImplicitParamType);
4749    return ICS;
4750  }
4751
4752  // Check the ref-qualifier.
4753  switch (Method->getRefQualifier()) {
4754  case RQ_None:
4755    // Do nothing; we don't care about lvalueness or rvalueness.
4756    break;
4757
4758  case RQ_LValue:
4759    if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4760      // non-const lvalue reference cannot bind to an rvalue
4761      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4762                 ImplicitParamType);
4763      return ICS;
4764    }
4765    break;
4766
4767  case RQ_RValue:
4768    if (!FromClassification.isRValue()) {
4769      // rvalue reference cannot bind to an lvalue
4770      ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4771                 ImplicitParamType);
4772      return ICS;
4773    }
4774    break;
4775  }
4776
4777  // Success. Mark this as a reference binding.
4778  ICS.setStandard();
4779  ICS.Standard.setAsIdentityConversion();
4780  ICS.Standard.Second = SecondKind;
4781  ICS.Standard.setFromType(FromType);
4782  ICS.Standard.setAllToTypes(ImplicitParamType);
4783  ICS.Standard.ReferenceBinding = true;
4784  ICS.Standard.DirectBinding = true;
4785  ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4786  ICS.Standard.BindsToFunctionLvalue = false;
4787  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4788  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4789    = (Method->getRefQualifier() == RQ_None);
4790  return ICS;
4791}
4792
4793/// PerformObjectArgumentInitialization - Perform initialization of
4794/// the implicit object parameter for the given Method with the given
4795/// expression.
4796ExprResult
4797Sema::PerformObjectArgumentInitialization(Expr *From,
4798                                          NestedNameSpecifier *Qualifier,
4799                                          NamedDecl *FoundDecl,
4800                                          CXXMethodDecl *Method) {
4801  QualType FromRecordType, DestType;
4802  QualType ImplicitParamRecordType  =
4803    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4804
4805  Expr::Classification FromClassification;
4806  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4807    FromRecordType = PT->getPointeeType();
4808    DestType = Method->getThisType(Context);
4809    FromClassification = Expr::Classification::makeSimpleLValue();
4810  } else {
4811    FromRecordType = From->getType();
4812    DestType = ImplicitParamRecordType;
4813    FromClassification = From->Classify(Context);
4814  }
4815
4816  // Note that we always use the true parent context when performing
4817  // the actual argument initialization.
4818  ImplicitConversionSequence ICS
4819    = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4820                                      Method, Method->getParent());
4821  if (ICS.isBad()) {
4822    if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4823      Qualifiers FromQs = FromRecordType.getQualifiers();
4824      Qualifiers ToQs = DestType.getQualifiers();
4825      unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4826      if (CVR) {
4827        Diag(From->getLocStart(),
4828             diag::err_member_function_call_bad_cvr)
4829          << Method->getDeclName() << FromRecordType << (CVR - 1)
4830          << From->getSourceRange();
4831        Diag(Method->getLocation(), diag::note_previous_decl)
4832          << Method->getDeclName();
4833        return ExprError();
4834      }
4835    }
4836
4837    return Diag(From->getLocStart(),
4838                diag::err_implicit_object_parameter_init)
4839       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4840  }
4841
4842  if (ICS.Standard.Second == ICK_Derived_To_Base) {
4843    ExprResult FromRes =
4844      PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4845    if (FromRes.isInvalid())
4846      return ExprError();
4847    From = FromRes.take();
4848  }
4849
4850  if (!Context.hasSameType(From->getType(), DestType))
4851    From = ImpCastExprToType(From, DestType, CK_NoOp,
4852                             From->getValueKind()).take();
4853  return Owned(From);
4854}
4855
4856/// TryContextuallyConvertToBool - Attempt to contextually convert the
4857/// expression From to bool (C++0x [conv]p3).
4858static ImplicitConversionSequence
4859TryContextuallyConvertToBool(Sema &S, Expr *From) {
4860  // FIXME: This is pretty broken.
4861  return TryImplicitConversion(S, From, S.Context.BoolTy,
4862                               // FIXME: Are these flags correct?
4863                               /*SuppressUserConversions=*/false,
4864                               /*AllowExplicit=*/true,
4865                               /*InOverloadResolution=*/false,
4866                               /*CStyle=*/false,
4867                               /*AllowObjCWritebackConversion=*/false);
4868}
4869
4870/// PerformContextuallyConvertToBool - Perform a contextual conversion
4871/// of the expression From to bool (C++0x [conv]p3).
4872ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4873  if (checkPlaceholderForOverload(*this, From))
4874    return ExprError();
4875
4876  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4877  if (!ICS.isBad())
4878    return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4879
4880  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4881    return Diag(From->getLocStart(),
4882                diag::err_typecheck_bool_condition)
4883                  << From->getType() << From->getSourceRange();
4884  return ExprError();
4885}
4886
4887/// Check that the specified conversion is permitted in a converted constant
4888/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4889/// is acceptable.
4890static bool CheckConvertedConstantConversions(Sema &S,
4891                                              StandardConversionSequence &SCS) {
4892  // Since we know that the target type is an integral or unscoped enumeration
4893  // type, most conversion kinds are impossible. All possible First and Third
4894  // conversions are fine.
4895  switch (SCS.Second) {
4896  case ICK_Identity:
4897  case ICK_Integral_Promotion:
4898  case ICK_Integral_Conversion:
4899  case ICK_Zero_Event_Conversion:
4900    return true;
4901
4902  case ICK_Boolean_Conversion:
4903    // Conversion from an integral or unscoped enumeration type to bool is
4904    // classified as ICK_Boolean_Conversion, but it's also an integral
4905    // conversion, so it's permitted in a converted constant expression.
4906    return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4907           SCS.getToType(2)->isBooleanType();
4908
4909  case ICK_Floating_Integral:
4910  case ICK_Complex_Real:
4911    return false;
4912
4913  case ICK_Lvalue_To_Rvalue:
4914  case ICK_Array_To_Pointer:
4915  case ICK_Function_To_Pointer:
4916  case ICK_NoReturn_Adjustment:
4917  case ICK_Qualification:
4918  case ICK_Compatible_Conversion:
4919  case ICK_Vector_Conversion:
4920  case ICK_Vector_Splat:
4921  case ICK_Derived_To_Base:
4922  case ICK_Pointer_Conversion:
4923  case ICK_Pointer_Member:
4924  case ICK_Block_Pointer_Conversion:
4925  case ICK_Writeback_Conversion:
4926  case ICK_Floating_Promotion:
4927  case ICK_Complex_Promotion:
4928  case ICK_Complex_Conversion:
4929  case ICK_Floating_Conversion:
4930  case ICK_TransparentUnionConversion:
4931    llvm_unreachable("unexpected second conversion kind");
4932
4933  case ICK_Num_Conversion_Kinds:
4934    break;
4935  }
4936
4937  llvm_unreachable("unknown conversion kind");
4938}
4939
4940/// CheckConvertedConstantExpression - Check that the expression From is a
4941/// converted constant expression of type T, perform the conversion and produce
4942/// the converted expression, per C++11 [expr.const]p3.
4943ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4944                                                  llvm::APSInt &Value,
4945                                                  CCEKind CCE) {
4946  assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4947  assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4948
4949  if (checkPlaceholderForOverload(*this, From))
4950    return ExprError();
4951
4952  // C++11 [expr.const]p3 with proposed wording fixes:
4953  //  A converted constant expression of type T is a core constant expression,
4954  //  implicitly converted to a prvalue of type T, where the converted
4955  //  expression is a literal constant expression and the implicit conversion
4956  //  sequence contains only user-defined conversions, lvalue-to-rvalue
4957  //  conversions, integral promotions, and integral conversions other than
4958  //  narrowing conversions.
4959  ImplicitConversionSequence ICS =
4960    TryImplicitConversion(From, T,
4961                          /*SuppressUserConversions=*/false,
4962                          /*AllowExplicit=*/false,
4963                          /*InOverloadResolution=*/false,
4964                          /*CStyle=*/false,
4965                          /*AllowObjcWritebackConversion=*/false);
4966  StandardConversionSequence *SCS = 0;
4967  switch (ICS.getKind()) {
4968  case ImplicitConversionSequence::StandardConversion:
4969    if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4970      return Diag(From->getLocStart(),
4971                  diag::err_typecheck_converted_constant_expression_disallowed)
4972               << From->getType() << From->getSourceRange() << T;
4973    SCS = &ICS.Standard;
4974    break;
4975  case ImplicitConversionSequence::UserDefinedConversion:
4976    // We are converting from class type to an integral or enumeration type, so
4977    // the Before sequence must be trivial.
4978    if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4979      return Diag(From->getLocStart(),
4980                  diag::err_typecheck_converted_constant_expression_disallowed)
4981               << From->getType() << From->getSourceRange() << T;
4982    SCS = &ICS.UserDefined.After;
4983    break;
4984  case ImplicitConversionSequence::AmbiguousConversion:
4985  case ImplicitConversionSequence::BadConversion:
4986    if (!DiagnoseMultipleUserDefinedConversion(From, T))
4987      return Diag(From->getLocStart(),
4988                  diag::err_typecheck_converted_constant_expression)
4989                    << From->getType() << From->getSourceRange() << T;
4990    return ExprError();
4991
4992  case ImplicitConversionSequence::EllipsisConversion:
4993    llvm_unreachable("ellipsis conversion in converted constant expression");
4994  }
4995
4996  ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4997  if (Result.isInvalid())
4998    return Result;
4999
5000  // Check for a narrowing implicit conversion.
5001  APValue PreNarrowingValue;
5002  QualType PreNarrowingType;
5003  switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5004                                PreNarrowingType)) {
5005  case NK_Variable_Narrowing:
5006    // Implicit conversion to a narrower type, and the value is not a constant
5007    // expression. We'll diagnose this in a moment.
5008  case NK_Not_Narrowing:
5009    break;
5010
5011  case NK_Constant_Narrowing:
5012    Diag(From->getLocStart(),
5013         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5014                             diag::err_cce_narrowing)
5015      << CCE << /*Constant*/1
5016      << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
5017    break;
5018
5019  case NK_Type_Narrowing:
5020    Diag(From->getLocStart(),
5021         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5022                             diag::err_cce_narrowing)
5023      << CCE << /*Constant*/0 << From->getType() << T;
5024    break;
5025  }
5026
5027  // Check the expression is a constant expression.
5028  SmallVector<PartialDiagnosticAt, 8> Notes;
5029  Expr::EvalResult Eval;
5030  Eval.Diag = &Notes;
5031
5032  if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
5033    // The expression can't be folded, so we can't keep it at this position in
5034    // the AST.
5035    Result = ExprError();
5036  } else {
5037    Value = Eval.Val.getInt();
5038
5039    if (Notes.empty()) {
5040      // It's a constant expression.
5041      return Result;
5042    }
5043  }
5044
5045  // It's not a constant expression. Produce an appropriate diagnostic.
5046  if (Notes.size() == 1 &&
5047      Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5048    Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5049  else {
5050    Diag(From->getLocStart(), diag::err_expr_not_cce)
5051      << CCE << From->getSourceRange();
5052    for (unsigned I = 0; I < Notes.size(); ++I)
5053      Diag(Notes[I].first, Notes[I].second);
5054  }
5055  return Result;
5056}
5057
5058/// dropPointerConversions - If the given standard conversion sequence
5059/// involves any pointer conversions, remove them.  This may change
5060/// the result type of the conversion sequence.
5061static void dropPointerConversion(StandardConversionSequence &SCS) {
5062  if (SCS.Second == ICK_Pointer_Conversion) {
5063    SCS.Second = ICK_Identity;
5064    SCS.Third = ICK_Identity;
5065    SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5066  }
5067}
5068
5069/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5070/// convert the expression From to an Objective-C pointer type.
5071static ImplicitConversionSequence
5072TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5073  // Do an implicit conversion to 'id'.
5074  QualType Ty = S.Context.getObjCIdType();
5075  ImplicitConversionSequence ICS
5076    = TryImplicitConversion(S, From, Ty,
5077                            // FIXME: Are these flags correct?
5078                            /*SuppressUserConversions=*/false,
5079                            /*AllowExplicit=*/true,
5080                            /*InOverloadResolution=*/false,
5081                            /*CStyle=*/false,
5082                            /*AllowObjCWritebackConversion=*/false);
5083
5084  // Strip off any final conversions to 'id'.
5085  switch (ICS.getKind()) {
5086  case ImplicitConversionSequence::BadConversion:
5087  case ImplicitConversionSequence::AmbiguousConversion:
5088  case ImplicitConversionSequence::EllipsisConversion:
5089    break;
5090
5091  case ImplicitConversionSequence::UserDefinedConversion:
5092    dropPointerConversion(ICS.UserDefined.After);
5093    break;
5094
5095  case ImplicitConversionSequence::StandardConversion:
5096    dropPointerConversion(ICS.Standard);
5097    break;
5098  }
5099
5100  return ICS;
5101}
5102
5103/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5104/// conversion of the expression From to an Objective-C pointer type.
5105ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5106  if (checkPlaceholderForOverload(*this, From))
5107    return ExprError();
5108
5109  QualType Ty = Context.getObjCIdType();
5110  ImplicitConversionSequence ICS =
5111    TryContextuallyConvertToObjCPointer(*this, From);
5112  if (!ICS.isBad())
5113    return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5114  return ExprError();
5115}
5116
5117/// Determine whether the provided type is an integral type, or an enumeration
5118/// type of a permitted flavor.
5119bool Sema::ICEConvertDiagnoser::match(QualType T) {
5120  return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5121                                 : T->isIntegralOrUnscopedEnumerationType();
5122}
5123
5124static ExprResult
5125diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5126                            Sema::ContextualImplicitConverter &Converter,
5127                            QualType T, UnresolvedSetImpl &ViableConversions) {
5128
5129  if (Converter.Suppress)
5130    return ExprError();
5131
5132  Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5133  for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5134    CXXConversionDecl *Conv =
5135        cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5136    QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5137    Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5138  }
5139  return SemaRef.Owned(From);
5140}
5141
5142static bool
5143diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5144                           Sema::ContextualImplicitConverter &Converter,
5145                           QualType T, bool HadMultipleCandidates,
5146                           UnresolvedSetImpl &ExplicitConversions) {
5147  if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5148    DeclAccessPair Found = ExplicitConversions[0];
5149    CXXConversionDecl *Conversion =
5150        cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5151
5152    // The user probably meant to invoke the given explicit
5153    // conversion; use it.
5154    QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5155    std::string TypeStr;
5156    ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5157
5158    Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5159        << FixItHint::CreateInsertion(From->getLocStart(),
5160                                      "static_cast<" + TypeStr + ">(")
5161        << FixItHint::CreateInsertion(
5162               SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5163    Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5164
5165    // If we aren't in a SFINAE context, build a call to the
5166    // explicit conversion function.
5167    if (SemaRef.isSFINAEContext())
5168      return true;
5169
5170    SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5171    ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5172                                                       HadMultipleCandidates);
5173    if (Result.isInvalid())
5174      return true;
5175    // Record usage of conversion in an implicit cast.
5176    From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5177                                    CK_UserDefinedConversion, Result.get(), 0,
5178                                    Result.get()->getValueKind());
5179  }
5180  return false;
5181}
5182
5183static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5184                             Sema::ContextualImplicitConverter &Converter,
5185                             QualType T, bool HadMultipleCandidates,
5186                             DeclAccessPair &Found) {
5187  CXXConversionDecl *Conversion =
5188      cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5189  SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5190
5191  QualType ToType = Conversion->getConversionType().getNonReferenceType();
5192  if (!Converter.SuppressConversion) {
5193    if (SemaRef.isSFINAEContext())
5194      return true;
5195
5196    Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5197        << From->getSourceRange();
5198  }
5199
5200  ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5201                                                     HadMultipleCandidates);
5202  if (Result.isInvalid())
5203    return true;
5204  // Record usage of conversion in an implicit cast.
5205  From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5206                                  CK_UserDefinedConversion, Result.get(), 0,
5207                                  Result.get()->getValueKind());
5208  return false;
5209}
5210
5211static ExprResult finishContextualImplicitConversion(
5212    Sema &SemaRef, SourceLocation Loc, Expr *From,
5213    Sema::ContextualImplicitConverter &Converter) {
5214  if (!Converter.match(From->getType()) && !Converter.Suppress)
5215    Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5216        << From->getSourceRange();
5217
5218  return SemaRef.DefaultLvalueConversion(From);
5219}
5220
5221static void
5222collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5223                                  UnresolvedSetImpl &ViableConversions,
5224                                  OverloadCandidateSet &CandidateSet) {
5225  for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5226    DeclAccessPair FoundDecl = ViableConversions[I];
5227    NamedDecl *D = FoundDecl.getDecl();
5228    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5229    if (isa<UsingShadowDecl>(D))
5230      D = cast<UsingShadowDecl>(D)->getTargetDecl();
5231
5232    CXXConversionDecl *Conv;
5233    FunctionTemplateDecl *ConvTemplate;
5234    if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5235      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5236    else
5237      Conv = cast<CXXConversionDecl>(D);
5238
5239    if (ConvTemplate)
5240      SemaRef.AddTemplateConversionCandidate(
5241          ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet);
5242    else
5243      SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5244                                     ToType, CandidateSet);
5245  }
5246}
5247
5248/// \brief Attempt to convert the given expression to a type which is accepted
5249/// by the given converter.
5250///
5251/// This routine will attempt to convert an expression of class type to a
5252/// type accepted by the specified converter. In C++11 and before, the class
5253/// must have a single non-explicit conversion function converting to a matching
5254/// type. In C++1y, there can be multiple such conversion functions, but only
5255/// one target type.
5256///
5257/// \param Loc The source location of the construct that requires the
5258/// conversion.
5259///
5260/// \param From The expression we're converting from.
5261///
5262/// \param Converter Used to control and diagnose the conversion process.
5263///
5264/// \returns The expression, converted to an integral or enumeration type if
5265/// successful.
5266ExprResult Sema::PerformContextualImplicitConversion(
5267    SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5268  // We can't perform any more checking for type-dependent expressions.
5269  if (From->isTypeDependent())
5270    return Owned(From);
5271
5272  // Process placeholders immediately.
5273  if (From->hasPlaceholderType()) {
5274    ExprResult result = CheckPlaceholderExpr(From);
5275    if (result.isInvalid())
5276      return result;
5277    From = result.take();
5278  }
5279
5280  // If the expression already has a matching type, we're golden.
5281  QualType T = From->getType();
5282  if (Converter.match(T))
5283    return DefaultLvalueConversion(From);
5284
5285  // FIXME: Check for missing '()' if T is a function type?
5286
5287  // We can only perform contextual implicit conversions on objects of class
5288  // type.
5289  const RecordType *RecordTy = T->getAs<RecordType>();
5290  if (!RecordTy || !getLangOpts().CPlusPlus) {
5291    if (!Converter.Suppress)
5292      Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5293    return Owned(From);
5294  }
5295
5296  // We must have a complete class type.
5297  struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5298    ContextualImplicitConverter &Converter;
5299    Expr *From;
5300
5301    TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5302        : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5303
5304    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5305      Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5306    }
5307  } IncompleteDiagnoser(Converter, From);
5308
5309  if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5310    return Owned(From);
5311
5312  // Look for a conversion to an integral or enumeration type.
5313  UnresolvedSet<4>
5314      ViableConversions; // These are *potentially* viable in C++1y.
5315  UnresolvedSet<4> ExplicitConversions;
5316  std::pair<CXXRecordDecl::conversion_iterator,
5317            CXXRecordDecl::conversion_iterator> Conversions =
5318      cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5319
5320  bool HadMultipleCandidates =
5321      (std::distance(Conversions.first, Conversions.second) > 1);
5322
5323  // To check that there is only one target type, in C++1y:
5324  QualType ToType;
5325  bool HasUniqueTargetType = true;
5326
5327  // Collect explicit or viable (potentially in C++1y) conversions.
5328  for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5329                                          E = Conversions.second;
5330       I != E; ++I) {
5331    NamedDecl *D = (*I)->getUnderlyingDecl();
5332    CXXConversionDecl *Conversion;
5333    FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5334    if (ConvTemplate) {
5335      if (getLangOpts().CPlusPlus1y)
5336        Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5337      else
5338        continue; // C++11 does not consider conversion operator templates(?).
5339    } else
5340      Conversion = cast<CXXConversionDecl>(D);
5341
5342    assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5343           "Conversion operator templates are considered potentially "
5344           "viable in C++1y");
5345
5346    QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5347    if (Converter.match(CurToType) || ConvTemplate) {
5348
5349      if (Conversion->isExplicit()) {
5350        // FIXME: For C++1y, do we need this restriction?
5351        // cf. diagnoseNoViableConversion()
5352        if (!ConvTemplate)
5353          ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5354      } else {
5355        if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5356          if (ToType.isNull())
5357            ToType = CurToType.getUnqualifiedType();
5358          else if (HasUniqueTargetType &&
5359                   (CurToType.getUnqualifiedType() != ToType))
5360            HasUniqueTargetType = false;
5361        }
5362        ViableConversions.addDecl(I.getDecl(), I.getAccess());
5363      }
5364    }
5365  }
5366
5367  if (getLangOpts().CPlusPlus1y) {
5368    // C++1y [conv]p6:
5369    // ... An expression e of class type E appearing in such a context
5370    // is said to be contextually implicitly converted to a specified
5371    // type T and is well-formed if and only if e can be implicitly
5372    // converted to a type T that is determined as follows: E is searched
5373    // for conversion functions whose return type is cv T or reference to
5374    // cv T such that T is allowed by the context. There shall be
5375    // exactly one such T.
5376
5377    // If no unique T is found:
5378    if (ToType.isNull()) {
5379      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5380                                     HadMultipleCandidates,
5381                                     ExplicitConversions))
5382        return ExprError();
5383      return finishContextualImplicitConversion(*this, Loc, From, Converter);
5384    }
5385
5386    // If more than one unique Ts are found:
5387    if (!HasUniqueTargetType)
5388      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5389                                         ViableConversions);
5390
5391    // If one unique T is found:
5392    // First, build a candidate set from the previously recorded
5393    // potentially viable conversions.
5394    OverloadCandidateSet CandidateSet(Loc);
5395    collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5396                                      CandidateSet);
5397
5398    // Then, perform overload resolution over the candidate set.
5399    OverloadCandidateSet::iterator Best;
5400    switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5401    case OR_Success: {
5402      // Apply this conversion.
5403      DeclAccessPair Found =
5404          DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5405      if (recordConversion(*this, Loc, From, Converter, T,
5406                           HadMultipleCandidates, Found))
5407        return ExprError();
5408      break;
5409    }
5410    case OR_Ambiguous:
5411      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5412                                         ViableConversions);
5413    case OR_No_Viable_Function:
5414      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5415                                     HadMultipleCandidates,
5416                                     ExplicitConversions))
5417        return ExprError();
5418    // fall through 'OR_Deleted' case.
5419    case OR_Deleted:
5420      // We'll complain below about a non-integral condition type.
5421      break;
5422    }
5423  } else {
5424    switch (ViableConversions.size()) {
5425    case 0: {
5426      if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5427                                     HadMultipleCandidates,
5428                                     ExplicitConversions))
5429        return ExprError();
5430
5431      // We'll complain below about a non-integral condition type.
5432      break;
5433    }
5434    case 1: {
5435      // Apply this conversion.
5436      DeclAccessPair Found = ViableConversions[0];
5437      if (recordConversion(*this, Loc, From, Converter, T,
5438                           HadMultipleCandidates, Found))
5439        return ExprError();
5440      break;
5441    }
5442    default:
5443      return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5444                                         ViableConversions);
5445    }
5446  }
5447
5448  return finishContextualImplicitConversion(*this, Loc, From, Converter);
5449}
5450
5451/// AddOverloadCandidate - Adds the given function to the set of
5452/// candidate functions, using the given function call arguments.  If
5453/// @p SuppressUserConversions, then don't allow user-defined
5454/// conversions via constructors or conversion operators.
5455///
5456/// \param PartialOverloading true if we are performing "partial" overloading
5457/// based on an incomplete set of function arguments. This feature is used by
5458/// code completion.
5459void
5460Sema::AddOverloadCandidate(FunctionDecl *Function,
5461                           DeclAccessPair FoundDecl,
5462                           ArrayRef<Expr *> Args,
5463                           OverloadCandidateSet& CandidateSet,
5464                           bool SuppressUserConversions,
5465                           bool PartialOverloading,
5466                           bool AllowExplicit) {
5467  const FunctionProtoType* Proto
5468    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5469  assert(Proto && "Functions without a prototype cannot be overloaded");
5470  assert(!Function->getDescribedFunctionTemplate() &&
5471         "Use AddTemplateOverloadCandidate for function templates");
5472
5473  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5474    if (!isa<CXXConstructorDecl>(Method)) {
5475      // If we get here, it's because we're calling a member function
5476      // that is named without a member access expression (e.g.,
5477      // "this->f") that was either written explicitly or created
5478      // implicitly. This can happen with a qualified call to a member
5479      // function, e.g., X::f(). We use an empty type for the implied
5480      // object argument (C++ [over.call.func]p3), and the acting context
5481      // is irrelevant.
5482      AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5483                         QualType(), Expr::Classification::makeSimpleLValue(),
5484                         Args, CandidateSet, SuppressUserConversions);
5485      return;
5486    }
5487    // We treat a constructor like a non-member function, since its object
5488    // argument doesn't participate in overload resolution.
5489  }
5490
5491  if (!CandidateSet.isNewCandidate(Function))
5492    return;
5493
5494  // Overload resolution is always an unevaluated context.
5495  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5496
5497  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5498    // C++ [class.copy]p3:
5499    //   A member function template is never instantiated to perform the copy
5500    //   of a class object to an object of its class type.
5501    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5502    if (Args.size() == 1 &&
5503        Constructor->isSpecializationCopyingObject() &&
5504        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5505         IsDerivedFrom(Args[0]->getType(), ClassType)))
5506      return;
5507  }
5508
5509  // Add this candidate
5510  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5511  Candidate.FoundDecl = FoundDecl;
5512  Candidate.Function = Function;
5513  Candidate.Viable = true;
5514  Candidate.IsSurrogate = false;
5515  Candidate.IgnoreObjectArgument = false;
5516  Candidate.ExplicitCallArguments = Args.size();
5517
5518  unsigned NumArgsInProto = Proto->getNumArgs();
5519
5520  // (C++ 13.3.2p2): A candidate function having fewer than m
5521  // parameters is viable only if it has an ellipsis in its parameter
5522  // list (8.3.5).
5523  if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5524      !Proto->isVariadic()) {
5525    Candidate.Viable = false;
5526    Candidate.FailureKind = ovl_fail_too_many_arguments;
5527    return;
5528  }
5529
5530  // (C++ 13.3.2p2): A candidate function having more than m parameters
5531  // is viable only if the (m+1)st parameter has a default argument
5532  // (8.3.6). For the purposes of overload resolution, the
5533  // parameter list is truncated on the right, so that there are
5534  // exactly m parameters.
5535  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5536  if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5537    // Not enough arguments.
5538    Candidate.Viable = false;
5539    Candidate.FailureKind = ovl_fail_too_few_arguments;
5540    return;
5541  }
5542
5543  // (CUDA B.1): Check for invalid calls between targets.
5544  if (getLangOpts().CUDA)
5545    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5546      if (CheckCUDATarget(Caller, Function)) {
5547        Candidate.Viable = false;
5548        Candidate.FailureKind = ovl_fail_bad_target;
5549        return;
5550      }
5551
5552  // Determine the implicit conversion sequences for each of the
5553  // arguments.
5554  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5555    if (ArgIdx < NumArgsInProto) {
5556      // (C++ 13.3.2p3): for F to be a viable function, there shall
5557      // exist for each argument an implicit conversion sequence
5558      // (13.3.3.1) that converts that argument to the corresponding
5559      // parameter of F.
5560      QualType ParamType = Proto->getArgType(ArgIdx);
5561      Candidate.Conversions[ArgIdx]
5562        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5563                                SuppressUserConversions,
5564                                /*InOverloadResolution=*/true,
5565                                /*AllowObjCWritebackConversion=*/
5566                                  getLangOpts().ObjCAutoRefCount,
5567                                AllowExplicit);
5568      if (Candidate.Conversions[ArgIdx].isBad()) {
5569        Candidate.Viable = false;
5570        Candidate.FailureKind = ovl_fail_bad_conversion;
5571        break;
5572      }
5573    } else {
5574      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5575      // argument for which there is no corresponding parameter is
5576      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5577      Candidate.Conversions[ArgIdx].setEllipsis();
5578    }
5579  }
5580}
5581
5582/// \brief Add all of the function declarations in the given function set to
5583/// the overload canddiate set.
5584void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5585                                 ArrayRef<Expr *> Args,
5586                                 OverloadCandidateSet& CandidateSet,
5587                                 bool SuppressUserConversions,
5588                               TemplateArgumentListInfo *ExplicitTemplateArgs) {
5589  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5590    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5591    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5592      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5593        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5594                           cast<CXXMethodDecl>(FD)->getParent(),
5595                           Args[0]->getType(), Args[0]->Classify(Context),
5596                           Args.slice(1), CandidateSet,
5597                           SuppressUserConversions);
5598      else
5599        AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5600                             SuppressUserConversions);
5601    } else {
5602      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5603      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5604          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5605        AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5606                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5607                                   ExplicitTemplateArgs,
5608                                   Args[0]->getType(),
5609                                   Args[0]->Classify(Context), Args.slice(1),
5610                                   CandidateSet, SuppressUserConversions);
5611      else
5612        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5613                                     ExplicitTemplateArgs, Args,
5614                                     CandidateSet, SuppressUserConversions);
5615    }
5616  }
5617}
5618
5619/// AddMethodCandidate - Adds a named decl (which is some kind of
5620/// method) as a method candidate to the given overload set.
5621void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5622                              QualType ObjectType,
5623                              Expr::Classification ObjectClassification,
5624                              ArrayRef<Expr *> Args,
5625                              OverloadCandidateSet& CandidateSet,
5626                              bool SuppressUserConversions) {
5627  NamedDecl *Decl = FoundDecl.getDecl();
5628  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5629
5630  if (isa<UsingShadowDecl>(Decl))
5631    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5632
5633  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5634    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5635           "Expected a member function template");
5636    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5637                               /*ExplicitArgs*/ 0,
5638                               ObjectType, ObjectClassification,
5639                               Args, CandidateSet,
5640                               SuppressUserConversions);
5641  } else {
5642    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5643                       ObjectType, ObjectClassification,
5644                       Args,
5645                       CandidateSet, SuppressUserConversions);
5646  }
5647}
5648
5649/// AddMethodCandidate - Adds the given C++ member function to the set
5650/// of candidate functions, using the given function call arguments
5651/// and the object argument (@c Object). For example, in a call
5652/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5653/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5654/// allow user-defined conversions via constructors or conversion
5655/// operators.
5656void
5657Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5658                         CXXRecordDecl *ActingContext, QualType ObjectType,
5659                         Expr::Classification ObjectClassification,
5660                         ArrayRef<Expr *> Args,
5661                         OverloadCandidateSet& CandidateSet,
5662                         bool SuppressUserConversions) {
5663  const FunctionProtoType* Proto
5664    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5665  assert(Proto && "Methods without a prototype cannot be overloaded");
5666  assert(!isa<CXXConstructorDecl>(Method) &&
5667         "Use AddOverloadCandidate for constructors");
5668
5669  if (!CandidateSet.isNewCandidate(Method))
5670    return;
5671
5672  // Overload resolution is always an unevaluated context.
5673  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5674
5675  // Add this candidate
5676  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5677  Candidate.FoundDecl = FoundDecl;
5678  Candidate.Function = Method;
5679  Candidate.IsSurrogate = false;
5680  Candidate.IgnoreObjectArgument = false;
5681  Candidate.ExplicitCallArguments = Args.size();
5682
5683  unsigned NumArgsInProto = Proto->getNumArgs();
5684
5685  // (C++ 13.3.2p2): A candidate function having fewer than m
5686  // parameters is viable only if it has an ellipsis in its parameter
5687  // list (8.3.5).
5688  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5689    Candidate.Viable = false;
5690    Candidate.FailureKind = ovl_fail_too_many_arguments;
5691    return;
5692  }
5693
5694  // (C++ 13.3.2p2): A candidate function having more than m parameters
5695  // is viable only if the (m+1)st parameter has a default argument
5696  // (8.3.6). For the purposes of overload resolution, the
5697  // parameter list is truncated on the right, so that there are
5698  // exactly m parameters.
5699  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5700  if (Args.size() < MinRequiredArgs) {
5701    // Not enough arguments.
5702    Candidate.Viable = false;
5703    Candidate.FailureKind = ovl_fail_too_few_arguments;
5704    return;
5705  }
5706
5707  Candidate.Viable = true;
5708
5709  if (Method->isStatic() || ObjectType.isNull())
5710    // The implicit object argument is ignored.
5711    Candidate.IgnoreObjectArgument = true;
5712  else {
5713    // Determine the implicit conversion sequence for the object
5714    // parameter.
5715    Candidate.Conversions[0]
5716      = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5717                                        Method, ActingContext);
5718    if (Candidate.Conversions[0].isBad()) {
5719      Candidate.Viable = false;
5720      Candidate.FailureKind = ovl_fail_bad_conversion;
5721      return;
5722    }
5723  }
5724
5725  // Determine the implicit conversion sequences for each of the
5726  // arguments.
5727  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5728    if (ArgIdx < NumArgsInProto) {
5729      // (C++ 13.3.2p3): for F to be a viable function, there shall
5730      // exist for each argument an implicit conversion sequence
5731      // (13.3.3.1) that converts that argument to the corresponding
5732      // parameter of F.
5733      QualType ParamType = Proto->getArgType(ArgIdx);
5734      Candidate.Conversions[ArgIdx + 1]
5735        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5736                                SuppressUserConversions,
5737                                /*InOverloadResolution=*/true,
5738                                /*AllowObjCWritebackConversion=*/
5739                                  getLangOpts().ObjCAutoRefCount);
5740      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5741        Candidate.Viable = false;
5742        Candidate.FailureKind = ovl_fail_bad_conversion;
5743        break;
5744      }
5745    } else {
5746      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5747      // argument for which there is no corresponding parameter is
5748      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5749      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5750    }
5751  }
5752}
5753
5754/// \brief Add a C++ member function template as a candidate to the candidate
5755/// set, using template argument deduction to produce an appropriate member
5756/// function template specialization.
5757void
5758Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5759                                 DeclAccessPair FoundDecl,
5760                                 CXXRecordDecl *ActingContext,
5761                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5762                                 QualType ObjectType,
5763                                 Expr::Classification ObjectClassification,
5764                                 ArrayRef<Expr *> Args,
5765                                 OverloadCandidateSet& CandidateSet,
5766                                 bool SuppressUserConversions) {
5767  if (!CandidateSet.isNewCandidate(MethodTmpl))
5768    return;
5769
5770  // C++ [over.match.funcs]p7:
5771  //   In each case where a candidate is a function template, candidate
5772  //   function template specializations are generated using template argument
5773  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5774  //   candidate functions in the usual way.113) A given name can refer to one
5775  //   or more function templates and also to a set of overloaded non-template
5776  //   functions. In such a case, the candidate functions generated from each
5777  //   function template are combined with the set of non-template candidate
5778  //   functions.
5779  TemplateDeductionInfo Info(CandidateSet.getLocation());
5780  FunctionDecl *Specialization = 0;
5781  if (TemplateDeductionResult Result
5782      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5783                                Specialization, Info)) {
5784    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5785    Candidate.FoundDecl = FoundDecl;
5786    Candidate.Function = MethodTmpl->getTemplatedDecl();
5787    Candidate.Viable = false;
5788    Candidate.FailureKind = ovl_fail_bad_deduction;
5789    Candidate.IsSurrogate = false;
5790    Candidate.IgnoreObjectArgument = false;
5791    Candidate.ExplicitCallArguments = Args.size();
5792    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5793                                                          Info);
5794    return;
5795  }
5796
5797  // Add the function template specialization produced by template argument
5798  // deduction as a candidate.
5799  assert(Specialization && "Missing member function template specialization?");
5800  assert(isa<CXXMethodDecl>(Specialization) &&
5801         "Specialization is not a member function?");
5802  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5803                     ActingContext, ObjectType, ObjectClassification, Args,
5804                     CandidateSet, SuppressUserConversions);
5805}
5806
5807/// \brief Add a C++ function template specialization as a candidate
5808/// in the candidate set, using template argument deduction to produce
5809/// an appropriate function template specialization.
5810void
5811Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5812                                   DeclAccessPair FoundDecl,
5813                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5814                                   ArrayRef<Expr *> Args,
5815                                   OverloadCandidateSet& CandidateSet,
5816                                   bool SuppressUserConversions) {
5817  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5818    return;
5819
5820  // C++ [over.match.funcs]p7:
5821  //   In each case where a candidate is a function template, candidate
5822  //   function template specializations are generated using template argument
5823  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5824  //   candidate functions in the usual way.113) A given name can refer to one
5825  //   or more function templates and also to a set of overloaded non-template
5826  //   functions. In such a case, the candidate functions generated from each
5827  //   function template are combined with the set of non-template candidate
5828  //   functions.
5829  TemplateDeductionInfo Info(CandidateSet.getLocation());
5830  FunctionDecl *Specialization = 0;
5831  if (TemplateDeductionResult Result
5832        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5833                                  Specialization, Info)) {
5834    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5835    Candidate.FoundDecl = FoundDecl;
5836    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5837    Candidate.Viable = false;
5838    Candidate.FailureKind = ovl_fail_bad_deduction;
5839    Candidate.IsSurrogate = false;
5840    Candidate.IgnoreObjectArgument = false;
5841    Candidate.ExplicitCallArguments = Args.size();
5842    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5843                                                          Info);
5844    return;
5845  }
5846
5847  // Add the function template specialization produced by template argument
5848  // deduction as a candidate.
5849  assert(Specialization && "Missing function template specialization?");
5850  AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5851                       SuppressUserConversions);
5852}
5853
5854/// AddConversionCandidate - Add a C++ conversion function as a
5855/// candidate in the candidate set (C++ [over.match.conv],
5856/// C++ [over.match.copy]). From is the expression we're converting from,
5857/// and ToType is the type that we're eventually trying to convert to
5858/// (which may or may not be the same type as the type that the
5859/// conversion function produces).
5860void
5861Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5862                             DeclAccessPair FoundDecl,
5863                             CXXRecordDecl *ActingContext,
5864                             Expr *From, QualType ToType,
5865                             OverloadCandidateSet& CandidateSet) {
5866  assert(!Conversion->getDescribedFunctionTemplate() &&
5867         "Conversion function templates use AddTemplateConversionCandidate");
5868  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5869  if (!CandidateSet.isNewCandidate(Conversion))
5870    return;
5871
5872  // If the conversion function has an undeduced return type, trigger its
5873  // deduction now.
5874  if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5875    if (DeduceReturnType(Conversion, From->getExprLoc()))
5876      return;
5877    ConvType = Conversion->getConversionType().getNonReferenceType();
5878  }
5879
5880  // Overload resolution is always an unevaluated context.
5881  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5882
5883  // Add this candidate
5884  OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5885  Candidate.FoundDecl = FoundDecl;
5886  Candidate.Function = Conversion;
5887  Candidate.IsSurrogate = false;
5888  Candidate.IgnoreObjectArgument = false;
5889  Candidate.FinalConversion.setAsIdentityConversion();
5890  Candidate.FinalConversion.setFromType(ConvType);
5891  Candidate.FinalConversion.setAllToTypes(ToType);
5892  Candidate.Viable = true;
5893  Candidate.ExplicitCallArguments = 1;
5894
5895  // C++ [over.match.funcs]p4:
5896  //   For conversion functions, the function is considered to be a member of
5897  //   the class of the implicit implied object argument for the purpose of
5898  //   defining the type of the implicit object parameter.
5899  //
5900  // Determine the implicit conversion sequence for the implicit
5901  // object parameter.
5902  QualType ImplicitParamType = From->getType();
5903  if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5904    ImplicitParamType = FromPtrType->getPointeeType();
5905  CXXRecordDecl *ConversionContext
5906    = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5907
5908  Candidate.Conversions[0]
5909    = TryObjectArgumentInitialization(*this, From->getType(),
5910                                      From->Classify(Context),
5911                                      Conversion, ConversionContext);
5912
5913  if (Candidate.Conversions[0].isBad()) {
5914    Candidate.Viable = false;
5915    Candidate.FailureKind = ovl_fail_bad_conversion;
5916    return;
5917  }
5918
5919  // We won't go through a user-define type conversion function to convert a
5920  // derived to base as such conversions are given Conversion Rank. They only
5921  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5922  QualType FromCanon
5923    = Context.getCanonicalType(From->getType().getUnqualifiedType());
5924  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5925  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5926    Candidate.Viable = false;
5927    Candidate.FailureKind = ovl_fail_trivial_conversion;
5928    return;
5929  }
5930
5931  // To determine what the conversion from the result of calling the
5932  // conversion function to the type we're eventually trying to
5933  // convert to (ToType), we need to synthesize a call to the
5934  // conversion function and attempt copy initialization from it. This
5935  // makes sure that we get the right semantics with respect to
5936  // lvalues/rvalues and the type. Fortunately, we can allocate this
5937  // call on the stack and we don't need its arguments to be
5938  // well-formed.
5939  DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5940                            VK_LValue, From->getLocStart());
5941  ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5942                                Context.getPointerType(Conversion->getType()),
5943                                CK_FunctionToPointerDecay,
5944                                &ConversionRef, VK_RValue);
5945
5946  QualType ConversionType = Conversion->getConversionType();
5947  if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5948    Candidate.Viable = false;
5949    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5950    return;
5951  }
5952
5953  ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5954
5955  // Note that it is safe to allocate CallExpr on the stack here because
5956  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5957  // allocator).
5958  QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5959  CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
5960                From->getLocStart());
5961  ImplicitConversionSequence ICS =
5962    TryCopyInitialization(*this, &Call, ToType,
5963                          /*SuppressUserConversions=*/true,
5964                          /*InOverloadResolution=*/false,
5965                          /*AllowObjCWritebackConversion=*/false);
5966
5967  switch (ICS.getKind()) {
5968  case ImplicitConversionSequence::StandardConversion:
5969    Candidate.FinalConversion = ICS.Standard;
5970
5971    // C++ [over.ics.user]p3:
5972    //   If the user-defined conversion is specified by a specialization of a
5973    //   conversion function template, the second standard conversion sequence
5974    //   shall have exact match rank.
5975    if (Conversion->getPrimaryTemplate() &&
5976        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5977      Candidate.Viable = false;
5978      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5979    }
5980
5981    // C++0x [dcl.init.ref]p5:
5982    //    In the second case, if the reference is an rvalue reference and
5983    //    the second standard conversion sequence of the user-defined
5984    //    conversion sequence includes an lvalue-to-rvalue conversion, the
5985    //    program is ill-formed.
5986    if (ToType->isRValueReferenceType() &&
5987        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5988      Candidate.Viable = false;
5989      Candidate.FailureKind = ovl_fail_bad_final_conversion;
5990    }
5991    break;
5992
5993  case ImplicitConversionSequence::BadConversion:
5994    Candidate.Viable = false;
5995    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5996    break;
5997
5998  default:
5999    llvm_unreachable(
6000           "Can only end up with a standard conversion sequence or failure");
6001  }
6002}
6003
6004/// \brief Adds a conversion function template specialization
6005/// candidate to the overload set, using template argument deduction
6006/// to deduce the template arguments of the conversion function
6007/// template from the type that we are converting to (C++
6008/// [temp.deduct.conv]).
6009void
6010Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6011                                     DeclAccessPair FoundDecl,
6012                                     CXXRecordDecl *ActingDC,
6013                                     Expr *From, QualType ToType,
6014                                     OverloadCandidateSet &CandidateSet) {
6015  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6016         "Only conversion function templates permitted here");
6017
6018  if (!CandidateSet.isNewCandidate(FunctionTemplate))
6019    return;
6020
6021  TemplateDeductionInfo Info(CandidateSet.getLocation());
6022  CXXConversionDecl *Specialization = 0;
6023  if (TemplateDeductionResult Result
6024        = DeduceTemplateArguments(FunctionTemplate, ToType,
6025                                  Specialization, Info)) {
6026    OverloadCandidate &Candidate = CandidateSet.addCandidate();
6027    Candidate.FoundDecl = FoundDecl;
6028    Candidate.Function = FunctionTemplate->getTemplatedDecl();
6029    Candidate.Viable = false;
6030    Candidate.FailureKind = ovl_fail_bad_deduction;
6031    Candidate.IsSurrogate = false;
6032    Candidate.IgnoreObjectArgument = false;
6033    Candidate.ExplicitCallArguments = 1;
6034    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6035                                                          Info);
6036    return;
6037  }
6038
6039  // Add the conversion function template specialization produced by
6040  // template argument deduction as a candidate.
6041  assert(Specialization && "Missing function template specialization?");
6042  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6043                         CandidateSet);
6044}
6045
6046/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6047/// converts the given @c Object to a function pointer via the
6048/// conversion function @c Conversion, and then attempts to call it
6049/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6050/// the type of function that we'll eventually be calling.
6051void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6052                                 DeclAccessPair FoundDecl,
6053                                 CXXRecordDecl *ActingContext,
6054                                 const FunctionProtoType *Proto,
6055                                 Expr *Object,
6056                                 ArrayRef<Expr *> Args,
6057                                 OverloadCandidateSet& CandidateSet) {
6058  if (!CandidateSet.isNewCandidate(Conversion))
6059    return;
6060
6061  // Overload resolution is always an unevaluated context.
6062  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6063
6064  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6065  Candidate.FoundDecl = FoundDecl;
6066  Candidate.Function = 0;
6067  Candidate.Surrogate = Conversion;
6068  Candidate.Viable = true;
6069  Candidate.IsSurrogate = true;
6070  Candidate.IgnoreObjectArgument = false;
6071  Candidate.ExplicitCallArguments = Args.size();
6072
6073  // Determine the implicit conversion sequence for the implicit
6074  // object parameter.
6075  ImplicitConversionSequence ObjectInit
6076    = TryObjectArgumentInitialization(*this, Object->getType(),
6077                                      Object->Classify(Context),
6078                                      Conversion, ActingContext);
6079  if (ObjectInit.isBad()) {
6080    Candidate.Viable = false;
6081    Candidate.FailureKind = ovl_fail_bad_conversion;
6082    Candidate.Conversions[0] = ObjectInit;
6083    return;
6084  }
6085
6086  // The first conversion is actually a user-defined conversion whose
6087  // first conversion is ObjectInit's standard conversion (which is
6088  // effectively a reference binding). Record it as such.
6089  Candidate.Conversions[0].setUserDefined();
6090  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6091  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6092  Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6093  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6094  Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6095  Candidate.Conversions[0].UserDefined.After
6096    = Candidate.Conversions[0].UserDefined.Before;
6097  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6098
6099  // Find the
6100  unsigned NumArgsInProto = Proto->getNumArgs();
6101
6102  // (C++ 13.3.2p2): A candidate function having fewer than m
6103  // parameters is viable only if it has an ellipsis in its parameter
6104  // list (8.3.5).
6105  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
6106    Candidate.Viable = false;
6107    Candidate.FailureKind = ovl_fail_too_many_arguments;
6108    return;
6109  }
6110
6111  // Function types don't have any default arguments, so just check if
6112  // we have enough arguments.
6113  if (Args.size() < NumArgsInProto) {
6114    // Not enough arguments.
6115    Candidate.Viable = false;
6116    Candidate.FailureKind = ovl_fail_too_few_arguments;
6117    return;
6118  }
6119
6120  // Determine the implicit conversion sequences for each of the
6121  // arguments.
6122  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6123    if (ArgIdx < NumArgsInProto) {
6124      // (C++ 13.3.2p3): for F to be a viable function, there shall
6125      // exist for each argument an implicit conversion sequence
6126      // (13.3.3.1) that converts that argument to the corresponding
6127      // parameter of F.
6128      QualType ParamType = Proto->getArgType(ArgIdx);
6129      Candidate.Conversions[ArgIdx + 1]
6130        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6131                                /*SuppressUserConversions=*/false,
6132                                /*InOverloadResolution=*/false,
6133                                /*AllowObjCWritebackConversion=*/
6134                                  getLangOpts().ObjCAutoRefCount);
6135      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6136        Candidate.Viable = false;
6137        Candidate.FailureKind = ovl_fail_bad_conversion;
6138        break;
6139      }
6140    } else {
6141      // (C++ 13.3.2p2): For the purposes of overload resolution, any
6142      // argument for which there is no corresponding parameter is
6143      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6144      Candidate.Conversions[ArgIdx + 1].setEllipsis();
6145    }
6146  }
6147}
6148
6149/// \brief Add overload candidates for overloaded operators that are
6150/// member functions.
6151///
6152/// Add the overloaded operator candidates that are member functions
6153/// for the operator Op that was used in an operator expression such
6154/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6155/// CandidateSet will store the added overload candidates. (C++
6156/// [over.match.oper]).
6157void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6158                                       SourceLocation OpLoc,
6159                                       ArrayRef<Expr *> Args,
6160                                       OverloadCandidateSet& CandidateSet,
6161                                       SourceRange OpRange) {
6162  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6163
6164  // C++ [over.match.oper]p3:
6165  //   For a unary operator @ with an operand of a type whose
6166  //   cv-unqualified version is T1, and for a binary operator @ with
6167  //   a left operand of a type whose cv-unqualified version is T1 and
6168  //   a right operand of a type whose cv-unqualified version is T2,
6169  //   three sets of candidate functions, designated member
6170  //   candidates, non-member candidates and built-in candidates, are
6171  //   constructed as follows:
6172  QualType T1 = Args[0]->getType();
6173
6174  //     -- If T1 is a complete class type or a class currently being
6175  //        defined, the set of member candidates is the result of the
6176  //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6177  //        the set of member candidates is empty.
6178  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6179    // Complete the type if it can be completed.
6180    RequireCompleteType(OpLoc, T1, 0);
6181    // If the type is neither complete nor being defined, bail out now.
6182    if (!T1Rec->getDecl()->getDefinition())
6183      return;
6184
6185    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6186    LookupQualifiedName(Operators, T1Rec->getDecl());
6187    Operators.suppressDiagnostics();
6188
6189    for (LookupResult::iterator Oper = Operators.begin(),
6190                             OperEnd = Operators.end();
6191         Oper != OperEnd;
6192         ++Oper)
6193      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6194                         Args[0]->Classify(Context),
6195                         Args.slice(1),
6196                         CandidateSet,
6197                         /* SuppressUserConversions = */ false);
6198  }
6199}
6200
6201/// AddBuiltinCandidate - Add a candidate for a built-in
6202/// operator. ResultTy and ParamTys are the result and parameter types
6203/// of the built-in candidate, respectively. Args and NumArgs are the
6204/// arguments being passed to the candidate. IsAssignmentOperator
6205/// should be true when this built-in candidate is an assignment
6206/// operator. NumContextualBoolArguments is the number of arguments
6207/// (at the beginning of the argument list) that will be contextually
6208/// converted to bool.
6209void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6210                               ArrayRef<Expr *> Args,
6211                               OverloadCandidateSet& CandidateSet,
6212                               bool IsAssignmentOperator,
6213                               unsigned NumContextualBoolArguments) {
6214  // Overload resolution is always an unevaluated context.
6215  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6216
6217  // Add this candidate
6218  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6219  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
6220  Candidate.Function = 0;
6221  Candidate.IsSurrogate = false;
6222  Candidate.IgnoreObjectArgument = false;
6223  Candidate.BuiltinTypes.ResultTy = ResultTy;
6224  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6225    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6226
6227  // Determine the implicit conversion sequences for each of the
6228  // arguments.
6229  Candidate.Viable = true;
6230  Candidate.ExplicitCallArguments = Args.size();
6231  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6232    // C++ [over.match.oper]p4:
6233    //   For the built-in assignment operators, conversions of the
6234    //   left operand are restricted as follows:
6235    //     -- no temporaries are introduced to hold the left operand, and
6236    //     -- no user-defined conversions are applied to the left
6237    //        operand to achieve a type match with the left-most
6238    //        parameter of a built-in candidate.
6239    //
6240    // We block these conversions by turning off user-defined
6241    // conversions, since that is the only way that initialization of
6242    // a reference to a non-class type can occur from something that
6243    // is not of the same type.
6244    if (ArgIdx < NumContextualBoolArguments) {
6245      assert(ParamTys[ArgIdx] == Context.BoolTy &&
6246             "Contextual conversion to bool requires bool type");
6247      Candidate.Conversions[ArgIdx]
6248        = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6249    } else {
6250      Candidate.Conversions[ArgIdx]
6251        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6252                                ArgIdx == 0 && IsAssignmentOperator,
6253                                /*InOverloadResolution=*/false,
6254                                /*AllowObjCWritebackConversion=*/
6255                                  getLangOpts().ObjCAutoRefCount);
6256    }
6257    if (Candidate.Conversions[ArgIdx].isBad()) {
6258      Candidate.Viable = false;
6259      Candidate.FailureKind = ovl_fail_bad_conversion;
6260      break;
6261    }
6262  }
6263}
6264
6265/// BuiltinCandidateTypeSet - A set of types that will be used for the
6266/// candidate operator functions for built-in operators (C++
6267/// [over.built]). The types are separated into pointer types and
6268/// enumeration types.
6269class BuiltinCandidateTypeSet  {
6270  /// TypeSet - A set of types.
6271  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6272
6273  /// PointerTypes - The set of pointer types that will be used in the
6274  /// built-in candidates.
6275  TypeSet PointerTypes;
6276
6277  /// MemberPointerTypes - The set of member pointer types that will be
6278  /// used in the built-in candidates.
6279  TypeSet MemberPointerTypes;
6280
6281  /// EnumerationTypes - The set of enumeration types that will be
6282  /// used in the built-in candidates.
6283  TypeSet EnumerationTypes;
6284
6285  /// \brief The set of vector types that will be used in the built-in
6286  /// candidates.
6287  TypeSet VectorTypes;
6288
6289  /// \brief A flag indicating non-record types are viable candidates
6290  bool HasNonRecordTypes;
6291
6292  /// \brief A flag indicating whether either arithmetic or enumeration types
6293  /// were present in the candidate set.
6294  bool HasArithmeticOrEnumeralTypes;
6295
6296  /// \brief A flag indicating whether the nullptr type was present in the
6297  /// candidate set.
6298  bool HasNullPtrType;
6299
6300  /// Sema - The semantic analysis instance where we are building the
6301  /// candidate type set.
6302  Sema &SemaRef;
6303
6304  /// Context - The AST context in which we will build the type sets.
6305  ASTContext &Context;
6306
6307  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6308                                               const Qualifiers &VisibleQuals);
6309  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6310
6311public:
6312  /// iterator - Iterates through the types that are part of the set.
6313  typedef TypeSet::iterator iterator;
6314
6315  BuiltinCandidateTypeSet(Sema &SemaRef)
6316    : HasNonRecordTypes(false),
6317      HasArithmeticOrEnumeralTypes(false),
6318      HasNullPtrType(false),
6319      SemaRef(SemaRef),
6320      Context(SemaRef.Context) { }
6321
6322  void AddTypesConvertedFrom(QualType Ty,
6323                             SourceLocation Loc,
6324                             bool AllowUserConversions,
6325                             bool AllowExplicitConversions,
6326                             const Qualifiers &VisibleTypeConversionsQuals);
6327
6328  /// pointer_begin - First pointer type found;
6329  iterator pointer_begin() { return PointerTypes.begin(); }
6330
6331  /// pointer_end - Past the last pointer type found;
6332  iterator pointer_end() { return PointerTypes.end(); }
6333
6334  /// member_pointer_begin - First member pointer type found;
6335  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6336
6337  /// member_pointer_end - Past the last member pointer type found;
6338  iterator member_pointer_end() { return MemberPointerTypes.end(); }
6339
6340  /// enumeration_begin - First enumeration type found;
6341  iterator enumeration_begin() { return EnumerationTypes.begin(); }
6342
6343  /// enumeration_end - Past the last enumeration type found;
6344  iterator enumeration_end() { return EnumerationTypes.end(); }
6345
6346  iterator vector_begin() { return VectorTypes.begin(); }
6347  iterator vector_end() { return VectorTypes.end(); }
6348
6349  bool hasNonRecordTypes() { return HasNonRecordTypes; }
6350  bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6351  bool hasNullPtrType() const { return HasNullPtrType; }
6352};
6353
6354/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6355/// the set of pointer types along with any more-qualified variants of
6356/// that type. For example, if @p Ty is "int const *", this routine
6357/// will add "int const *", "int const volatile *", "int const
6358/// restrict *", and "int const volatile restrict *" to the set of
6359/// pointer types. Returns true if the add of @p Ty itself succeeded,
6360/// false otherwise.
6361///
6362/// FIXME: what to do about extended qualifiers?
6363bool
6364BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6365                                             const Qualifiers &VisibleQuals) {
6366
6367  // Insert this type.
6368  if (!PointerTypes.insert(Ty))
6369    return false;
6370
6371  QualType PointeeTy;
6372  const PointerType *PointerTy = Ty->getAs<PointerType>();
6373  bool buildObjCPtr = false;
6374  if (!PointerTy) {
6375    const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6376    PointeeTy = PTy->getPointeeType();
6377    buildObjCPtr = true;
6378  } else {
6379    PointeeTy = PointerTy->getPointeeType();
6380  }
6381
6382  // Don't add qualified variants of arrays. For one, they're not allowed
6383  // (the qualifier would sink to the element type), and for another, the
6384  // only overload situation where it matters is subscript or pointer +- int,
6385  // and those shouldn't have qualifier variants anyway.
6386  if (PointeeTy->isArrayType())
6387    return true;
6388
6389  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6390  bool hasVolatile = VisibleQuals.hasVolatile();
6391  bool hasRestrict = VisibleQuals.hasRestrict();
6392
6393  // Iterate through all strict supersets of BaseCVR.
6394  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6395    if ((CVR | BaseCVR) != CVR) continue;
6396    // Skip over volatile if no volatile found anywhere in the types.
6397    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6398
6399    // Skip over restrict if no restrict found anywhere in the types, or if
6400    // the type cannot be restrict-qualified.
6401    if ((CVR & Qualifiers::Restrict) &&
6402        (!hasRestrict ||
6403         (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6404      continue;
6405
6406    // Build qualified pointee type.
6407    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6408
6409    // Build qualified pointer type.
6410    QualType QPointerTy;
6411    if (!buildObjCPtr)
6412      QPointerTy = Context.getPointerType(QPointeeTy);
6413    else
6414      QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6415
6416    // Insert qualified pointer type.
6417    PointerTypes.insert(QPointerTy);
6418  }
6419
6420  return true;
6421}
6422
6423/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6424/// to the set of pointer types along with any more-qualified variants of
6425/// that type. For example, if @p Ty is "int const *", this routine
6426/// will add "int const *", "int const volatile *", "int const
6427/// restrict *", and "int const volatile restrict *" to the set of
6428/// pointer types. Returns true if the add of @p Ty itself succeeded,
6429/// false otherwise.
6430///
6431/// FIXME: what to do about extended qualifiers?
6432bool
6433BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6434    QualType Ty) {
6435  // Insert this type.
6436  if (!MemberPointerTypes.insert(Ty))
6437    return false;
6438
6439  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6440  assert(PointerTy && "type was not a member pointer type!");
6441
6442  QualType PointeeTy = PointerTy->getPointeeType();
6443  // Don't add qualified variants of arrays. For one, they're not allowed
6444  // (the qualifier would sink to the element type), and for another, the
6445  // only overload situation where it matters is subscript or pointer +- int,
6446  // and those shouldn't have qualifier variants anyway.
6447  if (PointeeTy->isArrayType())
6448    return true;
6449  const Type *ClassTy = PointerTy->getClass();
6450
6451  // Iterate through all strict supersets of the pointee type's CVR
6452  // qualifiers.
6453  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6454  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6455    if ((CVR | BaseCVR) != CVR) continue;
6456
6457    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6458    MemberPointerTypes.insert(
6459      Context.getMemberPointerType(QPointeeTy, ClassTy));
6460  }
6461
6462  return true;
6463}
6464
6465/// AddTypesConvertedFrom - Add each of the types to which the type @p
6466/// Ty can be implicit converted to the given set of @p Types. We're
6467/// primarily interested in pointer types and enumeration types. We also
6468/// take member pointer types, for the conditional operator.
6469/// AllowUserConversions is true if we should look at the conversion
6470/// functions of a class type, and AllowExplicitConversions if we
6471/// should also include the explicit conversion functions of a class
6472/// type.
6473void
6474BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6475                                               SourceLocation Loc,
6476                                               bool AllowUserConversions,
6477                                               bool AllowExplicitConversions,
6478                                               const Qualifiers &VisibleQuals) {
6479  // Only deal with canonical types.
6480  Ty = Context.getCanonicalType(Ty);
6481
6482  // Look through reference types; they aren't part of the type of an
6483  // expression for the purposes of conversions.
6484  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6485    Ty = RefTy->getPointeeType();
6486
6487  // If we're dealing with an array type, decay to the pointer.
6488  if (Ty->isArrayType())
6489    Ty = SemaRef.Context.getArrayDecayedType(Ty);
6490
6491  // Otherwise, we don't care about qualifiers on the type.
6492  Ty = Ty.getLocalUnqualifiedType();
6493
6494  // Flag if we ever add a non-record type.
6495  const RecordType *TyRec = Ty->getAs<RecordType>();
6496  HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6497
6498  // Flag if we encounter an arithmetic type.
6499  HasArithmeticOrEnumeralTypes =
6500    HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6501
6502  if (Ty->isObjCIdType() || Ty->isObjCClassType())
6503    PointerTypes.insert(Ty);
6504  else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6505    // Insert our type, and its more-qualified variants, into the set
6506    // of types.
6507    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6508      return;
6509  } else if (Ty->isMemberPointerType()) {
6510    // Member pointers are far easier, since the pointee can't be converted.
6511    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6512      return;
6513  } else if (Ty->isEnumeralType()) {
6514    HasArithmeticOrEnumeralTypes = true;
6515    EnumerationTypes.insert(Ty);
6516  } else if (Ty->isVectorType()) {
6517    // We treat vector types as arithmetic types in many contexts as an
6518    // extension.
6519    HasArithmeticOrEnumeralTypes = true;
6520    VectorTypes.insert(Ty);
6521  } else if (Ty->isNullPtrType()) {
6522    HasNullPtrType = true;
6523  } else if (AllowUserConversions && TyRec) {
6524    // No conversion functions in incomplete types.
6525    if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6526      return;
6527
6528    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6529    std::pair<CXXRecordDecl::conversion_iterator,
6530              CXXRecordDecl::conversion_iterator>
6531      Conversions = ClassDecl->getVisibleConversionFunctions();
6532    for (CXXRecordDecl::conversion_iterator
6533           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6534      NamedDecl *D = I.getDecl();
6535      if (isa<UsingShadowDecl>(D))
6536        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6537
6538      // Skip conversion function templates; they don't tell us anything
6539      // about which builtin types we can convert to.
6540      if (isa<FunctionTemplateDecl>(D))
6541        continue;
6542
6543      CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6544      if (AllowExplicitConversions || !Conv->isExplicit()) {
6545        AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6546                              VisibleQuals);
6547      }
6548    }
6549  }
6550}
6551
6552/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6553/// the volatile- and non-volatile-qualified assignment operators for the
6554/// given type to the candidate set.
6555static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6556                                                   QualType T,
6557                                                   ArrayRef<Expr *> Args,
6558                                    OverloadCandidateSet &CandidateSet) {
6559  QualType ParamTypes[2];
6560
6561  // T& operator=(T&, T)
6562  ParamTypes[0] = S.Context.getLValueReferenceType(T);
6563  ParamTypes[1] = T;
6564  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6565                        /*IsAssignmentOperator=*/true);
6566
6567  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6568    // volatile T& operator=(volatile T&, T)
6569    ParamTypes[0]
6570      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6571    ParamTypes[1] = T;
6572    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6573                          /*IsAssignmentOperator=*/true);
6574  }
6575}
6576
6577/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6578/// if any, found in visible type conversion functions found in ArgExpr's type.
6579static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6580    Qualifiers VRQuals;
6581    const RecordType *TyRec;
6582    if (const MemberPointerType *RHSMPType =
6583        ArgExpr->getType()->getAs<MemberPointerType>())
6584      TyRec = RHSMPType->getClass()->getAs<RecordType>();
6585    else
6586      TyRec = ArgExpr->getType()->getAs<RecordType>();
6587    if (!TyRec) {
6588      // Just to be safe, assume the worst case.
6589      VRQuals.addVolatile();
6590      VRQuals.addRestrict();
6591      return VRQuals;
6592    }
6593
6594    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6595    if (!ClassDecl->hasDefinition())
6596      return VRQuals;
6597
6598    std::pair<CXXRecordDecl::conversion_iterator,
6599              CXXRecordDecl::conversion_iterator>
6600      Conversions = ClassDecl->getVisibleConversionFunctions();
6601
6602    for (CXXRecordDecl::conversion_iterator
6603           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6604      NamedDecl *D = I.getDecl();
6605      if (isa<UsingShadowDecl>(D))
6606        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6607      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6608        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6609        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6610          CanTy = ResTypeRef->getPointeeType();
6611        // Need to go down the pointer/mempointer chain and add qualifiers
6612        // as see them.
6613        bool done = false;
6614        while (!done) {
6615          if (CanTy.isRestrictQualified())
6616            VRQuals.addRestrict();
6617          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6618            CanTy = ResTypePtr->getPointeeType();
6619          else if (const MemberPointerType *ResTypeMPtr =
6620                CanTy->getAs<MemberPointerType>())
6621            CanTy = ResTypeMPtr->getPointeeType();
6622          else
6623            done = true;
6624          if (CanTy.isVolatileQualified())
6625            VRQuals.addVolatile();
6626          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6627            return VRQuals;
6628        }
6629      }
6630    }
6631    return VRQuals;
6632}
6633
6634namespace {
6635
6636/// \brief Helper class to manage the addition of builtin operator overload
6637/// candidates. It provides shared state and utility methods used throughout
6638/// the process, as well as a helper method to add each group of builtin
6639/// operator overloads from the standard to a candidate set.
6640class BuiltinOperatorOverloadBuilder {
6641  // Common instance state available to all overload candidate addition methods.
6642  Sema &S;
6643  ArrayRef<Expr *> Args;
6644  Qualifiers VisibleTypeConversionsQuals;
6645  bool HasArithmeticOrEnumeralCandidateType;
6646  SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6647  OverloadCandidateSet &CandidateSet;
6648
6649  // Define some constants used to index and iterate over the arithemetic types
6650  // provided via the getArithmeticType() method below.
6651  // The "promoted arithmetic types" are the arithmetic
6652  // types are that preserved by promotion (C++ [over.built]p2).
6653  static const unsigned FirstIntegralType = 3;
6654  static const unsigned LastIntegralType = 20;
6655  static const unsigned FirstPromotedIntegralType = 3,
6656                        LastPromotedIntegralType = 11;
6657  static const unsigned FirstPromotedArithmeticType = 0,
6658                        LastPromotedArithmeticType = 11;
6659  static const unsigned NumArithmeticTypes = 20;
6660
6661  /// \brief Get the canonical type for a given arithmetic type index.
6662  CanQualType getArithmeticType(unsigned index) {
6663    assert(index < NumArithmeticTypes);
6664    static CanQualType ASTContext::* const
6665      ArithmeticTypes[NumArithmeticTypes] = {
6666      // Start of promoted types.
6667      &ASTContext::FloatTy,
6668      &ASTContext::DoubleTy,
6669      &ASTContext::LongDoubleTy,
6670
6671      // Start of integral types.
6672      &ASTContext::IntTy,
6673      &ASTContext::LongTy,
6674      &ASTContext::LongLongTy,
6675      &ASTContext::Int128Ty,
6676      &ASTContext::UnsignedIntTy,
6677      &ASTContext::UnsignedLongTy,
6678      &ASTContext::UnsignedLongLongTy,
6679      &ASTContext::UnsignedInt128Ty,
6680      // End of promoted types.
6681
6682      &ASTContext::BoolTy,
6683      &ASTContext::CharTy,
6684      &ASTContext::WCharTy,
6685      &ASTContext::Char16Ty,
6686      &ASTContext::Char32Ty,
6687      &ASTContext::SignedCharTy,
6688      &ASTContext::ShortTy,
6689      &ASTContext::UnsignedCharTy,
6690      &ASTContext::UnsignedShortTy,
6691      // End of integral types.
6692      // FIXME: What about complex? What about half?
6693    };
6694    return S.Context.*ArithmeticTypes[index];
6695  }
6696
6697  /// \brief Gets the canonical type resulting from the usual arithemetic
6698  /// converions for the given arithmetic types.
6699  CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6700    // Accelerator table for performing the usual arithmetic conversions.
6701    // The rules are basically:
6702    //   - if either is floating-point, use the wider floating-point
6703    //   - if same signedness, use the higher rank
6704    //   - if same size, use unsigned of the higher rank
6705    //   - use the larger type
6706    // These rules, together with the axiom that higher ranks are
6707    // never smaller, are sufficient to precompute all of these results
6708    // *except* when dealing with signed types of higher rank.
6709    // (we could precompute SLL x UI for all known platforms, but it's
6710    // better not to make any assumptions).
6711    // We assume that int128 has a higher rank than long long on all platforms.
6712    enum PromotedType {
6713            Dep=-1,
6714            Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6715    };
6716    static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6717                                        [LastPromotedArithmeticType] = {
6718/* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6719/* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6720/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6721/*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6722/*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6723/* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6724/*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6725/*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6726/*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6727/* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6728/*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6729    };
6730
6731    assert(L < LastPromotedArithmeticType);
6732    assert(R < LastPromotedArithmeticType);
6733    int Idx = ConversionsTable[L][R];
6734
6735    // Fast path: the table gives us a concrete answer.
6736    if (Idx != Dep) return getArithmeticType(Idx);
6737
6738    // Slow path: we need to compare widths.
6739    // An invariant is that the signed type has higher rank.
6740    CanQualType LT = getArithmeticType(L),
6741                RT = getArithmeticType(R);
6742    unsigned LW = S.Context.getIntWidth(LT),
6743             RW = S.Context.getIntWidth(RT);
6744
6745    // If they're different widths, use the signed type.
6746    if (LW > RW) return LT;
6747    else if (LW < RW) return RT;
6748
6749    // Otherwise, use the unsigned type of the signed type's rank.
6750    if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6751    assert(L == SLL || R == SLL);
6752    return S.Context.UnsignedLongLongTy;
6753  }
6754
6755  /// \brief Helper method to factor out the common pattern of adding overloads
6756  /// for '++' and '--' builtin operators.
6757  void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6758                                           bool HasVolatile,
6759                                           bool HasRestrict) {
6760    QualType ParamTypes[2] = {
6761      S.Context.getLValueReferenceType(CandidateTy),
6762      S.Context.IntTy
6763    };
6764
6765    // Non-volatile version.
6766    if (Args.size() == 1)
6767      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6768    else
6769      S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6770
6771    // Use a heuristic to reduce number of builtin candidates in the set:
6772    // add volatile version only if there are conversions to a volatile type.
6773    if (HasVolatile) {
6774      ParamTypes[0] =
6775        S.Context.getLValueReferenceType(
6776          S.Context.getVolatileType(CandidateTy));
6777      if (Args.size() == 1)
6778        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6779      else
6780        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6781    }
6782
6783    // Add restrict version only if there are conversions to a restrict type
6784    // and our candidate type is a non-restrict-qualified pointer.
6785    if (HasRestrict && CandidateTy->isAnyPointerType() &&
6786        !CandidateTy.isRestrictQualified()) {
6787      ParamTypes[0]
6788        = S.Context.getLValueReferenceType(
6789            S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6790      if (Args.size() == 1)
6791        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6792      else
6793        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6794
6795      if (HasVolatile) {
6796        ParamTypes[0]
6797          = S.Context.getLValueReferenceType(
6798              S.Context.getCVRQualifiedType(CandidateTy,
6799                                            (Qualifiers::Volatile |
6800                                             Qualifiers::Restrict)));
6801        if (Args.size() == 1)
6802          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
6803        else
6804          S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
6805      }
6806    }
6807
6808  }
6809
6810public:
6811  BuiltinOperatorOverloadBuilder(
6812    Sema &S, ArrayRef<Expr *> Args,
6813    Qualifiers VisibleTypeConversionsQuals,
6814    bool HasArithmeticOrEnumeralCandidateType,
6815    SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6816    OverloadCandidateSet &CandidateSet)
6817    : S(S), Args(Args),
6818      VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6819      HasArithmeticOrEnumeralCandidateType(
6820        HasArithmeticOrEnumeralCandidateType),
6821      CandidateTypes(CandidateTypes),
6822      CandidateSet(CandidateSet) {
6823    // Validate some of our static helper constants in debug builds.
6824    assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6825           "Invalid first promoted integral type");
6826    assert(getArithmeticType(LastPromotedIntegralType - 1)
6827             == S.Context.UnsignedInt128Ty &&
6828           "Invalid last promoted integral type");
6829    assert(getArithmeticType(FirstPromotedArithmeticType)
6830             == S.Context.FloatTy &&
6831           "Invalid first promoted arithmetic type");
6832    assert(getArithmeticType(LastPromotedArithmeticType - 1)
6833             == S.Context.UnsignedInt128Ty &&
6834           "Invalid last promoted arithmetic type");
6835  }
6836
6837  // C++ [over.built]p3:
6838  //
6839  //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6840  //   is either volatile or empty, there exist candidate operator
6841  //   functions of the form
6842  //
6843  //       VQ T&      operator++(VQ T&);
6844  //       T          operator++(VQ T&, int);
6845  //
6846  // C++ [over.built]p4:
6847  //
6848  //   For every pair (T, VQ), where T is an arithmetic type other
6849  //   than bool, and VQ is either volatile or empty, there exist
6850  //   candidate operator functions of the form
6851  //
6852  //       VQ T&      operator--(VQ T&);
6853  //       T          operator--(VQ T&, int);
6854  void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6855    if (!HasArithmeticOrEnumeralCandidateType)
6856      return;
6857
6858    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6859         Arith < NumArithmeticTypes; ++Arith) {
6860      addPlusPlusMinusMinusStyleOverloads(
6861        getArithmeticType(Arith),
6862        VisibleTypeConversionsQuals.hasVolatile(),
6863        VisibleTypeConversionsQuals.hasRestrict());
6864    }
6865  }
6866
6867  // C++ [over.built]p5:
6868  //
6869  //   For every pair (T, VQ), where T is a cv-qualified or
6870  //   cv-unqualified object type, and VQ is either volatile or
6871  //   empty, there exist candidate operator functions of the form
6872  //
6873  //       T*VQ&      operator++(T*VQ&);
6874  //       T*VQ&      operator--(T*VQ&);
6875  //       T*         operator++(T*VQ&, int);
6876  //       T*         operator--(T*VQ&, int);
6877  void addPlusPlusMinusMinusPointerOverloads() {
6878    for (BuiltinCandidateTypeSet::iterator
6879              Ptr = CandidateTypes[0].pointer_begin(),
6880           PtrEnd = CandidateTypes[0].pointer_end();
6881         Ptr != PtrEnd; ++Ptr) {
6882      // Skip pointer types that aren't pointers to object types.
6883      if (!(*Ptr)->getPointeeType()->isObjectType())
6884        continue;
6885
6886      addPlusPlusMinusMinusStyleOverloads(*Ptr,
6887        (!(*Ptr).isVolatileQualified() &&
6888         VisibleTypeConversionsQuals.hasVolatile()),
6889        (!(*Ptr).isRestrictQualified() &&
6890         VisibleTypeConversionsQuals.hasRestrict()));
6891    }
6892  }
6893
6894  // C++ [over.built]p6:
6895  //   For every cv-qualified or cv-unqualified object type T, there
6896  //   exist candidate operator functions of the form
6897  //
6898  //       T&         operator*(T*);
6899  //
6900  // C++ [over.built]p7:
6901  //   For every function type T that does not have cv-qualifiers or a
6902  //   ref-qualifier, there exist candidate operator functions of the form
6903  //       T&         operator*(T*);
6904  void addUnaryStarPointerOverloads() {
6905    for (BuiltinCandidateTypeSet::iterator
6906              Ptr = CandidateTypes[0].pointer_begin(),
6907           PtrEnd = CandidateTypes[0].pointer_end();
6908         Ptr != PtrEnd; ++Ptr) {
6909      QualType ParamTy = *Ptr;
6910      QualType PointeeTy = ParamTy->getPointeeType();
6911      if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6912        continue;
6913
6914      if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6915        if (Proto->getTypeQuals() || Proto->getRefQualifier())
6916          continue;
6917
6918      S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6919                            &ParamTy, Args, CandidateSet);
6920    }
6921  }
6922
6923  // C++ [over.built]p9:
6924  //  For every promoted arithmetic type T, there exist candidate
6925  //  operator functions of the form
6926  //
6927  //       T         operator+(T);
6928  //       T         operator-(T);
6929  void addUnaryPlusOrMinusArithmeticOverloads() {
6930    if (!HasArithmeticOrEnumeralCandidateType)
6931      return;
6932
6933    for (unsigned Arith = FirstPromotedArithmeticType;
6934         Arith < LastPromotedArithmeticType; ++Arith) {
6935      QualType ArithTy = getArithmeticType(Arith);
6936      S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
6937    }
6938
6939    // Extension: We also add these operators for vector types.
6940    for (BuiltinCandidateTypeSet::iterator
6941              Vec = CandidateTypes[0].vector_begin(),
6942           VecEnd = CandidateTypes[0].vector_end();
6943         Vec != VecEnd; ++Vec) {
6944      QualType VecTy = *Vec;
6945      S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
6946    }
6947  }
6948
6949  // C++ [over.built]p8:
6950  //   For every type T, there exist candidate operator functions of
6951  //   the form
6952  //
6953  //       T*         operator+(T*);
6954  void addUnaryPlusPointerOverloads() {
6955    for (BuiltinCandidateTypeSet::iterator
6956              Ptr = CandidateTypes[0].pointer_begin(),
6957           PtrEnd = CandidateTypes[0].pointer_end();
6958         Ptr != PtrEnd; ++Ptr) {
6959      QualType ParamTy = *Ptr;
6960      S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
6961    }
6962  }
6963
6964  // C++ [over.built]p10:
6965  //   For every promoted integral type T, there exist candidate
6966  //   operator functions of the form
6967  //
6968  //        T         operator~(T);
6969  void addUnaryTildePromotedIntegralOverloads() {
6970    if (!HasArithmeticOrEnumeralCandidateType)
6971      return;
6972
6973    for (unsigned Int = FirstPromotedIntegralType;
6974         Int < LastPromotedIntegralType; ++Int) {
6975      QualType IntTy = getArithmeticType(Int);
6976      S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
6977    }
6978
6979    // Extension: We also add this operator for vector types.
6980    for (BuiltinCandidateTypeSet::iterator
6981              Vec = CandidateTypes[0].vector_begin(),
6982           VecEnd = CandidateTypes[0].vector_end();
6983         Vec != VecEnd; ++Vec) {
6984      QualType VecTy = *Vec;
6985      S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
6986    }
6987  }
6988
6989  // C++ [over.match.oper]p16:
6990  //   For every pointer to member type T, there exist candidate operator
6991  //   functions of the form
6992  //
6993  //        bool operator==(T,T);
6994  //        bool operator!=(T,T);
6995  void addEqualEqualOrNotEqualMemberPointerOverloads() {
6996    /// Set of (canonical) types that we've already handled.
6997    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6998
6999    for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7000      for (BuiltinCandidateTypeSet::iterator
7001                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7002             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7003           MemPtr != MemPtrEnd;
7004           ++MemPtr) {
7005        // Don't add the same builtin candidate twice.
7006        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7007          continue;
7008
7009        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7010        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7011      }
7012    }
7013  }
7014
7015  // C++ [over.built]p15:
7016  //
7017  //   For every T, where T is an enumeration type, a pointer type, or
7018  //   std::nullptr_t, there exist candidate operator functions of the form
7019  //
7020  //        bool       operator<(T, T);
7021  //        bool       operator>(T, T);
7022  //        bool       operator<=(T, T);
7023  //        bool       operator>=(T, T);
7024  //        bool       operator==(T, T);
7025  //        bool       operator!=(T, T);
7026  void addRelationalPointerOrEnumeralOverloads() {
7027    // C++ [over.match.oper]p3:
7028    //   [...]the built-in candidates include all of the candidate operator
7029    //   functions defined in 13.6 that, compared to the given operator, [...]
7030    //   do not have the same parameter-type-list as any non-template non-member
7031    //   candidate.
7032    //
7033    // Note that in practice, this only affects enumeration types because there
7034    // aren't any built-in candidates of record type, and a user-defined operator
7035    // must have an operand of record or enumeration type. Also, the only other
7036    // overloaded operator with enumeration arguments, operator=,
7037    // cannot be overloaded for enumeration types, so this is the only place
7038    // where we must suppress candidates like this.
7039    llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7040      UserDefinedBinaryOperators;
7041
7042    for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7043      if (CandidateTypes[ArgIdx].enumeration_begin() !=
7044          CandidateTypes[ArgIdx].enumeration_end()) {
7045        for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7046                                         CEnd = CandidateSet.end();
7047             C != CEnd; ++C) {
7048          if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7049            continue;
7050
7051          if (C->Function->isFunctionTemplateSpecialization())
7052            continue;
7053
7054          QualType FirstParamType =
7055            C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7056          QualType SecondParamType =
7057            C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7058
7059          // Skip if either parameter isn't of enumeral type.
7060          if (!FirstParamType->isEnumeralType() ||
7061              !SecondParamType->isEnumeralType())
7062            continue;
7063
7064          // Add this operator to the set of known user-defined operators.
7065          UserDefinedBinaryOperators.insert(
7066            std::make_pair(S.Context.getCanonicalType(FirstParamType),
7067                           S.Context.getCanonicalType(SecondParamType)));
7068        }
7069      }
7070    }
7071
7072    /// Set of (canonical) types that we've already handled.
7073    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7074
7075    for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7076      for (BuiltinCandidateTypeSet::iterator
7077                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7078             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7079           Ptr != PtrEnd; ++Ptr) {
7080        // Don't add the same builtin candidate twice.
7081        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7082          continue;
7083
7084        QualType ParamTypes[2] = { *Ptr, *Ptr };
7085        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7086      }
7087      for (BuiltinCandidateTypeSet::iterator
7088                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7089             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7090           Enum != EnumEnd; ++Enum) {
7091        CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7092
7093        // Don't add the same builtin candidate twice, or if a user defined
7094        // candidate exists.
7095        if (!AddedTypes.insert(CanonType) ||
7096            UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7097                                                            CanonType)))
7098          continue;
7099
7100        QualType ParamTypes[2] = { *Enum, *Enum };
7101        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7102      }
7103
7104      if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7105        CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7106        if (AddedTypes.insert(NullPtrTy) &&
7107            !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7108                                                             NullPtrTy))) {
7109          QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7110          S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7111                                CandidateSet);
7112        }
7113      }
7114    }
7115  }
7116
7117  // C++ [over.built]p13:
7118  //
7119  //   For every cv-qualified or cv-unqualified object type T
7120  //   there exist candidate operator functions of the form
7121  //
7122  //      T*         operator+(T*, ptrdiff_t);
7123  //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7124  //      T*         operator-(T*, ptrdiff_t);
7125  //      T*         operator+(ptrdiff_t, T*);
7126  //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7127  //
7128  // C++ [over.built]p14:
7129  //
7130  //   For every T, where T is a pointer to object type, there
7131  //   exist candidate operator functions of the form
7132  //
7133  //      ptrdiff_t  operator-(T, T);
7134  void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7135    /// Set of (canonical) types that we've already handled.
7136    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7137
7138    for (int Arg = 0; Arg < 2; ++Arg) {
7139      QualType AsymetricParamTypes[2] = {
7140        S.Context.getPointerDiffType(),
7141        S.Context.getPointerDiffType(),
7142      };
7143      for (BuiltinCandidateTypeSet::iterator
7144                Ptr = CandidateTypes[Arg].pointer_begin(),
7145             PtrEnd = CandidateTypes[Arg].pointer_end();
7146           Ptr != PtrEnd; ++Ptr) {
7147        QualType PointeeTy = (*Ptr)->getPointeeType();
7148        if (!PointeeTy->isObjectType())
7149          continue;
7150
7151        AsymetricParamTypes[Arg] = *Ptr;
7152        if (Arg == 0 || Op == OO_Plus) {
7153          // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7154          // T* operator+(ptrdiff_t, T*);
7155          S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7156        }
7157        if (Op == OO_Minus) {
7158          // ptrdiff_t operator-(T, T);
7159          if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7160            continue;
7161
7162          QualType ParamTypes[2] = { *Ptr, *Ptr };
7163          S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7164                                Args, CandidateSet);
7165        }
7166      }
7167    }
7168  }
7169
7170  // C++ [over.built]p12:
7171  //
7172  //   For every pair of promoted arithmetic types L and R, there
7173  //   exist candidate operator functions of the form
7174  //
7175  //        LR         operator*(L, R);
7176  //        LR         operator/(L, R);
7177  //        LR         operator+(L, R);
7178  //        LR         operator-(L, R);
7179  //        bool       operator<(L, R);
7180  //        bool       operator>(L, R);
7181  //        bool       operator<=(L, R);
7182  //        bool       operator>=(L, R);
7183  //        bool       operator==(L, R);
7184  //        bool       operator!=(L, R);
7185  //
7186  //   where LR is the result of the usual arithmetic conversions
7187  //   between types L and R.
7188  //
7189  // C++ [over.built]p24:
7190  //
7191  //   For every pair of promoted arithmetic types L and R, there exist
7192  //   candidate operator functions of the form
7193  //
7194  //        LR       operator?(bool, L, R);
7195  //
7196  //   where LR is the result of the usual arithmetic conversions
7197  //   between types L and R.
7198  // Our candidates ignore the first parameter.
7199  void addGenericBinaryArithmeticOverloads(bool isComparison) {
7200    if (!HasArithmeticOrEnumeralCandidateType)
7201      return;
7202
7203    for (unsigned Left = FirstPromotedArithmeticType;
7204         Left < LastPromotedArithmeticType; ++Left) {
7205      for (unsigned Right = FirstPromotedArithmeticType;
7206           Right < LastPromotedArithmeticType; ++Right) {
7207        QualType LandR[2] = { getArithmeticType(Left),
7208                              getArithmeticType(Right) };
7209        QualType Result =
7210          isComparison ? S.Context.BoolTy
7211                       : getUsualArithmeticConversions(Left, Right);
7212        S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7213      }
7214    }
7215
7216    // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7217    // conditional operator for vector types.
7218    for (BuiltinCandidateTypeSet::iterator
7219              Vec1 = CandidateTypes[0].vector_begin(),
7220           Vec1End = CandidateTypes[0].vector_end();
7221         Vec1 != Vec1End; ++Vec1) {
7222      for (BuiltinCandidateTypeSet::iterator
7223                Vec2 = CandidateTypes[1].vector_begin(),
7224             Vec2End = CandidateTypes[1].vector_end();
7225           Vec2 != Vec2End; ++Vec2) {
7226        QualType LandR[2] = { *Vec1, *Vec2 };
7227        QualType Result = S.Context.BoolTy;
7228        if (!isComparison) {
7229          if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7230            Result = *Vec1;
7231          else
7232            Result = *Vec2;
7233        }
7234
7235        S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7236      }
7237    }
7238  }
7239
7240  // C++ [over.built]p17:
7241  //
7242  //   For every pair of promoted integral types L and R, there
7243  //   exist candidate operator functions of the form
7244  //
7245  //      LR         operator%(L, R);
7246  //      LR         operator&(L, R);
7247  //      LR         operator^(L, R);
7248  //      LR         operator|(L, R);
7249  //      L          operator<<(L, R);
7250  //      L          operator>>(L, R);
7251  //
7252  //   where LR is the result of the usual arithmetic conversions
7253  //   between types L and R.
7254  void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7255    if (!HasArithmeticOrEnumeralCandidateType)
7256      return;
7257
7258    for (unsigned Left = FirstPromotedIntegralType;
7259         Left < LastPromotedIntegralType; ++Left) {
7260      for (unsigned Right = FirstPromotedIntegralType;
7261           Right < LastPromotedIntegralType; ++Right) {
7262        QualType LandR[2] = { getArithmeticType(Left),
7263                              getArithmeticType(Right) };
7264        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7265            ? LandR[0]
7266            : getUsualArithmeticConversions(Left, Right);
7267        S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7268      }
7269    }
7270  }
7271
7272  // C++ [over.built]p20:
7273  //
7274  //   For every pair (T, VQ), where T is an enumeration or
7275  //   pointer to member type and VQ is either volatile or
7276  //   empty, there exist candidate operator functions of the form
7277  //
7278  //        VQ T&      operator=(VQ T&, T);
7279  void addAssignmentMemberPointerOrEnumeralOverloads() {
7280    /// Set of (canonical) types that we've already handled.
7281    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7282
7283    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7284      for (BuiltinCandidateTypeSet::iterator
7285                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7286             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7287           Enum != EnumEnd; ++Enum) {
7288        if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7289          continue;
7290
7291        AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7292      }
7293
7294      for (BuiltinCandidateTypeSet::iterator
7295                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7296             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7297           MemPtr != MemPtrEnd; ++MemPtr) {
7298        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7299          continue;
7300
7301        AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7302      }
7303    }
7304  }
7305
7306  // C++ [over.built]p19:
7307  //
7308  //   For every pair (T, VQ), where T is any type and VQ is either
7309  //   volatile or empty, there exist candidate operator functions
7310  //   of the form
7311  //
7312  //        T*VQ&      operator=(T*VQ&, T*);
7313  //
7314  // C++ [over.built]p21:
7315  //
7316  //   For every pair (T, VQ), where T is a cv-qualified or
7317  //   cv-unqualified object type and VQ is either volatile or
7318  //   empty, there exist candidate operator functions of the form
7319  //
7320  //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7321  //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7322  void addAssignmentPointerOverloads(bool isEqualOp) {
7323    /// Set of (canonical) types that we've already handled.
7324    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7325
7326    for (BuiltinCandidateTypeSet::iterator
7327              Ptr = CandidateTypes[0].pointer_begin(),
7328           PtrEnd = CandidateTypes[0].pointer_end();
7329         Ptr != PtrEnd; ++Ptr) {
7330      // If this is operator=, keep track of the builtin candidates we added.
7331      if (isEqualOp)
7332        AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7333      else if (!(*Ptr)->getPointeeType()->isObjectType())
7334        continue;
7335
7336      // non-volatile version
7337      QualType ParamTypes[2] = {
7338        S.Context.getLValueReferenceType(*Ptr),
7339        isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7340      };
7341      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7342                            /*IsAssigmentOperator=*/ isEqualOp);
7343
7344      bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7345                          VisibleTypeConversionsQuals.hasVolatile();
7346      if (NeedVolatile) {
7347        // volatile version
7348        ParamTypes[0] =
7349          S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7350        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7351                              /*IsAssigmentOperator=*/isEqualOp);
7352      }
7353
7354      if (!(*Ptr).isRestrictQualified() &&
7355          VisibleTypeConversionsQuals.hasRestrict()) {
7356        // restrict version
7357        ParamTypes[0]
7358          = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7359        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7360                              /*IsAssigmentOperator=*/isEqualOp);
7361
7362        if (NeedVolatile) {
7363          // volatile restrict version
7364          ParamTypes[0]
7365            = S.Context.getLValueReferenceType(
7366                S.Context.getCVRQualifiedType(*Ptr,
7367                                              (Qualifiers::Volatile |
7368                                               Qualifiers::Restrict)));
7369          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7370                                /*IsAssigmentOperator=*/isEqualOp);
7371        }
7372      }
7373    }
7374
7375    if (isEqualOp) {
7376      for (BuiltinCandidateTypeSet::iterator
7377                Ptr = CandidateTypes[1].pointer_begin(),
7378             PtrEnd = CandidateTypes[1].pointer_end();
7379           Ptr != PtrEnd; ++Ptr) {
7380        // Make sure we don't add the same candidate twice.
7381        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7382          continue;
7383
7384        QualType ParamTypes[2] = {
7385          S.Context.getLValueReferenceType(*Ptr),
7386          *Ptr,
7387        };
7388
7389        // non-volatile version
7390        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7391                              /*IsAssigmentOperator=*/true);
7392
7393        bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7394                           VisibleTypeConversionsQuals.hasVolatile();
7395        if (NeedVolatile) {
7396          // volatile version
7397          ParamTypes[0] =
7398            S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7399          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7400                                /*IsAssigmentOperator=*/true);
7401        }
7402
7403        if (!(*Ptr).isRestrictQualified() &&
7404            VisibleTypeConversionsQuals.hasRestrict()) {
7405          // restrict version
7406          ParamTypes[0]
7407            = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7408          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7409                                /*IsAssigmentOperator=*/true);
7410
7411          if (NeedVolatile) {
7412            // volatile restrict version
7413            ParamTypes[0]
7414              = S.Context.getLValueReferenceType(
7415                  S.Context.getCVRQualifiedType(*Ptr,
7416                                                (Qualifiers::Volatile |
7417                                                 Qualifiers::Restrict)));
7418            S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7419                                  /*IsAssigmentOperator=*/true);
7420          }
7421        }
7422      }
7423    }
7424  }
7425
7426  // C++ [over.built]p18:
7427  //
7428  //   For every triple (L, VQ, R), where L is an arithmetic type,
7429  //   VQ is either volatile or empty, and R is a promoted
7430  //   arithmetic type, there exist candidate operator functions of
7431  //   the form
7432  //
7433  //        VQ L&      operator=(VQ L&, R);
7434  //        VQ L&      operator*=(VQ L&, R);
7435  //        VQ L&      operator/=(VQ L&, R);
7436  //        VQ L&      operator+=(VQ L&, R);
7437  //        VQ L&      operator-=(VQ L&, R);
7438  void addAssignmentArithmeticOverloads(bool isEqualOp) {
7439    if (!HasArithmeticOrEnumeralCandidateType)
7440      return;
7441
7442    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7443      for (unsigned Right = FirstPromotedArithmeticType;
7444           Right < LastPromotedArithmeticType; ++Right) {
7445        QualType ParamTypes[2];
7446        ParamTypes[1] = getArithmeticType(Right);
7447
7448        // Add this built-in operator as a candidate (VQ is empty).
7449        ParamTypes[0] =
7450          S.Context.getLValueReferenceType(getArithmeticType(Left));
7451        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7452                              /*IsAssigmentOperator=*/isEqualOp);
7453
7454        // Add this built-in operator as a candidate (VQ is 'volatile').
7455        if (VisibleTypeConversionsQuals.hasVolatile()) {
7456          ParamTypes[0] =
7457            S.Context.getVolatileType(getArithmeticType(Left));
7458          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7459          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7460                                /*IsAssigmentOperator=*/isEqualOp);
7461        }
7462      }
7463    }
7464
7465    // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7466    for (BuiltinCandidateTypeSet::iterator
7467              Vec1 = CandidateTypes[0].vector_begin(),
7468           Vec1End = CandidateTypes[0].vector_end();
7469         Vec1 != Vec1End; ++Vec1) {
7470      for (BuiltinCandidateTypeSet::iterator
7471                Vec2 = CandidateTypes[1].vector_begin(),
7472             Vec2End = CandidateTypes[1].vector_end();
7473           Vec2 != Vec2End; ++Vec2) {
7474        QualType ParamTypes[2];
7475        ParamTypes[1] = *Vec2;
7476        // Add this built-in operator as a candidate (VQ is empty).
7477        ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7478        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7479                              /*IsAssigmentOperator=*/isEqualOp);
7480
7481        // Add this built-in operator as a candidate (VQ is 'volatile').
7482        if (VisibleTypeConversionsQuals.hasVolatile()) {
7483          ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7484          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7485          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7486                                /*IsAssigmentOperator=*/isEqualOp);
7487        }
7488      }
7489    }
7490  }
7491
7492  // C++ [over.built]p22:
7493  //
7494  //   For every triple (L, VQ, R), where L is an integral type, VQ
7495  //   is either volatile or empty, and R is a promoted integral
7496  //   type, there exist candidate operator functions of the form
7497  //
7498  //        VQ L&       operator%=(VQ L&, R);
7499  //        VQ L&       operator<<=(VQ L&, R);
7500  //        VQ L&       operator>>=(VQ L&, R);
7501  //        VQ L&       operator&=(VQ L&, R);
7502  //        VQ L&       operator^=(VQ L&, R);
7503  //        VQ L&       operator|=(VQ L&, R);
7504  void addAssignmentIntegralOverloads() {
7505    if (!HasArithmeticOrEnumeralCandidateType)
7506      return;
7507
7508    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7509      for (unsigned Right = FirstPromotedIntegralType;
7510           Right < LastPromotedIntegralType; ++Right) {
7511        QualType ParamTypes[2];
7512        ParamTypes[1] = getArithmeticType(Right);
7513
7514        // Add this built-in operator as a candidate (VQ is empty).
7515        ParamTypes[0] =
7516          S.Context.getLValueReferenceType(getArithmeticType(Left));
7517        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7518        if (VisibleTypeConversionsQuals.hasVolatile()) {
7519          // Add this built-in operator as a candidate (VQ is 'volatile').
7520          ParamTypes[0] = getArithmeticType(Left);
7521          ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7522          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7523          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7524        }
7525      }
7526    }
7527  }
7528
7529  // C++ [over.operator]p23:
7530  //
7531  //   There also exist candidate operator functions of the form
7532  //
7533  //        bool        operator!(bool);
7534  //        bool        operator&&(bool, bool);
7535  //        bool        operator||(bool, bool);
7536  void addExclaimOverload() {
7537    QualType ParamTy = S.Context.BoolTy;
7538    S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7539                          /*IsAssignmentOperator=*/false,
7540                          /*NumContextualBoolArguments=*/1);
7541  }
7542  void addAmpAmpOrPipePipeOverload() {
7543    QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7544    S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7545                          /*IsAssignmentOperator=*/false,
7546                          /*NumContextualBoolArguments=*/2);
7547  }
7548
7549  // C++ [over.built]p13:
7550  //
7551  //   For every cv-qualified or cv-unqualified object type T there
7552  //   exist candidate operator functions of the form
7553  //
7554  //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7555  //        T&         operator[](T*, ptrdiff_t);
7556  //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7557  //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7558  //        T&         operator[](ptrdiff_t, T*);
7559  void addSubscriptOverloads() {
7560    for (BuiltinCandidateTypeSet::iterator
7561              Ptr = CandidateTypes[0].pointer_begin(),
7562           PtrEnd = CandidateTypes[0].pointer_end();
7563         Ptr != PtrEnd; ++Ptr) {
7564      QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7565      QualType PointeeType = (*Ptr)->getPointeeType();
7566      if (!PointeeType->isObjectType())
7567        continue;
7568
7569      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7570
7571      // T& operator[](T*, ptrdiff_t)
7572      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7573    }
7574
7575    for (BuiltinCandidateTypeSet::iterator
7576              Ptr = CandidateTypes[1].pointer_begin(),
7577           PtrEnd = CandidateTypes[1].pointer_end();
7578         Ptr != PtrEnd; ++Ptr) {
7579      QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7580      QualType PointeeType = (*Ptr)->getPointeeType();
7581      if (!PointeeType->isObjectType())
7582        continue;
7583
7584      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7585
7586      // T& operator[](ptrdiff_t, T*)
7587      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7588    }
7589  }
7590
7591  // C++ [over.built]p11:
7592  //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7593  //    C1 is the same type as C2 or is a derived class of C2, T is an object
7594  //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7595  //    there exist candidate operator functions of the form
7596  //
7597  //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7598  //
7599  //    where CV12 is the union of CV1 and CV2.
7600  void addArrowStarOverloads() {
7601    for (BuiltinCandidateTypeSet::iterator
7602             Ptr = CandidateTypes[0].pointer_begin(),
7603           PtrEnd = CandidateTypes[0].pointer_end();
7604         Ptr != PtrEnd; ++Ptr) {
7605      QualType C1Ty = (*Ptr);
7606      QualType C1;
7607      QualifierCollector Q1;
7608      C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7609      if (!isa<RecordType>(C1))
7610        continue;
7611      // heuristic to reduce number of builtin candidates in the set.
7612      // Add volatile/restrict version only if there are conversions to a
7613      // volatile/restrict type.
7614      if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7615        continue;
7616      if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7617        continue;
7618      for (BuiltinCandidateTypeSet::iterator
7619                MemPtr = CandidateTypes[1].member_pointer_begin(),
7620             MemPtrEnd = CandidateTypes[1].member_pointer_end();
7621           MemPtr != MemPtrEnd; ++MemPtr) {
7622        const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7623        QualType C2 = QualType(mptr->getClass(), 0);
7624        C2 = C2.getUnqualifiedType();
7625        if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7626          break;
7627        QualType ParamTypes[2] = { *Ptr, *MemPtr };
7628        // build CV12 T&
7629        QualType T = mptr->getPointeeType();
7630        if (!VisibleTypeConversionsQuals.hasVolatile() &&
7631            T.isVolatileQualified())
7632          continue;
7633        if (!VisibleTypeConversionsQuals.hasRestrict() &&
7634            T.isRestrictQualified())
7635          continue;
7636        T = Q1.apply(S.Context, T);
7637        QualType ResultTy = S.Context.getLValueReferenceType(T);
7638        S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7639      }
7640    }
7641  }
7642
7643  // Note that we don't consider the first argument, since it has been
7644  // contextually converted to bool long ago. The candidates below are
7645  // therefore added as binary.
7646  //
7647  // C++ [over.built]p25:
7648  //   For every type T, where T is a pointer, pointer-to-member, or scoped
7649  //   enumeration type, there exist candidate operator functions of the form
7650  //
7651  //        T        operator?(bool, T, T);
7652  //
7653  void addConditionalOperatorOverloads() {
7654    /// Set of (canonical) types that we've already handled.
7655    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7656
7657    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7658      for (BuiltinCandidateTypeSet::iterator
7659                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7660             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7661           Ptr != PtrEnd; ++Ptr) {
7662        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7663          continue;
7664
7665        QualType ParamTypes[2] = { *Ptr, *Ptr };
7666        S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
7667      }
7668
7669      for (BuiltinCandidateTypeSet::iterator
7670                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7671             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7672           MemPtr != MemPtrEnd; ++MemPtr) {
7673        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7674          continue;
7675
7676        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7677        S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
7678      }
7679
7680      if (S.getLangOpts().CPlusPlus11) {
7681        for (BuiltinCandidateTypeSet::iterator
7682                  Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7683               EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7684             Enum != EnumEnd; ++Enum) {
7685          if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7686            continue;
7687
7688          if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7689            continue;
7690
7691          QualType ParamTypes[2] = { *Enum, *Enum };
7692          S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
7693        }
7694      }
7695    }
7696  }
7697};
7698
7699} // end anonymous namespace
7700
7701/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7702/// operator overloads to the candidate set (C++ [over.built]), based
7703/// on the operator @p Op and the arguments given. For example, if the
7704/// operator is a binary '+', this routine might add "int
7705/// operator+(int, int)" to cover integer addition.
7706void
7707Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7708                                   SourceLocation OpLoc,
7709                                   llvm::ArrayRef<Expr *> Args,
7710                                   OverloadCandidateSet& CandidateSet) {
7711  // Find all of the types that the arguments can convert to, but only
7712  // if the operator we're looking at has built-in operator candidates
7713  // that make use of these types. Also record whether we encounter non-record
7714  // candidate types or either arithmetic or enumeral candidate types.
7715  Qualifiers VisibleTypeConversionsQuals;
7716  VisibleTypeConversionsQuals.addConst();
7717  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7718    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7719
7720  bool HasNonRecordCandidateType = false;
7721  bool HasArithmeticOrEnumeralCandidateType = false;
7722  SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7723  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7724    CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7725    CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7726                                                 OpLoc,
7727                                                 true,
7728                                                 (Op == OO_Exclaim ||
7729                                                  Op == OO_AmpAmp ||
7730                                                  Op == OO_PipePipe),
7731                                                 VisibleTypeConversionsQuals);
7732    HasNonRecordCandidateType = HasNonRecordCandidateType ||
7733        CandidateTypes[ArgIdx].hasNonRecordTypes();
7734    HasArithmeticOrEnumeralCandidateType =
7735        HasArithmeticOrEnumeralCandidateType ||
7736        CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7737  }
7738
7739  // Exit early when no non-record types have been added to the candidate set
7740  // for any of the arguments to the operator.
7741  //
7742  // We can't exit early for !, ||, or &&, since there we have always have
7743  // 'bool' overloads.
7744  if (!HasNonRecordCandidateType &&
7745      !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7746    return;
7747
7748  // Setup an object to manage the common state for building overloads.
7749  BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
7750                                           VisibleTypeConversionsQuals,
7751                                           HasArithmeticOrEnumeralCandidateType,
7752                                           CandidateTypes, CandidateSet);
7753
7754  // Dispatch over the operation to add in only those overloads which apply.
7755  switch (Op) {
7756  case OO_None:
7757  case NUM_OVERLOADED_OPERATORS:
7758    llvm_unreachable("Expected an overloaded operator");
7759
7760  case OO_New:
7761  case OO_Delete:
7762  case OO_Array_New:
7763  case OO_Array_Delete:
7764  case OO_Call:
7765    llvm_unreachable(
7766                    "Special operators don't use AddBuiltinOperatorCandidates");
7767
7768  case OO_Comma:
7769  case OO_Arrow:
7770    // C++ [over.match.oper]p3:
7771    //   -- For the operator ',', the unary operator '&', or the
7772    //      operator '->', the built-in candidates set is empty.
7773    break;
7774
7775  case OO_Plus: // '+' is either unary or binary
7776    if (Args.size() == 1)
7777      OpBuilder.addUnaryPlusPointerOverloads();
7778    // Fall through.
7779
7780  case OO_Minus: // '-' is either unary or binary
7781    if (Args.size() == 1) {
7782      OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7783    } else {
7784      OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7785      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7786    }
7787    break;
7788
7789  case OO_Star: // '*' is either unary or binary
7790    if (Args.size() == 1)
7791      OpBuilder.addUnaryStarPointerOverloads();
7792    else
7793      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7794    break;
7795
7796  case OO_Slash:
7797    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7798    break;
7799
7800  case OO_PlusPlus:
7801  case OO_MinusMinus:
7802    OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7803    OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7804    break;
7805
7806  case OO_EqualEqual:
7807  case OO_ExclaimEqual:
7808    OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7809    // Fall through.
7810
7811  case OO_Less:
7812  case OO_Greater:
7813  case OO_LessEqual:
7814  case OO_GreaterEqual:
7815    OpBuilder.addRelationalPointerOrEnumeralOverloads();
7816    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7817    break;
7818
7819  case OO_Percent:
7820  case OO_Caret:
7821  case OO_Pipe:
7822  case OO_LessLess:
7823  case OO_GreaterGreater:
7824    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7825    break;
7826
7827  case OO_Amp: // '&' is either unary or binary
7828    if (Args.size() == 1)
7829      // C++ [over.match.oper]p3:
7830      //   -- For the operator ',', the unary operator '&', or the
7831      //      operator '->', the built-in candidates set is empty.
7832      break;
7833
7834    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7835    break;
7836
7837  case OO_Tilde:
7838    OpBuilder.addUnaryTildePromotedIntegralOverloads();
7839    break;
7840
7841  case OO_Equal:
7842    OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7843    // Fall through.
7844
7845  case OO_PlusEqual:
7846  case OO_MinusEqual:
7847    OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7848    // Fall through.
7849
7850  case OO_StarEqual:
7851  case OO_SlashEqual:
7852    OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7853    break;
7854
7855  case OO_PercentEqual:
7856  case OO_LessLessEqual:
7857  case OO_GreaterGreaterEqual:
7858  case OO_AmpEqual:
7859  case OO_CaretEqual:
7860  case OO_PipeEqual:
7861    OpBuilder.addAssignmentIntegralOverloads();
7862    break;
7863
7864  case OO_Exclaim:
7865    OpBuilder.addExclaimOverload();
7866    break;
7867
7868  case OO_AmpAmp:
7869  case OO_PipePipe:
7870    OpBuilder.addAmpAmpOrPipePipeOverload();
7871    break;
7872
7873  case OO_Subscript:
7874    OpBuilder.addSubscriptOverloads();
7875    break;
7876
7877  case OO_ArrowStar:
7878    OpBuilder.addArrowStarOverloads();
7879    break;
7880
7881  case OO_Conditional:
7882    OpBuilder.addConditionalOperatorOverloads();
7883    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7884    break;
7885  }
7886}
7887
7888/// \brief Add function candidates found via argument-dependent lookup
7889/// to the set of overloading candidates.
7890///
7891/// This routine performs argument-dependent name lookup based on the
7892/// given function name (which may also be an operator name) and adds
7893/// all of the overload candidates found by ADL to the overload
7894/// candidate set (C++ [basic.lookup.argdep]).
7895void
7896Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7897                                           bool Operator, SourceLocation Loc,
7898                                           ArrayRef<Expr *> Args,
7899                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
7900                                           OverloadCandidateSet& CandidateSet,
7901                                           bool PartialOverloading) {
7902  ADLResult Fns;
7903
7904  // FIXME: This approach for uniquing ADL results (and removing
7905  // redundant candidates from the set) relies on pointer-equality,
7906  // which means we need to key off the canonical decl.  However,
7907  // always going back to the canonical decl might not get us the
7908  // right set of default arguments.  What default arguments are
7909  // we supposed to consider on ADL candidates, anyway?
7910
7911  // FIXME: Pass in the explicit template arguments?
7912  ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
7913
7914  // Erase all of the candidates we already knew about.
7915  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7916                                   CandEnd = CandidateSet.end();
7917       Cand != CandEnd; ++Cand)
7918    if (Cand->Function) {
7919      Fns.erase(Cand->Function);
7920      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7921        Fns.erase(FunTmpl);
7922    }
7923
7924  // For each of the ADL candidates we found, add it to the overload
7925  // set.
7926  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7927    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7928    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7929      if (ExplicitTemplateArgs)
7930        continue;
7931
7932      AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7933                           PartialOverloading);
7934    } else
7935      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7936                                   FoundDecl, ExplicitTemplateArgs,
7937                                   Args, CandidateSet);
7938  }
7939}
7940
7941/// isBetterOverloadCandidate - Determines whether the first overload
7942/// candidate is a better candidate than the second (C++ 13.3.3p1).
7943bool
7944isBetterOverloadCandidate(Sema &S,
7945                          const OverloadCandidate &Cand1,
7946                          const OverloadCandidate &Cand2,
7947                          SourceLocation Loc,
7948                          bool UserDefinedConversion) {
7949  // Define viable functions to be better candidates than non-viable
7950  // functions.
7951  if (!Cand2.Viable)
7952    return Cand1.Viable;
7953  else if (!Cand1.Viable)
7954    return false;
7955
7956  // C++ [over.match.best]p1:
7957  //
7958  //   -- if F is a static member function, ICS1(F) is defined such
7959  //      that ICS1(F) is neither better nor worse than ICS1(G) for
7960  //      any function G, and, symmetrically, ICS1(G) is neither
7961  //      better nor worse than ICS1(F).
7962  unsigned StartArg = 0;
7963  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7964    StartArg = 1;
7965
7966  // C++ [over.match.best]p1:
7967  //   A viable function F1 is defined to be a better function than another
7968  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
7969  //   conversion sequence than ICSi(F2), and then...
7970  unsigned NumArgs = Cand1.NumConversions;
7971  assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7972  bool HasBetterConversion = false;
7973  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7974    switch (CompareImplicitConversionSequences(S,
7975                                               Cand1.Conversions[ArgIdx],
7976                                               Cand2.Conversions[ArgIdx])) {
7977    case ImplicitConversionSequence::Better:
7978      // Cand1 has a better conversion sequence.
7979      HasBetterConversion = true;
7980      break;
7981
7982    case ImplicitConversionSequence::Worse:
7983      // Cand1 can't be better than Cand2.
7984      return false;
7985
7986    case ImplicitConversionSequence::Indistinguishable:
7987      // Do nothing.
7988      break;
7989    }
7990  }
7991
7992  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
7993  //       ICSj(F2), or, if not that,
7994  if (HasBetterConversion)
7995    return true;
7996
7997  //     - F1 is a non-template function and F2 is a function template
7998  //       specialization, or, if not that,
7999  if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
8000      Cand2.Function && Cand2.Function->getPrimaryTemplate())
8001    return true;
8002
8003  //   -- F1 and F2 are function template specializations, and the function
8004  //      template for F1 is more specialized than the template for F2
8005  //      according to the partial ordering rules described in 14.5.5.2, or,
8006  //      if not that,
8007  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
8008      Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
8009    if (FunctionTemplateDecl *BetterTemplate
8010          = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8011                                         Cand2.Function->getPrimaryTemplate(),
8012                                         Loc,
8013                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8014                                                             : TPOC_Call,
8015                                         Cand1.ExplicitCallArguments))
8016      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8017  }
8018
8019  //   -- the context is an initialization by user-defined conversion
8020  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8021  //      from the return type of F1 to the destination type (i.e.,
8022  //      the type of the entity being initialized) is a better
8023  //      conversion sequence than the standard conversion sequence
8024  //      from the return type of F2 to the destination type.
8025  if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8026      isa<CXXConversionDecl>(Cand1.Function) &&
8027      isa<CXXConversionDecl>(Cand2.Function)) {
8028    // First check whether we prefer one of the conversion functions over the
8029    // other. This only distinguishes the results in non-standard, extension
8030    // cases such as the conversion from a lambda closure type to a function
8031    // pointer or block.
8032    ImplicitConversionSequence::CompareKind FuncResult
8033      = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8034    if (FuncResult != ImplicitConversionSequence::Indistinguishable)
8035      return FuncResult;
8036
8037    switch (CompareStandardConversionSequences(S,
8038                                               Cand1.FinalConversion,
8039                                               Cand2.FinalConversion)) {
8040    case ImplicitConversionSequence::Better:
8041      // Cand1 has a better conversion sequence.
8042      return true;
8043
8044    case ImplicitConversionSequence::Worse:
8045      // Cand1 can't be better than Cand2.
8046      return false;
8047
8048    case ImplicitConversionSequence::Indistinguishable:
8049      // Do nothing
8050      break;
8051    }
8052  }
8053
8054  return false;
8055}
8056
8057/// \brief Computes the best viable function (C++ 13.3.3)
8058/// within an overload candidate set.
8059///
8060/// \param Loc The location of the function name (or operator symbol) for
8061/// which overload resolution occurs.
8062///
8063/// \param Best If overload resolution was successful or found a deleted
8064/// function, \p Best points to the candidate function found.
8065///
8066/// \returns The result of overload resolution.
8067OverloadingResult
8068OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8069                                         iterator &Best,
8070                                         bool UserDefinedConversion) {
8071  // Find the best viable function.
8072  Best = end();
8073  for (iterator Cand = begin(); Cand != end(); ++Cand) {
8074    if (Cand->Viable)
8075      if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8076                                                     UserDefinedConversion))
8077        Best = Cand;
8078  }
8079
8080  // If we didn't find any viable functions, abort.
8081  if (Best == end())
8082    return OR_No_Viable_Function;
8083
8084  // Make sure that this function is better than every other viable
8085  // function. If not, we have an ambiguity.
8086  for (iterator Cand = begin(); Cand != end(); ++Cand) {
8087    if (Cand->Viable &&
8088        Cand != Best &&
8089        !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8090                                   UserDefinedConversion)) {
8091      Best = end();
8092      return OR_Ambiguous;
8093    }
8094  }
8095
8096  // Best is the best viable function.
8097  if (Best->Function &&
8098      (Best->Function->isDeleted() ||
8099       S.isFunctionConsideredUnavailable(Best->Function)))
8100    return OR_Deleted;
8101
8102  return OR_Success;
8103}
8104
8105namespace {
8106
8107enum OverloadCandidateKind {
8108  oc_function,
8109  oc_method,
8110  oc_constructor,
8111  oc_function_template,
8112  oc_method_template,
8113  oc_constructor_template,
8114  oc_implicit_default_constructor,
8115  oc_implicit_copy_constructor,
8116  oc_implicit_move_constructor,
8117  oc_implicit_copy_assignment,
8118  oc_implicit_move_assignment,
8119  oc_implicit_inherited_constructor
8120};
8121
8122OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8123                                                FunctionDecl *Fn,
8124                                                std::string &Description) {
8125  bool isTemplate = false;
8126
8127  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8128    isTemplate = true;
8129    Description = S.getTemplateArgumentBindingsText(
8130      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8131  }
8132
8133  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8134    if (!Ctor->isImplicit())
8135      return isTemplate ? oc_constructor_template : oc_constructor;
8136
8137    if (Ctor->getInheritedConstructor())
8138      return oc_implicit_inherited_constructor;
8139
8140    if (Ctor->isDefaultConstructor())
8141      return oc_implicit_default_constructor;
8142
8143    if (Ctor->isMoveConstructor())
8144      return oc_implicit_move_constructor;
8145
8146    assert(Ctor->isCopyConstructor() &&
8147           "unexpected sort of implicit constructor");
8148    return oc_implicit_copy_constructor;
8149  }
8150
8151  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8152    // This actually gets spelled 'candidate function' for now, but
8153    // it doesn't hurt to split it out.
8154    if (!Meth->isImplicit())
8155      return isTemplate ? oc_method_template : oc_method;
8156
8157    if (Meth->isMoveAssignmentOperator())
8158      return oc_implicit_move_assignment;
8159
8160    if (Meth->isCopyAssignmentOperator())
8161      return oc_implicit_copy_assignment;
8162
8163    assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8164    return oc_method;
8165  }
8166
8167  return isTemplate ? oc_function_template : oc_function;
8168}
8169
8170void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
8171  const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8172  if (!Ctor) return;
8173
8174  Ctor = Ctor->getInheritedConstructor();
8175  if (!Ctor) return;
8176
8177  S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8178}
8179
8180} // end anonymous namespace
8181
8182// Notes the location of an overload candidate.
8183void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8184  std::string FnDesc;
8185  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8186  PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8187                             << (unsigned) K << FnDesc;
8188  HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8189  Diag(Fn->getLocation(), PD);
8190  MaybeEmitInheritedConstructorNote(*this, Fn);
8191}
8192
8193//Notes the location of all overload candidates designated through
8194// OverloadedExpr
8195void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8196  assert(OverloadedExpr->getType() == Context.OverloadTy);
8197
8198  OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8199  OverloadExpr *OvlExpr = Ovl.Expression;
8200
8201  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8202                            IEnd = OvlExpr->decls_end();
8203       I != IEnd; ++I) {
8204    if (FunctionTemplateDecl *FunTmpl =
8205                dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8206      NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8207    } else if (FunctionDecl *Fun
8208                      = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8209      NoteOverloadCandidate(Fun, DestType);
8210    }
8211  }
8212}
8213
8214/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8215/// "lead" diagnostic; it will be given two arguments, the source and
8216/// target types of the conversion.
8217void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8218                                 Sema &S,
8219                                 SourceLocation CaretLoc,
8220                                 const PartialDiagnostic &PDiag) const {
8221  S.Diag(CaretLoc, PDiag)
8222    << Ambiguous.getFromType() << Ambiguous.getToType();
8223  // FIXME: The note limiting machinery is borrowed from
8224  // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8225  // refactoring here.
8226  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8227  unsigned CandsShown = 0;
8228  AmbiguousConversionSequence::const_iterator I, E;
8229  for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8230    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8231      break;
8232    ++CandsShown;
8233    S.NoteOverloadCandidate(*I);
8234  }
8235  if (I != E)
8236    S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8237}
8238
8239namespace {
8240
8241void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8242  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8243  assert(Conv.isBad());
8244  assert(Cand->Function && "for now, candidate must be a function");
8245  FunctionDecl *Fn = Cand->Function;
8246
8247  // There's a conversion slot for the object argument if this is a
8248  // non-constructor method.  Note that 'I' corresponds the
8249  // conversion-slot index.
8250  bool isObjectArgument = false;
8251  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8252    if (I == 0)
8253      isObjectArgument = true;
8254    else
8255      I--;
8256  }
8257
8258  std::string FnDesc;
8259  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8260
8261  Expr *FromExpr = Conv.Bad.FromExpr;
8262  QualType FromTy = Conv.Bad.getFromType();
8263  QualType ToTy = Conv.Bad.getToType();
8264
8265  if (FromTy == S.Context.OverloadTy) {
8266    assert(FromExpr && "overload set argument came from implicit argument?");
8267    Expr *E = FromExpr->IgnoreParens();
8268    if (isa<UnaryOperator>(E))
8269      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8270    DeclarationName Name = cast<OverloadExpr>(E)->getName();
8271
8272    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8273      << (unsigned) FnKind << FnDesc
8274      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8275      << ToTy << Name << I+1;
8276    MaybeEmitInheritedConstructorNote(S, Fn);
8277    return;
8278  }
8279
8280  // Do some hand-waving analysis to see if the non-viability is due
8281  // to a qualifier mismatch.
8282  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8283  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8284  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8285    CToTy = RT->getPointeeType();
8286  else {
8287    // TODO: detect and diagnose the full richness of const mismatches.
8288    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8289      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8290        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8291  }
8292
8293  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8294      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8295    Qualifiers FromQs = CFromTy.getQualifiers();
8296    Qualifiers ToQs = CToTy.getQualifiers();
8297
8298    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8299      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8300        << (unsigned) FnKind << FnDesc
8301        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8302        << FromTy
8303        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8304        << (unsigned) isObjectArgument << I+1;
8305      MaybeEmitInheritedConstructorNote(S, Fn);
8306      return;
8307    }
8308
8309    if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8310      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8311        << (unsigned) FnKind << FnDesc
8312        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8313        << FromTy
8314        << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8315        << (unsigned) isObjectArgument << I+1;
8316      MaybeEmitInheritedConstructorNote(S, Fn);
8317      return;
8318    }
8319
8320    if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8321      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8322      << (unsigned) FnKind << FnDesc
8323      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8324      << FromTy
8325      << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8326      << (unsigned) isObjectArgument << I+1;
8327      MaybeEmitInheritedConstructorNote(S, Fn);
8328      return;
8329    }
8330
8331    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8332    assert(CVR && "unexpected qualifiers mismatch");
8333
8334    if (isObjectArgument) {
8335      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8336        << (unsigned) FnKind << FnDesc
8337        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8338        << FromTy << (CVR - 1);
8339    } else {
8340      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8341        << (unsigned) FnKind << FnDesc
8342        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8343        << FromTy << (CVR - 1) << I+1;
8344    }
8345    MaybeEmitInheritedConstructorNote(S, Fn);
8346    return;
8347  }
8348
8349  // Special diagnostic for failure to convert an initializer list, since
8350  // telling the user that it has type void is not useful.
8351  if (FromExpr && isa<InitListExpr>(FromExpr)) {
8352    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8353      << (unsigned) FnKind << FnDesc
8354      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8355      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8356    MaybeEmitInheritedConstructorNote(S, Fn);
8357    return;
8358  }
8359
8360  // Diagnose references or pointers to incomplete types differently,
8361  // since it's far from impossible that the incompleteness triggered
8362  // the failure.
8363  QualType TempFromTy = FromTy.getNonReferenceType();
8364  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8365    TempFromTy = PTy->getPointeeType();
8366  if (TempFromTy->isIncompleteType()) {
8367    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8368      << (unsigned) FnKind << FnDesc
8369      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8370      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8371    MaybeEmitInheritedConstructorNote(S, Fn);
8372    return;
8373  }
8374
8375  // Diagnose base -> derived pointer conversions.
8376  unsigned BaseToDerivedConversion = 0;
8377  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8378    if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8379      if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8380                                               FromPtrTy->getPointeeType()) &&
8381          !FromPtrTy->getPointeeType()->isIncompleteType() &&
8382          !ToPtrTy->getPointeeType()->isIncompleteType() &&
8383          S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8384                          FromPtrTy->getPointeeType()))
8385        BaseToDerivedConversion = 1;
8386    }
8387  } else if (const ObjCObjectPointerType *FromPtrTy
8388                                    = FromTy->getAs<ObjCObjectPointerType>()) {
8389    if (const ObjCObjectPointerType *ToPtrTy
8390                                        = ToTy->getAs<ObjCObjectPointerType>())
8391      if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8392        if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8393          if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8394                                                FromPtrTy->getPointeeType()) &&
8395              FromIface->isSuperClassOf(ToIface))
8396            BaseToDerivedConversion = 2;
8397  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8398    if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8399        !FromTy->isIncompleteType() &&
8400        !ToRefTy->getPointeeType()->isIncompleteType() &&
8401        S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8402      BaseToDerivedConversion = 3;
8403    } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8404               ToTy.getNonReferenceType().getCanonicalType() ==
8405               FromTy.getNonReferenceType().getCanonicalType()) {
8406      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8407        << (unsigned) FnKind << FnDesc
8408        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8409        << (unsigned) isObjectArgument << I + 1;
8410      MaybeEmitInheritedConstructorNote(S, Fn);
8411      return;
8412    }
8413  }
8414
8415  if (BaseToDerivedConversion) {
8416    S.Diag(Fn->getLocation(),
8417           diag::note_ovl_candidate_bad_base_to_derived_conv)
8418      << (unsigned) FnKind << FnDesc
8419      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8420      << (BaseToDerivedConversion - 1)
8421      << FromTy << ToTy << I+1;
8422    MaybeEmitInheritedConstructorNote(S, Fn);
8423    return;
8424  }
8425
8426  if (isa<ObjCObjectPointerType>(CFromTy) &&
8427      isa<PointerType>(CToTy)) {
8428      Qualifiers FromQs = CFromTy.getQualifiers();
8429      Qualifiers ToQs = CToTy.getQualifiers();
8430      if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8431        S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8432        << (unsigned) FnKind << FnDesc
8433        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8434        << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8435        MaybeEmitInheritedConstructorNote(S, Fn);
8436        return;
8437      }
8438  }
8439
8440  // Emit the generic diagnostic and, optionally, add the hints to it.
8441  PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8442  FDiag << (unsigned) FnKind << FnDesc
8443    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8444    << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8445    << (unsigned) (Cand->Fix.Kind);
8446
8447  // If we can fix the conversion, suggest the FixIts.
8448  for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8449       HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8450    FDiag << *HI;
8451  S.Diag(Fn->getLocation(), FDiag);
8452
8453  MaybeEmitInheritedConstructorNote(S, Fn);
8454}
8455
8456void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8457                           unsigned NumFormalArgs) {
8458  // TODO: treat calls to a missing default constructor as a special case
8459
8460  FunctionDecl *Fn = Cand->Function;
8461  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8462
8463  unsigned MinParams = Fn->getMinRequiredArguments();
8464
8465  // With invalid overloaded operators, it's possible that we think we
8466  // have an arity mismatch when it fact it looks like we have the
8467  // right number of arguments, because only overloaded operators have
8468  // the weird behavior of overloading member and non-member functions.
8469  // Just don't report anything.
8470  if (Fn->isInvalidDecl() &&
8471      Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8472    return;
8473
8474  // at least / at most / exactly
8475  unsigned mode, modeCount;
8476  if (NumFormalArgs < MinParams) {
8477    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8478           (Cand->FailureKind == ovl_fail_bad_deduction &&
8479            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8480    if (MinParams != FnTy->getNumArgs() ||
8481        FnTy->isVariadic() || FnTy->isTemplateVariadic())
8482      mode = 0; // "at least"
8483    else
8484      mode = 2; // "exactly"
8485    modeCount = MinParams;
8486  } else {
8487    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8488           (Cand->FailureKind == ovl_fail_bad_deduction &&
8489            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8490    if (MinParams != FnTy->getNumArgs())
8491      mode = 1; // "at most"
8492    else
8493      mode = 2; // "exactly"
8494    modeCount = FnTy->getNumArgs();
8495  }
8496
8497  std::string Description;
8498  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8499
8500  if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8501    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8502      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8503      << Fn->getParamDecl(0) << NumFormalArgs;
8504  else
8505    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8506      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8507      << modeCount << NumFormalArgs;
8508  MaybeEmitInheritedConstructorNote(S, Fn);
8509}
8510
8511/// Diagnose a failed template-argument deduction.
8512void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
8513                          unsigned NumArgs) {
8514  FunctionDecl *Fn = Cand->Function; // pattern
8515
8516  TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
8517  NamedDecl *ParamD;
8518  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8519  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8520  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8521  switch (Cand->DeductionFailure.Result) {
8522  case Sema::TDK_Success:
8523    llvm_unreachable("TDK_success while diagnosing bad deduction");
8524
8525  case Sema::TDK_Incomplete: {
8526    assert(ParamD && "no parameter found for incomplete deduction result");
8527    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8528      << ParamD->getDeclName();
8529    MaybeEmitInheritedConstructorNote(S, Fn);
8530    return;
8531  }
8532
8533  case Sema::TDK_Underqualified: {
8534    assert(ParamD && "no parameter found for bad qualifiers deduction result");
8535    TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8536
8537    QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8538
8539    // Param will have been canonicalized, but it should just be a
8540    // qualified version of ParamD, so move the qualifiers to that.
8541    QualifierCollector Qs;
8542    Qs.strip(Param);
8543    QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8544    assert(S.Context.hasSameType(Param, NonCanonParam));
8545
8546    // Arg has also been canonicalized, but there's nothing we can do
8547    // about that.  It also doesn't matter as much, because it won't
8548    // have any template parameters in it (because deduction isn't
8549    // done on dependent types).
8550    QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8551
8552    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8553      << ParamD->getDeclName() << Arg << NonCanonParam;
8554    MaybeEmitInheritedConstructorNote(S, Fn);
8555    return;
8556  }
8557
8558  case Sema::TDK_Inconsistent: {
8559    assert(ParamD && "no parameter found for inconsistent deduction result");
8560    int which = 0;
8561    if (isa<TemplateTypeParmDecl>(ParamD))
8562      which = 0;
8563    else if (isa<NonTypeTemplateParmDecl>(ParamD))
8564      which = 1;
8565    else {
8566      which = 2;
8567    }
8568
8569    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
8570      << which << ParamD->getDeclName()
8571      << *Cand->DeductionFailure.getFirstArg()
8572      << *Cand->DeductionFailure.getSecondArg();
8573    MaybeEmitInheritedConstructorNote(S, Fn);
8574    return;
8575  }
8576
8577  case Sema::TDK_InvalidExplicitArguments:
8578    assert(ParamD && "no parameter found for invalid explicit arguments");
8579    if (ParamD->getDeclName())
8580      S.Diag(Fn->getLocation(),
8581             diag::note_ovl_candidate_explicit_arg_mismatch_named)
8582        << ParamD->getDeclName();
8583    else {
8584      int index = 0;
8585      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8586        index = TTP->getIndex();
8587      else if (NonTypeTemplateParmDecl *NTTP
8588                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8589        index = NTTP->getIndex();
8590      else
8591        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8592      S.Diag(Fn->getLocation(),
8593             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8594        << (index + 1);
8595    }
8596    MaybeEmitInheritedConstructorNote(S, Fn);
8597    return;
8598
8599  case Sema::TDK_TooManyArguments:
8600  case Sema::TDK_TooFewArguments:
8601    DiagnoseArityMismatch(S, Cand, NumArgs);
8602    return;
8603
8604  case Sema::TDK_InstantiationDepth:
8605    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
8606    MaybeEmitInheritedConstructorNote(S, Fn);
8607    return;
8608
8609  case Sema::TDK_SubstitutionFailure: {
8610    // Format the template argument list into the argument string.
8611    SmallString<128> TemplateArgString;
8612    if (TemplateArgumentList *Args =
8613          Cand->DeductionFailure.getTemplateArgumentList()) {
8614      TemplateArgString = " ";
8615      TemplateArgString += S.getTemplateArgumentBindingsText(
8616          Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8617    }
8618
8619    // If this candidate was disabled by enable_if, say so.
8620    PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8621    if (PDiag && PDiag->second.getDiagID() ==
8622          diag::err_typename_nested_not_found_enable_if) {
8623      // FIXME: Use the source range of the condition, and the fully-qualified
8624      //        name of the enable_if template. These are both present in PDiag.
8625      S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8626        << "'enable_if'" << TemplateArgString;
8627      return;
8628    }
8629
8630    // Format the SFINAE diagnostic into the argument string.
8631    // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8632    //        formatted message in another diagnostic.
8633    SmallString<128> SFINAEArgString;
8634    SourceRange R;
8635    if (PDiag) {
8636      SFINAEArgString = ": ";
8637      R = SourceRange(PDiag->first, PDiag->first);
8638      PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8639    }
8640
8641    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8642      << TemplateArgString << SFINAEArgString << R;
8643    MaybeEmitInheritedConstructorNote(S, Fn);
8644    return;
8645  }
8646
8647  case Sema::TDK_FailedOverloadResolution: {
8648    OverloadExpr::FindResult R =
8649        OverloadExpr::find(Cand->DeductionFailure.getExpr());
8650    S.Diag(Fn->getLocation(),
8651           diag::note_ovl_candidate_failed_overload_resolution)
8652      << R.Expression->getName();
8653    return;
8654  }
8655
8656  case Sema::TDK_NonDeducedMismatch: {
8657    // FIXME: Provide a source location to indicate what we couldn't match.
8658    TemplateArgument FirstTA = *Cand->DeductionFailure.getFirstArg();
8659    TemplateArgument SecondTA = *Cand->DeductionFailure.getSecondArg();
8660    if (FirstTA.getKind() == TemplateArgument::Template &&
8661        SecondTA.getKind() == TemplateArgument::Template) {
8662      TemplateName FirstTN = FirstTA.getAsTemplate();
8663      TemplateName SecondTN = SecondTA.getAsTemplate();
8664      if (FirstTN.getKind() == TemplateName::Template &&
8665          SecondTN.getKind() == TemplateName::Template) {
8666        if (FirstTN.getAsTemplateDecl()->getName() ==
8667            SecondTN.getAsTemplateDecl()->getName()) {
8668          // FIXME: This fixes a bad diagnostic where both templates are named
8669          // the same.  This particular case is a bit difficult since:
8670          // 1) It is passed as a string to the diagnostic printer.
8671          // 2) The diagnostic printer only attempts to find a better
8672          //    name for types, not decls.
8673          // Ideally, this should folded into the diagnostic printer.
8674          S.Diag(Fn->getLocation(),
8675                 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8676              << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8677          return;
8678        }
8679      }
8680    }
8681    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
8682      << FirstTA << SecondTA;
8683    return;
8684  }
8685  // TODO: diagnose these individually, then kill off
8686  // note_ovl_candidate_bad_deduction, which is uselessly vague.
8687  case Sema::TDK_MiscellaneousDeductionFailure:
8688    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
8689    MaybeEmitInheritedConstructorNote(S, Fn);
8690    return;
8691  }
8692}
8693
8694/// CUDA: diagnose an invalid call across targets.
8695void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8696  FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8697  FunctionDecl *Callee = Cand->Function;
8698
8699  Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8700                           CalleeTarget = S.IdentifyCUDATarget(Callee);
8701
8702  std::string FnDesc;
8703  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8704
8705  S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8706      << (unsigned) FnKind << CalleeTarget << CallerTarget;
8707}
8708
8709/// Generates a 'note' diagnostic for an overload candidate.  We've
8710/// already generated a primary error at the call site.
8711///
8712/// It really does need to be a single diagnostic with its caret
8713/// pointed at the candidate declaration.  Yes, this creates some
8714/// major challenges of technical writing.  Yes, this makes pointing
8715/// out problems with specific arguments quite awkward.  It's still
8716/// better than generating twenty screens of text for every failed
8717/// overload.
8718///
8719/// It would be great to be able to express per-candidate problems
8720/// more richly for those diagnostic clients that cared, but we'd
8721/// still have to be just as careful with the default diagnostics.
8722void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8723                           unsigned NumArgs) {
8724  FunctionDecl *Fn = Cand->Function;
8725
8726  // Note deleted candidates, but only if they're viable.
8727  if (Cand->Viable && (Fn->isDeleted() ||
8728      S.isFunctionConsideredUnavailable(Fn))) {
8729    std::string FnDesc;
8730    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8731
8732    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8733      << FnKind << FnDesc
8734      << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8735    MaybeEmitInheritedConstructorNote(S, Fn);
8736    return;
8737  }
8738
8739  // We don't really have anything else to say about viable candidates.
8740  if (Cand->Viable) {
8741    S.NoteOverloadCandidate(Fn);
8742    return;
8743  }
8744
8745  switch (Cand->FailureKind) {
8746  case ovl_fail_too_many_arguments:
8747  case ovl_fail_too_few_arguments:
8748    return DiagnoseArityMismatch(S, Cand, NumArgs);
8749
8750  case ovl_fail_bad_deduction:
8751    return DiagnoseBadDeduction(S, Cand, NumArgs);
8752
8753  case ovl_fail_trivial_conversion:
8754  case ovl_fail_bad_final_conversion:
8755  case ovl_fail_final_conversion_not_exact:
8756    return S.NoteOverloadCandidate(Fn);
8757
8758  case ovl_fail_bad_conversion: {
8759    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8760    for (unsigned N = Cand->NumConversions; I != N; ++I)
8761      if (Cand->Conversions[I].isBad())
8762        return DiagnoseBadConversion(S, Cand, I);
8763
8764    // FIXME: this currently happens when we're called from SemaInit
8765    // when user-conversion overload fails.  Figure out how to handle
8766    // those conditions and diagnose them well.
8767    return S.NoteOverloadCandidate(Fn);
8768  }
8769
8770  case ovl_fail_bad_target:
8771    return DiagnoseBadTarget(S, Cand);
8772  }
8773}
8774
8775void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8776  // Desugar the type of the surrogate down to a function type,
8777  // retaining as many typedefs as possible while still showing
8778  // the function type (and, therefore, its parameter types).
8779  QualType FnType = Cand->Surrogate->getConversionType();
8780  bool isLValueReference = false;
8781  bool isRValueReference = false;
8782  bool isPointer = false;
8783  if (const LValueReferenceType *FnTypeRef =
8784        FnType->getAs<LValueReferenceType>()) {
8785    FnType = FnTypeRef->getPointeeType();
8786    isLValueReference = true;
8787  } else if (const RValueReferenceType *FnTypeRef =
8788               FnType->getAs<RValueReferenceType>()) {
8789    FnType = FnTypeRef->getPointeeType();
8790    isRValueReference = true;
8791  }
8792  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8793    FnType = FnTypePtr->getPointeeType();
8794    isPointer = true;
8795  }
8796  // Desugar down to a function type.
8797  FnType = QualType(FnType->getAs<FunctionType>(), 0);
8798  // Reconstruct the pointer/reference as appropriate.
8799  if (isPointer) FnType = S.Context.getPointerType(FnType);
8800  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8801  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8802
8803  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8804    << FnType;
8805  MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8806}
8807
8808void NoteBuiltinOperatorCandidate(Sema &S,
8809                                  StringRef Opc,
8810                                  SourceLocation OpLoc,
8811                                  OverloadCandidate *Cand) {
8812  assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8813  std::string TypeStr("operator");
8814  TypeStr += Opc;
8815  TypeStr += "(";
8816  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8817  if (Cand->NumConversions == 1) {
8818    TypeStr += ")";
8819    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8820  } else {
8821    TypeStr += ", ";
8822    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8823    TypeStr += ")";
8824    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8825  }
8826}
8827
8828void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8829                                  OverloadCandidate *Cand) {
8830  unsigned NoOperands = Cand->NumConversions;
8831  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8832    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8833    if (ICS.isBad()) break; // all meaningless after first invalid
8834    if (!ICS.isAmbiguous()) continue;
8835
8836    ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8837                              S.PDiag(diag::note_ambiguous_type_conversion));
8838  }
8839}
8840
8841SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8842  if (Cand->Function)
8843    return Cand->Function->getLocation();
8844  if (Cand->IsSurrogate)
8845    return Cand->Surrogate->getLocation();
8846  return SourceLocation();
8847}
8848
8849static unsigned
8850RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
8851  switch ((Sema::TemplateDeductionResult)DFI.Result) {
8852  case Sema::TDK_Success:
8853    llvm_unreachable("TDK_success while diagnosing bad deduction");
8854
8855  case Sema::TDK_Invalid:
8856  case Sema::TDK_Incomplete:
8857    return 1;
8858
8859  case Sema::TDK_Underqualified:
8860  case Sema::TDK_Inconsistent:
8861    return 2;
8862
8863  case Sema::TDK_SubstitutionFailure:
8864  case Sema::TDK_NonDeducedMismatch:
8865  case Sema::TDK_MiscellaneousDeductionFailure:
8866    return 3;
8867
8868  case Sema::TDK_InstantiationDepth:
8869  case Sema::TDK_FailedOverloadResolution:
8870    return 4;
8871
8872  case Sema::TDK_InvalidExplicitArguments:
8873    return 5;
8874
8875  case Sema::TDK_TooManyArguments:
8876  case Sema::TDK_TooFewArguments:
8877    return 6;
8878  }
8879  llvm_unreachable("Unhandled deduction result");
8880}
8881
8882struct CompareOverloadCandidatesForDisplay {
8883  Sema &S;
8884  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8885
8886  bool operator()(const OverloadCandidate *L,
8887                  const OverloadCandidate *R) {
8888    // Fast-path this check.
8889    if (L == R) return false;
8890
8891    // Order first by viability.
8892    if (L->Viable) {
8893      if (!R->Viable) return true;
8894
8895      // TODO: introduce a tri-valued comparison for overload
8896      // candidates.  Would be more worthwhile if we had a sort
8897      // that could exploit it.
8898      if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8899      if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8900    } else if (R->Viable)
8901      return false;
8902
8903    assert(L->Viable == R->Viable);
8904
8905    // Criteria by which we can sort non-viable candidates:
8906    if (!L->Viable) {
8907      // 1. Arity mismatches come after other candidates.
8908      if (L->FailureKind == ovl_fail_too_many_arguments ||
8909          L->FailureKind == ovl_fail_too_few_arguments)
8910        return false;
8911      if (R->FailureKind == ovl_fail_too_many_arguments ||
8912          R->FailureKind == ovl_fail_too_few_arguments)
8913        return true;
8914
8915      // 2. Bad conversions come first and are ordered by the number
8916      // of bad conversions and quality of good conversions.
8917      if (L->FailureKind == ovl_fail_bad_conversion) {
8918        if (R->FailureKind != ovl_fail_bad_conversion)
8919          return true;
8920
8921        // The conversion that can be fixed with a smaller number of changes,
8922        // comes first.
8923        unsigned numLFixes = L->Fix.NumConversionsFixed;
8924        unsigned numRFixes = R->Fix.NumConversionsFixed;
8925        numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8926        numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8927        if (numLFixes != numRFixes) {
8928          if (numLFixes < numRFixes)
8929            return true;
8930          else
8931            return false;
8932        }
8933
8934        // If there's any ordering between the defined conversions...
8935        // FIXME: this might not be transitive.
8936        assert(L->NumConversions == R->NumConversions);
8937
8938        int leftBetter = 0;
8939        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8940        for (unsigned E = L->NumConversions; I != E; ++I) {
8941          switch (CompareImplicitConversionSequences(S,
8942                                                     L->Conversions[I],
8943                                                     R->Conversions[I])) {
8944          case ImplicitConversionSequence::Better:
8945            leftBetter++;
8946            break;
8947
8948          case ImplicitConversionSequence::Worse:
8949            leftBetter--;
8950            break;
8951
8952          case ImplicitConversionSequence::Indistinguishable:
8953            break;
8954          }
8955        }
8956        if (leftBetter > 0) return true;
8957        if (leftBetter < 0) return false;
8958
8959      } else if (R->FailureKind == ovl_fail_bad_conversion)
8960        return false;
8961
8962      if (L->FailureKind == ovl_fail_bad_deduction) {
8963        if (R->FailureKind != ovl_fail_bad_deduction)
8964          return true;
8965
8966        if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8967          return RankDeductionFailure(L->DeductionFailure)
8968               < RankDeductionFailure(R->DeductionFailure);
8969      } else if (R->FailureKind == ovl_fail_bad_deduction)
8970        return false;
8971
8972      // TODO: others?
8973    }
8974
8975    // Sort everything else by location.
8976    SourceLocation LLoc = GetLocationForCandidate(L);
8977    SourceLocation RLoc = GetLocationForCandidate(R);
8978
8979    // Put candidates without locations (e.g. builtins) at the end.
8980    if (LLoc.isInvalid()) return false;
8981    if (RLoc.isInvalid()) return true;
8982
8983    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8984  }
8985};
8986
8987/// CompleteNonViableCandidate - Normally, overload resolution only
8988/// computes up to the first. Produces the FixIt set if possible.
8989void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8990                                ArrayRef<Expr *> Args) {
8991  assert(!Cand->Viable);
8992
8993  // Don't do anything on failures other than bad conversion.
8994  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8995
8996  // We only want the FixIts if all the arguments can be corrected.
8997  bool Unfixable = false;
8998  // Use a implicit copy initialization to check conversion fixes.
8999  Cand->Fix.setConversionChecker(TryCopyInitialization);
9000
9001  // Skip forward to the first bad conversion.
9002  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9003  unsigned ConvCount = Cand->NumConversions;
9004  while (true) {
9005    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9006    ConvIdx++;
9007    if (Cand->Conversions[ConvIdx - 1].isBad()) {
9008      Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9009      break;
9010    }
9011  }
9012
9013  if (ConvIdx == ConvCount)
9014    return;
9015
9016  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9017         "remaining conversion is initialized?");
9018
9019  // FIXME: this should probably be preserved from the overload
9020  // operation somehow.
9021  bool SuppressUserConversions = false;
9022
9023  const FunctionProtoType* Proto;
9024  unsigned ArgIdx = ConvIdx;
9025
9026  if (Cand->IsSurrogate) {
9027    QualType ConvType
9028      = Cand->Surrogate->getConversionType().getNonReferenceType();
9029    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9030      ConvType = ConvPtrType->getPointeeType();
9031    Proto = ConvType->getAs<FunctionProtoType>();
9032    ArgIdx--;
9033  } else if (Cand->Function) {
9034    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9035    if (isa<CXXMethodDecl>(Cand->Function) &&
9036        !isa<CXXConstructorDecl>(Cand->Function))
9037      ArgIdx--;
9038  } else {
9039    // Builtin binary operator with a bad first conversion.
9040    assert(ConvCount <= 3);
9041    for (; ConvIdx != ConvCount; ++ConvIdx)
9042      Cand->Conversions[ConvIdx]
9043        = TryCopyInitialization(S, Args[ConvIdx],
9044                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
9045                                SuppressUserConversions,
9046                                /*InOverloadResolution*/ true,
9047                                /*AllowObjCWritebackConversion=*/
9048                                  S.getLangOpts().ObjCAutoRefCount);
9049    return;
9050  }
9051
9052  // Fill in the rest of the conversions.
9053  unsigned NumArgsInProto = Proto->getNumArgs();
9054  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9055    if (ArgIdx < NumArgsInProto) {
9056      Cand->Conversions[ConvIdx]
9057        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
9058                                SuppressUserConversions,
9059                                /*InOverloadResolution=*/true,
9060                                /*AllowObjCWritebackConversion=*/
9061                                  S.getLangOpts().ObjCAutoRefCount);
9062      // Store the FixIt in the candidate if it exists.
9063      if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9064        Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9065    }
9066    else
9067      Cand->Conversions[ConvIdx].setEllipsis();
9068  }
9069}
9070
9071} // end anonymous namespace
9072
9073/// PrintOverloadCandidates - When overload resolution fails, prints
9074/// diagnostic messages containing the candidates in the candidate
9075/// set.
9076void OverloadCandidateSet::NoteCandidates(Sema &S,
9077                                          OverloadCandidateDisplayKind OCD,
9078                                          ArrayRef<Expr *> Args,
9079                                          StringRef Opc,
9080                                          SourceLocation OpLoc) {
9081  // Sort the candidates by viability and position.  Sorting directly would
9082  // be prohibitive, so we make a set of pointers and sort those.
9083  SmallVector<OverloadCandidate*, 32> Cands;
9084  if (OCD == OCD_AllCandidates) Cands.reserve(size());
9085  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9086    if (Cand->Viable)
9087      Cands.push_back(Cand);
9088    else if (OCD == OCD_AllCandidates) {
9089      CompleteNonViableCandidate(S, Cand, Args);
9090      if (Cand->Function || Cand->IsSurrogate)
9091        Cands.push_back(Cand);
9092      // Otherwise, this a non-viable builtin candidate.  We do not, in general,
9093      // want to list every possible builtin candidate.
9094    }
9095  }
9096
9097  std::sort(Cands.begin(), Cands.end(),
9098            CompareOverloadCandidatesForDisplay(S));
9099
9100  bool ReportedAmbiguousConversions = false;
9101
9102  SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9103  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9104  unsigned CandsShown = 0;
9105  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9106    OverloadCandidate *Cand = *I;
9107
9108    // Set an arbitrary limit on the number of candidate functions we'll spam
9109    // the user with.  FIXME: This limit should depend on details of the
9110    // candidate list.
9111    if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9112      break;
9113    }
9114    ++CandsShown;
9115
9116    if (Cand->Function)
9117      NoteFunctionCandidate(S, Cand, Args.size());
9118    else if (Cand->IsSurrogate)
9119      NoteSurrogateCandidate(S, Cand);
9120    else {
9121      assert(Cand->Viable &&
9122             "Non-viable built-in candidates are not added to Cands.");
9123      // Generally we only see ambiguities including viable builtin
9124      // operators if overload resolution got screwed up by an
9125      // ambiguous user-defined conversion.
9126      //
9127      // FIXME: It's quite possible for different conversions to see
9128      // different ambiguities, though.
9129      if (!ReportedAmbiguousConversions) {
9130        NoteAmbiguousUserConversions(S, OpLoc, Cand);
9131        ReportedAmbiguousConversions = true;
9132      }
9133
9134      // If this is a viable builtin, print it.
9135      NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9136    }
9137  }
9138
9139  if (I != E)
9140    S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9141}
9142
9143// [PossiblyAFunctionType]  -->   [Return]
9144// NonFunctionType --> NonFunctionType
9145// R (A) --> R(A)
9146// R (*)(A) --> R (A)
9147// R (&)(A) --> R (A)
9148// R (S::*)(A) --> R (A)
9149QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9150  QualType Ret = PossiblyAFunctionType;
9151  if (const PointerType *ToTypePtr =
9152    PossiblyAFunctionType->getAs<PointerType>())
9153    Ret = ToTypePtr->getPointeeType();
9154  else if (const ReferenceType *ToTypeRef =
9155    PossiblyAFunctionType->getAs<ReferenceType>())
9156    Ret = ToTypeRef->getPointeeType();
9157  else if (const MemberPointerType *MemTypePtr =
9158    PossiblyAFunctionType->getAs<MemberPointerType>())
9159    Ret = MemTypePtr->getPointeeType();
9160  Ret =
9161    Context.getCanonicalType(Ret).getUnqualifiedType();
9162  return Ret;
9163}
9164
9165// A helper class to help with address of function resolution
9166// - allows us to avoid passing around all those ugly parameters
9167class AddressOfFunctionResolver
9168{
9169  Sema& S;
9170  Expr* SourceExpr;
9171  const QualType& TargetType;
9172  QualType TargetFunctionType; // Extracted function type from target type
9173
9174  bool Complain;
9175  //DeclAccessPair& ResultFunctionAccessPair;
9176  ASTContext& Context;
9177
9178  bool TargetTypeIsNonStaticMemberFunction;
9179  bool FoundNonTemplateFunction;
9180
9181  OverloadExpr::FindResult OvlExprInfo;
9182  OverloadExpr *OvlExpr;
9183  TemplateArgumentListInfo OvlExplicitTemplateArgs;
9184  SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9185
9186public:
9187  AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
9188                            const QualType& TargetType, bool Complain)
9189    : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9190      Complain(Complain), Context(S.getASTContext()),
9191      TargetTypeIsNonStaticMemberFunction(
9192                                    !!TargetType->getAs<MemberPointerType>()),
9193      FoundNonTemplateFunction(false),
9194      OvlExprInfo(OverloadExpr::find(SourceExpr)),
9195      OvlExpr(OvlExprInfo.Expression)
9196  {
9197    ExtractUnqualifiedFunctionTypeFromTargetType();
9198
9199    if (!TargetFunctionType->isFunctionType()) {
9200      if (OvlExpr->hasExplicitTemplateArgs()) {
9201        DeclAccessPair dap;
9202        if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
9203                                            OvlExpr, false, &dap) ) {
9204
9205          if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9206            if (!Method->isStatic()) {
9207              // If the target type is a non-function type and the function
9208              // found is a non-static member function, pretend as if that was
9209              // the target, it's the only possible type to end up with.
9210              TargetTypeIsNonStaticMemberFunction = true;
9211
9212              // And skip adding the function if its not in the proper form.
9213              // We'll diagnose this due to an empty set of functions.
9214              if (!OvlExprInfo.HasFormOfMemberPointer)
9215                return;
9216            }
9217          }
9218
9219          Matches.push_back(std::make_pair(dap,Fn));
9220        }
9221      }
9222      return;
9223    }
9224
9225    if (OvlExpr->hasExplicitTemplateArgs())
9226      OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9227
9228    if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9229      // C++ [over.over]p4:
9230      //   If more than one function is selected, [...]
9231      if (Matches.size() > 1) {
9232        if (FoundNonTemplateFunction)
9233          EliminateAllTemplateMatches();
9234        else
9235          EliminateAllExceptMostSpecializedTemplate();
9236      }
9237    }
9238  }
9239
9240private:
9241  bool isTargetTypeAFunction() const {
9242    return TargetFunctionType->isFunctionType();
9243  }
9244
9245  // [ToType]     [Return]
9246
9247  // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9248  // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9249  // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9250  void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9251    TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9252  }
9253
9254  // return true if any matching specializations were found
9255  bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9256                                   const DeclAccessPair& CurAccessFunPair) {
9257    if (CXXMethodDecl *Method
9258              = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9259      // Skip non-static function templates when converting to pointer, and
9260      // static when converting to member pointer.
9261      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9262        return false;
9263    }
9264    else if (TargetTypeIsNonStaticMemberFunction)
9265      return false;
9266
9267    // C++ [over.over]p2:
9268    //   If the name is a function template, template argument deduction is
9269    //   done (14.8.2.2), and if the argument deduction succeeds, the
9270    //   resulting template argument list is used to generate a single
9271    //   function template specialization, which is added to the set of
9272    //   overloaded functions considered.
9273    FunctionDecl *Specialization = 0;
9274    TemplateDeductionInfo Info(OvlExpr->getNameLoc());
9275    if (Sema::TemplateDeductionResult Result
9276          = S.DeduceTemplateArguments(FunctionTemplate,
9277                                      &OvlExplicitTemplateArgs,
9278                                      TargetFunctionType, Specialization,
9279                                      Info, /*InOverloadResolution=*/true)) {
9280      // FIXME: make a note of the failed deduction for diagnostics.
9281      (void)Result;
9282      return false;
9283    }
9284
9285    // Template argument deduction ensures that we have an exact match or
9286    // compatible pointer-to-function arguments that would be adjusted by ICS.
9287    // This function template specicalization works.
9288    Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9289    assert(S.isSameOrCompatibleFunctionType(
9290              Context.getCanonicalType(Specialization->getType()),
9291              Context.getCanonicalType(TargetFunctionType)));
9292    Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9293    return true;
9294  }
9295
9296  bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9297                                      const DeclAccessPair& CurAccessFunPair) {
9298    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9299      // Skip non-static functions when converting to pointer, and static
9300      // when converting to member pointer.
9301      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9302        return false;
9303    }
9304    else if (TargetTypeIsNonStaticMemberFunction)
9305      return false;
9306
9307    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9308      if (S.getLangOpts().CUDA)
9309        if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9310          if (S.CheckCUDATarget(Caller, FunDecl))
9311            return false;
9312
9313      // If any candidate has a placeholder return type, trigger its deduction
9314      // now.
9315      if (S.getLangOpts().CPlusPlus1y &&
9316          FunDecl->getResultType()->isUndeducedType() &&
9317          S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9318        return false;
9319
9320      QualType ResultTy;
9321      if (Context.hasSameUnqualifiedType(TargetFunctionType,
9322                                         FunDecl->getType()) ||
9323          S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9324                                 ResultTy)) {
9325        Matches.push_back(std::make_pair(CurAccessFunPair,
9326          cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9327        FoundNonTemplateFunction = true;
9328        return true;
9329      }
9330    }
9331
9332    return false;
9333  }
9334
9335  bool FindAllFunctionsThatMatchTargetTypeExactly() {
9336    bool Ret = false;
9337
9338    // If the overload expression doesn't have the form of a pointer to
9339    // member, don't try to convert it to a pointer-to-member type.
9340    if (IsInvalidFormOfPointerToMemberFunction())
9341      return false;
9342
9343    for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9344                               E = OvlExpr->decls_end();
9345         I != E; ++I) {
9346      // Look through any using declarations to find the underlying function.
9347      NamedDecl *Fn = (*I)->getUnderlyingDecl();
9348
9349      // C++ [over.over]p3:
9350      //   Non-member functions and static member functions match
9351      //   targets of type "pointer-to-function" or "reference-to-function."
9352      //   Nonstatic member functions match targets of
9353      //   type "pointer-to-member-function."
9354      // Note that according to DR 247, the containing class does not matter.
9355      if (FunctionTemplateDecl *FunctionTemplate
9356                                        = dyn_cast<FunctionTemplateDecl>(Fn)) {
9357        if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9358          Ret = true;
9359      }
9360      // If we have explicit template arguments supplied, skip non-templates.
9361      else if (!OvlExpr->hasExplicitTemplateArgs() &&
9362               AddMatchingNonTemplateFunction(Fn, I.getPair()))
9363        Ret = true;
9364    }
9365    assert(Ret || Matches.empty());
9366    return Ret;
9367  }
9368
9369  void EliminateAllExceptMostSpecializedTemplate() {
9370    //   [...] and any given function template specialization F1 is
9371    //   eliminated if the set contains a second function template
9372    //   specialization whose function template is more specialized
9373    //   than the function template of F1 according to the partial
9374    //   ordering rules of 14.5.5.2.
9375
9376    // The algorithm specified above is quadratic. We instead use a
9377    // two-pass algorithm (similar to the one used to identify the
9378    // best viable function in an overload set) that identifies the
9379    // best function template (if it exists).
9380
9381    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9382    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9383      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9384
9385    UnresolvedSetIterator Result =
9386      S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9387                           TPOC_Other, 0, SourceExpr->getLocStart(),
9388                           S.PDiag(),
9389                           S.PDiag(diag::err_addr_ovl_ambiguous)
9390                             << Matches[0].second->getDeclName(),
9391                           S.PDiag(diag::note_ovl_candidate)
9392                             << (unsigned) oc_function_template,
9393                           Complain, TargetFunctionType);
9394
9395    if (Result != MatchesCopy.end()) {
9396      // Make it the first and only element
9397      Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9398      Matches[0].second = cast<FunctionDecl>(*Result);
9399      Matches.resize(1);
9400    }
9401  }
9402
9403  void EliminateAllTemplateMatches() {
9404    //   [...] any function template specializations in the set are
9405    //   eliminated if the set also contains a non-template function, [...]
9406    for (unsigned I = 0, N = Matches.size(); I != N; ) {
9407      if (Matches[I].second->getPrimaryTemplate() == 0)
9408        ++I;
9409      else {
9410        Matches[I] = Matches[--N];
9411        Matches.set_size(N);
9412      }
9413    }
9414  }
9415
9416public:
9417  void ComplainNoMatchesFound() const {
9418    assert(Matches.empty());
9419    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9420        << OvlExpr->getName() << TargetFunctionType
9421        << OvlExpr->getSourceRange();
9422    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9423  }
9424
9425  bool IsInvalidFormOfPointerToMemberFunction() const {
9426    return TargetTypeIsNonStaticMemberFunction &&
9427      !OvlExprInfo.HasFormOfMemberPointer;
9428  }
9429
9430  void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9431      // TODO: Should we condition this on whether any functions might
9432      // have matched, or is it more appropriate to do that in callers?
9433      // TODO: a fixit wouldn't hurt.
9434      S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9435        << TargetType << OvlExpr->getSourceRange();
9436  }
9437
9438  void ComplainOfInvalidConversion() const {
9439    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9440      << OvlExpr->getName() << TargetType;
9441  }
9442
9443  void ComplainMultipleMatchesFound() const {
9444    assert(Matches.size() > 1);
9445    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9446      << OvlExpr->getName()
9447      << OvlExpr->getSourceRange();
9448    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9449  }
9450
9451  bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9452
9453  int getNumMatches() const { return Matches.size(); }
9454
9455  FunctionDecl* getMatchingFunctionDecl() const {
9456    if (Matches.size() != 1) return 0;
9457    return Matches[0].second;
9458  }
9459
9460  const DeclAccessPair* getMatchingFunctionAccessPair() const {
9461    if (Matches.size() != 1) return 0;
9462    return &Matches[0].first;
9463  }
9464};
9465
9466/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9467/// an overloaded function (C++ [over.over]), where @p From is an
9468/// expression with overloaded function type and @p ToType is the type
9469/// we're trying to resolve to. For example:
9470///
9471/// @code
9472/// int f(double);
9473/// int f(int);
9474///
9475/// int (*pfd)(double) = f; // selects f(double)
9476/// @endcode
9477///
9478/// This routine returns the resulting FunctionDecl if it could be
9479/// resolved, and NULL otherwise. When @p Complain is true, this
9480/// routine will emit diagnostics if there is an error.
9481FunctionDecl *
9482Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9483                                         QualType TargetType,
9484                                         bool Complain,
9485                                         DeclAccessPair &FoundResult,
9486                                         bool *pHadMultipleCandidates) {
9487  assert(AddressOfExpr->getType() == Context.OverloadTy);
9488
9489  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9490                                     Complain);
9491  int NumMatches = Resolver.getNumMatches();
9492  FunctionDecl* Fn = 0;
9493  if (NumMatches == 0 && Complain) {
9494    if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9495      Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9496    else
9497      Resolver.ComplainNoMatchesFound();
9498  }
9499  else if (NumMatches > 1 && Complain)
9500    Resolver.ComplainMultipleMatchesFound();
9501  else if (NumMatches == 1) {
9502    Fn = Resolver.getMatchingFunctionDecl();
9503    assert(Fn);
9504    FoundResult = *Resolver.getMatchingFunctionAccessPair();
9505    if (Complain)
9506      CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9507  }
9508
9509  if (pHadMultipleCandidates)
9510    *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9511  return Fn;
9512}
9513
9514/// \brief Given an expression that refers to an overloaded function, try to
9515/// resolve that overloaded function expression down to a single function.
9516///
9517/// This routine can only resolve template-ids that refer to a single function
9518/// template, where that template-id refers to a single template whose template
9519/// arguments are either provided by the template-id or have defaults,
9520/// as described in C++0x [temp.arg.explicit]p3.
9521FunctionDecl *
9522Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9523                                                  bool Complain,
9524                                                  DeclAccessPair *FoundResult) {
9525  // C++ [over.over]p1:
9526  //   [...] [Note: any redundant set of parentheses surrounding the
9527  //   overloaded function name is ignored (5.1). ]
9528  // C++ [over.over]p1:
9529  //   [...] The overloaded function name can be preceded by the &
9530  //   operator.
9531
9532  // If we didn't actually find any template-ids, we're done.
9533  if (!ovl->hasExplicitTemplateArgs())
9534    return 0;
9535
9536  TemplateArgumentListInfo ExplicitTemplateArgs;
9537  ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9538
9539  // Look through all of the overloaded functions, searching for one
9540  // whose type matches exactly.
9541  FunctionDecl *Matched = 0;
9542  for (UnresolvedSetIterator I = ovl->decls_begin(),
9543         E = ovl->decls_end(); I != E; ++I) {
9544    // C++0x [temp.arg.explicit]p3:
9545    //   [...] In contexts where deduction is done and fails, or in contexts
9546    //   where deduction is not done, if a template argument list is
9547    //   specified and it, along with any default template arguments,
9548    //   identifies a single function template specialization, then the
9549    //   template-id is an lvalue for the function template specialization.
9550    FunctionTemplateDecl *FunctionTemplate
9551      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9552
9553    // C++ [over.over]p2:
9554    //   If the name is a function template, template argument deduction is
9555    //   done (14.8.2.2), and if the argument deduction succeeds, the
9556    //   resulting template argument list is used to generate a single
9557    //   function template specialization, which is added to the set of
9558    //   overloaded functions considered.
9559    FunctionDecl *Specialization = 0;
9560    TemplateDeductionInfo Info(ovl->getNameLoc());
9561    if (TemplateDeductionResult Result
9562          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9563                                    Specialization, Info,
9564                                    /*InOverloadResolution=*/true)) {
9565      // FIXME: make a note of the failed deduction for diagnostics.
9566      (void)Result;
9567      continue;
9568    }
9569
9570    assert(Specialization && "no specialization and no error?");
9571
9572    // Multiple matches; we can't resolve to a single declaration.
9573    if (Matched) {
9574      if (Complain) {
9575        Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9576          << ovl->getName();
9577        NoteAllOverloadCandidates(ovl);
9578      }
9579      return 0;
9580    }
9581
9582    Matched = Specialization;
9583    if (FoundResult) *FoundResult = I.getPair();
9584  }
9585
9586  if (Matched && getLangOpts().CPlusPlus1y &&
9587      Matched->getResultType()->isUndeducedType() &&
9588      DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9589    return 0;
9590
9591  return Matched;
9592}
9593
9594
9595
9596
9597// Resolve and fix an overloaded expression that can be resolved
9598// because it identifies a single function template specialization.
9599//
9600// Last three arguments should only be supplied if Complain = true
9601//
9602// Return true if it was logically possible to so resolve the
9603// expression, regardless of whether or not it succeeded.  Always
9604// returns true if 'complain' is set.
9605bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9606                      ExprResult &SrcExpr, bool doFunctionPointerConverion,
9607                   bool complain, const SourceRange& OpRangeForComplaining,
9608                                           QualType DestTypeForComplaining,
9609                                            unsigned DiagIDForComplaining) {
9610  assert(SrcExpr.get()->getType() == Context.OverloadTy);
9611
9612  OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9613
9614  DeclAccessPair found;
9615  ExprResult SingleFunctionExpression;
9616  if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9617                           ovl.Expression, /*complain*/ false, &found)) {
9618    if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9619      SrcExpr = ExprError();
9620      return true;
9621    }
9622
9623    // It is only correct to resolve to an instance method if we're
9624    // resolving a form that's permitted to be a pointer to member.
9625    // Otherwise we'll end up making a bound member expression, which
9626    // is illegal in all the contexts we resolve like this.
9627    if (!ovl.HasFormOfMemberPointer &&
9628        isa<CXXMethodDecl>(fn) &&
9629        cast<CXXMethodDecl>(fn)->isInstance()) {
9630      if (!complain) return false;
9631
9632      Diag(ovl.Expression->getExprLoc(),
9633           diag::err_bound_member_function)
9634        << 0 << ovl.Expression->getSourceRange();
9635
9636      // TODO: I believe we only end up here if there's a mix of
9637      // static and non-static candidates (otherwise the expression
9638      // would have 'bound member' type, not 'overload' type).
9639      // Ideally we would note which candidate was chosen and why
9640      // the static candidates were rejected.
9641      SrcExpr = ExprError();
9642      return true;
9643    }
9644
9645    // Fix the expression to refer to 'fn'.
9646    SingleFunctionExpression =
9647      Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9648
9649    // If desired, do function-to-pointer decay.
9650    if (doFunctionPointerConverion) {
9651      SingleFunctionExpression =
9652        DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9653      if (SingleFunctionExpression.isInvalid()) {
9654        SrcExpr = ExprError();
9655        return true;
9656      }
9657    }
9658  }
9659
9660  if (!SingleFunctionExpression.isUsable()) {
9661    if (complain) {
9662      Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9663        << ovl.Expression->getName()
9664        << DestTypeForComplaining
9665        << OpRangeForComplaining
9666        << ovl.Expression->getQualifierLoc().getSourceRange();
9667      NoteAllOverloadCandidates(SrcExpr.get());
9668
9669      SrcExpr = ExprError();
9670      return true;
9671    }
9672
9673    return false;
9674  }
9675
9676  SrcExpr = SingleFunctionExpression;
9677  return true;
9678}
9679
9680/// \brief Add a single candidate to the overload set.
9681static void AddOverloadedCallCandidate(Sema &S,
9682                                       DeclAccessPair FoundDecl,
9683                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
9684                                       ArrayRef<Expr *> Args,
9685                                       OverloadCandidateSet &CandidateSet,
9686                                       bool PartialOverloading,
9687                                       bool KnownValid) {
9688  NamedDecl *Callee = FoundDecl.getDecl();
9689  if (isa<UsingShadowDecl>(Callee))
9690    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9691
9692  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9693    if (ExplicitTemplateArgs) {
9694      assert(!KnownValid && "Explicit template arguments?");
9695      return;
9696    }
9697    S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9698                           PartialOverloading);
9699    return;
9700  }
9701
9702  if (FunctionTemplateDecl *FuncTemplate
9703      = dyn_cast<FunctionTemplateDecl>(Callee)) {
9704    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9705                                   ExplicitTemplateArgs, Args, CandidateSet);
9706    return;
9707  }
9708
9709  assert(!KnownValid && "unhandled case in overloaded call candidate");
9710}
9711
9712/// \brief Add the overload candidates named by callee and/or found by argument
9713/// dependent lookup to the given overload set.
9714void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9715                                       ArrayRef<Expr *> Args,
9716                                       OverloadCandidateSet &CandidateSet,
9717                                       bool PartialOverloading) {
9718
9719#ifndef NDEBUG
9720  // Verify that ArgumentDependentLookup is consistent with the rules
9721  // in C++0x [basic.lookup.argdep]p3:
9722  //
9723  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9724  //   and let Y be the lookup set produced by argument dependent
9725  //   lookup (defined as follows). If X contains
9726  //
9727  //     -- a declaration of a class member, or
9728  //
9729  //     -- a block-scope function declaration that is not a
9730  //        using-declaration, or
9731  //
9732  //     -- a declaration that is neither a function or a function
9733  //        template
9734  //
9735  //   then Y is empty.
9736
9737  if (ULE->requiresADL()) {
9738    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9739           E = ULE->decls_end(); I != E; ++I) {
9740      assert(!(*I)->getDeclContext()->isRecord());
9741      assert(isa<UsingShadowDecl>(*I) ||
9742             !(*I)->getDeclContext()->isFunctionOrMethod());
9743      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9744    }
9745  }
9746#endif
9747
9748  // It would be nice to avoid this copy.
9749  TemplateArgumentListInfo TABuffer;
9750  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9751  if (ULE->hasExplicitTemplateArgs()) {
9752    ULE->copyTemplateArgumentsInto(TABuffer);
9753    ExplicitTemplateArgs = &TABuffer;
9754  }
9755
9756  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9757         E = ULE->decls_end(); I != E; ++I)
9758    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9759                               CandidateSet, PartialOverloading,
9760                               /*KnownValid*/ true);
9761
9762  if (ULE->requiresADL())
9763    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9764                                         ULE->getExprLoc(),
9765                                         Args, ExplicitTemplateArgs,
9766                                         CandidateSet, PartialOverloading);
9767}
9768
9769/// Attempt to recover from an ill-formed use of a non-dependent name in a
9770/// template, where the non-dependent name was declared after the template
9771/// was defined. This is common in code written for a compilers which do not
9772/// correctly implement two-stage name lookup.
9773///
9774/// Returns true if a viable candidate was found and a diagnostic was issued.
9775static bool
9776DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9777                       const CXXScopeSpec &SS, LookupResult &R,
9778                       TemplateArgumentListInfo *ExplicitTemplateArgs,
9779                       ArrayRef<Expr *> Args) {
9780  if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9781    return false;
9782
9783  for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9784    if (DC->isTransparentContext())
9785      continue;
9786
9787    SemaRef.LookupQualifiedName(R, DC);
9788
9789    if (!R.empty()) {
9790      R.suppressDiagnostics();
9791
9792      if (isa<CXXRecordDecl>(DC)) {
9793        // Don't diagnose names we find in classes; we get much better
9794        // diagnostics for these from DiagnoseEmptyLookup.
9795        R.clear();
9796        return false;
9797      }
9798
9799      OverloadCandidateSet Candidates(FnLoc);
9800      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9801        AddOverloadedCallCandidate(SemaRef, I.getPair(),
9802                                   ExplicitTemplateArgs, Args,
9803                                   Candidates, false, /*KnownValid*/ false);
9804
9805      OverloadCandidateSet::iterator Best;
9806      if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9807        // No viable functions. Don't bother the user with notes for functions
9808        // which don't work and shouldn't be found anyway.
9809        R.clear();
9810        return false;
9811      }
9812
9813      // Find the namespaces where ADL would have looked, and suggest
9814      // declaring the function there instead.
9815      Sema::AssociatedNamespaceSet AssociatedNamespaces;
9816      Sema::AssociatedClassSet AssociatedClasses;
9817      SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
9818                                                 AssociatedNamespaces,
9819                                                 AssociatedClasses);
9820      Sema::AssociatedNamespaceSet SuggestedNamespaces;
9821      DeclContext *Std = SemaRef.getStdNamespace();
9822      for (Sema::AssociatedNamespaceSet::iterator
9823             it = AssociatedNamespaces.begin(),
9824             end = AssociatedNamespaces.end(); it != end; ++it) {
9825        // Never suggest declaring a function within namespace 'std'.
9826        if (Std && Std->Encloses(*it))
9827          continue;
9828
9829        // Never suggest declaring a function within a namespace with a reserved
9830        // name, like __gnu_cxx.
9831        NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9832        if (NS &&
9833            NS->getQualifiedNameAsString().find("__") != std::string::npos)
9834          continue;
9835
9836        SuggestedNamespaces.insert(*it);
9837      }
9838
9839      SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9840        << R.getLookupName();
9841      if (SuggestedNamespaces.empty()) {
9842        SemaRef.Diag(Best->Function->getLocation(),
9843                     diag::note_not_found_by_two_phase_lookup)
9844          << R.getLookupName() << 0;
9845      } else if (SuggestedNamespaces.size() == 1) {
9846        SemaRef.Diag(Best->Function->getLocation(),
9847                     diag::note_not_found_by_two_phase_lookup)
9848          << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
9849      } else {
9850        // FIXME: It would be useful to list the associated namespaces here,
9851        // but the diagnostics infrastructure doesn't provide a way to produce
9852        // a localized representation of a list of items.
9853        SemaRef.Diag(Best->Function->getLocation(),
9854                     diag::note_not_found_by_two_phase_lookup)
9855          << R.getLookupName() << 2;
9856      }
9857
9858      // Try to recover by calling this function.
9859      return true;
9860    }
9861
9862    R.clear();
9863  }
9864
9865  return false;
9866}
9867
9868/// Attempt to recover from ill-formed use of a non-dependent operator in a
9869/// template, where the non-dependent operator was declared after the template
9870/// was defined.
9871///
9872/// Returns true if a viable candidate was found and a diagnostic was issued.
9873static bool
9874DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9875                               SourceLocation OpLoc,
9876                               ArrayRef<Expr *> Args) {
9877  DeclarationName OpName =
9878    SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9879  LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9880  return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9881                                /*ExplicitTemplateArgs=*/0, Args);
9882}
9883
9884namespace {
9885// Callback to limit the allowed keywords and to only accept typo corrections
9886// that are keywords or whose decls refer to functions (or template functions)
9887// that accept the given number of arguments.
9888class RecoveryCallCCC : public CorrectionCandidateCallback {
9889 public:
9890  RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9891      : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9892    WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
9893    WantRemainingKeywords = false;
9894  }
9895
9896  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9897    if (!candidate.getCorrectionDecl())
9898      return candidate.isKeyword();
9899
9900    for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9901           DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9902      FunctionDecl *FD = 0;
9903      NamedDecl *ND = (*DI)->getUnderlyingDecl();
9904      if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9905        FD = FTD->getTemplatedDecl();
9906      if (!HasExplicitTemplateArgs && !FD) {
9907        if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9908          // If the Decl is neither a function nor a template function,
9909          // determine if it is a pointer or reference to a function. If so,
9910          // check against the number of arguments expected for the pointee.
9911          QualType ValType = cast<ValueDecl>(ND)->getType();
9912          if (ValType->isAnyPointerType() || ValType->isReferenceType())
9913            ValType = ValType->getPointeeType();
9914          if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9915            if (FPT->getNumArgs() == NumArgs)
9916              return true;
9917        }
9918      }
9919      if (FD && FD->getNumParams() >= NumArgs &&
9920          FD->getMinRequiredArguments() <= NumArgs)
9921        return true;
9922    }
9923    return false;
9924  }
9925
9926 private:
9927  unsigned NumArgs;
9928  bool HasExplicitTemplateArgs;
9929};
9930
9931// Callback that effectively disabled typo correction
9932class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9933 public:
9934  NoTypoCorrectionCCC() {
9935    WantTypeSpecifiers = false;
9936    WantExpressionKeywords = false;
9937    WantCXXNamedCasts = false;
9938    WantRemainingKeywords = false;
9939  }
9940
9941  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9942    return false;
9943  }
9944};
9945
9946class BuildRecoveryCallExprRAII {
9947  Sema &SemaRef;
9948public:
9949  BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9950    assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9951    SemaRef.IsBuildingRecoveryCallExpr = true;
9952  }
9953
9954  ~BuildRecoveryCallExprRAII() {
9955    SemaRef.IsBuildingRecoveryCallExpr = false;
9956  }
9957};
9958
9959}
9960
9961/// Attempts to recover from a call where no functions were found.
9962///
9963/// Returns true if new candidates were found.
9964static ExprResult
9965BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9966                      UnresolvedLookupExpr *ULE,
9967                      SourceLocation LParenLoc,
9968                      llvm::MutableArrayRef<Expr *> Args,
9969                      SourceLocation RParenLoc,
9970                      bool EmptyLookup, bool AllowTypoCorrection) {
9971  // Do not try to recover if it is already building a recovery call.
9972  // This stops infinite loops for template instantiations like
9973  //
9974  // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9975  // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9976  //
9977  if (SemaRef.IsBuildingRecoveryCallExpr)
9978    return ExprError();
9979  BuildRecoveryCallExprRAII RCE(SemaRef);
9980
9981  CXXScopeSpec SS;
9982  SS.Adopt(ULE->getQualifierLoc());
9983  SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
9984
9985  TemplateArgumentListInfo TABuffer;
9986  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9987  if (ULE->hasExplicitTemplateArgs()) {
9988    ULE->copyTemplateArgumentsInto(TABuffer);
9989    ExplicitTemplateArgs = &TABuffer;
9990  }
9991
9992  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9993                 Sema::LookupOrdinaryName);
9994  RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
9995  NoTypoCorrectionCCC RejectAll;
9996  CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9997      (CorrectionCandidateCallback*)&Validator :
9998      (CorrectionCandidateCallback*)&RejectAll;
9999  if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10000                              ExplicitTemplateArgs, Args) &&
10001      (!EmptyLookup ||
10002       SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
10003                                   ExplicitTemplateArgs, Args)))
10004    return ExprError();
10005
10006  assert(!R.empty() && "lookup results empty despite recovery");
10007
10008  // Build an implicit member call if appropriate.  Just drop the
10009  // casts and such from the call, we don't really care.
10010  ExprResult NewFn = ExprError();
10011  if ((*R.begin())->isCXXClassMember())
10012    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10013                                                    R, ExplicitTemplateArgs);
10014  else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10015    NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10016                                        ExplicitTemplateArgs);
10017  else
10018    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10019
10020  if (NewFn.isInvalid())
10021    return ExprError();
10022
10023  // This shouldn't cause an infinite loop because we're giving it
10024  // an expression with viable lookup results, which should never
10025  // end up here.
10026  return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
10027                               MultiExprArg(Args.data(), Args.size()),
10028                               RParenLoc);
10029}
10030
10031/// \brief Constructs and populates an OverloadedCandidateSet from
10032/// the given function.
10033/// \returns true when an the ExprResult output parameter has been set.
10034bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10035                                  UnresolvedLookupExpr *ULE,
10036                                  MultiExprArg Args,
10037                                  SourceLocation RParenLoc,
10038                                  OverloadCandidateSet *CandidateSet,
10039                                  ExprResult *Result) {
10040#ifndef NDEBUG
10041  if (ULE->requiresADL()) {
10042    // To do ADL, we must have found an unqualified name.
10043    assert(!ULE->getQualifier() && "qualified name with ADL");
10044
10045    // We don't perform ADL for implicit declarations of builtins.
10046    // Verify that this was correctly set up.
10047    FunctionDecl *F;
10048    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10049        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10050        F->getBuiltinID() && F->isImplicit())
10051      llvm_unreachable("performing ADL for builtin");
10052
10053    // We don't perform ADL in C.
10054    assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10055  }
10056#endif
10057
10058  UnbridgedCastsSet UnbridgedCasts;
10059  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10060    *Result = ExprError();
10061    return true;
10062  }
10063
10064  // Add the functions denoted by the callee to the set of candidate
10065  // functions, including those from argument-dependent lookup.
10066  AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10067
10068  // If we found nothing, try to recover.
10069  // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10070  // out if it fails.
10071  if (CandidateSet->empty()) {
10072    // In Microsoft mode, if we are inside a template class member function then
10073    // create a type dependent CallExpr. The goal is to postpone name lookup
10074    // to instantiation time to be able to search into type dependent base
10075    // classes.
10076    if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
10077        (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10078      CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10079                                            Context.DependentTy, VK_RValue,
10080                                            RParenLoc);
10081      CE->setTypeDependent(true);
10082      *Result = Owned(CE);
10083      return true;
10084    }
10085    return false;
10086  }
10087
10088  UnbridgedCasts.restore();
10089  return false;
10090}
10091
10092/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10093/// the completed call expression. If overload resolution fails, emits
10094/// diagnostics and returns ExprError()
10095static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10096                                           UnresolvedLookupExpr *ULE,
10097                                           SourceLocation LParenLoc,
10098                                           MultiExprArg Args,
10099                                           SourceLocation RParenLoc,
10100                                           Expr *ExecConfig,
10101                                           OverloadCandidateSet *CandidateSet,
10102                                           OverloadCandidateSet::iterator *Best,
10103                                           OverloadingResult OverloadResult,
10104                                           bool AllowTypoCorrection) {
10105  if (CandidateSet->empty())
10106    return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10107                                 RParenLoc, /*EmptyLookup=*/true,
10108                                 AllowTypoCorrection);
10109
10110  switch (OverloadResult) {
10111  case OR_Success: {
10112    FunctionDecl *FDecl = (*Best)->Function;
10113    SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10114    if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10115      return ExprError();
10116    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10117    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10118                                         ExecConfig);
10119  }
10120
10121  case OR_No_Viable_Function: {
10122    // Try to recover by looking for viable functions which the user might
10123    // have meant to call.
10124    ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10125                                                Args, RParenLoc,
10126                                                /*EmptyLookup=*/false,
10127                                                AllowTypoCorrection);
10128    if (!Recovery.isInvalid())
10129      return Recovery;
10130
10131    SemaRef.Diag(Fn->getLocStart(),
10132         diag::err_ovl_no_viable_function_in_call)
10133      << ULE->getName() << Fn->getSourceRange();
10134    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10135    break;
10136  }
10137
10138  case OR_Ambiguous:
10139    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10140      << ULE->getName() << Fn->getSourceRange();
10141    CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10142    break;
10143
10144  case OR_Deleted: {
10145    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10146      << (*Best)->Function->isDeleted()
10147      << ULE->getName()
10148      << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10149      << Fn->getSourceRange();
10150    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10151
10152    // We emitted an error for the unvailable/deleted function call but keep
10153    // the call in the AST.
10154    FunctionDecl *FDecl = (*Best)->Function;
10155    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10156    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10157                                         ExecConfig);
10158  }
10159  }
10160
10161  // Overload resolution failed.
10162  return ExprError();
10163}
10164
10165/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10166/// (which eventually refers to the declaration Func) and the call
10167/// arguments Args/NumArgs, attempt to resolve the function call down
10168/// to a specific function. If overload resolution succeeds, returns
10169/// the call expression produced by overload resolution.
10170/// Otherwise, emits diagnostics and returns ExprError.
10171ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10172                                         UnresolvedLookupExpr *ULE,
10173                                         SourceLocation LParenLoc,
10174                                         MultiExprArg Args,
10175                                         SourceLocation RParenLoc,
10176                                         Expr *ExecConfig,
10177                                         bool AllowTypoCorrection) {
10178  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10179  ExprResult result;
10180
10181  if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10182                             &result))
10183    return result;
10184
10185  OverloadCandidateSet::iterator Best;
10186  OverloadingResult OverloadResult =
10187      CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10188
10189  return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10190                                  RParenLoc, ExecConfig, &CandidateSet,
10191                                  &Best, OverloadResult,
10192                                  AllowTypoCorrection);
10193}
10194
10195static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10196  return Functions.size() > 1 ||
10197    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10198}
10199
10200/// \brief Create a unary operation that may resolve to an overloaded
10201/// operator.
10202///
10203/// \param OpLoc The location of the operator itself (e.g., '*').
10204///
10205/// \param OpcIn The UnaryOperator::Opcode that describes this
10206/// operator.
10207///
10208/// \param Fns The set of non-member functions that will be
10209/// considered by overload resolution. The caller needs to build this
10210/// set based on the context using, e.g.,
10211/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10212/// set should not contain any member functions; those will be added
10213/// by CreateOverloadedUnaryOp().
10214///
10215/// \param Input The input argument.
10216ExprResult
10217Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10218                              const UnresolvedSetImpl &Fns,
10219                              Expr *Input) {
10220  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10221
10222  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10223  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10224  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10225  // TODO: provide better source location info.
10226  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10227
10228  if (checkPlaceholderForOverload(*this, Input))
10229    return ExprError();
10230
10231  Expr *Args[2] = { Input, 0 };
10232  unsigned NumArgs = 1;
10233
10234  // For post-increment and post-decrement, add the implicit '0' as
10235  // the second argument, so that we know this is a post-increment or
10236  // post-decrement.
10237  if (Opc == UO_PostInc || Opc == UO_PostDec) {
10238    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10239    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10240                                     SourceLocation());
10241    NumArgs = 2;
10242  }
10243
10244  ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10245
10246  if (Input->isTypeDependent()) {
10247    if (Fns.empty())
10248      return Owned(new (Context) UnaryOperator(Input,
10249                                               Opc,
10250                                               Context.DependentTy,
10251                                               VK_RValue, OK_Ordinary,
10252                                               OpLoc));
10253
10254    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
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, ArgsArray,
10261                                                   Context.DependentTy,
10262                                                   VK_RValue,
10263                                                   OpLoc, false));
10264  }
10265
10266  // Build an empty overload set.
10267  OverloadCandidateSet CandidateSet(OpLoc);
10268
10269  // Add the candidates from the given function set.
10270  AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
10271
10272  // Add operator candidates that are member functions.
10273  AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10274
10275  // Add candidates from ADL.
10276  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10277                                       ArgsArray, /*ExplicitTemplateArgs*/ 0,
10278                                       CandidateSet);
10279
10280  // Add builtin operator candidates.
10281  AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10282
10283  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10284
10285  // Perform overload resolution.
10286  OverloadCandidateSet::iterator Best;
10287  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10288  case OR_Success: {
10289    // We found a built-in operator or an overloaded operator.
10290    FunctionDecl *FnDecl = Best->Function;
10291
10292    if (FnDecl) {
10293      // We matched an overloaded operator. Build a call to that
10294      // operator.
10295
10296      // Convert the arguments.
10297      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10298        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
10299
10300        ExprResult InputRes =
10301          PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10302                                              Best->FoundDecl, Method);
10303        if (InputRes.isInvalid())
10304          return ExprError();
10305        Input = InputRes.take();
10306      } else {
10307        // Convert the arguments.
10308        ExprResult InputInit
10309          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10310                                                      Context,
10311                                                      FnDecl->getParamDecl(0)),
10312                                      SourceLocation(),
10313                                      Input);
10314        if (InputInit.isInvalid())
10315          return ExprError();
10316        Input = InputInit.take();
10317      }
10318
10319      // Determine the result type.
10320      QualType ResultTy = FnDecl->getResultType();
10321      ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10322      ResultTy = ResultTy.getNonLValueExprType(Context);
10323
10324      // Build the actual expression node.
10325      ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10326                                                HadMultipleCandidates, OpLoc);
10327      if (FnExpr.isInvalid())
10328        return ExprError();
10329
10330      Args[0] = Input;
10331      CallExpr *TheCall =
10332        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
10333                                          ResultTy, VK, OpLoc, false);
10334
10335      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10336                              FnDecl))
10337        return ExprError();
10338
10339      return MaybeBindToTemporary(TheCall);
10340    } else {
10341      // We matched a built-in operator. Convert the arguments, then
10342      // break out so that we will build the appropriate built-in
10343      // operator node.
10344      ExprResult InputRes =
10345        PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10346                                  Best->Conversions[0], AA_Passing);
10347      if (InputRes.isInvalid())
10348        return ExprError();
10349      Input = InputRes.take();
10350      break;
10351    }
10352  }
10353
10354  case OR_No_Viable_Function:
10355    // This is an erroneous use of an operator which can be overloaded by
10356    // a non-member function. Check for non-member operators which were
10357    // defined too late to be candidates.
10358    if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
10359      // FIXME: Recover by calling the found function.
10360      return ExprError();
10361
10362    // No viable function; fall through to handling this as a
10363    // built-in operator, which will produce an error message for us.
10364    break;
10365
10366  case OR_Ambiguous:
10367    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10368        << UnaryOperator::getOpcodeStr(Opc)
10369        << Input->getType()
10370        << Input->getSourceRange();
10371    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
10372                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10373    return ExprError();
10374
10375  case OR_Deleted:
10376    Diag(OpLoc, diag::err_ovl_deleted_oper)
10377      << Best->Function->isDeleted()
10378      << UnaryOperator::getOpcodeStr(Opc)
10379      << getDeletedOrUnavailableSuffix(Best->Function)
10380      << Input->getSourceRange();
10381    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
10382                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10383    return ExprError();
10384  }
10385
10386  // Either we found no viable overloaded operator or we matched a
10387  // built-in operator. In either case, fall through to trying to
10388  // build a built-in operation.
10389  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10390}
10391
10392/// \brief Create a binary operation that may resolve to an overloaded
10393/// operator.
10394///
10395/// \param OpLoc The location of the operator itself (e.g., '+').
10396///
10397/// \param OpcIn The BinaryOperator::Opcode that describes this
10398/// operator.
10399///
10400/// \param Fns The set of non-member functions that will be
10401/// considered by overload resolution. The caller needs to build this
10402/// set based on the context using, e.g.,
10403/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10404/// set should not contain any member functions; those will be added
10405/// by CreateOverloadedBinOp().
10406///
10407/// \param LHS Left-hand argument.
10408/// \param RHS Right-hand argument.
10409ExprResult
10410Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10411                            unsigned OpcIn,
10412                            const UnresolvedSetImpl &Fns,
10413                            Expr *LHS, Expr *RHS) {
10414  Expr *Args[2] = { LHS, RHS };
10415  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
10416
10417  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10418  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10419  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10420
10421  // If either side is type-dependent, create an appropriate dependent
10422  // expression.
10423  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10424    if (Fns.empty()) {
10425      // If there are no functions to store, just build a dependent
10426      // BinaryOperator or CompoundAssignment.
10427      if (Opc <= BO_Assign || Opc > BO_OrAssign)
10428        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
10429                                                  Context.DependentTy,
10430                                                  VK_RValue, OK_Ordinary,
10431                                                  OpLoc,
10432                                                  FPFeatures.fp_contract));
10433
10434      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10435                                                        Context.DependentTy,
10436                                                        VK_LValue,
10437                                                        OK_Ordinary,
10438                                                        Context.DependentTy,
10439                                                        Context.DependentTy,
10440                                                        OpLoc,
10441                                                        FPFeatures.fp_contract));
10442    }
10443
10444    // FIXME: save results of ADL from here?
10445    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10446    // TODO: provide better source location info in DNLoc component.
10447    DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10448    UnresolvedLookupExpr *Fn
10449      = UnresolvedLookupExpr::Create(Context, NamingClass,
10450                                     NestedNameSpecifierLoc(), OpNameInfo,
10451                                     /*ADL*/ true, IsOverloaded(Fns),
10452                                     Fns.begin(), Fns.end());
10453    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10454                                                Context.DependentTy, VK_RValue,
10455                                                OpLoc, FPFeatures.fp_contract));
10456  }
10457
10458  // Always do placeholder-like conversions on the RHS.
10459  if (checkPlaceholderForOverload(*this, Args[1]))
10460    return ExprError();
10461
10462  // Do placeholder-like conversion on the LHS; note that we should
10463  // not get here with a PseudoObject LHS.
10464  assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10465  if (checkPlaceholderForOverload(*this, Args[0]))
10466    return ExprError();
10467
10468  // If this is the assignment operator, we only perform overload resolution
10469  // if the left-hand side is a class or enumeration type. This is actually
10470  // a hack. The standard requires that we do overload resolution between the
10471  // various built-in candidates, but as DR507 points out, this can lead to
10472  // problems. So we do it this way, which pretty much follows what GCC does.
10473  // Note that we go the traditional code path for compound assignment forms.
10474  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10475    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10476
10477  // If this is the .* operator, which is not overloadable, just
10478  // create a built-in binary operator.
10479  if (Opc == BO_PtrMemD)
10480    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10481
10482  // Build an empty overload set.
10483  OverloadCandidateSet CandidateSet(OpLoc);
10484
10485  // Add the candidates from the given function set.
10486  AddFunctionCandidates(Fns, Args, CandidateSet, false);
10487
10488  // Add operator candidates that are member functions.
10489  AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10490
10491  // Add candidates from ADL.
10492  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10493                                       OpLoc, Args,
10494                                       /*ExplicitTemplateArgs*/ 0,
10495                                       CandidateSet);
10496
10497  // Add builtin operator candidates.
10498  AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10499
10500  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10501
10502  // Perform overload resolution.
10503  OverloadCandidateSet::iterator Best;
10504  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10505    case OR_Success: {
10506      // We found a built-in operator or an overloaded operator.
10507      FunctionDecl *FnDecl = Best->Function;
10508
10509      if (FnDecl) {
10510        // We matched an overloaded operator. Build a call to that
10511        // operator.
10512
10513        // Convert the arguments.
10514        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10515          // Best->Access is only meaningful for class members.
10516          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10517
10518          ExprResult Arg1 =
10519            PerformCopyInitialization(
10520              InitializedEntity::InitializeParameter(Context,
10521                                                     FnDecl->getParamDecl(0)),
10522              SourceLocation(), Owned(Args[1]));
10523          if (Arg1.isInvalid())
10524            return ExprError();
10525
10526          ExprResult Arg0 =
10527            PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10528                                                Best->FoundDecl, Method);
10529          if (Arg0.isInvalid())
10530            return ExprError();
10531          Args[0] = Arg0.takeAs<Expr>();
10532          Args[1] = RHS = Arg1.takeAs<Expr>();
10533        } else {
10534          // Convert the arguments.
10535          ExprResult Arg0 = PerformCopyInitialization(
10536            InitializedEntity::InitializeParameter(Context,
10537                                                   FnDecl->getParamDecl(0)),
10538            SourceLocation(), Owned(Args[0]));
10539          if (Arg0.isInvalid())
10540            return ExprError();
10541
10542          ExprResult Arg1 =
10543            PerformCopyInitialization(
10544              InitializedEntity::InitializeParameter(Context,
10545                                                     FnDecl->getParamDecl(1)),
10546              SourceLocation(), Owned(Args[1]));
10547          if (Arg1.isInvalid())
10548            return ExprError();
10549          Args[0] = LHS = Arg0.takeAs<Expr>();
10550          Args[1] = RHS = Arg1.takeAs<Expr>();
10551        }
10552
10553        // Determine the result type.
10554        QualType ResultTy = FnDecl->getResultType();
10555        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10556        ResultTy = ResultTy.getNonLValueExprType(Context);
10557
10558        // Build the actual expression node.
10559        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10560                                                  Best->FoundDecl,
10561                                                  HadMultipleCandidates, OpLoc);
10562        if (FnExpr.isInvalid())
10563          return ExprError();
10564
10565        CXXOperatorCallExpr *TheCall =
10566          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10567                                            Args, ResultTy, VK, OpLoc,
10568                                            FPFeatures.fp_contract);
10569
10570        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10571                                FnDecl))
10572          return ExprError();
10573
10574        ArrayRef<const Expr *> ArgsArray(Args, 2);
10575        // Cut off the implicit 'this'.
10576        if (isa<CXXMethodDecl>(FnDecl))
10577          ArgsArray = ArgsArray.slice(1);
10578        checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10579                  TheCall->getSourceRange(), VariadicDoesNotApply);
10580
10581        return MaybeBindToTemporary(TheCall);
10582      } else {
10583        // We matched a built-in operator. Convert the arguments, then
10584        // break out so that we will build the appropriate built-in
10585        // operator node.
10586        ExprResult ArgsRes0 =
10587          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10588                                    Best->Conversions[0], AA_Passing);
10589        if (ArgsRes0.isInvalid())
10590          return ExprError();
10591        Args[0] = ArgsRes0.take();
10592
10593        ExprResult ArgsRes1 =
10594          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10595                                    Best->Conversions[1], AA_Passing);
10596        if (ArgsRes1.isInvalid())
10597          return ExprError();
10598        Args[1] = ArgsRes1.take();
10599        break;
10600      }
10601    }
10602
10603    case OR_No_Viable_Function: {
10604      // C++ [over.match.oper]p9:
10605      //   If the operator is the operator , [...] and there are no
10606      //   viable functions, then the operator is assumed to be the
10607      //   built-in operator and interpreted according to clause 5.
10608      if (Opc == BO_Comma)
10609        break;
10610
10611      // For class as left operand for assignment or compound assigment
10612      // operator do not fall through to handling in built-in, but report that
10613      // no overloaded assignment operator found
10614      ExprResult Result = ExprError();
10615      if (Args[0]->getType()->isRecordType() &&
10616          Opc >= BO_Assign && Opc <= BO_OrAssign) {
10617        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10618             << BinaryOperator::getOpcodeStr(Opc)
10619             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10620      } else {
10621        // This is an erroneous use of an operator which can be overloaded by
10622        // a non-member function. Check for non-member operators which were
10623        // defined too late to be candidates.
10624        if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10625          // FIXME: Recover by calling the found function.
10626          return ExprError();
10627
10628        // No viable function; try to create a built-in operation, which will
10629        // produce an error. Then, show the non-viable candidates.
10630        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10631      }
10632      assert(Result.isInvalid() &&
10633             "C++ binary operator overloading is missing candidates!");
10634      if (Result.isInvalid())
10635        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10636                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
10637      return Result;
10638    }
10639
10640    case OR_Ambiguous:
10641      Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10642          << BinaryOperator::getOpcodeStr(Opc)
10643          << Args[0]->getType() << Args[1]->getType()
10644          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10645      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10646                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10647      return ExprError();
10648
10649    case OR_Deleted:
10650      if (isImplicitlyDeleted(Best->Function)) {
10651        CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10652        Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10653          << Context.getRecordType(Method->getParent())
10654          << getSpecialMember(Method);
10655
10656        // The user probably meant to call this special member. Just
10657        // explain why it's deleted.
10658        NoteDeletedFunction(Method);
10659        return ExprError();
10660      } else {
10661        Diag(OpLoc, diag::err_ovl_deleted_oper)
10662          << Best->Function->isDeleted()
10663          << BinaryOperator::getOpcodeStr(Opc)
10664          << getDeletedOrUnavailableSuffix(Best->Function)
10665          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10666      }
10667      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10668                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10669      return ExprError();
10670  }
10671
10672  // We matched a built-in operator; build it.
10673  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10674}
10675
10676ExprResult
10677Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10678                                         SourceLocation RLoc,
10679                                         Expr *Base, Expr *Idx) {
10680  Expr *Args[2] = { Base, Idx };
10681  DeclarationName OpName =
10682      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10683
10684  // If either side is type-dependent, create an appropriate dependent
10685  // expression.
10686  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10687
10688    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10689    // CHECKME: no 'operator' keyword?
10690    DeclarationNameInfo OpNameInfo(OpName, LLoc);
10691    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10692    UnresolvedLookupExpr *Fn
10693      = UnresolvedLookupExpr::Create(Context, NamingClass,
10694                                     NestedNameSpecifierLoc(), OpNameInfo,
10695                                     /*ADL*/ true, /*Overloaded*/ false,
10696                                     UnresolvedSetIterator(),
10697                                     UnresolvedSetIterator());
10698    // Can't add any actual overloads yet
10699
10700    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10701                                                   Args,
10702                                                   Context.DependentTy,
10703                                                   VK_RValue,
10704                                                   RLoc, false));
10705  }
10706
10707  // Handle placeholders on both operands.
10708  if (checkPlaceholderForOverload(*this, Args[0]))
10709    return ExprError();
10710  if (checkPlaceholderForOverload(*this, Args[1]))
10711    return ExprError();
10712
10713  // Build an empty overload set.
10714  OverloadCandidateSet CandidateSet(LLoc);
10715
10716  // Subscript can only be overloaded as a member function.
10717
10718  // Add operator candidates that are member functions.
10719  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
10720
10721  // Add builtin operator candidates.
10722  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
10723
10724  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10725
10726  // Perform overload resolution.
10727  OverloadCandidateSet::iterator Best;
10728  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10729    case OR_Success: {
10730      // We found a built-in operator or an overloaded operator.
10731      FunctionDecl *FnDecl = Best->Function;
10732
10733      if (FnDecl) {
10734        // We matched an overloaded operator. Build a call to that
10735        // operator.
10736
10737        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10738
10739        // Convert the arguments.
10740        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10741        ExprResult Arg0 =
10742          PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10743                                              Best->FoundDecl, Method);
10744        if (Arg0.isInvalid())
10745          return ExprError();
10746        Args[0] = Arg0.take();
10747
10748        // Convert the arguments.
10749        ExprResult InputInit
10750          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10751                                                      Context,
10752                                                      FnDecl->getParamDecl(0)),
10753                                      SourceLocation(),
10754                                      Owned(Args[1]));
10755        if (InputInit.isInvalid())
10756          return ExprError();
10757
10758        Args[1] = InputInit.takeAs<Expr>();
10759
10760        // Determine the result type
10761        QualType ResultTy = FnDecl->getResultType();
10762        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10763        ResultTy = ResultTy.getNonLValueExprType(Context);
10764
10765        // Build the actual expression node.
10766        DeclarationNameInfo OpLocInfo(OpName, LLoc);
10767        OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10768        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10769                                                  Best->FoundDecl,
10770                                                  HadMultipleCandidates,
10771                                                  OpLocInfo.getLoc(),
10772                                                  OpLocInfo.getInfo());
10773        if (FnExpr.isInvalid())
10774          return ExprError();
10775
10776        CXXOperatorCallExpr *TheCall =
10777          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10778                                            FnExpr.take(), Args,
10779                                            ResultTy, VK, RLoc,
10780                                            false);
10781
10782        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10783                                FnDecl))
10784          return ExprError();
10785
10786        return MaybeBindToTemporary(TheCall);
10787      } else {
10788        // We matched a built-in operator. Convert the arguments, then
10789        // break out so that we will build the appropriate built-in
10790        // operator node.
10791        ExprResult ArgsRes0 =
10792          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10793                                    Best->Conversions[0], AA_Passing);
10794        if (ArgsRes0.isInvalid())
10795          return ExprError();
10796        Args[0] = ArgsRes0.take();
10797
10798        ExprResult ArgsRes1 =
10799          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10800                                    Best->Conversions[1], AA_Passing);
10801        if (ArgsRes1.isInvalid())
10802          return ExprError();
10803        Args[1] = ArgsRes1.take();
10804
10805        break;
10806      }
10807    }
10808
10809    case OR_No_Viable_Function: {
10810      if (CandidateSet.empty())
10811        Diag(LLoc, diag::err_ovl_no_oper)
10812          << Args[0]->getType() << /*subscript*/ 0
10813          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10814      else
10815        Diag(LLoc, diag::err_ovl_no_viable_subscript)
10816          << Args[0]->getType()
10817          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10818      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10819                                  "[]", LLoc);
10820      return ExprError();
10821    }
10822
10823    case OR_Ambiguous:
10824      Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10825          << "[]"
10826          << Args[0]->getType() << Args[1]->getType()
10827          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10828      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10829                                  "[]", LLoc);
10830      return ExprError();
10831
10832    case OR_Deleted:
10833      Diag(LLoc, diag::err_ovl_deleted_oper)
10834        << Best->Function->isDeleted() << "[]"
10835        << getDeletedOrUnavailableSuffix(Best->Function)
10836        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10837      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10838                                  "[]", LLoc);
10839      return ExprError();
10840    }
10841
10842  // We matched a built-in operator; build it.
10843  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10844}
10845
10846/// BuildCallToMemberFunction - Build a call to a member
10847/// function. MemExpr is the expression that refers to the member
10848/// function (and includes the object parameter), Args/NumArgs are the
10849/// arguments to the function call (not including the object
10850/// parameter). The caller needs to validate that the member
10851/// expression refers to a non-static member function or an overloaded
10852/// member function.
10853ExprResult
10854Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10855                                SourceLocation LParenLoc,
10856                                MultiExprArg Args,
10857                                SourceLocation RParenLoc) {
10858  assert(MemExprE->getType() == Context.BoundMemberTy ||
10859         MemExprE->getType() == Context.OverloadTy);
10860
10861  // Dig out the member expression. This holds both the object
10862  // argument and the member function we're referring to.
10863  Expr *NakedMemExpr = MemExprE->IgnoreParens();
10864
10865  // Determine whether this is a call to a pointer-to-member function.
10866  if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10867    assert(op->getType() == Context.BoundMemberTy);
10868    assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10869
10870    QualType fnType =
10871      op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10872
10873    const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10874    QualType resultType = proto->getCallResultType(Context);
10875    ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10876
10877    // Check that the object type isn't more qualified than the
10878    // member function we're calling.
10879    Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10880
10881    QualType objectType = op->getLHS()->getType();
10882    if (op->getOpcode() == BO_PtrMemI)
10883      objectType = objectType->castAs<PointerType>()->getPointeeType();
10884    Qualifiers objectQuals = objectType.getQualifiers();
10885
10886    Qualifiers difference = objectQuals - funcQuals;
10887    difference.removeObjCGCAttr();
10888    difference.removeAddressSpace();
10889    if (difference) {
10890      std::string qualsString = difference.getAsString();
10891      Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10892        << fnType.getUnqualifiedType()
10893        << qualsString
10894        << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10895    }
10896
10897    CXXMemberCallExpr *call
10898      = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
10899                                        resultType, valueKind, RParenLoc);
10900
10901    if (CheckCallReturnType(proto->getResultType(),
10902                            op->getRHS()->getLocStart(),
10903                            call, 0))
10904      return ExprError();
10905
10906    if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
10907      return ExprError();
10908
10909    return MaybeBindToTemporary(call);
10910  }
10911
10912  UnbridgedCastsSet UnbridgedCasts;
10913  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
10914    return ExprError();
10915
10916  MemberExpr *MemExpr;
10917  CXXMethodDecl *Method = 0;
10918  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
10919  NestedNameSpecifier *Qualifier = 0;
10920  if (isa<MemberExpr>(NakedMemExpr)) {
10921    MemExpr = cast<MemberExpr>(NakedMemExpr);
10922    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
10923    FoundDecl = MemExpr->getFoundDecl();
10924    Qualifier = MemExpr->getQualifier();
10925    UnbridgedCasts.restore();
10926  } else {
10927    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
10928    Qualifier = UnresExpr->getQualifier();
10929
10930    QualType ObjectType = UnresExpr->getBaseType();
10931    Expr::Classification ObjectClassification
10932      = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10933                            : UnresExpr->getBase()->Classify(Context);
10934
10935    // Add overload candidates
10936    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
10937
10938    // FIXME: avoid copy.
10939    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10940    if (UnresExpr->hasExplicitTemplateArgs()) {
10941      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10942      TemplateArgs = &TemplateArgsBuffer;
10943    }
10944
10945    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10946           E = UnresExpr->decls_end(); I != E; ++I) {
10947
10948      NamedDecl *Func = *I;
10949      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10950      if (isa<UsingShadowDecl>(Func))
10951        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10952
10953
10954      // Microsoft supports direct constructor calls.
10955      if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
10956        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10957                             Args, CandidateSet);
10958      } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
10959        // If explicit template arguments were provided, we can't call a
10960        // non-template member function.
10961        if (TemplateArgs)
10962          continue;
10963
10964        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
10965                           ObjectClassification, Args, CandidateSet,
10966                           /*SuppressUserConversions=*/false);
10967      } else {
10968        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
10969                                   I.getPair(), ActingDC, TemplateArgs,
10970                                   ObjectType,  ObjectClassification,
10971                                   Args, CandidateSet,
10972                                   /*SuppressUsedConversions=*/false);
10973      }
10974    }
10975
10976    DeclarationName DeclName = UnresExpr->getMemberName();
10977
10978    UnbridgedCasts.restore();
10979
10980    OverloadCandidateSet::iterator Best;
10981    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
10982                                            Best)) {
10983    case OR_Success:
10984      Method = cast<CXXMethodDecl>(Best->Function);
10985      FoundDecl = Best->FoundDecl;
10986      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
10987      if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
10988        return ExprError();
10989      break;
10990
10991    case OR_No_Viable_Function:
10992      Diag(UnresExpr->getMemberLoc(),
10993           diag::err_ovl_no_viable_member_function_in_call)
10994        << DeclName << MemExprE->getSourceRange();
10995      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
10996      // FIXME: Leaking incoming expressions!
10997      return ExprError();
10998
10999    case OR_Ambiguous:
11000      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11001        << DeclName << MemExprE->getSourceRange();
11002      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11003      // FIXME: Leaking incoming expressions!
11004      return ExprError();
11005
11006    case OR_Deleted:
11007      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11008        << Best->Function->isDeleted()
11009        << DeclName
11010        << getDeletedOrUnavailableSuffix(Best->Function)
11011        << MemExprE->getSourceRange();
11012      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11013      // FIXME: Leaking incoming expressions!
11014      return ExprError();
11015    }
11016
11017    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11018
11019    // If overload resolution picked a static member, build a
11020    // non-member call based on that function.
11021    if (Method->isStatic()) {
11022      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11023                                   RParenLoc);
11024    }
11025
11026    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11027  }
11028
11029  QualType ResultType = Method->getResultType();
11030  ExprValueKind VK = Expr::getValueKindForType(ResultType);
11031  ResultType = ResultType.getNonLValueExprType(Context);
11032
11033  assert(Method && "Member call to something that isn't a method?");
11034  CXXMemberCallExpr *TheCall =
11035    new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11036                                    ResultType, VK, RParenLoc);
11037
11038  // Check for a valid return type.
11039  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
11040                          TheCall, Method))
11041    return ExprError();
11042
11043  // Convert the object argument (for a non-static member function call).
11044  // We only need to do this if there was actually an overload; otherwise
11045  // it was done at lookup.
11046  if (!Method->isStatic()) {
11047    ExprResult ObjectArg =
11048      PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11049                                          FoundDecl, Method);
11050    if (ObjectArg.isInvalid())
11051      return ExprError();
11052    MemExpr->setBase(ObjectArg.take());
11053  }
11054
11055  // Convert the rest of the arguments
11056  const FunctionProtoType *Proto =
11057    Method->getType()->getAs<FunctionProtoType>();
11058  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11059                              RParenLoc))
11060    return ExprError();
11061
11062  DiagnoseSentinelCalls(Method, LParenLoc, Args);
11063
11064  if (CheckFunctionCall(Method, TheCall, Proto))
11065    return ExprError();
11066
11067  if ((isa<CXXConstructorDecl>(CurContext) ||
11068       isa<CXXDestructorDecl>(CurContext)) &&
11069      TheCall->getMethodDecl()->isPure()) {
11070    const CXXMethodDecl *MD = TheCall->getMethodDecl();
11071
11072    if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11073      Diag(MemExpr->getLocStart(),
11074           diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11075        << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11076        << MD->getParent()->getDeclName();
11077
11078      Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11079    }
11080  }
11081  return MaybeBindToTemporary(TheCall);
11082}
11083
11084/// BuildCallToObjectOfClassType - Build a call to an object of class
11085/// type (C++ [over.call.object]), which can end up invoking an
11086/// overloaded function call operator (@c operator()) or performing a
11087/// user-defined conversion on the object argument.
11088ExprResult
11089Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11090                                   SourceLocation LParenLoc,
11091                                   MultiExprArg Args,
11092                                   SourceLocation RParenLoc) {
11093  if (checkPlaceholderForOverload(*this, Obj))
11094    return ExprError();
11095  ExprResult Object = Owned(Obj);
11096
11097  UnbridgedCastsSet UnbridgedCasts;
11098  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11099    return ExprError();
11100
11101  assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11102  const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11103
11104  // C++ [over.call.object]p1:
11105  //  If the primary-expression E in the function call syntax
11106  //  evaluates to a class object of type "cv T", then the set of
11107  //  candidate functions includes at least the function call
11108  //  operators of T. The function call operators of T are obtained by
11109  //  ordinary lookup of the name operator() in the context of
11110  //  (E).operator().
11111  OverloadCandidateSet CandidateSet(LParenLoc);
11112  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11113
11114  if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11115                          diag::err_incomplete_object_call, Object.get()))
11116    return true;
11117
11118  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11119  LookupQualifiedName(R, Record->getDecl());
11120  R.suppressDiagnostics();
11121
11122  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11123       Oper != OperEnd; ++Oper) {
11124    AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11125                       Object.get()->Classify(Context),
11126                       Args, CandidateSet,
11127                       /*SuppressUserConversions=*/ false);
11128  }
11129
11130  // C++ [over.call.object]p2:
11131  //   In addition, for each (non-explicit in C++0x) conversion function
11132  //   declared in T of the form
11133  //
11134  //        operator conversion-type-id () cv-qualifier;
11135  //
11136  //   where cv-qualifier is the same cv-qualification as, or a
11137  //   greater cv-qualification than, cv, and where conversion-type-id
11138  //   denotes the type "pointer to function of (P1,...,Pn) returning
11139  //   R", or the type "reference to pointer to function of
11140  //   (P1,...,Pn) returning R", or the type "reference to function
11141  //   of (P1,...,Pn) returning R", a surrogate call function [...]
11142  //   is also considered as a candidate function. Similarly,
11143  //   surrogate call functions are added to the set of candidate
11144  //   functions for each conversion function declared in an
11145  //   accessible base class provided the function is not hidden
11146  //   within T by another intervening declaration.
11147  std::pair<CXXRecordDecl::conversion_iterator,
11148            CXXRecordDecl::conversion_iterator> Conversions
11149    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11150  for (CXXRecordDecl::conversion_iterator
11151         I = Conversions.first, E = Conversions.second; I != E; ++I) {
11152    NamedDecl *D = *I;
11153    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11154    if (isa<UsingShadowDecl>(D))
11155      D = cast<UsingShadowDecl>(D)->getTargetDecl();
11156
11157    // Skip over templated conversion functions; they aren't
11158    // surrogates.
11159    if (isa<FunctionTemplateDecl>(D))
11160      continue;
11161
11162    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11163    if (!Conv->isExplicit()) {
11164      // Strip the reference type (if any) and then the pointer type (if
11165      // any) to get down to what might be a function type.
11166      QualType ConvType = Conv->getConversionType().getNonReferenceType();
11167      if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11168        ConvType = ConvPtrType->getPointeeType();
11169
11170      if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11171      {
11172        AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11173                              Object.get(), Args, CandidateSet);
11174      }
11175    }
11176  }
11177
11178  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11179
11180  // Perform overload resolution.
11181  OverloadCandidateSet::iterator Best;
11182  switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11183                             Best)) {
11184  case OR_Success:
11185    // Overload resolution succeeded; we'll build the appropriate call
11186    // below.
11187    break;
11188
11189  case OR_No_Viable_Function:
11190    if (CandidateSet.empty())
11191      Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11192        << Object.get()->getType() << /*call*/ 1
11193        << Object.get()->getSourceRange();
11194    else
11195      Diag(Object.get()->getLocStart(),
11196           diag::err_ovl_no_viable_object_call)
11197        << Object.get()->getType() << Object.get()->getSourceRange();
11198    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11199    break;
11200
11201  case OR_Ambiguous:
11202    Diag(Object.get()->getLocStart(),
11203         diag::err_ovl_ambiguous_object_call)
11204      << Object.get()->getType() << Object.get()->getSourceRange();
11205    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11206    break;
11207
11208  case OR_Deleted:
11209    Diag(Object.get()->getLocStart(),
11210         diag::err_ovl_deleted_object_call)
11211      << Best->Function->isDeleted()
11212      << Object.get()->getType()
11213      << getDeletedOrUnavailableSuffix(Best->Function)
11214      << Object.get()->getSourceRange();
11215    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11216    break;
11217  }
11218
11219  if (Best == CandidateSet.end())
11220    return true;
11221
11222  UnbridgedCasts.restore();
11223
11224  if (Best->Function == 0) {
11225    // Since there is no function declaration, this is one of the
11226    // surrogate candidates. Dig out the conversion function.
11227    CXXConversionDecl *Conv
11228      = cast<CXXConversionDecl>(
11229                         Best->Conversions[0].UserDefined.ConversionFunction);
11230
11231    CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11232    if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11233      return ExprError();
11234
11235    // We selected one of the surrogate functions that converts the
11236    // object parameter to a function pointer. Perform the conversion
11237    // on the object argument, then let ActOnCallExpr finish the job.
11238
11239    // Create an implicit member expr to refer to the conversion operator.
11240    // and then call it.
11241    ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11242                                             Conv, HadMultipleCandidates);
11243    if (Call.isInvalid())
11244      return ExprError();
11245    // Record usage of conversion in an implicit cast.
11246    Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11247                                          CK_UserDefinedConversion,
11248                                          Call.get(), 0, VK_RValue));
11249
11250    return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11251  }
11252
11253  CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11254
11255  // We found an overloaded operator(). Build a CXXOperatorCallExpr
11256  // that calls this method, using Object for the implicit object
11257  // parameter and passing along the remaining arguments.
11258  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11259
11260  // An error diagnostic has already been printed when parsing the declaration.
11261  if (Method->isInvalidDecl())
11262    return ExprError();
11263
11264  const FunctionProtoType *Proto =
11265    Method->getType()->getAs<FunctionProtoType>();
11266
11267  unsigned NumArgsInProto = Proto->getNumArgs();
11268  unsigned NumArgsToCheck = Args.size();
11269
11270  // Build the full argument list for the method call (the
11271  // implicit object parameter is placed at the beginning of the
11272  // list).
11273  Expr **MethodArgs;
11274  if (Args.size() < NumArgsInProto) {
11275    NumArgsToCheck = NumArgsInProto;
11276    MethodArgs = new Expr*[NumArgsInProto + 1];
11277  } else {
11278    MethodArgs = new Expr*[Args.size() + 1];
11279  }
11280  MethodArgs[0] = Object.get();
11281  for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx)
11282    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
11283
11284  DeclarationNameInfo OpLocInfo(
11285               Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11286  OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11287  ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11288                                           HadMultipleCandidates,
11289                                           OpLocInfo.getLoc(),
11290                                           OpLocInfo.getInfo());
11291  if (NewFn.isInvalid())
11292    return true;
11293
11294  // Once we've built TheCall, all of the expressions are properly
11295  // owned.
11296  QualType ResultTy = Method->getResultType();
11297  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11298  ResultTy = ResultTy.getNonLValueExprType(Context);
11299
11300  CXXOperatorCallExpr *TheCall =
11301    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11302                                      llvm::makeArrayRef(MethodArgs, Args.size()+1),
11303                                      ResultTy, VK, RParenLoc, false);
11304  delete [] MethodArgs;
11305
11306  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
11307                          Method))
11308    return true;
11309
11310  // We may have default arguments. If so, we need to allocate more
11311  // slots in the call for them.
11312  if (Args.size() < NumArgsInProto)
11313    TheCall->setNumArgs(Context, NumArgsInProto + 1);
11314  else if (Args.size() > NumArgsInProto)
11315    NumArgsToCheck = NumArgsInProto;
11316
11317  bool IsError = false;
11318
11319  // Initialize the implicit object parameter.
11320  ExprResult ObjRes =
11321    PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11322                                        Best->FoundDecl, Method);
11323  if (ObjRes.isInvalid())
11324    IsError = true;
11325  else
11326    Object = ObjRes;
11327  TheCall->setArg(0, Object.take());
11328
11329  // Check the argument types.
11330  for (unsigned i = 0; i != NumArgsToCheck; i++) {
11331    Expr *Arg;
11332    if (i < Args.size()) {
11333      Arg = Args[i];
11334
11335      // Pass the argument.
11336
11337      ExprResult InputInit
11338        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11339                                                    Context,
11340                                                    Method->getParamDecl(i)),
11341                                    SourceLocation(), Arg);
11342
11343      IsError |= InputInit.isInvalid();
11344      Arg = InputInit.takeAs<Expr>();
11345    } else {
11346      ExprResult DefArg
11347        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11348      if (DefArg.isInvalid()) {
11349        IsError = true;
11350        break;
11351      }
11352
11353      Arg = DefArg.takeAs<Expr>();
11354    }
11355
11356    TheCall->setArg(i + 1, Arg);
11357  }
11358
11359  // If this is a variadic call, handle args passed through "...".
11360  if (Proto->isVariadic()) {
11361    // Promote the arguments (C99 6.5.2.2p7).
11362    for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
11363      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11364      IsError |= Arg.isInvalid();
11365      TheCall->setArg(i + 1, Arg.take());
11366    }
11367  }
11368
11369  if (IsError) return true;
11370
11371  DiagnoseSentinelCalls(Method, LParenLoc, Args);
11372
11373  if (CheckFunctionCall(Method, TheCall, Proto))
11374    return true;
11375
11376  return MaybeBindToTemporary(TheCall);
11377}
11378
11379/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11380///  (if one exists), where @c Base is an expression of class type and
11381/// @c Member is the name of the member we're trying to find.
11382ExprResult
11383Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
11384  assert(Base->getType()->isRecordType() &&
11385         "left-hand side must have class type");
11386
11387  if (checkPlaceholderForOverload(*this, Base))
11388    return ExprError();
11389
11390  SourceLocation Loc = Base->getExprLoc();
11391
11392  // C++ [over.ref]p1:
11393  //
11394  //   [...] An expression x->m is interpreted as (x.operator->())->m
11395  //   for a class object x of type T if T::operator->() exists and if
11396  //   the operator is selected as the best match function by the
11397  //   overload resolution mechanism (13.3).
11398  DeclarationName OpName =
11399    Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11400  OverloadCandidateSet CandidateSet(Loc);
11401  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11402
11403  if (RequireCompleteType(Loc, Base->getType(),
11404                          diag::err_typecheck_incomplete_tag, Base))
11405    return ExprError();
11406
11407  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11408  LookupQualifiedName(R, BaseRecord->getDecl());
11409  R.suppressDiagnostics();
11410
11411  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11412       Oper != OperEnd; ++Oper) {
11413    AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11414                       None, CandidateSet, /*SuppressUserConversions=*/false);
11415  }
11416
11417  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11418
11419  // Perform overload resolution.
11420  OverloadCandidateSet::iterator Best;
11421  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11422  case OR_Success:
11423    // Overload resolution succeeded; we'll build the call below.
11424    break;
11425
11426  case OR_No_Viable_Function:
11427    if (CandidateSet.empty())
11428      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11429        << Base->getType() << Base->getSourceRange();
11430    else
11431      Diag(OpLoc, diag::err_ovl_no_viable_oper)
11432        << "operator->" << Base->getSourceRange();
11433    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11434    return ExprError();
11435
11436  case OR_Ambiguous:
11437    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11438      << "->" << Base->getType() << Base->getSourceRange();
11439    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11440    return ExprError();
11441
11442  case OR_Deleted:
11443    Diag(OpLoc,  diag::err_ovl_deleted_oper)
11444      << Best->Function->isDeleted()
11445      << "->"
11446      << getDeletedOrUnavailableSuffix(Best->Function)
11447      << Base->getSourceRange();
11448    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11449    return ExprError();
11450  }
11451
11452  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11453
11454  // Convert the object parameter.
11455  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11456  ExprResult BaseResult =
11457    PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11458                                        Best->FoundDecl, Method);
11459  if (BaseResult.isInvalid())
11460    return ExprError();
11461  Base = BaseResult.take();
11462
11463  // Build the operator call.
11464  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11465                                            HadMultipleCandidates, OpLoc);
11466  if (FnExpr.isInvalid())
11467    return ExprError();
11468
11469  QualType ResultTy = Method->getResultType();
11470  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11471  ResultTy = ResultTy.getNonLValueExprType(Context);
11472  CXXOperatorCallExpr *TheCall =
11473    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11474                                      Base, ResultTy, VK, OpLoc, false);
11475
11476  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11477                          Method))
11478          return ExprError();
11479
11480  return MaybeBindToTemporary(TheCall);
11481}
11482
11483/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11484/// a literal operator described by the provided lookup results.
11485ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11486                                          DeclarationNameInfo &SuffixInfo,
11487                                          ArrayRef<Expr*> Args,
11488                                          SourceLocation LitEndLoc,
11489                                       TemplateArgumentListInfo *TemplateArgs) {
11490  SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11491
11492  OverloadCandidateSet CandidateSet(UDSuffixLoc);
11493  AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11494                        TemplateArgs);
11495
11496  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11497
11498  // Perform overload resolution. This will usually be trivial, but might need
11499  // to perform substitutions for a literal operator template.
11500  OverloadCandidateSet::iterator Best;
11501  switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11502  case OR_Success:
11503  case OR_Deleted:
11504    break;
11505
11506  case OR_No_Viable_Function:
11507    Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11508      << R.getLookupName();
11509    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11510    return ExprError();
11511
11512  case OR_Ambiguous:
11513    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11514    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11515    return ExprError();
11516  }
11517
11518  FunctionDecl *FD = Best->Function;
11519  ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11520                                        HadMultipleCandidates,
11521                                        SuffixInfo.getLoc(),
11522                                        SuffixInfo.getInfo());
11523  if (Fn.isInvalid())
11524    return true;
11525
11526  // Check the argument types. This should almost always be a no-op, except
11527  // that array-to-pointer decay is applied to string literals.
11528  Expr *ConvArgs[2];
11529  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
11530    ExprResult InputInit = PerformCopyInitialization(
11531      InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11532      SourceLocation(), Args[ArgIdx]);
11533    if (InputInit.isInvalid())
11534      return true;
11535    ConvArgs[ArgIdx] = InputInit.take();
11536  }
11537
11538  QualType ResultTy = FD->getResultType();
11539  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11540  ResultTy = ResultTy.getNonLValueExprType(Context);
11541
11542  UserDefinedLiteral *UDL =
11543    new (Context) UserDefinedLiteral(Context, Fn.take(),
11544                                     llvm::makeArrayRef(ConvArgs, Args.size()),
11545                                     ResultTy, VK, LitEndLoc, UDSuffixLoc);
11546
11547  if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11548    return ExprError();
11549
11550  if (CheckFunctionCall(FD, UDL, NULL))
11551    return ExprError();
11552
11553  return MaybeBindToTemporary(UDL);
11554}
11555
11556/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11557/// given LookupResult is non-empty, it is assumed to describe a member which
11558/// will be invoked. Otherwise, the function will be found via argument
11559/// dependent lookup.
11560/// CallExpr is set to a valid expression and FRS_Success returned on success,
11561/// otherwise CallExpr is set to ExprError() and some non-success value
11562/// is returned.
11563Sema::ForRangeStatus
11564Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11565                                SourceLocation RangeLoc, VarDecl *Decl,
11566                                BeginEndFunction BEF,
11567                                const DeclarationNameInfo &NameInfo,
11568                                LookupResult &MemberLookup,
11569                                OverloadCandidateSet *CandidateSet,
11570                                Expr *Range, ExprResult *CallExpr) {
11571  CandidateSet->clear();
11572  if (!MemberLookup.empty()) {
11573    ExprResult MemberRef =
11574        BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11575                                 /*IsPtr=*/false, CXXScopeSpec(),
11576                                 /*TemplateKWLoc=*/SourceLocation(),
11577                                 /*FirstQualifierInScope=*/0,
11578                                 MemberLookup,
11579                                 /*TemplateArgs=*/0);
11580    if (MemberRef.isInvalid()) {
11581      *CallExpr = ExprError();
11582      Diag(Range->getLocStart(), diag::note_in_for_range)
11583          << RangeLoc << BEF << Range->getType();
11584      return FRS_DiagnosticIssued;
11585    }
11586    *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
11587    if (CallExpr->isInvalid()) {
11588      *CallExpr = ExprError();
11589      Diag(Range->getLocStart(), diag::note_in_for_range)
11590          << RangeLoc << BEF << Range->getType();
11591      return FRS_DiagnosticIssued;
11592    }
11593  } else {
11594    UnresolvedSet<0> FoundNames;
11595    UnresolvedLookupExpr *Fn =
11596      UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11597                                   NestedNameSpecifierLoc(), NameInfo,
11598                                   /*NeedsADL=*/true, /*Overloaded=*/false,
11599                                   FoundNames.begin(), FoundNames.end());
11600
11601    bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
11602                                                    CandidateSet, CallExpr);
11603    if (CandidateSet->empty() || CandidateSetError) {
11604      *CallExpr = ExprError();
11605      return FRS_NoViableFunction;
11606    }
11607    OverloadCandidateSet::iterator Best;
11608    OverloadingResult OverloadResult =
11609        CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11610
11611    if (OverloadResult == OR_No_Viable_Function) {
11612      *CallExpr = ExprError();
11613      return FRS_NoViableFunction;
11614    }
11615    *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
11616                                         Loc, 0, CandidateSet, &Best,
11617                                         OverloadResult,
11618                                         /*AllowTypoCorrection=*/false);
11619    if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11620      *CallExpr = ExprError();
11621      Diag(Range->getLocStart(), diag::note_in_for_range)
11622          << RangeLoc << BEF << Range->getType();
11623      return FRS_DiagnosticIssued;
11624    }
11625  }
11626  return FRS_Success;
11627}
11628
11629
11630/// FixOverloadedFunctionReference - E is an expression that refers to
11631/// a C++ overloaded function (possibly with some parentheses and
11632/// perhaps a '&' around it). We have resolved the overloaded function
11633/// to the function declaration Fn, so patch up the expression E to
11634/// refer (possibly indirectly) to Fn. Returns the new expr.
11635Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11636                                           FunctionDecl *Fn) {
11637  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11638    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11639                                                   Found, Fn);
11640    if (SubExpr == PE->getSubExpr())
11641      return PE;
11642
11643    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11644  }
11645
11646  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11647    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11648                                                   Found, Fn);
11649    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11650                               SubExpr->getType()) &&
11651           "Implicit cast type cannot be determined from overload");
11652    assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11653    if (SubExpr == ICE->getSubExpr())
11654      return ICE;
11655
11656    return ImplicitCastExpr::Create(Context, ICE->getType(),
11657                                    ICE->getCastKind(),
11658                                    SubExpr, 0,
11659                                    ICE->getValueKind());
11660  }
11661
11662  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11663    assert(UnOp->getOpcode() == UO_AddrOf &&
11664           "Can only take the address of an overloaded function");
11665    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11666      if (Method->isStatic()) {
11667        // Do nothing: static member functions aren't any different
11668        // from non-member functions.
11669      } else {
11670        // Fix the sub expression, which really has to be an
11671        // UnresolvedLookupExpr holding an overloaded member function
11672        // or template.
11673        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11674                                                       Found, Fn);
11675        if (SubExpr == UnOp->getSubExpr())
11676          return UnOp;
11677
11678        assert(isa<DeclRefExpr>(SubExpr)
11679               && "fixed to something other than a decl ref");
11680        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11681               && "fixed to a member ref with no nested name qualifier");
11682
11683        // We have taken the address of a pointer to member
11684        // function. Perform the computation here so that we get the
11685        // appropriate pointer to member type.
11686        QualType ClassType
11687          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11688        QualType MemPtrType
11689          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11690
11691        return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11692                                           VK_RValue, OK_Ordinary,
11693                                           UnOp->getOperatorLoc());
11694      }
11695    }
11696    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11697                                                   Found, Fn);
11698    if (SubExpr == UnOp->getSubExpr())
11699      return UnOp;
11700
11701    return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11702                                     Context.getPointerType(SubExpr->getType()),
11703                                       VK_RValue, OK_Ordinary,
11704                                       UnOp->getOperatorLoc());
11705  }
11706
11707  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11708    // FIXME: avoid copy.
11709    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11710    if (ULE->hasExplicitTemplateArgs()) {
11711      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11712      TemplateArgs = &TemplateArgsBuffer;
11713    }
11714
11715    DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11716                                           ULE->getQualifierLoc(),
11717                                           ULE->getTemplateKeywordLoc(),
11718                                           Fn,
11719                                           /*enclosing*/ false, // FIXME?
11720                                           ULE->getNameLoc(),
11721                                           Fn->getType(),
11722                                           VK_LValue,
11723                                           Found.getDecl(),
11724                                           TemplateArgs);
11725    MarkDeclRefReferenced(DRE);
11726    DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11727    return DRE;
11728  }
11729
11730  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11731    // FIXME: avoid copy.
11732    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11733    if (MemExpr->hasExplicitTemplateArgs()) {
11734      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11735      TemplateArgs = &TemplateArgsBuffer;
11736    }
11737
11738    Expr *Base;
11739
11740    // If we're filling in a static method where we used to have an
11741    // implicit member access, rewrite to a simple decl ref.
11742    if (MemExpr->isImplicitAccess()) {
11743      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11744        DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11745                                               MemExpr->getQualifierLoc(),
11746                                               MemExpr->getTemplateKeywordLoc(),
11747                                               Fn,
11748                                               /*enclosing*/ false,
11749                                               MemExpr->getMemberLoc(),
11750                                               Fn->getType(),
11751                                               VK_LValue,
11752                                               Found.getDecl(),
11753                                               TemplateArgs);
11754        MarkDeclRefReferenced(DRE);
11755        DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11756        return DRE;
11757      } else {
11758        SourceLocation Loc = MemExpr->getMemberLoc();
11759        if (MemExpr->getQualifier())
11760          Loc = MemExpr->getQualifierLoc().getBeginLoc();
11761        CheckCXXThisCapture(Loc);
11762        Base = new (Context) CXXThisExpr(Loc,
11763                                         MemExpr->getBaseType(),
11764                                         /*isImplicit=*/true);
11765      }
11766    } else
11767      Base = MemExpr->getBase();
11768
11769    ExprValueKind valueKind;
11770    QualType type;
11771    if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11772      valueKind = VK_LValue;
11773      type = Fn->getType();
11774    } else {
11775      valueKind = VK_RValue;
11776      type = Context.BoundMemberTy;
11777    }
11778
11779    MemberExpr *ME = MemberExpr::Create(Context, Base,
11780                                        MemExpr->isArrow(),
11781                                        MemExpr->getQualifierLoc(),
11782                                        MemExpr->getTemplateKeywordLoc(),
11783                                        Fn,
11784                                        Found,
11785                                        MemExpr->getMemberNameInfo(),
11786                                        TemplateArgs,
11787                                        type, valueKind, OK_Ordinary);
11788    ME->setHadMultipleCandidates(true);
11789    MarkMemberReferenced(ME);
11790    return ME;
11791  }
11792
11793  llvm_unreachable("Invalid reference to overloaded function");
11794}
11795
11796ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11797                                                DeclAccessPair Found,
11798                                                FunctionDecl *Fn) {
11799  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11800}
11801
11802} // end namespace clang
11803