SemaOverload.cpp revision cfa88f893915ceb8ae4ce2f17c46c24a4d67502f
1//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/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
40/// function.
41static ExprResult
42CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
43                      SourceLocation Loc = SourceLocation(),
44                      const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
45  DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
46                                                 VK_LValue, Loc, LocInfo);
47  if (HadMultipleCandidates)
48    DRE->setHadMultipleCandidates(true);
49  ExprResult E = S.Owned(DRE);
50  E = S.DefaultFunctionArrayConversion(E.take());
51  if (E.isInvalid())
52    return ExprError();
53  return E;
54}
55
56static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
57                                 bool InOverloadResolution,
58                                 StandardConversionSequence &SCS,
59                                 bool CStyle,
60                                 bool AllowObjCWritebackConversion);
61
62static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
63                                                 QualType &ToType,
64                                                 bool InOverloadResolution,
65                                                 StandardConversionSequence &SCS,
66                                                 bool CStyle);
67static OverloadingResult
68IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
69                        UserDefinedConversionSequence& User,
70                        OverloadCandidateSet& Conversions,
71                        bool AllowExplicit);
72
73
74static ImplicitConversionSequence::CompareKind
75CompareStandardConversionSequences(Sema &S,
76                                   const StandardConversionSequence& SCS1,
77                                   const StandardConversionSequence& SCS2);
78
79static ImplicitConversionSequence::CompareKind
80CompareQualificationConversions(Sema &S,
81                                const StandardConversionSequence& SCS1,
82                                const StandardConversionSequence& SCS2);
83
84static ImplicitConversionSequence::CompareKind
85CompareDerivedToBaseConversions(Sema &S,
86                                const StandardConversionSequence& SCS1,
87                                const StandardConversionSequence& SCS2);
88
89
90
91/// GetConversionCategory - Retrieve the implicit conversion
92/// category corresponding to the given implicit conversion kind.
93ImplicitConversionCategory
94GetConversionCategory(ImplicitConversionKind Kind) {
95  static const ImplicitConversionCategory
96    Category[(int)ICK_Num_Conversion_Kinds] = {
97    ICC_Identity,
98    ICC_Lvalue_Transformation,
99    ICC_Lvalue_Transformation,
100    ICC_Lvalue_Transformation,
101    ICC_Identity,
102    ICC_Qualification_Adjustment,
103    ICC_Promotion,
104    ICC_Promotion,
105    ICC_Promotion,
106    ICC_Conversion,
107    ICC_Conversion,
108    ICC_Conversion,
109    ICC_Conversion,
110    ICC_Conversion,
111    ICC_Conversion,
112    ICC_Conversion,
113    ICC_Conversion,
114    ICC_Conversion,
115    ICC_Conversion,
116    ICC_Conversion,
117    ICC_Conversion,
118    ICC_Conversion
119  };
120  return Category[(int)Kind];
121}
122
123/// GetConversionRank - Retrieve the implicit conversion rank
124/// corresponding to the given implicit conversion kind.
125ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
126  static const ImplicitConversionRank
127    Rank[(int)ICK_Num_Conversion_Kinds] = {
128    ICR_Exact_Match,
129    ICR_Exact_Match,
130    ICR_Exact_Match,
131    ICR_Exact_Match,
132    ICR_Exact_Match,
133    ICR_Exact_Match,
134    ICR_Promotion,
135    ICR_Promotion,
136    ICR_Promotion,
137    ICR_Conversion,
138    ICR_Conversion,
139    ICR_Conversion,
140    ICR_Conversion,
141    ICR_Conversion,
142    ICR_Conversion,
143    ICR_Conversion,
144    ICR_Conversion,
145    ICR_Conversion,
146    ICR_Conversion,
147    ICR_Conversion,
148    ICR_Complex_Real_Conversion,
149    ICR_Conversion,
150    ICR_Conversion,
151    ICR_Writeback_Conversion
152  };
153  return Rank[(int)Kind];
154}
155
156/// GetImplicitConversionName - Return the name of this kind of
157/// implicit conversion.
158const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
159  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
160    "No conversion",
161    "Lvalue-to-rvalue",
162    "Array-to-pointer",
163    "Function-to-pointer",
164    "Noreturn adjustment",
165    "Qualification",
166    "Integral promotion",
167    "Floating point promotion",
168    "Complex promotion",
169    "Integral conversion",
170    "Floating conversion",
171    "Complex conversion",
172    "Floating-integral conversion",
173    "Pointer conversion",
174    "Pointer-to-member conversion",
175    "Boolean conversion",
176    "Compatible-types conversion",
177    "Derived-to-base conversion",
178    "Vector conversion",
179    "Vector splat",
180    "Complex-real conversion",
181    "Block Pointer conversion",
182    "Transparent Union Conversion"
183    "Writeback conversion"
184  };
185  return Name[Kind];
186}
187
188/// StandardConversionSequence - Set the standard conversion
189/// sequence to the identity conversion.
190void StandardConversionSequence::setAsIdentityConversion() {
191  First = ICK_Identity;
192  Second = ICK_Identity;
193  Third = ICK_Identity;
194  DeprecatedStringLiteralToCharPtr = false;
195  QualificationIncludesObjCLifetime = false;
196  ReferenceBinding = false;
197  DirectBinding = false;
198  IsLvalueReference = true;
199  BindsToFunctionLvalue = false;
200  BindsToRvalue = false;
201  BindsImplicitObjectArgumentWithoutRefQualifier = false;
202  ObjCLifetimeConversionBinding = false;
203  CopyConstructor = 0;
204}
205
206/// getRank - Retrieve the rank of this standard conversion sequence
207/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
208/// implicit conversions.
209ImplicitConversionRank StandardConversionSequence::getRank() const {
210  ImplicitConversionRank Rank = ICR_Exact_Match;
211  if  (GetConversionRank(First) > Rank)
212    Rank = GetConversionRank(First);
213  if  (GetConversionRank(Second) > Rank)
214    Rank = GetConversionRank(Second);
215  if  (GetConversionRank(Third) > Rank)
216    Rank = GetConversionRank(Third);
217  return Rank;
218}
219
220/// isPointerConversionToBool - Determines whether this conversion is
221/// a conversion of a pointer or pointer-to-member to bool. This is
222/// used as part of the ranking of standard conversion sequences
223/// (C++ 13.3.3.2p4).
224bool StandardConversionSequence::isPointerConversionToBool() const {
225  // Note that FromType has not necessarily been transformed by the
226  // array-to-pointer or function-to-pointer implicit conversions, so
227  // check for their presence as well as checking whether FromType is
228  // a pointer.
229  if (getToType(1)->isBooleanType() &&
230      (getFromType()->isPointerType() ||
231       getFromType()->isObjCObjectPointerType() ||
232       getFromType()->isBlockPointerType() ||
233       getFromType()->isNullPtrType() ||
234       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
235    return true;
236
237  return false;
238}
239
240/// isPointerConversionToVoidPointer - Determines whether this
241/// conversion is a conversion of a pointer to a void pointer. This is
242/// used as part of the ranking of standard conversion sequences (C++
243/// 13.3.3.2p4).
244bool
245StandardConversionSequence::
246isPointerConversionToVoidPointer(ASTContext& Context) const {
247  QualType FromType = getFromType();
248  QualType ToType = getToType(1);
249
250  // Note that FromType has not necessarily been transformed by the
251  // array-to-pointer implicit conversion, so check for its presence
252  // and redo the conversion to get a pointer.
253  if (First == ICK_Array_To_Pointer)
254    FromType = Context.getArrayDecayedType(FromType);
255
256  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
257    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
258      return ToPtrType->getPointeeType()->isVoidType();
259
260  return false;
261}
262
263/// Skip any implicit casts which could be either part of a narrowing conversion
264/// or after one in an implicit conversion.
265static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
266  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
267    switch (ICE->getCastKind()) {
268    case CK_NoOp:
269    case CK_IntegralCast:
270    case CK_IntegralToBoolean:
271    case CK_IntegralToFloating:
272    case CK_FloatingToIntegral:
273    case CK_FloatingToBoolean:
274    case CK_FloatingCast:
275      Converted = ICE->getSubExpr();
276      continue;
277
278    default:
279      return Converted;
280    }
281  }
282
283  return Converted;
284}
285
286/// Check if this standard conversion sequence represents a narrowing
287/// conversion, according to C++11 [dcl.init.list]p7.
288///
289/// \param Ctx  The AST context.
290/// \param Converted  The result of applying this standard conversion sequence.
291/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
292///        value of the expression prior to the narrowing conversion.
293/// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
294///        type of the expression prior to the narrowing conversion.
295NarrowingKind
296StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
297                                             const Expr *Converted,
298                                             APValue &ConstantValue,
299                                             QualType &ConstantType) const {
300  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
301
302  // C++11 [dcl.init.list]p7:
303  //   A narrowing conversion is an implicit conversion ...
304  QualType FromType = getToType(0);
305  QualType ToType = getToType(1);
306  switch (Second) {
307  // -- from a floating-point type to an integer type, or
308  //
309  // -- from an integer type or unscoped enumeration type to a floating-point
310  //    type, except where the source is a constant expression and the actual
311  //    value after conversion will fit into the target type and will produce
312  //    the original value when converted back to the original type, or
313  case ICK_Floating_Integral:
314    if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
315      return NK_Type_Narrowing;
316    } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
317      llvm::APSInt IntConstantValue;
318      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
319      if (Initializer &&
320          Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
321        // Convert the integer to the floating type.
322        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
323        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
324                                llvm::APFloat::rmNearestTiesToEven);
325        // And back.
326        llvm::APSInt ConvertedValue = IntConstantValue;
327        bool ignored;
328        Result.convertToInteger(ConvertedValue,
329                                llvm::APFloat::rmTowardZero, &ignored);
330        // If the resulting value is different, this was a narrowing conversion.
331        if (IntConstantValue != ConvertedValue) {
332          ConstantValue = APValue(IntConstantValue);
333          ConstantType = Initializer->getType();
334          return NK_Constant_Narrowing;
335        }
336      } else {
337        // Variables are always narrowings.
338        return NK_Variable_Narrowing;
339      }
340    }
341    return NK_Not_Narrowing;
342
343  // -- from long double to double or float, or from double to float, except
344  //    where the source is a constant expression and the actual value after
345  //    conversion is within the range of values that can be represented (even
346  //    if it cannot be represented exactly), or
347  case ICK_Floating_Conversion:
348    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
349        Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
350      // FromType is larger than ToType.
351      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
352      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
353        // Constant!
354        assert(ConstantValue.isFloat());
355        llvm::APFloat FloatVal = ConstantValue.getFloat();
356        // Convert the source value into the target type.
357        bool ignored;
358        llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
359          Ctx.getFloatTypeSemantics(ToType),
360          llvm::APFloat::rmNearestTiesToEven, &ignored);
361        // If there was no overflow, the source value is within the range of
362        // values that can be represented.
363        if (ConvertStatus & llvm::APFloat::opOverflow) {
364          ConstantType = Initializer->getType();
365          return NK_Constant_Narrowing;
366        }
367      } else {
368        return NK_Variable_Narrowing;
369      }
370    }
371    return NK_Not_Narrowing;
372
373  // -- from an integer type or unscoped enumeration type to an integer type
374  //    that cannot represent all the values of the original type, except where
375  //    the source is a constant expression and the actual value after
376  //    conversion will fit into the target type and will produce the original
377  //    value when converted back to the original type.
378  case ICK_Boolean_Conversion:  // Bools are integers too.
379    if (!FromType->isIntegralOrUnscopedEnumerationType()) {
380      // Boolean conversions can be from pointers and pointers to members
381      // [conv.bool], and those aren't considered narrowing conversions.
382      return NK_Not_Narrowing;
383    }  // Otherwise, fall through to the integral case.
384  case ICK_Integral_Conversion: {
385    assert(FromType->isIntegralOrUnscopedEnumerationType());
386    assert(ToType->isIntegralOrUnscopedEnumerationType());
387    const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
388    const unsigned FromWidth = Ctx.getIntWidth(FromType);
389    const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
390    const unsigned ToWidth = Ctx.getIntWidth(ToType);
391
392    if (FromWidth > ToWidth ||
393        (FromWidth == ToWidth && FromSigned != ToSigned) ||
394        (FromSigned && !ToSigned)) {
395      // Not all values of FromType can be represented in ToType.
396      llvm::APSInt InitializerValue;
397      const Expr *Initializer = IgnoreNarrowingConversion(Converted);
398      if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
399        // Such conversions on variables are always narrowing.
400        return NK_Variable_Narrowing;
401      }
402      bool Narrowing = false;
403      if (FromWidth < ToWidth) {
404        // Negative -> unsigned is narrowing. Otherwise, more bits is never
405        // narrowing.
406        if (InitializerValue.isSigned() && InitializerValue.isNegative())
407          Narrowing = true;
408      } else {
409        // Add a bit to the InitializerValue so we don't have to worry about
410        // signed vs. unsigned comparisons.
411        InitializerValue = InitializerValue.extend(
412          InitializerValue.getBitWidth() + 1);
413        // Convert the initializer to and from the target width and signed-ness.
414        llvm::APSInt ConvertedValue = InitializerValue;
415        ConvertedValue = ConvertedValue.trunc(ToWidth);
416        ConvertedValue.setIsSigned(ToSigned);
417        ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
418        ConvertedValue.setIsSigned(InitializerValue.isSigned());
419        // If the result is different, this was a narrowing conversion.
420        if (ConvertedValue != InitializerValue)
421          Narrowing = true;
422      }
423      if (Narrowing) {
424        ConstantType = Initializer->getType();
425        ConstantValue = APValue(InitializerValue);
426        return NK_Constant_Narrowing;
427      }
428    }
429    return NK_Not_Narrowing;
430  }
431
432  default:
433    // Other kinds of conversions are not narrowings.
434    return NK_Not_Narrowing;
435  }
436}
437
438/// DebugPrint - Print this standard conversion sequence to standard
439/// error. Useful for debugging overloading issues.
440void StandardConversionSequence::DebugPrint() const {
441  raw_ostream &OS = llvm::errs();
442  bool PrintedSomething = false;
443  if (First != ICK_Identity) {
444    OS << GetImplicitConversionName(First);
445    PrintedSomething = true;
446  }
447
448  if (Second != ICK_Identity) {
449    if (PrintedSomething) {
450      OS << " -> ";
451    }
452    OS << GetImplicitConversionName(Second);
453
454    if (CopyConstructor) {
455      OS << " (by copy constructor)";
456    } else if (DirectBinding) {
457      OS << " (direct reference binding)";
458    } else if (ReferenceBinding) {
459      OS << " (reference binding)";
460    }
461    PrintedSomething = true;
462  }
463
464  if (Third != ICK_Identity) {
465    if (PrintedSomething) {
466      OS << " -> ";
467    }
468    OS << GetImplicitConversionName(Third);
469    PrintedSomething = true;
470  }
471
472  if (!PrintedSomething) {
473    OS << "No conversions required";
474  }
475}
476
477/// DebugPrint - Print this user-defined conversion sequence to standard
478/// error. Useful for debugging overloading issues.
479void UserDefinedConversionSequence::DebugPrint() const {
480  raw_ostream &OS = llvm::errs();
481  if (Before.First || Before.Second || Before.Third) {
482    Before.DebugPrint();
483    OS << " -> ";
484  }
485  if (ConversionFunction)
486    OS << '\'' << *ConversionFunction << '\'';
487  else
488    OS << "aggregate initialization";
489  if (After.First || After.Second || After.Third) {
490    OS << " -> ";
491    After.DebugPrint();
492  }
493}
494
495/// DebugPrint - Print this implicit conversion sequence to standard
496/// error. Useful for debugging overloading issues.
497void ImplicitConversionSequence::DebugPrint() const {
498  raw_ostream &OS = llvm::errs();
499  switch (ConversionKind) {
500  case StandardConversion:
501    OS << "Standard conversion: ";
502    Standard.DebugPrint();
503    break;
504  case UserDefinedConversion:
505    OS << "User-defined conversion: ";
506    UserDefined.DebugPrint();
507    break;
508  case EllipsisConversion:
509    OS << "Ellipsis conversion";
510    break;
511  case AmbiguousConversion:
512    OS << "Ambiguous conversion";
513    break;
514  case BadConversion:
515    OS << "Bad conversion";
516    break;
517  }
518
519  OS << "\n";
520}
521
522void AmbiguousConversionSequence::construct() {
523  new (&conversions()) ConversionSet();
524}
525
526void AmbiguousConversionSequence::destruct() {
527  conversions().~ConversionSet();
528}
529
530void
531AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
532  FromTypePtr = O.FromTypePtr;
533  ToTypePtr = O.ToTypePtr;
534  new (&conversions()) ConversionSet(O.conversions());
535}
536
537namespace {
538  // Structure used by OverloadCandidate::DeductionFailureInfo to store
539  // template parameter and template argument information.
540  struct DFIParamWithArguments {
541    TemplateParameter Param;
542    TemplateArgument FirstArg;
543    TemplateArgument SecondArg;
544  };
545}
546
547/// \brief Convert from Sema's representation of template deduction information
548/// to the form used in overload-candidate information.
549OverloadCandidate::DeductionFailureInfo
550static MakeDeductionFailureInfo(ASTContext &Context,
551                                Sema::TemplateDeductionResult TDK,
552                                TemplateDeductionInfo &Info) {
553  OverloadCandidate::DeductionFailureInfo Result;
554  Result.Result = static_cast<unsigned>(TDK);
555  Result.HasDiagnostic = false;
556  Result.Data = 0;
557  switch (TDK) {
558  case Sema::TDK_Success:
559  case Sema::TDK_Invalid:
560  case Sema::TDK_InstantiationDepth:
561  case Sema::TDK_TooManyArguments:
562  case Sema::TDK_TooFewArguments:
563    break;
564
565  case Sema::TDK_Incomplete:
566  case Sema::TDK_InvalidExplicitArguments:
567    Result.Data = Info.Param.getOpaqueValue();
568    break;
569
570  case Sema::TDK_Inconsistent:
571  case Sema::TDK_Underqualified: {
572    // FIXME: Should allocate from normal heap so that we can free this later.
573    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
574    Saved->Param = Info.Param;
575    Saved->FirstArg = Info.FirstArg;
576    Saved->SecondArg = Info.SecondArg;
577    Result.Data = Saved;
578    break;
579  }
580
581  case Sema::TDK_SubstitutionFailure:
582    Result.Data = Info.take();
583    if (Info.hasSFINAEDiagnostic()) {
584      PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
585          SourceLocation(), PartialDiagnostic::NullDiagnostic());
586      Info.takeSFINAEDiagnostic(*Diag);
587      Result.HasDiagnostic = true;
588    }
589    break;
590
591  case Sema::TDK_NonDeducedMismatch:
592  case Sema::TDK_FailedOverloadResolution:
593    break;
594  }
595
596  return Result;
597}
598
599void OverloadCandidate::DeductionFailureInfo::Destroy() {
600  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
601  case Sema::TDK_Success:
602  case Sema::TDK_Invalid:
603  case Sema::TDK_InstantiationDepth:
604  case Sema::TDK_Incomplete:
605  case Sema::TDK_TooManyArguments:
606  case Sema::TDK_TooFewArguments:
607  case Sema::TDK_InvalidExplicitArguments:
608    break;
609
610  case Sema::TDK_Inconsistent:
611  case Sema::TDK_Underqualified:
612    // FIXME: Destroy the data?
613    Data = 0;
614    break;
615
616  case Sema::TDK_SubstitutionFailure:
617    // FIXME: Destroy the template argument list?
618    Data = 0;
619    if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
620      Diag->~PartialDiagnosticAt();
621      HasDiagnostic = false;
622    }
623    break;
624
625  // Unhandled
626  case Sema::TDK_NonDeducedMismatch:
627  case Sema::TDK_FailedOverloadResolution:
628    break;
629  }
630}
631
632PartialDiagnosticAt *
633OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
634  if (HasDiagnostic)
635    return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
636  return 0;
637}
638
639TemplateParameter
640OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
641  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
642  case Sema::TDK_Success:
643  case Sema::TDK_Invalid:
644  case Sema::TDK_InstantiationDepth:
645  case Sema::TDK_TooManyArguments:
646  case Sema::TDK_TooFewArguments:
647  case Sema::TDK_SubstitutionFailure:
648    return TemplateParameter();
649
650  case Sema::TDK_Incomplete:
651  case Sema::TDK_InvalidExplicitArguments:
652    return TemplateParameter::getFromOpaqueValue(Data);
653
654  case Sema::TDK_Inconsistent:
655  case Sema::TDK_Underqualified:
656    return static_cast<DFIParamWithArguments*>(Data)->Param;
657
658  // Unhandled
659  case Sema::TDK_NonDeducedMismatch:
660  case Sema::TDK_FailedOverloadResolution:
661    break;
662  }
663
664  return TemplateParameter();
665}
666
667TemplateArgumentList *
668OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
669  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
670    case Sema::TDK_Success:
671    case Sema::TDK_Invalid:
672    case Sema::TDK_InstantiationDepth:
673    case Sema::TDK_TooManyArguments:
674    case Sema::TDK_TooFewArguments:
675    case Sema::TDK_Incomplete:
676    case Sema::TDK_InvalidExplicitArguments:
677    case Sema::TDK_Inconsistent:
678    case Sema::TDK_Underqualified:
679      return 0;
680
681    case Sema::TDK_SubstitutionFailure:
682      return static_cast<TemplateArgumentList*>(Data);
683
684    // Unhandled
685    case Sema::TDK_NonDeducedMismatch:
686    case Sema::TDK_FailedOverloadResolution:
687      break;
688  }
689
690  return 0;
691}
692
693const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
694  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695  case Sema::TDK_Success:
696  case Sema::TDK_Invalid:
697  case Sema::TDK_InstantiationDepth:
698  case Sema::TDK_Incomplete:
699  case Sema::TDK_TooManyArguments:
700  case Sema::TDK_TooFewArguments:
701  case Sema::TDK_InvalidExplicitArguments:
702  case Sema::TDK_SubstitutionFailure:
703    return 0;
704
705  case Sema::TDK_Inconsistent:
706  case Sema::TDK_Underqualified:
707    return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
708
709  // Unhandled
710  case Sema::TDK_NonDeducedMismatch:
711  case Sema::TDK_FailedOverloadResolution:
712    break;
713  }
714
715  return 0;
716}
717
718const TemplateArgument *
719OverloadCandidate::DeductionFailureInfo::getSecondArg() {
720  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
721  case Sema::TDK_Success:
722  case Sema::TDK_Invalid:
723  case Sema::TDK_InstantiationDepth:
724  case Sema::TDK_Incomplete:
725  case Sema::TDK_TooManyArguments:
726  case Sema::TDK_TooFewArguments:
727  case Sema::TDK_InvalidExplicitArguments:
728  case Sema::TDK_SubstitutionFailure:
729    return 0;
730
731  case Sema::TDK_Inconsistent:
732  case Sema::TDK_Underqualified:
733    return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
734
735  // Unhandled
736  case Sema::TDK_NonDeducedMismatch:
737  case Sema::TDK_FailedOverloadResolution:
738    break;
739  }
740
741  return 0;
742}
743
744void OverloadCandidateSet::destroyCandidates() {
745  for (iterator i = begin(), e = end(); i != e; ++i) {
746    for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
747      i->Conversions[ii].~ImplicitConversionSequence();
748    if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
749      i->DeductionFailure.Destroy();
750  }
751}
752
753void OverloadCandidateSet::clear() {
754  destroyCandidates();
755  NumInlineSequences = 0;
756  Candidates.clear();
757  Functions.clear();
758}
759
760namespace {
761  class UnbridgedCastsSet {
762    struct Entry {
763      Expr **Addr;
764      Expr *Saved;
765    };
766    SmallVector<Entry, 2> Entries;
767
768  public:
769    void save(Sema &S, Expr *&E) {
770      assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
771      Entry entry = { &E, E };
772      Entries.push_back(entry);
773      E = S.stripARCUnbridgedCast(E);
774    }
775
776    void restore() {
777      for (SmallVectorImpl<Entry>::iterator
778             i = Entries.begin(), e = Entries.end(); i != e; ++i)
779        *i->Addr = i->Saved;
780    }
781  };
782}
783
784/// checkPlaceholderForOverload - Do any interesting placeholder-like
785/// preprocessing on the given expression.
786///
787/// \param unbridgedCasts a collection to which to add unbridged casts;
788///   without this, they will be immediately diagnosed as errors
789///
790/// Return true on unrecoverable error.
791static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
792                                        UnbridgedCastsSet *unbridgedCasts = 0) {
793  if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
794    // We can't handle overloaded expressions here because overload
795    // resolution might reasonably tweak them.
796    if (placeholder->getKind() == BuiltinType::Overload) return false;
797
798    // If the context potentially accepts unbridged ARC casts, strip
799    // the unbridged cast and add it to the collection for later restoration.
800    if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
801        unbridgedCasts) {
802      unbridgedCasts->save(S, E);
803      return false;
804    }
805
806    // Go ahead and check everything else.
807    ExprResult result = S.CheckPlaceholderExpr(E);
808    if (result.isInvalid())
809      return true;
810
811    E = result.take();
812    return false;
813  }
814
815  // Nothing to do.
816  return false;
817}
818
819/// checkArgPlaceholdersForOverload - Check a set of call operands for
820/// placeholders.
821static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
822                                            unsigned numArgs,
823                                            UnbridgedCastsSet &unbridged) {
824  for (unsigned i = 0; i != numArgs; ++i)
825    if (checkPlaceholderForOverload(S, args[i], &unbridged))
826      return true;
827
828  return false;
829}
830
831// IsOverload - Determine whether the given New declaration is an
832// overload of the declarations in Old. This routine returns false if
833// New and Old cannot be overloaded, e.g., if New has the same
834// signature as some function in Old (C++ 1.3.10) or if the Old
835// declarations aren't functions (or function templates) at all. When
836// it does return false, MatchedDecl will point to the decl that New
837// cannot be overloaded with.  This decl may be a UsingShadowDecl on
838// top of the underlying declaration.
839//
840// Example: Given the following input:
841//
842//   void f(int, float); // #1
843//   void f(int, int); // #2
844//   int f(int, int); // #3
845//
846// When we process #1, there is no previous declaration of "f",
847// so IsOverload will not be used.
848//
849// When we process #2, Old contains only the FunctionDecl for #1.  By
850// comparing the parameter types, we see that #1 and #2 are overloaded
851// (since they have different signatures), so this routine returns
852// false; MatchedDecl is unchanged.
853//
854// When we process #3, Old is an overload set containing #1 and #2. We
855// compare the signatures of #3 to #1 (they're overloaded, so we do
856// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
857// identical (return types of functions are not part of the
858// signature), IsOverload returns false and MatchedDecl will be set to
859// point to the FunctionDecl for #2.
860//
861// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
862// into a class by a using declaration.  The rules for whether to hide
863// shadow declarations ignore some properties which otherwise figure
864// into a function template's signature.
865Sema::OverloadKind
866Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
867                    NamedDecl *&Match, bool NewIsUsingDecl) {
868  for (LookupResult::iterator I = Old.begin(), E = Old.end();
869         I != E; ++I) {
870    NamedDecl *OldD = *I;
871
872    bool OldIsUsingDecl = false;
873    if (isa<UsingShadowDecl>(OldD)) {
874      OldIsUsingDecl = true;
875
876      // We can always introduce two using declarations into the same
877      // context, even if they have identical signatures.
878      if (NewIsUsingDecl) continue;
879
880      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
881    }
882
883    // If either declaration was introduced by a using declaration,
884    // we'll need to use slightly different rules for matching.
885    // Essentially, these rules are the normal rules, except that
886    // function templates hide function templates with different
887    // return types or template parameter lists.
888    bool UseMemberUsingDeclRules =
889      (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
890
891    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
892      if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
893        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
894          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
895          continue;
896        }
897
898        Match = *I;
899        return Ovl_Match;
900      }
901    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
902      if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
903        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
904          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
905          continue;
906        }
907
908        Match = *I;
909        return Ovl_Match;
910      }
911    } else if (isa<UsingDecl>(OldD)) {
912      // We can overload with these, which can show up when doing
913      // redeclaration checks for UsingDecls.
914      assert(Old.getLookupKind() == LookupUsingDeclName);
915    } else if (isa<TagDecl>(OldD)) {
916      // We can always overload with tags by hiding them.
917    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
918      // Optimistically assume that an unresolved using decl will
919      // overload; if it doesn't, we'll have to diagnose during
920      // template instantiation.
921    } else {
922      // (C++ 13p1):
923      //   Only function declarations can be overloaded; object and type
924      //   declarations cannot be overloaded.
925      Match = *I;
926      return Ovl_NonFunction;
927    }
928  }
929
930  return Ovl_Overload;
931}
932
933static bool canBeOverloaded(const FunctionDecl &D) {
934  if (D.getAttr<OverloadableAttr>())
935    return true;
936  if (D.hasCLanguageLinkage())
937    return false;
938
939  // Main cannot be overloaded (basic.start.main).
940  if (D.isMain())
941    return false;
942
943  return true;
944}
945
946bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
947                      bool UseUsingDeclRules) {
948  // If both of the functions are extern "C", then they are not
949  // overloads.
950  if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
951    return false;
952
953  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
954  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
955
956  // C++ [temp.fct]p2:
957  //   A function template can be overloaded with other function templates
958  //   and with normal (non-template) functions.
959  if ((OldTemplate == 0) != (NewTemplate == 0))
960    return true;
961
962  // Is the function New an overload of the function Old?
963  QualType OldQType = Context.getCanonicalType(Old->getType());
964  QualType NewQType = Context.getCanonicalType(New->getType());
965
966  // Compare the signatures (C++ 1.3.10) of the two functions to
967  // determine whether they are overloads. If we find any mismatch
968  // in the signature, they are overloads.
969
970  // If either of these functions is a K&R-style function (no
971  // prototype), then we consider them to have matching signatures.
972  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
973      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
974    return false;
975
976  const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
977  const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
978
979  // The signature of a function includes the types of its
980  // parameters (C++ 1.3.10), which includes the presence or absence
981  // of the ellipsis; see C++ DR 357).
982  if (OldQType != NewQType &&
983      (OldType->getNumArgs() != NewType->getNumArgs() ||
984       OldType->isVariadic() != NewType->isVariadic() ||
985       !FunctionArgTypesAreEqual(OldType, NewType)))
986    return true;
987
988  // C++ [temp.over.link]p4:
989  //   The signature of a function template consists of its function
990  //   signature, its return type and its template parameter list. The names
991  //   of the template parameters are significant only for establishing the
992  //   relationship between the template parameters and the rest of the
993  //   signature.
994  //
995  // We check the return type and template parameter lists for function
996  // templates first; the remaining checks follow.
997  //
998  // However, we don't consider either of these when deciding whether
999  // a member introduced by a shadow declaration is hidden.
1000  if (!UseUsingDeclRules && NewTemplate &&
1001      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1002                                       OldTemplate->getTemplateParameters(),
1003                                       false, TPL_TemplateMatch) ||
1004       OldType->getResultType() != NewType->getResultType()))
1005    return true;
1006
1007  // If the function is a class member, its signature includes the
1008  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1009  //
1010  // As part of this, also check whether one of the member functions
1011  // is static, in which case they are not overloads (C++
1012  // 13.1p2). While not part of the definition of the signature,
1013  // this check is important to determine whether these functions
1014  // can be overloaded.
1015  CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1016  CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1017  if (OldMethod && NewMethod &&
1018      !OldMethod->isStatic() && !NewMethod->isStatic() &&
1019      (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
1020       OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
1021    if (!UseUsingDeclRules &&
1022        OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
1023        (OldMethod->getRefQualifier() == RQ_None ||
1024         NewMethod->getRefQualifier() == RQ_None)) {
1025      // C++0x [over.load]p2:
1026      //   - Member function declarations with the same name and the same
1027      //     parameter-type-list as well as member function template
1028      //     declarations with the same name, the same parameter-type-list, and
1029      //     the same template parameter lists cannot be overloaded if any of
1030      //     them, but not all, have a ref-qualifier (8.3.5).
1031      Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1032        << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1033      Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1034    }
1035
1036    return true;
1037  }
1038
1039  // The signatures match; this is not an overload.
1040  return false;
1041}
1042
1043/// \brief Checks availability of the function depending on the current
1044/// function context. Inside an unavailable function, unavailability is ignored.
1045///
1046/// \returns true if \arg FD is unavailable and current context is inside
1047/// an available function, false otherwise.
1048bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1049  return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1050}
1051
1052/// \brief Tries a user-defined conversion from From to ToType.
1053///
1054/// Produces an implicit conversion sequence for when a standard conversion
1055/// is not an option. See TryImplicitConversion for more information.
1056static ImplicitConversionSequence
1057TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1058                         bool SuppressUserConversions,
1059                         bool AllowExplicit,
1060                         bool InOverloadResolution,
1061                         bool CStyle,
1062                         bool AllowObjCWritebackConversion) {
1063  ImplicitConversionSequence ICS;
1064
1065  if (SuppressUserConversions) {
1066    // We're not in the case above, so there is no conversion that
1067    // we can perform.
1068    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1069    return ICS;
1070  }
1071
1072  // Attempt user-defined conversion.
1073  OverloadCandidateSet Conversions(From->getExprLoc());
1074  OverloadingResult UserDefResult
1075    = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1076                              AllowExplicit);
1077
1078  if (UserDefResult == OR_Success) {
1079    ICS.setUserDefined();
1080    // C++ [over.ics.user]p4:
1081    //   A conversion of an expression of class type to the same class
1082    //   type is given Exact Match rank, and a conversion of an
1083    //   expression of class type to a base class of that type is
1084    //   given Conversion rank, in spite of the fact that a copy
1085    //   constructor (i.e., a user-defined conversion function) is
1086    //   called for those cases.
1087    if (CXXConstructorDecl *Constructor
1088          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1089      QualType FromCanon
1090        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1091      QualType ToCanon
1092        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1093      if (Constructor->isCopyConstructor() &&
1094          (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1095        // Turn this into a "standard" conversion sequence, so that it
1096        // gets ranked with standard conversion sequences.
1097        ICS.setStandard();
1098        ICS.Standard.setAsIdentityConversion();
1099        ICS.Standard.setFromType(From->getType());
1100        ICS.Standard.setAllToTypes(ToType);
1101        ICS.Standard.CopyConstructor = Constructor;
1102        if (ToCanon != FromCanon)
1103          ICS.Standard.Second = ICK_Derived_To_Base;
1104      }
1105    }
1106
1107    // C++ [over.best.ics]p4:
1108    //   However, when considering the argument of a user-defined
1109    //   conversion function that is a candidate by 13.3.1.3 when
1110    //   invoked for the copying of the temporary in the second step
1111    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1112    //   13.3.1.6 in all cases, only standard conversion sequences and
1113    //   ellipsis conversion sequences are allowed.
1114    if (SuppressUserConversions && ICS.isUserDefined()) {
1115      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1116    }
1117  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1118    ICS.setAmbiguous();
1119    ICS.Ambiguous.setFromType(From->getType());
1120    ICS.Ambiguous.setToType(ToType);
1121    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1122         Cand != Conversions.end(); ++Cand)
1123      if (Cand->Viable)
1124        ICS.Ambiguous.addConversion(Cand->Function);
1125  } else {
1126    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1127  }
1128
1129  return ICS;
1130}
1131
1132/// TryImplicitConversion - Attempt to perform an implicit conversion
1133/// from the given expression (Expr) to the given type (ToType). This
1134/// function returns an implicit conversion sequence that can be used
1135/// to perform the initialization. Given
1136///
1137///   void f(float f);
1138///   void g(int i) { f(i); }
1139///
1140/// this routine would produce an implicit conversion sequence to
1141/// describe the initialization of f from i, which will be a standard
1142/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1143/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1144//
1145/// Note that this routine only determines how the conversion can be
1146/// performed; it does not actually perform the conversion. As such,
1147/// it will not produce any diagnostics if no conversion is available,
1148/// but will instead return an implicit conversion sequence of kind
1149/// "BadConversion".
1150///
1151/// If @p SuppressUserConversions, then user-defined conversions are
1152/// not permitted.
1153/// If @p AllowExplicit, then explicit user-defined conversions are
1154/// permitted.
1155///
1156/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1157/// writeback conversion, which allows __autoreleasing id* parameters to
1158/// be initialized with __strong id* or __weak id* arguments.
1159static ImplicitConversionSequence
1160TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1161                      bool SuppressUserConversions,
1162                      bool AllowExplicit,
1163                      bool InOverloadResolution,
1164                      bool CStyle,
1165                      bool AllowObjCWritebackConversion) {
1166  ImplicitConversionSequence ICS;
1167  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1168                           ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1169    ICS.setStandard();
1170    return ICS;
1171  }
1172
1173  if (!S.getLangOpts().CPlusPlus) {
1174    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1175    return ICS;
1176  }
1177
1178  // C++ [over.ics.user]p4:
1179  //   A conversion of an expression of class type to the same class
1180  //   type is given Exact Match rank, and a conversion of an
1181  //   expression of class type to a base class of that type is
1182  //   given Conversion rank, in spite of the fact that a copy/move
1183  //   constructor (i.e., a user-defined conversion function) is
1184  //   called for those cases.
1185  QualType FromType = From->getType();
1186  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1187      (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1188       S.IsDerivedFrom(FromType, ToType))) {
1189    ICS.setStandard();
1190    ICS.Standard.setAsIdentityConversion();
1191    ICS.Standard.setFromType(FromType);
1192    ICS.Standard.setAllToTypes(ToType);
1193
1194    // We don't actually check at this point whether there is a valid
1195    // copy/move constructor, since overloading just assumes that it
1196    // exists. When we actually perform initialization, we'll find the
1197    // appropriate constructor to copy the returned object, if needed.
1198    ICS.Standard.CopyConstructor = 0;
1199
1200    // Determine whether this is considered a derived-to-base conversion.
1201    if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1202      ICS.Standard.Second = ICK_Derived_To_Base;
1203
1204    return ICS;
1205  }
1206
1207  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1208                                  AllowExplicit, InOverloadResolution, CStyle,
1209                                  AllowObjCWritebackConversion);
1210}
1211
1212ImplicitConversionSequence
1213Sema::TryImplicitConversion(Expr *From, QualType ToType,
1214                            bool SuppressUserConversions,
1215                            bool AllowExplicit,
1216                            bool InOverloadResolution,
1217                            bool CStyle,
1218                            bool AllowObjCWritebackConversion) {
1219  return clang::TryImplicitConversion(*this, From, ToType,
1220                                      SuppressUserConversions, AllowExplicit,
1221                                      InOverloadResolution, CStyle,
1222                                      AllowObjCWritebackConversion);
1223}
1224
1225/// PerformImplicitConversion - Perform an implicit conversion of the
1226/// expression From to the type ToType. Returns the
1227/// converted expression. Flavor is the kind of conversion we're
1228/// performing, used in the error message. If @p AllowExplicit,
1229/// explicit user-defined conversions are permitted.
1230ExprResult
1231Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1232                                AssignmentAction Action, bool AllowExplicit) {
1233  ImplicitConversionSequence ICS;
1234  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1235}
1236
1237ExprResult
1238Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1239                                AssignmentAction Action, bool AllowExplicit,
1240                                ImplicitConversionSequence& ICS) {
1241  if (checkPlaceholderForOverload(*this, From))
1242    return ExprError();
1243
1244  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1245  bool AllowObjCWritebackConversion
1246    = getLangOpts().ObjCAutoRefCount &&
1247      (Action == AA_Passing || Action == AA_Sending);
1248
1249  ICS = clang::TryImplicitConversion(*this, From, ToType,
1250                                     /*SuppressUserConversions=*/false,
1251                                     AllowExplicit,
1252                                     /*InOverloadResolution=*/false,
1253                                     /*CStyle=*/false,
1254                                     AllowObjCWritebackConversion);
1255  return PerformImplicitConversion(From, ToType, ICS, Action);
1256}
1257
1258/// \brief Determine whether the conversion from FromType to ToType is a valid
1259/// conversion that strips "noreturn" off the nested function type.
1260bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1261                                QualType &ResultTy) {
1262  if (Context.hasSameUnqualifiedType(FromType, ToType))
1263    return false;
1264
1265  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1266  // where F adds one of the following at most once:
1267  //   - a pointer
1268  //   - a member pointer
1269  //   - a block pointer
1270  CanQualType CanTo = Context.getCanonicalType(ToType);
1271  CanQualType CanFrom = Context.getCanonicalType(FromType);
1272  Type::TypeClass TyClass = CanTo->getTypeClass();
1273  if (TyClass != CanFrom->getTypeClass()) return false;
1274  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1275    if (TyClass == Type::Pointer) {
1276      CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1277      CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1278    } else if (TyClass == Type::BlockPointer) {
1279      CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1280      CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1281    } else if (TyClass == Type::MemberPointer) {
1282      CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1283      CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1284    } else {
1285      return false;
1286    }
1287
1288    TyClass = CanTo->getTypeClass();
1289    if (TyClass != CanFrom->getTypeClass()) return false;
1290    if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1291      return false;
1292  }
1293
1294  const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1295  FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1296  if (!EInfo.getNoReturn()) return false;
1297
1298  FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1299  assert(QualType(FromFn, 0).isCanonical());
1300  if (QualType(FromFn, 0) != CanTo) return false;
1301
1302  ResultTy = ToType;
1303  return true;
1304}
1305
1306/// \brief Determine whether the conversion from FromType to ToType is a valid
1307/// vector conversion.
1308///
1309/// \param ICK Will be set to the vector conversion kind, if this is a vector
1310/// conversion.
1311static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1312                               QualType ToType, ImplicitConversionKind &ICK) {
1313  // We need at least one of these types to be a vector type to have a vector
1314  // conversion.
1315  if (!ToType->isVectorType() && !FromType->isVectorType())
1316    return false;
1317
1318  // Identical types require no conversions.
1319  if (Context.hasSameUnqualifiedType(FromType, ToType))
1320    return false;
1321
1322  // There are no conversions between extended vector types, only identity.
1323  if (ToType->isExtVectorType()) {
1324    // There are no conversions between extended vector types other than the
1325    // identity conversion.
1326    if (FromType->isExtVectorType())
1327      return false;
1328
1329    // Vector splat from any arithmetic type to a vector.
1330    if (FromType->isArithmeticType()) {
1331      ICK = ICK_Vector_Splat;
1332      return true;
1333    }
1334  }
1335
1336  // We can perform the conversion between vector types in the following cases:
1337  // 1)vector types are equivalent AltiVec and GCC vector types
1338  // 2)lax vector conversions are permitted and the vector types are of the
1339  //   same size
1340  if (ToType->isVectorType() && FromType->isVectorType()) {
1341    if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1342        (Context.getLangOpts().LaxVectorConversions &&
1343         (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1344      ICK = ICK_Vector_Conversion;
1345      return true;
1346    }
1347  }
1348
1349  return false;
1350}
1351
1352static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1353                                bool InOverloadResolution,
1354                                StandardConversionSequence &SCS,
1355                                bool CStyle);
1356
1357/// IsStandardConversion - Determines whether there is a standard
1358/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1359/// expression From to the type ToType. Standard conversion sequences
1360/// only consider non-class types; for conversions that involve class
1361/// types, use TryImplicitConversion. If a conversion exists, SCS will
1362/// contain the standard conversion sequence required to perform this
1363/// conversion and this routine will return true. Otherwise, this
1364/// routine will return false and the value of SCS is unspecified.
1365static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1366                                 bool InOverloadResolution,
1367                                 StandardConversionSequence &SCS,
1368                                 bool CStyle,
1369                                 bool AllowObjCWritebackConversion) {
1370  QualType FromType = From->getType();
1371
1372  // Standard conversions (C++ [conv])
1373  SCS.setAsIdentityConversion();
1374  SCS.DeprecatedStringLiteralToCharPtr = false;
1375  SCS.IncompatibleObjC = false;
1376  SCS.setFromType(FromType);
1377  SCS.CopyConstructor = 0;
1378
1379  // There are no standard conversions for class types in C++, so
1380  // abort early. When overloading in C, however, we do permit
1381  if (FromType->isRecordType() || ToType->isRecordType()) {
1382    if (S.getLangOpts().CPlusPlus)
1383      return false;
1384
1385    // When we're overloading in C, we allow, as standard conversions,
1386  }
1387
1388  // The first conversion can be an lvalue-to-rvalue conversion,
1389  // array-to-pointer conversion, or function-to-pointer conversion
1390  // (C++ 4p1).
1391
1392  if (FromType == S.Context.OverloadTy) {
1393    DeclAccessPair AccessPair;
1394    if (FunctionDecl *Fn
1395          = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1396                                                 AccessPair)) {
1397      // We were able to resolve the address of the overloaded function,
1398      // so we can convert to the type of that function.
1399      FromType = Fn->getType();
1400
1401      // we can sometimes resolve &foo<int> regardless of ToType, so check
1402      // if the type matches (identity) or we are converting to bool
1403      if (!S.Context.hasSameUnqualifiedType(
1404                      S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1405        QualType resultTy;
1406        // if the function type matches except for [[noreturn]], it's ok
1407        if (!S.IsNoReturnConversion(FromType,
1408              S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1409          // otherwise, only a boolean conversion is standard
1410          if (!ToType->isBooleanType())
1411            return false;
1412      }
1413
1414      // Check if the "from" expression is taking the address of an overloaded
1415      // function and recompute the FromType accordingly. Take advantage of the
1416      // fact that non-static member functions *must* have such an address-of
1417      // expression.
1418      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1419      if (Method && !Method->isStatic()) {
1420        assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1421               "Non-unary operator on non-static member address");
1422        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1423               == UO_AddrOf &&
1424               "Non-address-of operator on non-static member address");
1425        const Type *ClassType
1426          = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1427        FromType = S.Context.getMemberPointerType(FromType, ClassType);
1428      } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1429        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1430               UO_AddrOf &&
1431               "Non-address-of operator for overloaded function expression");
1432        FromType = S.Context.getPointerType(FromType);
1433      }
1434
1435      // Check that we've computed the proper type after overload resolution.
1436      assert(S.Context.hasSameType(
1437        FromType,
1438        S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1439    } else {
1440      return false;
1441    }
1442  }
1443  // Lvalue-to-rvalue conversion (C++11 4.1):
1444  //   A glvalue (3.10) of a non-function, non-array type T can
1445  //   be converted to a prvalue.
1446  bool argIsLValue = From->isGLValue();
1447  if (argIsLValue &&
1448      !FromType->isFunctionType() && !FromType->isArrayType() &&
1449      S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1450    SCS.First = ICK_Lvalue_To_Rvalue;
1451
1452    // C11 6.3.2.1p2:
1453    //   ... if the lvalue has atomic type, the value has the non-atomic version
1454    //   of the type of the lvalue ...
1455    if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1456      FromType = Atomic->getValueType();
1457
1458    // If T is a non-class type, the type of the rvalue is the
1459    // cv-unqualified version of T. Otherwise, the type of the rvalue
1460    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1461    // just strip the qualifiers because they don't matter.
1462    FromType = FromType.getUnqualifiedType();
1463  } else if (FromType->isArrayType()) {
1464    // Array-to-pointer conversion (C++ 4.2)
1465    SCS.First = ICK_Array_To_Pointer;
1466
1467    // An lvalue or rvalue of type "array of N T" or "array of unknown
1468    // bound of T" can be converted to an rvalue of type "pointer to
1469    // T" (C++ 4.2p1).
1470    FromType = S.Context.getArrayDecayedType(FromType);
1471
1472    if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1473      // This conversion is deprecated. (C++ D.4).
1474      SCS.DeprecatedStringLiteralToCharPtr = true;
1475
1476      // For the purpose of ranking in overload resolution
1477      // (13.3.3.1.1), this conversion is considered an
1478      // array-to-pointer conversion followed by a qualification
1479      // conversion (4.4). (C++ 4.2p2)
1480      SCS.Second = ICK_Identity;
1481      SCS.Third = ICK_Qualification;
1482      SCS.QualificationIncludesObjCLifetime = false;
1483      SCS.setAllToTypes(FromType);
1484      return true;
1485    }
1486  } else if (FromType->isFunctionType() && argIsLValue) {
1487    // Function-to-pointer conversion (C++ 4.3).
1488    SCS.First = ICK_Function_To_Pointer;
1489
1490    // An lvalue of function type T can be converted to an rvalue of
1491    // type "pointer to T." The result is a pointer to the
1492    // function. (C++ 4.3p1).
1493    FromType = S.Context.getPointerType(FromType);
1494  } else {
1495    // We don't require any conversions for the first step.
1496    SCS.First = ICK_Identity;
1497  }
1498  SCS.setToType(0, FromType);
1499
1500  // The second conversion can be an integral promotion, floating
1501  // point promotion, integral conversion, floating point conversion,
1502  // floating-integral conversion, pointer conversion,
1503  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1504  // For overloading in C, this can also be a "compatible-type"
1505  // conversion.
1506  bool IncompatibleObjC = false;
1507  ImplicitConversionKind SecondICK = ICK_Identity;
1508  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1509    // The unqualified versions of the types are the same: there's no
1510    // conversion to do.
1511    SCS.Second = ICK_Identity;
1512  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1513    // Integral promotion (C++ 4.5).
1514    SCS.Second = ICK_Integral_Promotion;
1515    FromType = ToType.getUnqualifiedType();
1516  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1517    // Floating point promotion (C++ 4.6).
1518    SCS.Second = ICK_Floating_Promotion;
1519    FromType = ToType.getUnqualifiedType();
1520  } else if (S.IsComplexPromotion(FromType, ToType)) {
1521    // Complex promotion (Clang extension)
1522    SCS.Second = ICK_Complex_Promotion;
1523    FromType = ToType.getUnqualifiedType();
1524  } else if (ToType->isBooleanType() &&
1525             (FromType->isArithmeticType() ||
1526              FromType->isAnyPointerType() ||
1527              FromType->isBlockPointerType() ||
1528              FromType->isMemberPointerType() ||
1529              FromType->isNullPtrType())) {
1530    // Boolean conversions (C++ 4.12).
1531    SCS.Second = ICK_Boolean_Conversion;
1532    FromType = S.Context.BoolTy;
1533  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1534             ToType->isIntegralType(S.Context)) {
1535    // Integral conversions (C++ 4.7).
1536    SCS.Second = ICK_Integral_Conversion;
1537    FromType = ToType.getUnqualifiedType();
1538  } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1539    // Complex conversions (C99 6.3.1.6)
1540    SCS.Second = ICK_Complex_Conversion;
1541    FromType = ToType.getUnqualifiedType();
1542  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1543             (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1544    // Complex-real conversions (C99 6.3.1.7)
1545    SCS.Second = ICK_Complex_Real;
1546    FromType = ToType.getUnqualifiedType();
1547  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1548    // Floating point conversions (C++ 4.8).
1549    SCS.Second = ICK_Floating_Conversion;
1550    FromType = ToType.getUnqualifiedType();
1551  } else if ((FromType->isRealFloatingType() &&
1552              ToType->isIntegralType(S.Context)) ||
1553             (FromType->isIntegralOrUnscopedEnumerationType() &&
1554              ToType->isRealFloatingType())) {
1555    // Floating-integral conversions (C++ 4.9).
1556    SCS.Second = ICK_Floating_Integral;
1557    FromType = ToType.getUnqualifiedType();
1558  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1559    SCS.Second = ICK_Block_Pointer_Conversion;
1560  } else if (AllowObjCWritebackConversion &&
1561             S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1562    SCS.Second = ICK_Writeback_Conversion;
1563  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1564                                   FromType, IncompatibleObjC)) {
1565    // Pointer conversions (C++ 4.10).
1566    SCS.Second = ICK_Pointer_Conversion;
1567    SCS.IncompatibleObjC = IncompatibleObjC;
1568    FromType = FromType.getUnqualifiedType();
1569  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1570                                         InOverloadResolution, FromType)) {
1571    // Pointer to member conversions (4.11).
1572    SCS.Second = ICK_Pointer_Member;
1573  } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1574    SCS.Second = SecondICK;
1575    FromType = ToType.getUnqualifiedType();
1576  } else if (!S.getLangOpts().CPlusPlus &&
1577             S.Context.typesAreCompatible(ToType, FromType)) {
1578    // Compatible conversions (Clang extension for C function overloading)
1579    SCS.Second = ICK_Compatible_Conversion;
1580    FromType = ToType.getUnqualifiedType();
1581  } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1582    // Treat a conversion that strips "noreturn" as an identity conversion.
1583    SCS.Second = ICK_NoReturn_Adjustment;
1584  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1585                                             InOverloadResolution,
1586                                             SCS, CStyle)) {
1587    SCS.Second = ICK_TransparentUnionConversion;
1588    FromType = ToType;
1589  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1590                                 CStyle)) {
1591    // tryAtomicConversion has updated the standard conversion sequence
1592    // appropriately.
1593    return true;
1594  } else {
1595    // No second conversion required.
1596    SCS.Second = ICK_Identity;
1597  }
1598  SCS.setToType(1, FromType);
1599
1600  QualType CanonFrom;
1601  QualType CanonTo;
1602  // The third conversion can be a qualification conversion (C++ 4p1).
1603  bool ObjCLifetimeConversion;
1604  if (S.IsQualificationConversion(FromType, ToType, CStyle,
1605                                  ObjCLifetimeConversion)) {
1606    SCS.Third = ICK_Qualification;
1607    SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1608    FromType = ToType;
1609    CanonFrom = S.Context.getCanonicalType(FromType);
1610    CanonTo = S.Context.getCanonicalType(ToType);
1611  } else {
1612    // No conversion required
1613    SCS.Third = ICK_Identity;
1614
1615    // C++ [over.best.ics]p6:
1616    //   [...] Any difference in top-level cv-qualification is
1617    //   subsumed by the initialization itself and does not constitute
1618    //   a conversion. [...]
1619    CanonFrom = S.Context.getCanonicalType(FromType);
1620    CanonTo = S.Context.getCanonicalType(ToType);
1621    if (CanonFrom.getLocalUnqualifiedType()
1622                                       == CanonTo.getLocalUnqualifiedType() &&
1623        (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1624         || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1625         || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
1626      FromType = ToType;
1627      CanonFrom = CanonTo;
1628    }
1629  }
1630  SCS.setToType(2, FromType);
1631
1632  // If we have not converted the argument type to the parameter type,
1633  // this is a bad conversion sequence.
1634  if (CanonFrom != CanonTo)
1635    return false;
1636
1637  return true;
1638}
1639
1640static bool
1641IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1642                                     QualType &ToType,
1643                                     bool InOverloadResolution,
1644                                     StandardConversionSequence &SCS,
1645                                     bool CStyle) {
1646
1647  const RecordType *UT = ToType->getAsUnionType();
1648  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1649    return false;
1650  // The field to initialize within the transparent union.
1651  RecordDecl *UD = UT->getDecl();
1652  // It's compatible if the expression matches any of the fields.
1653  for (RecordDecl::field_iterator it = UD->field_begin(),
1654       itend = UD->field_end();
1655       it != itend; ++it) {
1656    if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1657                             CStyle, /*ObjCWritebackConversion=*/false)) {
1658      ToType = it->getType();
1659      return true;
1660    }
1661  }
1662  return false;
1663}
1664
1665/// IsIntegralPromotion - Determines whether the conversion from the
1666/// expression From (whose potentially-adjusted type is FromType) to
1667/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1668/// sets PromotedType to the promoted type.
1669bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1670  const BuiltinType *To = ToType->getAs<BuiltinType>();
1671  // All integers are built-in.
1672  if (!To) {
1673    return false;
1674  }
1675
1676  // An rvalue of type char, signed char, unsigned char, short int, or
1677  // unsigned short int can be converted to an rvalue of type int if
1678  // int can represent all the values of the source type; otherwise,
1679  // the source rvalue can be converted to an rvalue of type unsigned
1680  // int (C++ 4.5p1).
1681  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1682      !FromType->isEnumeralType()) {
1683    if (// We can promote any signed, promotable integer type to an int
1684        (FromType->isSignedIntegerType() ||
1685         // We can promote any unsigned integer type whose size is
1686         // less than int to an int.
1687         (!FromType->isSignedIntegerType() &&
1688          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1689      return To->getKind() == BuiltinType::Int;
1690    }
1691
1692    return To->getKind() == BuiltinType::UInt;
1693  }
1694
1695  // C++11 [conv.prom]p3:
1696  //   A prvalue of an unscoped enumeration type whose underlying type is not
1697  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1698  //   following types that can represent all the values of the enumeration
1699  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1700  //   unsigned int, long int, unsigned long int, long long int, or unsigned
1701  //   long long int. If none of the types in that list can represent all the
1702  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1703  //   type can be converted to an rvalue a prvalue of the extended integer type
1704  //   with lowest integer conversion rank (4.13) greater than the rank of long
1705  //   long in which all the values of the enumeration can be represented. If
1706  //   there are two such extended types, the signed one is chosen.
1707  // C++11 [conv.prom]p4:
1708  //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1709  //   can be converted to a prvalue of its underlying type. Moreover, if
1710  //   integral promotion can be applied to its underlying type, a prvalue of an
1711  //   unscoped enumeration type whose underlying type is fixed can also be
1712  //   converted to a prvalue of the promoted underlying type.
1713  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1714    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1715    // provided for a scoped enumeration.
1716    if (FromEnumType->getDecl()->isScoped())
1717      return false;
1718
1719    // We can perform an integral promotion to the underlying type of the enum,
1720    // even if that's not the promoted type.
1721    if (FromEnumType->getDecl()->isFixed()) {
1722      QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1723      return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1724             IsIntegralPromotion(From, Underlying, ToType);
1725    }
1726
1727    // We have already pre-calculated the promotion type, so this is trivial.
1728    if (ToType->isIntegerType() &&
1729        !RequireCompleteType(From->getLocStart(), FromType, 0))
1730      return Context.hasSameUnqualifiedType(ToType,
1731                                FromEnumType->getDecl()->getPromotionType());
1732  }
1733
1734  // C++0x [conv.prom]p2:
1735  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1736  //   to an rvalue a prvalue of the first of the following types that can
1737  //   represent all the values of its underlying type: int, unsigned int,
1738  //   long int, unsigned long int, long long int, or unsigned long long int.
1739  //   If none of the types in that list can represent all the values of its
1740  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1741  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1742  //   type.
1743  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1744      ToType->isIntegerType()) {
1745    // Determine whether the type we're converting from is signed or
1746    // unsigned.
1747    bool FromIsSigned = FromType->isSignedIntegerType();
1748    uint64_t FromSize = Context.getTypeSize(FromType);
1749
1750    // The types we'll try to promote to, in the appropriate
1751    // order. Try each of these types.
1752    QualType PromoteTypes[6] = {
1753      Context.IntTy, Context.UnsignedIntTy,
1754      Context.LongTy, Context.UnsignedLongTy ,
1755      Context.LongLongTy, Context.UnsignedLongLongTy
1756    };
1757    for (int Idx = 0; Idx < 6; ++Idx) {
1758      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1759      if (FromSize < ToSize ||
1760          (FromSize == ToSize &&
1761           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1762        // We found the type that we can promote to. If this is the
1763        // type we wanted, we have a promotion. Otherwise, no
1764        // promotion.
1765        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1766      }
1767    }
1768  }
1769
1770  // An rvalue for an integral bit-field (9.6) can be converted to an
1771  // rvalue of type int if int can represent all the values of the
1772  // bit-field; otherwise, it can be converted to unsigned int if
1773  // unsigned int can represent all the values of the bit-field. If
1774  // the bit-field is larger yet, no integral promotion applies to
1775  // it. If the bit-field has an enumerated type, it is treated as any
1776  // other value of that type for promotion purposes (C++ 4.5p3).
1777  // FIXME: We should delay checking of bit-fields until we actually perform the
1778  // conversion.
1779  using llvm::APSInt;
1780  if (From)
1781    if (FieldDecl *MemberDecl = From->getBitField()) {
1782      APSInt BitWidth;
1783      if (FromType->isIntegralType(Context) &&
1784          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1785        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1786        ToSize = Context.getTypeSize(ToType);
1787
1788        // Are we promoting to an int from a bitfield that fits in an int?
1789        if (BitWidth < ToSize ||
1790            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1791          return To->getKind() == BuiltinType::Int;
1792        }
1793
1794        // Are we promoting to an unsigned int from an unsigned bitfield
1795        // that fits into an unsigned int?
1796        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1797          return To->getKind() == BuiltinType::UInt;
1798        }
1799
1800        return false;
1801      }
1802    }
1803
1804  // An rvalue of type bool can be converted to an rvalue of type int,
1805  // with false becoming zero and true becoming one (C++ 4.5p4).
1806  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1807    return true;
1808  }
1809
1810  return false;
1811}
1812
1813/// IsFloatingPointPromotion - Determines whether the conversion from
1814/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1815/// returns true and sets PromotedType to the promoted type.
1816bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1817  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1818    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1819      /// An rvalue of type float can be converted to an rvalue of type
1820      /// double. (C++ 4.6p1).
1821      if (FromBuiltin->getKind() == BuiltinType::Float &&
1822          ToBuiltin->getKind() == BuiltinType::Double)
1823        return true;
1824
1825      // C99 6.3.1.5p1:
1826      //   When a float is promoted to double or long double, or a
1827      //   double is promoted to long double [...].
1828      if (!getLangOpts().CPlusPlus &&
1829          (FromBuiltin->getKind() == BuiltinType::Float ||
1830           FromBuiltin->getKind() == BuiltinType::Double) &&
1831          (ToBuiltin->getKind() == BuiltinType::LongDouble))
1832        return true;
1833
1834      // Half can be promoted to float.
1835      if (FromBuiltin->getKind() == BuiltinType::Half &&
1836          ToBuiltin->getKind() == BuiltinType::Float)
1837        return true;
1838    }
1839
1840  return false;
1841}
1842
1843/// \brief Determine if a conversion is a complex promotion.
1844///
1845/// A complex promotion is defined as a complex -> complex conversion
1846/// where the conversion between the underlying real types is a
1847/// floating-point or integral promotion.
1848bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1849  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1850  if (!FromComplex)
1851    return false;
1852
1853  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1854  if (!ToComplex)
1855    return false;
1856
1857  return IsFloatingPointPromotion(FromComplex->getElementType(),
1858                                  ToComplex->getElementType()) ||
1859    IsIntegralPromotion(0, FromComplex->getElementType(),
1860                        ToComplex->getElementType());
1861}
1862
1863/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1864/// the pointer type FromPtr to a pointer to type ToPointee, with the
1865/// same type qualifiers as FromPtr has on its pointee type. ToType,
1866/// if non-empty, will be a pointer to ToType that may or may not have
1867/// the right set of qualifiers on its pointee.
1868///
1869static QualType
1870BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1871                                   QualType ToPointee, QualType ToType,
1872                                   ASTContext &Context,
1873                                   bool StripObjCLifetime = false) {
1874  assert((FromPtr->getTypeClass() == Type::Pointer ||
1875          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1876         "Invalid similarly-qualified pointer type");
1877
1878  /// Conversions to 'id' subsume cv-qualifier conversions.
1879  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1880    return ToType.getUnqualifiedType();
1881
1882  QualType CanonFromPointee
1883    = Context.getCanonicalType(FromPtr->getPointeeType());
1884  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1885  Qualifiers Quals = CanonFromPointee.getQualifiers();
1886
1887  if (StripObjCLifetime)
1888    Quals.removeObjCLifetime();
1889
1890  // Exact qualifier match -> return the pointer type we're converting to.
1891  if (CanonToPointee.getLocalQualifiers() == Quals) {
1892    // ToType is exactly what we need. Return it.
1893    if (!ToType.isNull())
1894      return ToType.getUnqualifiedType();
1895
1896    // Build a pointer to ToPointee. It has the right qualifiers
1897    // already.
1898    if (isa<ObjCObjectPointerType>(ToType))
1899      return Context.getObjCObjectPointerType(ToPointee);
1900    return Context.getPointerType(ToPointee);
1901  }
1902
1903  // Just build a canonical type that has the right qualifiers.
1904  QualType QualifiedCanonToPointee
1905    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1906
1907  if (isa<ObjCObjectPointerType>(ToType))
1908    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1909  return Context.getPointerType(QualifiedCanonToPointee);
1910}
1911
1912static bool isNullPointerConstantForConversion(Expr *Expr,
1913                                               bool InOverloadResolution,
1914                                               ASTContext &Context) {
1915  // Handle value-dependent integral null pointer constants correctly.
1916  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1917  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1918      Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1919    return !InOverloadResolution;
1920
1921  return Expr->isNullPointerConstant(Context,
1922                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1923                                        : Expr::NPC_ValueDependentIsNull);
1924}
1925
1926/// IsPointerConversion - Determines whether the conversion of the
1927/// expression From, which has the (possibly adjusted) type FromType,
1928/// can be converted to the type ToType via a pointer conversion (C++
1929/// 4.10). If so, returns true and places the converted type (that
1930/// might differ from ToType in its cv-qualifiers at some level) into
1931/// ConvertedType.
1932///
1933/// This routine also supports conversions to and from block pointers
1934/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1935/// pointers to interfaces. FIXME: Once we've determined the
1936/// appropriate overloading rules for Objective-C, we may want to
1937/// split the Objective-C checks into a different routine; however,
1938/// GCC seems to consider all of these conversions to be pointer
1939/// conversions, so for now they live here. IncompatibleObjC will be
1940/// set if the conversion is an allowed Objective-C conversion that
1941/// should result in a warning.
1942bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1943                               bool InOverloadResolution,
1944                               QualType& ConvertedType,
1945                               bool &IncompatibleObjC) {
1946  IncompatibleObjC = false;
1947  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1948                              IncompatibleObjC))
1949    return true;
1950
1951  // Conversion from a null pointer constant to any Objective-C pointer type.
1952  if (ToType->isObjCObjectPointerType() &&
1953      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1954    ConvertedType = ToType;
1955    return true;
1956  }
1957
1958  // Blocks: Block pointers can be converted to void*.
1959  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1960      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1961    ConvertedType = ToType;
1962    return true;
1963  }
1964  // Blocks: A null pointer constant can be converted to a block
1965  // pointer type.
1966  if (ToType->isBlockPointerType() &&
1967      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1968    ConvertedType = ToType;
1969    return true;
1970  }
1971
1972  // If the left-hand-side is nullptr_t, the right side can be a null
1973  // pointer constant.
1974  if (ToType->isNullPtrType() &&
1975      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1976    ConvertedType = ToType;
1977    return true;
1978  }
1979
1980  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
1981  if (!ToTypePtr)
1982    return false;
1983
1984  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
1985  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1986    ConvertedType = ToType;
1987    return true;
1988  }
1989
1990  // Beyond this point, both types need to be pointers
1991  // , including objective-c pointers.
1992  QualType ToPointeeType = ToTypePtr->getPointeeType();
1993  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1994      !getLangOpts().ObjCAutoRefCount) {
1995    ConvertedType = BuildSimilarlyQualifiedPointerType(
1996                                      FromType->getAs<ObjCObjectPointerType>(),
1997                                                       ToPointeeType,
1998                                                       ToType, Context);
1999    return true;
2000  }
2001  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2002  if (!FromTypePtr)
2003    return false;
2004
2005  QualType FromPointeeType = FromTypePtr->getPointeeType();
2006
2007  // If the unqualified pointee types are the same, this can't be a
2008  // pointer conversion, so don't do all of the work below.
2009  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2010    return false;
2011
2012  // An rvalue of type "pointer to cv T," where T is an object type,
2013  // can be converted to an rvalue of type "pointer to cv void" (C++
2014  // 4.10p2).
2015  if (FromPointeeType->isIncompleteOrObjectType() &&
2016      ToPointeeType->isVoidType()) {
2017    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2018                                                       ToPointeeType,
2019                                                       ToType, Context,
2020                                                   /*StripObjCLifetime=*/true);
2021    return true;
2022  }
2023
2024  // MSVC allows implicit function to void* type conversion.
2025  if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2026      ToPointeeType->isVoidType()) {
2027    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2028                                                       ToPointeeType,
2029                                                       ToType, Context);
2030    return true;
2031  }
2032
2033  // When we're overloading in C, we allow a special kind of pointer
2034  // conversion for compatible-but-not-identical pointee types.
2035  if (!getLangOpts().CPlusPlus &&
2036      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2037    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2038                                                       ToPointeeType,
2039                                                       ToType, Context);
2040    return true;
2041  }
2042
2043  // C++ [conv.ptr]p3:
2044  //
2045  //   An rvalue of type "pointer to cv D," where D is a class type,
2046  //   can be converted to an rvalue of type "pointer to cv B," where
2047  //   B is a base class (clause 10) of D. If B is an inaccessible
2048  //   (clause 11) or ambiguous (10.2) base class of D, a program that
2049  //   necessitates this conversion is ill-formed. The result of the
2050  //   conversion is a pointer to the base class sub-object of the
2051  //   derived class object. The null pointer value is converted to
2052  //   the null pointer value of the destination type.
2053  //
2054  // Note that we do not check for ambiguity or inaccessibility
2055  // here. That is handled by CheckPointerConversion.
2056  if (getLangOpts().CPlusPlus &&
2057      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2058      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2059      !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2060      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2061    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2062                                                       ToPointeeType,
2063                                                       ToType, Context);
2064    return true;
2065  }
2066
2067  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2068      Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2069    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2070                                                       ToPointeeType,
2071                                                       ToType, Context);
2072    return true;
2073  }
2074
2075  return false;
2076}
2077
2078/// \brief Adopt the given qualifiers for the given type.
2079static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2080  Qualifiers TQs = T.getQualifiers();
2081
2082  // Check whether qualifiers already match.
2083  if (TQs == Qs)
2084    return T;
2085
2086  if (Qs.compatiblyIncludes(TQs))
2087    return Context.getQualifiedType(T, Qs);
2088
2089  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2090}
2091
2092/// isObjCPointerConversion - Determines whether this is an
2093/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2094/// with the same arguments and return values.
2095bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2096                                   QualType& ConvertedType,
2097                                   bool &IncompatibleObjC) {
2098  if (!getLangOpts().ObjC1)
2099    return false;
2100
2101  // The set of qualifiers on the type we're converting from.
2102  Qualifiers FromQualifiers = FromType.getQualifiers();
2103
2104  // First, we handle all conversions on ObjC object pointer types.
2105  const ObjCObjectPointerType* ToObjCPtr =
2106    ToType->getAs<ObjCObjectPointerType>();
2107  const ObjCObjectPointerType *FromObjCPtr =
2108    FromType->getAs<ObjCObjectPointerType>();
2109
2110  if (ToObjCPtr && FromObjCPtr) {
2111    // If the pointee types are the same (ignoring qualifications),
2112    // then this is not a pointer conversion.
2113    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2114                                       FromObjCPtr->getPointeeType()))
2115      return false;
2116
2117    // Check for compatible
2118    // Objective C++: We're able to convert between "id" or "Class" and a
2119    // pointer to any interface (in both directions).
2120    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2121      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2122      return true;
2123    }
2124    // Conversions with Objective-C's id<...>.
2125    if ((FromObjCPtr->isObjCQualifiedIdType() ||
2126         ToObjCPtr->isObjCQualifiedIdType()) &&
2127        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2128                                                  /*compare=*/false)) {
2129      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2130      return true;
2131    }
2132    // Objective C++: We're able to convert from a pointer to an
2133    // interface to a pointer to a different interface.
2134    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2135      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2136      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2137      if (getLangOpts().CPlusPlus && LHS && RHS &&
2138          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2139                                                FromObjCPtr->getPointeeType()))
2140        return false;
2141      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2142                                                   ToObjCPtr->getPointeeType(),
2143                                                         ToType, Context);
2144      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2145      return true;
2146    }
2147
2148    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2149      // Okay: this is some kind of implicit downcast of Objective-C
2150      // interfaces, which is permitted. However, we're going to
2151      // complain about it.
2152      IncompatibleObjC = true;
2153      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2154                                                   ToObjCPtr->getPointeeType(),
2155                                                         ToType, Context);
2156      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2157      return true;
2158    }
2159  }
2160  // Beyond this point, both types need to be C pointers or block pointers.
2161  QualType ToPointeeType;
2162  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2163    ToPointeeType = ToCPtr->getPointeeType();
2164  else if (const BlockPointerType *ToBlockPtr =
2165            ToType->getAs<BlockPointerType>()) {
2166    // Objective C++: We're able to convert from a pointer to any object
2167    // to a block pointer type.
2168    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2169      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2170      return true;
2171    }
2172    ToPointeeType = ToBlockPtr->getPointeeType();
2173  }
2174  else if (FromType->getAs<BlockPointerType>() &&
2175           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2176    // Objective C++: We're able to convert from a block pointer type to a
2177    // pointer to any object.
2178    ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2179    return true;
2180  }
2181  else
2182    return false;
2183
2184  QualType FromPointeeType;
2185  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2186    FromPointeeType = FromCPtr->getPointeeType();
2187  else if (const BlockPointerType *FromBlockPtr =
2188           FromType->getAs<BlockPointerType>())
2189    FromPointeeType = FromBlockPtr->getPointeeType();
2190  else
2191    return false;
2192
2193  // If we have pointers to pointers, recursively check whether this
2194  // is an Objective-C conversion.
2195  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2196      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2197                              IncompatibleObjC)) {
2198    // We always complain about this conversion.
2199    IncompatibleObjC = true;
2200    ConvertedType = Context.getPointerType(ConvertedType);
2201    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2202    return true;
2203  }
2204  // Allow conversion of pointee being objective-c pointer to another one;
2205  // as in I* to id.
2206  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2207      ToPointeeType->getAs<ObjCObjectPointerType>() &&
2208      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2209                              IncompatibleObjC)) {
2210
2211    ConvertedType = Context.getPointerType(ConvertedType);
2212    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2213    return true;
2214  }
2215
2216  // If we have pointers to functions or blocks, check whether the only
2217  // differences in the argument and result types are in Objective-C
2218  // pointer conversions. If so, we permit the conversion (but
2219  // complain about it).
2220  const FunctionProtoType *FromFunctionType
2221    = FromPointeeType->getAs<FunctionProtoType>();
2222  const FunctionProtoType *ToFunctionType
2223    = ToPointeeType->getAs<FunctionProtoType>();
2224  if (FromFunctionType && ToFunctionType) {
2225    // If the function types are exactly the same, this isn't an
2226    // Objective-C pointer conversion.
2227    if (Context.getCanonicalType(FromPointeeType)
2228          == Context.getCanonicalType(ToPointeeType))
2229      return false;
2230
2231    // Perform the quick checks that will tell us whether these
2232    // function types are obviously different.
2233    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2234        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2235        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2236      return false;
2237
2238    bool HasObjCConversion = false;
2239    if (Context.getCanonicalType(FromFunctionType->getResultType())
2240          == Context.getCanonicalType(ToFunctionType->getResultType())) {
2241      // Okay, the types match exactly. Nothing to do.
2242    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2243                                       ToFunctionType->getResultType(),
2244                                       ConvertedType, IncompatibleObjC)) {
2245      // Okay, we have an Objective-C pointer conversion.
2246      HasObjCConversion = true;
2247    } else {
2248      // Function types are too different. Abort.
2249      return false;
2250    }
2251
2252    // Check argument types.
2253    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2254         ArgIdx != NumArgs; ++ArgIdx) {
2255      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2256      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2257      if (Context.getCanonicalType(FromArgType)
2258            == Context.getCanonicalType(ToArgType)) {
2259        // Okay, the types match exactly. Nothing to do.
2260      } else if (isObjCPointerConversion(FromArgType, ToArgType,
2261                                         ConvertedType, IncompatibleObjC)) {
2262        // Okay, we have an Objective-C pointer conversion.
2263        HasObjCConversion = true;
2264      } else {
2265        // Argument types are too different. Abort.
2266        return false;
2267      }
2268    }
2269
2270    if (HasObjCConversion) {
2271      // We had an Objective-C conversion. Allow this pointer
2272      // conversion, but complain about it.
2273      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2274      IncompatibleObjC = true;
2275      return true;
2276    }
2277  }
2278
2279  return false;
2280}
2281
2282/// \brief Determine whether this is an Objective-C writeback conversion,
2283/// used for parameter passing when performing automatic reference counting.
2284///
2285/// \param FromType The type we're converting form.
2286///
2287/// \param ToType The type we're converting to.
2288///
2289/// \param ConvertedType The type that will be produced after applying
2290/// this conversion.
2291bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2292                                     QualType &ConvertedType) {
2293  if (!getLangOpts().ObjCAutoRefCount ||
2294      Context.hasSameUnqualifiedType(FromType, ToType))
2295    return false;
2296
2297  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2298  QualType ToPointee;
2299  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2300    ToPointee = ToPointer->getPointeeType();
2301  else
2302    return false;
2303
2304  Qualifiers ToQuals = ToPointee.getQualifiers();
2305  if (!ToPointee->isObjCLifetimeType() ||
2306      ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2307      !ToQuals.withoutObjCLifetime().empty())
2308    return false;
2309
2310  // Argument must be a pointer to __strong to __weak.
2311  QualType FromPointee;
2312  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2313    FromPointee = FromPointer->getPointeeType();
2314  else
2315    return false;
2316
2317  Qualifiers FromQuals = FromPointee.getQualifiers();
2318  if (!FromPointee->isObjCLifetimeType() ||
2319      (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2320       FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2321    return false;
2322
2323  // Make sure that we have compatible qualifiers.
2324  FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2325  if (!ToQuals.compatiblyIncludes(FromQuals))
2326    return false;
2327
2328  // Remove qualifiers from the pointee type we're converting from; they
2329  // aren't used in the compatibility check belong, and we'll be adding back
2330  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2331  FromPointee = FromPointee.getUnqualifiedType();
2332
2333  // The unqualified form of the pointee types must be compatible.
2334  ToPointee = ToPointee.getUnqualifiedType();
2335  bool IncompatibleObjC;
2336  if (Context.typesAreCompatible(FromPointee, ToPointee))
2337    FromPointee = ToPointee;
2338  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2339                                    IncompatibleObjC))
2340    return false;
2341
2342  /// \brief Construct the type we're converting to, which is a pointer to
2343  /// __autoreleasing pointee.
2344  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2345  ConvertedType = Context.getPointerType(FromPointee);
2346  return true;
2347}
2348
2349bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2350                                    QualType& ConvertedType) {
2351  QualType ToPointeeType;
2352  if (const BlockPointerType *ToBlockPtr =
2353        ToType->getAs<BlockPointerType>())
2354    ToPointeeType = ToBlockPtr->getPointeeType();
2355  else
2356    return false;
2357
2358  QualType FromPointeeType;
2359  if (const BlockPointerType *FromBlockPtr =
2360      FromType->getAs<BlockPointerType>())
2361    FromPointeeType = FromBlockPtr->getPointeeType();
2362  else
2363    return false;
2364  // We have pointer to blocks, check whether the only
2365  // differences in the argument and result types are in Objective-C
2366  // pointer conversions. If so, we permit the conversion.
2367
2368  const FunctionProtoType *FromFunctionType
2369    = FromPointeeType->getAs<FunctionProtoType>();
2370  const FunctionProtoType *ToFunctionType
2371    = ToPointeeType->getAs<FunctionProtoType>();
2372
2373  if (!FromFunctionType || !ToFunctionType)
2374    return false;
2375
2376  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2377    return true;
2378
2379  // Perform the quick checks that will tell us whether these
2380  // function types are obviously different.
2381  if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2382      FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2383    return false;
2384
2385  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2386  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2387  if (FromEInfo != ToEInfo)
2388    return false;
2389
2390  bool IncompatibleObjC = false;
2391  if (Context.hasSameType(FromFunctionType->getResultType(),
2392                          ToFunctionType->getResultType())) {
2393    // Okay, the types match exactly. Nothing to do.
2394  } else {
2395    QualType RHS = FromFunctionType->getResultType();
2396    QualType LHS = ToFunctionType->getResultType();
2397    if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2398        !RHS.hasQualifiers() && LHS.hasQualifiers())
2399       LHS = LHS.getUnqualifiedType();
2400
2401     if (Context.hasSameType(RHS,LHS)) {
2402       // OK exact match.
2403     } else if (isObjCPointerConversion(RHS, LHS,
2404                                        ConvertedType, IncompatibleObjC)) {
2405     if (IncompatibleObjC)
2406       return false;
2407     // Okay, we have an Objective-C pointer conversion.
2408     }
2409     else
2410       return false;
2411   }
2412
2413   // Check argument types.
2414   for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2415        ArgIdx != NumArgs; ++ArgIdx) {
2416     IncompatibleObjC = false;
2417     QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2418     QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2419     if (Context.hasSameType(FromArgType, ToArgType)) {
2420       // Okay, the types match exactly. Nothing to do.
2421     } else if (isObjCPointerConversion(ToArgType, FromArgType,
2422                                        ConvertedType, IncompatibleObjC)) {
2423       if (IncompatibleObjC)
2424         return false;
2425       // Okay, we have an Objective-C pointer conversion.
2426     } else
2427       // Argument types are too different. Abort.
2428       return false;
2429   }
2430   if (LangOpts.ObjCAutoRefCount &&
2431       !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2432                                                    ToFunctionType))
2433     return false;
2434
2435   ConvertedType = ToType;
2436   return true;
2437}
2438
2439enum {
2440  ft_default,
2441  ft_different_class,
2442  ft_parameter_arity,
2443  ft_parameter_mismatch,
2444  ft_return_type,
2445  ft_qualifer_mismatch
2446};
2447
2448/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2449/// function types.  Catches different number of parameter, mismatch in
2450/// parameter types, and different return types.
2451void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2452                                      QualType FromType, QualType ToType) {
2453  // If either type is not valid, include no extra info.
2454  if (FromType.isNull() || ToType.isNull()) {
2455    PDiag << ft_default;
2456    return;
2457  }
2458
2459  // Get the function type from the pointers.
2460  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2461    const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2462                            *ToMember = ToType->getAs<MemberPointerType>();
2463    if (FromMember->getClass() != ToMember->getClass()) {
2464      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2465            << QualType(FromMember->getClass(), 0);
2466      return;
2467    }
2468    FromType = FromMember->getPointeeType();
2469    ToType = ToMember->getPointeeType();
2470  }
2471
2472  if (FromType->isPointerType())
2473    FromType = FromType->getPointeeType();
2474  if (ToType->isPointerType())
2475    ToType = ToType->getPointeeType();
2476
2477  // Remove references.
2478  FromType = FromType.getNonReferenceType();
2479  ToType = ToType.getNonReferenceType();
2480
2481  // Don't print extra info for non-specialized template functions.
2482  if (FromType->isInstantiationDependentType() &&
2483      !FromType->getAs<TemplateSpecializationType>()) {
2484    PDiag << ft_default;
2485    return;
2486  }
2487
2488  // No extra info for same types.
2489  if (Context.hasSameType(FromType, ToType)) {
2490    PDiag << ft_default;
2491    return;
2492  }
2493
2494  const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2495                          *ToFunction = ToType->getAs<FunctionProtoType>();
2496
2497  // Both types need to be function types.
2498  if (!FromFunction || !ToFunction) {
2499    PDiag << ft_default;
2500    return;
2501  }
2502
2503  if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2504    PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2505          << FromFunction->getNumArgs();
2506    return;
2507  }
2508
2509  // Handle different parameter types.
2510  unsigned ArgPos;
2511  if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2512    PDiag << ft_parameter_mismatch << ArgPos + 1
2513          << ToFunction->getArgType(ArgPos)
2514          << FromFunction->getArgType(ArgPos);
2515    return;
2516  }
2517
2518  // Handle different return type.
2519  if (!Context.hasSameType(FromFunction->getResultType(),
2520                           ToFunction->getResultType())) {
2521    PDiag << ft_return_type << ToFunction->getResultType()
2522          << FromFunction->getResultType();
2523    return;
2524  }
2525
2526  unsigned FromQuals = FromFunction->getTypeQuals(),
2527           ToQuals = ToFunction->getTypeQuals();
2528  if (FromQuals != ToQuals) {
2529    PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2530    return;
2531  }
2532
2533  // Unable to find a difference, so add no extra info.
2534  PDiag << ft_default;
2535}
2536
2537/// FunctionArgTypesAreEqual - This routine checks two function proto types
2538/// for equality of their argument types. Caller has already checked that
2539/// they have same number of arguments. This routine assumes that Objective-C
2540/// pointer types which only differ in their protocol qualifiers are equal.
2541/// If the parameters are different, ArgPos will have the parameter index
2542/// of the first different parameter.
2543bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2544                                    const FunctionProtoType *NewType,
2545                                    unsigned *ArgPos) {
2546  if (!getLangOpts().ObjC1) {
2547    for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2548         N = NewType->arg_type_begin(),
2549         E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2550      if (!Context.hasSameType(*O, *N)) {
2551        if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2552        return false;
2553      }
2554    }
2555    return true;
2556  }
2557
2558  for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2559       N = NewType->arg_type_begin(),
2560       E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2561    QualType ToType = (*O);
2562    QualType FromType = (*N);
2563    if (!Context.hasSameType(ToType, FromType)) {
2564      if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2565        if (const PointerType *PTFr = FromType->getAs<PointerType>())
2566          if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2567               PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2568              (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2569               PTFr->getPointeeType()->isObjCQualifiedClassType()))
2570            continue;
2571      }
2572      else if (const ObjCObjectPointerType *PTTo =
2573                 ToType->getAs<ObjCObjectPointerType>()) {
2574        if (const ObjCObjectPointerType *PTFr =
2575              FromType->getAs<ObjCObjectPointerType>())
2576          if (Context.hasSameUnqualifiedType(
2577                PTTo->getObjectType()->getBaseType(),
2578                PTFr->getObjectType()->getBaseType()))
2579            continue;
2580      }
2581      if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2582      return false;
2583    }
2584  }
2585  return true;
2586}
2587
2588/// CheckPointerConversion - Check the pointer conversion from the
2589/// expression From to the type ToType. This routine checks for
2590/// ambiguous or inaccessible derived-to-base pointer
2591/// conversions for which IsPointerConversion has already returned
2592/// true. It returns true and produces a diagnostic if there was an
2593/// error, or returns false otherwise.
2594bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2595                                  CastKind &Kind,
2596                                  CXXCastPath& BasePath,
2597                                  bool IgnoreBaseAccess) {
2598  QualType FromType = From->getType();
2599  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2600
2601  Kind = CK_BitCast;
2602
2603  if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2604      From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2605      Expr::NPCK_ZeroExpression) {
2606    if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2607      DiagRuntimeBehavior(From->getExprLoc(), From,
2608                          PDiag(diag::warn_impcast_bool_to_null_pointer)
2609                            << ToType << From->getSourceRange());
2610    else if (!isUnevaluatedContext())
2611      Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2612        << ToType << From->getSourceRange();
2613  }
2614  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2615    if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2616      QualType FromPointeeType = FromPtrType->getPointeeType(),
2617               ToPointeeType   = ToPtrType->getPointeeType();
2618
2619      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2620          !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2621        // We must have a derived-to-base conversion. Check an
2622        // ambiguous or inaccessible conversion.
2623        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2624                                         From->getExprLoc(),
2625                                         From->getSourceRange(), &BasePath,
2626                                         IgnoreBaseAccess))
2627          return true;
2628
2629        // The conversion was successful.
2630        Kind = CK_DerivedToBase;
2631      }
2632    }
2633  } else if (const ObjCObjectPointerType *ToPtrType =
2634               ToType->getAs<ObjCObjectPointerType>()) {
2635    if (const ObjCObjectPointerType *FromPtrType =
2636          FromType->getAs<ObjCObjectPointerType>()) {
2637      // Objective-C++ conversions are always okay.
2638      // FIXME: We should have a different class of conversions for the
2639      // Objective-C++ implicit conversions.
2640      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2641        return false;
2642    } else if (FromType->isBlockPointerType()) {
2643      Kind = CK_BlockPointerToObjCPointerCast;
2644    } else {
2645      Kind = CK_CPointerToObjCPointerCast;
2646    }
2647  } else if (ToType->isBlockPointerType()) {
2648    if (!FromType->isBlockPointerType())
2649      Kind = CK_AnyPointerToBlockPointerCast;
2650  }
2651
2652  // We shouldn't fall into this case unless it's valid for other
2653  // reasons.
2654  if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2655    Kind = CK_NullToPointer;
2656
2657  return false;
2658}
2659
2660/// IsMemberPointerConversion - Determines whether the conversion of the
2661/// expression From, which has the (possibly adjusted) type FromType, can be
2662/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2663/// If so, returns true and places the converted type (that might differ from
2664/// ToType in its cv-qualifiers at some level) into ConvertedType.
2665bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2666                                     QualType ToType,
2667                                     bool InOverloadResolution,
2668                                     QualType &ConvertedType) {
2669  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2670  if (!ToTypePtr)
2671    return false;
2672
2673  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2674  if (From->isNullPointerConstant(Context,
2675                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2676                                        : Expr::NPC_ValueDependentIsNull)) {
2677    ConvertedType = ToType;
2678    return true;
2679  }
2680
2681  // Otherwise, both types have to be member pointers.
2682  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2683  if (!FromTypePtr)
2684    return false;
2685
2686  // A pointer to member of B can be converted to a pointer to member of D,
2687  // where D is derived from B (C++ 4.11p2).
2688  QualType FromClass(FromTypePtr->getClass(), 0);
2689  QualType ToClass(ToTypePtr->getClass(), 0);
2690
2691  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2692      !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2693      IsDerivedFrom(ToClass, FromClass)) {
2694    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2695                                                 ToClass.getTypePtr());
2696    return true;
2697  }
2698
2699  return false;
2700}
2701
2702/// CheckMemberPointerConversion - Check the member pointer conversion from the
2703/// expression From to the type ToType. This routine checks for ambiguous or
2704/// virtual or inaccessible base-to-derived member pointer conversions
2705/// for which IsMemberPointerConversion has already returned true. It returns
2706/// true and produces a diagnostic if there was an error, or returns false
2707/// otherwise.
2708bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2709                                        CastKind &Kind,
2710                                        CXXCastPath &BasePath,
2711                                        bool IgnoreBaseAccess) {
2712  QualType FromType = From->getType();
2713  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2714  if (!FromPtrType) {
2715    // This must be a null pointer to member pointer conversion
2716    assert(From->isNullPointerConstant(Context,
2717                                       Expr::NPC_ValueDependentIsNull) &&
2718           "Expr must be null pointer constant!");
2719    Kind = CK_NullToMemberPointer;
2720    return false;
2721  }
2722
2723  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2724  assert(ToPtrType && "No member pointer cast has a target type "
2725                      "that is not a member pointer.");
2726
2727  QualType FromClass = QualType(FromPtrType->getClass(), 0);
2728  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2729
2730  // FIXME: What about dependent types?
2731  assert(FromClass->isRecordType() && "Pointer into non-class.");
2732  assert(ToClass->isRecordType() && "Pointer into non-class.");
2733
2734  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2735                     /*DetectVirtual=*/true);
2736  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2737  assert(DerivationOkay &&
2738         "Should not have been called if derivation isn't OK.");
2739  (void)DerivationOkay;
2740
2741  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2742                                  getUnqualifiedType())) {
2743    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2744    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2745      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2746    return true;
2747  }
2748
2749  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2750    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2751      << FromClass << ToClass << QualType(VBase, 0)
2752      << From->getSourceRange();
2753    return true;
2754  }
2755
2756  if (!IgnoreBaseAccess)
2757    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2758                         Paths.front(),
2759                         diag::err_downcast_from_inaccessible_base);
2760
2761  // Must be a base to derived member conversion.
2762  BuildBasePathArray(Paths, BasePath);
2763  Kind = CK_BaseToDerivedMemberPointer;
2764  return false;
2765}
2766
2767/// IsQualificationConversion - Determines whether the conversion from
2768/// an rvalue of type FromType to ToType is a qualification conversion
2769/// (C++ 4.4).
2770///
2771/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2772/// when the qualification conversion involves a change in the Objective-C
2773/// object lifetime.
2774bool
2775Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2776                                bool CStyle, bool &ObjCLifetimeConversion) {
2777  FromType = Context.getCanonicalType(FromType);
2778  ToType = Context.getCanonicalType(ToType);
2779  ObjCLifetimeConversion = false;
2780
2781  // If FromType and ToType are the same type, this is not a
2782  // qualification conversion.
2783  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2784    return false;
2785
2786  // (C++ 4.4p4):
2787  //   A conversion can add cv-qualifiers at levels other than the first
2788  //   in multi-level pointers, subject to the following rules: [...]
2789  bool PreviousToQualsIncludeConst = true;
2790  bool UnwrappedAnyPointer = false;
2791  while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2792    // Within each iteration of the loop, we check the qualifiers to
2793    // determine if this still looks like a qualification
2794    // conversion. Then, if all is well, we unwrap one more level of
2795    // pointers or pointers-to-members and do it all again
2796    // until there are no more pointers or pointers-to-members left to
2797    // unwrap.
2798    UnwrappedAnyPointer = true;
2799
2800    Qualifiers FromQuals = FromType.getQualifiers();
2801    Qualifiers ToQuals = ToType.getQualifiers();
2802
2803    // Objective-C ARC:
2804    //   Check Objective-C lifetime conversions.
2805    if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2806        UnwrappedAnyPointer) {
2807      if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2808        ObjCLifetimeConversion = true;
2809        FromQuals.removeObjCLifetime();
2810        ToQuals.removeObjCLifetime();
2811      } else {
2812        // Qualification conversions cannot cast between different
2813        // Objective-C lifetime qualifiers.
2814        return false;
2815      }
2816    }
2817
2818    // Allow addition/removal of GC attributes but not changing GC attributes.
2819    if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2820        (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2821      FromQuals.removeObjCGCAttr();
2822      ToQuals.removeObjCGCAttr();
2823    }
2824
2825    //   -- for every j > 0, if const is in cv 1,j then const is in cv
2826    //      2,j, and similarly for volatile.
2827    if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2828      return false;
2829
2830    //   -- if the cv 1,j and cv 2,j are different, then const is in
2831    //      every cv for 0 < k < j.
2832    if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2833        && !PreviousToQualsIncludeConst)
2834      return false;
2835
2836    // Keep track of whether all prior cv-qualifiers in the "to" type
2837    // include const.
2838    PreviousToQualsIncludeConst
2839      = PreviousToQualsIncludeConst && ToQuals.hasConst();
2840  }
2841
2842  // We are left with FromType and ToType being the pointee types
2843  // after unwrapping the original FromType and ToType the same number
2844  // of types. If we unwrapped any pointers, and if FromType and
2845  // ToType have the same unqualified type (since we checked
2846  // qualifiers above), then this is a qualification conversion.
2847  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2848}
2849
2850/// \brief - Determine whether this is a conversion from a scalar type to an
2851/// atomic type.
2852///
2853/// If successful, updates \c SCS's second and third steps in the conversion
2854/// sequence to finish the conversion.
2855static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2856                                bool InOverloadResolution,
2857                                StandardConversionSequence &SCS,
2858                                bool CStyle) {
2859  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2860  if (!ToAtomic)
2861    return false;
2862
2863  StandardConversionSequence InnerSCS;
2864  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2865                            InOverloadResolution, InnerSCS,
2866                            CStyle, /*AllowObjCWritebackConversion=*/false))
2867    return false;
2868
2869  SCS.Second = InnerSCS.Second;
2870  SCS.setToType(1, InnerSCS.getToType(1));
2871  SCS.Third = InnerSCS.Third;
2872  SCS.QualificationIncludesObjCLifetime
2873    = InnerSCS.QualificationIncludesObjCLifetime;
2874  SCS.setToType(2, InnerSCS.getToType(2));
2875  return true;
2876}
2877
2878static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2879                                              CXXConstructorDecl *Constructor,
2880                                              QualType Type) {
2881  const FunctionProtoType *CtorType =
2882      Constructor->getType()->getAs<FunctionProtoType>();
2883  if (CtorType->getNumArgs() > 0) {
2884    QualType FirstArg = CtorType->getArgType(0);
2885    if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2886      return true;
2887  }
2888  return false;
2889}
2890
2891static OverloadingResult
2892IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2893                                       CXXRecordDecl *To,
2894                                       UserDefinedConversionSequence &User,
2895                                       OverloadCandidateSet &CandidateSet,
2896                                       bool AllowExplicit) {
2897  DeclContext::lookup_result R = S.LookupConstructors(To);
2898  for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2899       Con != ConEnd; ++Con) {
2900    NamedDecl *D = *Con;
2901    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2902
2903    // Find the constructor (which may be a template).
2904    CXXConstructorDecl *Constructor = 0;
2905    FunctionTemplateDecl *ConstructorTmpl
2906      = dyn_cast<FunctionTemplateDecl>(D);
2907    if (ConstructorTmpl)
2908      Constructor
2909        = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2910    else
2911      Constructor = cast<CXXConstructorDecl>(D);
2912
2913    bool Usable = !Constructor->isInvalidDecl() &&
2914                  S.isInitListConstructor(Constructor) &&
2915                  (AllowExplicit || !Constructor->isExplicit());
2916    if (Usable) {
2917      // If the first argument is (a reference to) the target type,
2918      // suppress conversions.
2919      bool SuppressUserConversions =
2920          isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2921      if (ConstructorTmpl)
2922        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2923                                       /*ExplicitArgs*/ 0,
2924                                       From, CandidateSet,
2925                                       SuppressUserConversions);
2926      else
2927        S.AddOverloadCandidate(Constructor, FoundDecl,
2928                               From, CandidateSet,
2929                               SuppressUserConversions);
2930    }
2931  }
2932
2933  bool HadMultipleCandidates = (CandidateSet.size() > 1);
2934
2935  OverloadCandidateSet::iterator Best;
2936  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2937  case OR_Success: {
2938    // Record the standard conversion we used and the conversion function.
2939    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2940    QualType ThisType = Constructor->getThisType(S.Context);
2941    // Initializer lists don't have conversions as such.
2942    User.Before.setAsIdentityConversion();
2943    User.HadMultipleCandidates = HadMultipleCandidates;
2944    User.ConversionFunction = Constructor;
2945    User.FoundConversionFunction = Best->FoundDecl;
2946    User.After.setAsIdentityConversion();
2947    User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2948    User.After.setAllToTypes(ToType);
2949    return OR_Success;
2950  }
2951
2952  case OR_No_Viable_Function:
2953    return OR_No_Viable_Function;
2954  case OR_Deleted:
2955    return OR_Deleted;
2956  case OR_Ambiguous:
2957    return OR_Ambiguous;
2958  }
2959
2960  llvm_unreachable("Invalid OverloadResult!");
2961}
2962
2963/// Determines whether there is a user-defined conversion sequence
2964/// (C++ [over.ics.user]) that converts expression From to the type
2965/// ToType. If such a conversion exists, User will contain the
2966/// user-defined conversion sequence that performs such a conversion
2967/// and this routine will return true. Otherwise, this routine returns
2968/// false and User is unspecified.
2969///
2970/// \param AllowExplicit  true if the conversion should consider C++0x
2971/// "explicit" conversion functions as well as non-explicit conversion
2972/// functions (C++0x [class.conv.fct]p2).
2973static OverloadingResult
2974IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2975                        UserDefinedConversionSequence &User,
2976                        OverloadCandidateSet &CandidateSet,
2977                        bool AllowExplicit) {
2978  // Whether we will only visit constructors.
2979  bool ConstructorsOnly = false;
2980
2981  // If the type we are conversion to is a class type, enumerate its
2982  // constructors.
2983  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2984    // C++ [over.match.ctor]p1:
2985    //   When objects of class type are direct-initialized (8.5), or
2986    //   copy-initialized from an expression of the same or a
2987    //   derived class type (8.5), overload resolution selects the
2988    //   constructor. [...] For copy-initialization, the candidate
2989    //   functions are all the converting constructors (12.3.1) of
2990    //   that class. The argument list is the expression-list within
2991    //   the parentheses of the initializer.
2992    if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
2993        (From->getType()->getAs<RecordType>() &&
2994         S.IsDerivedFrom(From->getType(), ToType)))
2995      ConstructorsOnly = true;
2996
2997    S.RequireCompleteType(From->getExprLoc(), ToType, 0);
2998    // RequireCompleteType may have returned true due to some invalid decl
2999    // during template instantiation, but ToType may be complete enough now
3000    // to try to recover.
3001    if (ToType->isIncompleteType()) {
3002      // We're not going to find any constructors.
3003    } else if (CXXRecordDecl *ToRecordDecl
3004                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3005
3006      Expr **Args = &From;
3007      unsigned NumArgs = 1;
3008      bool ListInitializing = false;
3009      if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3010        // But first, see if there is an init-list-contructor that will work.
3011        OverloadingResult Result = IsInitializerListConstructorConversion(
3012            S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3013        if (Result != OR_No_Viable_Function)
3014          return Result;
3015        // Never mind.
3016        CandidateSet.clear();
3017
3018        // If we're list-initializing, we pass the individual elements as
3019        // arguments, not the entire list.
3020        Args = InitList->getInits();
3021        NumArgs = InitList->getNumInits();
3022        ListInitializing = true;
3023      }
3024
3025      DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3026      for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3027           Con != ConEnd; ++Con) {
3028        NamedDecl *D = *Con;
3029        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3030
3031        // Find the constructor (which may be a template).
3032        CXXConstructorDecl *Constructor = 0;
3033        FunctionTemplateDecl *ConstructorTmpl
3034          = dyn_cast<FunctionTemplateDecl>(D);
3035        if (ConstructorTmpl)
3036          Constructor
3037            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3038        else
3039          Constructor = cast<CXXConstructorDecl>(D);
3040
3041        bool Usable = !Constructor->isInvalidDecl();
3042        if (ListInitializing)
3043          Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3044        else
3045          Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3046        if (Usable) {
3047          bool SuppressUserConversions = !ConstructorsOnly;
3048          if (SuppressUserConversions && ListInitializing) {
3049            SuppressUserConversions = false;
3050            if (NumArgs == 1) {
3051              // If the first argument is (a reference to) the target type,
3052              // suppress conversions.
3053              SuppressUserConversions = isFirstArgumentCompatibleWithType(
3054                                                S.Context, Constructor, ToType);
3055            }
3056          }
3057          if (ConstructorTmpl)
3058            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3059                                           /*ExplicitArgs*/ 0,
3060                                           llvm::makeArrayRef(Args, NumArgs),
3061                                           CandidateSet, SuppressUserConversions);
3062          else
3063            // Allow one user-defined conversion when user specifies a
3064            // From->ToType conversion via an static cast (c-style, etc).
3065            S.AddOverloadCandidate(Constructor, FoundDecl,
3066                                   llvm::makeArrayRef(Args, NumArgs),
3067                                   CandidateSet, SuppressUserConversions);
3068        }
3069      }
3070    }
3071  }
3072
3073  // Enumerate conversion functions, if we're allowed to.
3074  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3075  } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3076    // No conversion functions from incomplete types.
3077  } else if (const RecordType *FromRecordType
3078                                   = From->getType()->getAs<RecordType>()) {
3079    if (CXXRecordDecl *FromRecordDecl
3080         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3081      // Add all of the conversion functions as candidates.
3082      std::pair<CXXRecordDecl::conversion_iterator,
3083                CXXRecordDecl::conversion_iterator>
3084        Conversions = FromRecordDecl->getVisibleConversionFunctions();
3085      for (CXXRecordDecl::conversion_iterator
3086             I = Conversions.first, E = Conversions.second; I != E; ++I) {
3087        DeclAccessPair FoundDecl = I.getPair();
3088        NamedDecl *D = FoundDecl.getDecl();
3089        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3090        if (isa<UsingShadowDecl>(D))
3091          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3092
3093        CXXConversionDecl *Conv;
3094        FunctionTemplateDecl *ConvTemplate;
3095        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3096          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3097        else
3098          Conv = cast<CXXConversionDecl>(D);
3099
3100        if (AllowExplicit || !Conv->isExplicit()) {
3101          if (ConvTemplate)
3102            S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3103                                             ActingContext, From, ToType,
3104                                             CandidateSet);
3105          else
3106            S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3107                                     From, ToType, CandidateSet);
3108        }
3109      }
3110    }
3111  }
3112
3113  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3114
3115  OverloadCandidateSet::iterator Best;
3116  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3117  case OR_Success:
3118    // Record the standard conversion we used and the conversion function.
3119    if (CXXConstructorDecl *Constructor
3120          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3121      // C++ [over.ics.user]p1:
3122      //   If the user-defined conversion is specified by a
3123      //   constructor (12.3.1), the initial standard conversion
3124      //   sequence converts the source type to the type required by
3125      //   the argument of the constructor.
3126      //
3127      QualType ThisType = Constructor->getThisType(S.Context);
3128      if (isa<InitListExpr>(From)) {
3129        // Initializer lists don't have conversions as such.
3130        User.Before.setAsIdentityConversion();
3131      } else {
3132        if (Best->Conversions[0].isEllipsis())
3133          User.EllipsisConversion = true;
3134        else {
3135          User.Before = Best->Conversions[0].Standard;
3136          User.EllipsisConversion = false;
3137        }
3138      }
3139      User.HadMultipleCandidates = HadMultipleCandidates;
3140      User.ConversionFunction = Constructor;
3141      User.FoundConversionFunction = Best->FoundDecl;
3142      User.After.setAsIdentityConversion();
3143      User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3144      User.After.setAllToTypes(ToType);
3145      return OR_Success;
3146    }
3147    if (CXXConversionDecl *Conversion
3148                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3149      // C++ [over.ics.user]p1:
3150      //
3151      //   [...] If the user-defined conversion is specified by a
3152      //   conversion function (12.3.2), the initial standard
3153      //   conversion sequence converts the source type to the
3154      //   implicit object parameter of the conversion function.
3155      User.Before = Best->Conversions[0].Standard;
3156      User.HadMultipleCandidates = HadMultipleCandidates;
3157      User.ConversionFunction = Conversion;
3158      User.FoundConversionFunction = Best->FoundDecl;
3159      User.EllipsisConversion = false;
3160
3161      // C++ [over.ics.user]p2:
3162      //   The second standard conversion sequence converts the
3163      //   result of the user-defined conversion to the target type
3164      //   for the sequence. Since an implicit conversion sequence
3165      //   is an initialization, the special rules for
3166      //   initialization by user-defined conversion apply when
3167      //   selecting the best user-defined conversion for a
3168      //   user-defined conversion sequence (see 13.3.3 and
3169      //   13.3.3.1).
3170      User.After = Best->FinalConversion;
3171      return OR_Success;
3172    }
3173    llvm_unreachable("Not a constructor or conversion function?");
3174
3175  case OR_No_Viable_Function:
3176    return OR_No_Viable_Function;
3177  case OR_Deleted:
3178    // No conversion here! We're done.
3179    return OR_Deleted;
3180
3181  case OR_Ambiguous:
3182    return OR_Ambiguous;
3183  }
3184
3185  llvm_unreachable("Invalid OverloadResult!");
3186}
3187
3188bool
3189Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3190  ImplicitConversionSequence ICS;
3191  OverloadCandidateSet CandidateSet(From->getExprLoc());
3192  OverloadingResult OvResult =
3193    IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3194                            CandidateSet, false);
3195  if (OvResult == OR_Ambiguous)
3196    Diag(From->getLocStart(),
3197         diag::err_typecheck_ambiguous_condition)
3198          << From->getType() << ToType << From->getSourceRange();
3199  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3200    Diag(From->getLocStart(),
3201         diag::err_typecheck_nonviable_condition)
3202    << From->getType() << ToType << From->getSourceRange();
3203  else
3204    return false;
3205  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3206  return true;
3207}
3208
3209/// \brief Compare the user-defined conversion functions or constructors
3210/// of two user-defined conversion sequences to determine whether any ordering
3211/// is possible.
3212static ImplicitConversionSequence::CompareKind
3213compareConversionFunctions(Sema &S,
3214                           FunctionDecl *Function1,
3215                           FunctionDecl *Function2) {
3216  if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3217    return ImplicitConversionSequence::Indistinguishable;
3218
3219  // Objective-C++:
3220  //   If both conversion functions are implicitly-declared conversions from
3221  //   a lambda closure type to a function pointer and a block pointer,
3222  //   respectively, always prefer the conversion to a function pointer,
3223  //   because the function pointer is more lightweight and is more likely
3224  //   to keep code working.
3225  CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3226  if (!Conv1)
3227    return ImplicitConversionSequence::Indistinguishable;
3228
3229  CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3230  if (!Conv2)
3231    return ImplicitConversionSequence::Indistinguishable;
3232
3233  if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3234    bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3235    bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3236    if (Block1 != Block2)
3237      return Block1? ImplicitConversionSequence::Worse
3238                   : ImplicitConversionSequence::Better;
3239  }
3240
3241  return ImplicitConversionSequence::Indistinguishable;
3242}
3243
3244/// CompareImplicitConversionSequences - Compare two implicit
3245/// conversion sequences to determine whether one is better than the
3246/// other or if they are indistinguishable (C++ 13.3.3.2).
3247static ImplicitConversionSequence::CompareKind
3248CompareImplicitConversionSequences(Sema &S,
3249                                   const ImplicitConversionSequence& ICS1,
3250                                   const ImplicitConversionSequence& ICS2)
3251{
3252  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3253  // conversion sequences (as defined in 13.3.3.1)
3254  //   -- a standard conversion sequence (13.3.3.1.1) is a better
3255  //      conversion sequence than a user-defined conversion sequence or
3256  //      an ellipsis conversion sequence, and
3257  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3258  //      conversion sequence than an ellipsis conversion sequence
3259  //      (13.3.3.1.3).
3260  //
3261  // C++0x [over.best.ics]p10:
3262  //   For the purpose of ranking implicit conversion sequences as
3263  //   described in 13.3.3.2, the ambiguous conversion sequence is
3264  //   treated as a user-defined sequence that is indistinguishable
3265  //   from any other user-defined conversion sequence.
3266  if (ICS1.getKindRank() < ICS2.getKindRank())
3267    return ImplicitConversionSequence::Better;
3268  if (ICS2.getKindRank() < ICS1.getKindRank())
3269    return ImplicitConversionSequence::Worse;
3270
3271  // The following checks require both conversion sequences to be of
3272  // the same kind.
3273  if (ICS1.getKind() != ICS2.getKind())
3274    return ImplicitConversionSequence::Indistinguishable;
3275
3276  ImplicitConversionSequence::CompareKind Result =
3277      ImplicitConversionSequence::Indistinguishable;
3278
3279  // Two implicit conversion sequences of the same form are
3280  // indistinguishable conversion sequences unless one of the
3281  // following rules apply: (C++ 13.3.3.2p3):
3282  if (ICS1.isStandard())
3283    Result = CompareStandardConversionSequences(S,
3284                                                ICS1.Standard, ICS2.Standard);
3285  else if (ICS1.isUserDefined()) {
3286    // User-defined conversion sequence U1 is a better conversion
3287    // sequence than another user-defined conversion sequence U2 if
3288    // they contain the same user-defined conversion function or
3289    // constructor and if the second standard conversion sequence of
3290    // U1 is better than the second standard conversion sequence of
3291    // U2 (C++ 13.3.3.2p3).
3292    if (ICS1.UserDefined.ConversionFunction ==
3293          ICS2.UserDefined.ConversionFunction)
3294      Result = CompareStandardConversionSequences(S,
3295                                                  ICS1.UserDefined.After,
3296                                                  ICS2.UserDefined.After);
3297    else
3298      Result = compareConversionFunctions(S,
3299                                          ICS1.UserDefined.ConversionFunction,
3300                                          ICS2.UserDefined.ConversionFunction);
3301  }
3302
3303  // List-initialization sequence L1 is a better conversion sequence than
3304  // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3305  // for some X and L2 does not.
3306  if (Result == ImplicitConversionSequence::Indistinguishable &&
3307      !ICS1.isBad() &&
3308      ICS1.isListInitializationSequence() &&
3309      ICS2.isListInitializationSequence()) {
3310    if (ICS1.isStdInitializerListElement() &&
3311        !ICS2.isStdInitializerListElement())
3312      return ImplicitConversionSequence::Better;
3313    if (!ICS1.isStdInitializerListElement() &&
3314        ICS2.isStdInitializerListElement())
3315      return ImplicitConversionSequence::Worse;
3316  }
3317
3318  return Result;
3319}
3320
3321static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3322  while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3323    Qualifiers Quals;
3324    T1 = Context.getUnqualifiedArrayType(T1, Quals);
3325    T2 = Context.getUnqualifiedArrayType(T2, Quals);
3326  }
3327
3328  return Context.hasSameUnqualifiedType(T1, T2);
3329}
3330
3331// Per 13.3.3.2p3, compare the given standard conversion sequences to
3332// determine if one is a proper subset of the other.
3333static ImplicitConversionSequence::CompareKind
3334compareStandardConversionSubsets(ASTContext &Context,
3335                                 const StandardConversionSequence& SCS1,
3336                                 const StandardConversionSequence& SCS2) {
3337  ImplicitConversionSequence::CompareKind Result
3338    = ImplicitConversionSequence::Indistinguishable;
3339
3340  // the identity conversion sequence is considered to be a subsequence of
3341  // any non-identity conversion sequence
3342  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3343    return ImplicitConversionSequence::Better;
3344  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3345    return ImplicitConversionSequence::Worse;
3346
3347  if (SCS1.Second != SCS2.Second) {
3348    if (SCS1.Second == ICK_Identity)
3349      Result = ImplicitConversionSequence::Better;
3350    else if (SCS2.Second == ICK_Identity)
3351      Result = ImplicitConversionSequence::Worse;
3352    else
3353      return ImplicitConversionSequence::Indistinguishable;
3354  } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3355    return ImplicitConversionSequence::Indistinguishable;
3356
3357  if (SCS1.Third == SCS2.Third) {
3358    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3359                             : ImplicitConversionSequence::Indistinguishable;
3360  }
3361
3362  if (SCS1.Third == ICK_Identity)
3363    return Result == ImplicitConversionSequence::Worse
3364             ? ImplicitConversionSequence::Indistinguishable
3365             : ImplicitConversionSequence::Better;
3366
3367  if (SCS2.Third == ICK_Identity)
3368    return Result == ImplicitConversionSequence::Better
3369             ? ImplicitConversionSequence::Indistinguishable
3370             : ImplicitConversionSequence::Worse;
3371
3372  return ImplicitConversionSequence::Indistinguishable;
3373}
3374
3375/// \brief Determine whether one of the given reference bindings is better
3376/// than the other based on what kind of bindings they are.
3377static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3378                                       const StandardConversionSequence &SCS2) {
3379  // C++0x [over.ics.rank]p3b4:
3380  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3381  //      implicit object parameter of a non-static member function declared
3382  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3383  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3384  //      lvalue reference to a function lvalue and S2 binds an rvalue
3385  //      reference*.
3386  //
3387  // FIXME: Rvalue references. We're going rogue with the above edits,
3388  // because the semantics in the current C++0x working paper (N3225 at the
3389  // time of this writing) break the standard definition of std::forward
3390  // and std::reference_wrapper when dealing with references to functions.
3391  // Proposed wording changes submitted to CWG for consideration.
3392  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3393      SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3394    return false;
3395
3396  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3397          SCS2.IsLvalueReference) ||
3398         (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3399          !SCS2.IsLvalueReference);
3400}
3401
3402/// CompareStandardConversionSequences - Compare two standard
3403/// conversion sequences to determine whether one is better than the
3404/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3405static ImplicitConversionSequence::CompareKind
3406CompareStandardConversionSequences(Sema &S,
3407                                   const StandardConversionSequence& SCS1,
3408                                   const StandardConversionSequence& SCS2)
3409{
3410  // Standard conversion sequence S1 is a better conversion sequence
3411  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3412
3413  //  -- S1 is a proper subsequence of S2 (comparing the conversion
3414  //     sequences in the canonical form defined by 13.3.3.1.1,
3415  //     excluding any Lvalue Transformation; the identity conversion
3416  //     sequence is considered to be a subsequence of any
3417  //     non-identity conversion sequence) or, if not that,
3418  if (ImplicitConversionSequence::CompareKind CK
3419        = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3420    return CK;
3421
3422  //  -- the rank of S1 is better than the rank of S2 (by the rules
3423  //     defined below), or, if not that,
3424  ImplicitConversionRank Rank1 = SCS1.getRank();
3425  ImplicitConversionRank Rank2 = SCS2.getRank();
3426  if (Rank1 < Rank2)
3427    return ImplicitConversionSequence::Better;
3428  else if (Rank2 < Rank1)
3429    return ImplicitConversionSequence::Worse;
3430
3431  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3432  // are indistinguishable unless one of the following rules
3433  // applies:
3434
3435  //   A conversion that is not a conversion of a pointer, or
3436  //   pointer to member, to bool is better than another conversion
3437  //   that is such a conversion.
3438  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3439    return SCS2.isPointerConversionToBool()
3440             ? ImplicitConversionSequence::Better
3441             : ImplicitConversionSequence::Worse;
3442
3443  // C++ [over.ics.rank]p4b2:
3444  //
3445  //   If class B is derived directly or indirectly from class A,
3446  //   conversion of B* to A* is better than conversion of B* to
3447  //   void*, and conversion of A* to void* is better than conversion
3448  //   of B* to void*.
3449  bool SCS1ConvertsToVoid
3450    = SCS1.isPointerConversionToVoidPointer(S.Context);
3451  bool SCS2ConvertsToVoid
3452    = SCS2.isPointerConversionToVoidPointer(S.Context);
3453  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3454    // Exactly one of the conversion sequences is a conversion to
3455    // a void pointer; it's the worse conversion.
3456    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3457                              : ImplicitConversionSequence::Worse;
3458  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3459    // Neither conversion sequence converts to a void pointer; compare
3460    // their derived-to-base conversions.
3461    if (ImplicitConversionSequence::CompareKind DerivedCK
3462          = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3463      return DerivedCK;
3464  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3465             !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3466    // Both conversion sequences are conversions to void
3467    // pointers. Compare the source types to determine if there's an
3468    // inheritance relationship in their sources.
3469    QualType FromType1 = SCS1.getFromType();
3470    QualType FromType2 = SCS2.getFromType();
3471
3472    // Adjust the types we're converting from via the array-to-pointer
3473    // conversion, if we need to.
3474    if (SCS1.First == ICK_Array_To_Pointer)
3475      FromType1 = S.Context.getArrayDecayedType(FromType1);
3476    if (SCS2.First == ICK_Array_To_Pointer)
3477      FromType2 = S.Context.getArrayDecayedType(FromType2);
3478
3479    QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3480    QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3481
3482    if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3483      return ImplicitConversionSequence::Better;
3484    else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3485      return ImplicitConversionSequence::Worse;
3486
3487    // Objective-C++: If one interface is more specific than the
3488    // other, it is the better one.
3489    const ObjCObjectPointerType* FromObjCPtr1
3490      = FromType1->getAs<ObjCObjectPointerType>();
3491    const ObjCObjectPointerType* FromObjCPtr2
3492      = FromType2->getAs<ObjCObjectPointerType>();
3493    if (FromObjCPtr1 && FromObjCPtr2) {
3494      bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3495                                                          FromObjCPtr2);
3496      bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3497                                                           FromObjCPtr1);
3498      if (AssignLeft != AssignRight) {
3499        return AssignLeft? ImplicitConversionSequence::Better
3500                         : ImplicitConversionSequence::Worse;
3501      }
3502    }
3503  }
3504
3505  // Compare based on qualification conversions (C++ 13.3.3.2p3,
3506  // bullet 3).
3507  if (ImplicitConversionSequence::CompareKind QualCK
3508        = CompareQualificationConversions(S, SCS1, SCS2))
3509    return QualCK;
3510
3511  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3512    // Check for a better reference binding based on the kind of bindings.
3513    if (isBetterReferenceBindingKind(SCS1, SCS2))
3514      return ImplicitConversionSequence::Better;
3515    else if (isBetterReferenceBindingKind(SCS2, SCS1))
3516      return ImplicitConversionSequence::Worse;
3517
3518    // C++ [over.ics.rank]p3b4:
3519    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3520    //      which the references refer are the same type except for
3521    //      top-level cv-qualifiers, and the type to which the reference
3522    //      initialized by S2 refers is more cv-qualified than the type
3523    //      to which the reference initialized by S1 refers.
3524    QualType T1 = SCS1.getToType(2);
3525    QualType T2 = SCS2.getToType(2);
3526    T1 = S.Context.getCanonicalType(T1);
3527    T2 = S.Context.getCanonicalType(T2);
3528    Qualifiers T1Quals, T2Quals;
3529    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3530    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3531    if (UnqualT1 == UnqualT2) {
3532      // Objective-C++ ARC: If the references refer to objects with different
3533      // lifetimes, prefer bindings that don't change lifetime.
3534      if (SCS1.ObjCLifetimeConversionBinding !=
3535                                          SCS2.ObjCLifetimeConversionBinding) {
3536        return SCS1.ObjCLifetimeConversionBinding
3537                                           ? ImplicitConversionSequence::Worse
3538                                           : ImplicitConversionSequence::Better;
3539      }
3540
3541      // If the type is an array type, promote the element qualifiers to the
3542      // type for comparison.
3543      if (isa<ArrayType>(T1) && T1Quals)
3544        T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3545      if (isa<ArrayType>(T2) && T2Quals)
3546        T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3547      if (T2.isMoreQualifiedThan(T1))
3548        return ImplicitConversionSequence::Better;
3549      else if (T1.isMoreQualifiedThan(T2))
3550        return ImplicitConversionSequence::Worse;
3551    }
3552  }
3553
3554  // In Microsoft mode, prefer an integral conversion to a
3555  // floating-to-integral conversion if the integral conversion
3556  // is between types of the same size.
3557  // For example:
3558  // void f(float);
3559  // void f(int);
3560  // int main {
3561  //    long a;
3562  //    f(a);
3563  // }
3564  // Here, MSVC will call f(int) instead of generating a compile error
3565  // as clang will do in standard mode.
3566  if (S.getLangOpts().MicrosoftMode &&
3567      SCS1.Second == ICK_Integral_Conversion &&
3568      SCS2.Second == ICK_Floating_Integral &&
3569      S.Context.getTypeSize(SCS1.getFromType()) ==
3570      S.Context.getTypeSize(SCS1.getToType(2)))
3571    return ImplicitConversionSequence::Better;
3572
3573  return ImplicitConversionSequence::Indistinguishable;
3574}
3575
3576/// CompareQualificationConversions - Compares two standard conversion
3577/// sequences to determine whether they can be ranked based on their
3578/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3579ImplicitConversionSequence::CompareKind
3580CompareQualificationConversions(Sema &S,
3581                                const StandardConversionSequence& SCS1,
3582                                const StandardConversionSequence& SCS2) {
3583  // C++ 13.3.3.2p3:
3584  //  -- S1 and S2 differ only in their qualification conversion and
3585  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3586  //     cv-qualification signature of type T1 is a proper subset of
3587  //     the cv-qualification signature of type T2, and S1 is not the
3588  //     deprecated string literal array-to-pointer conversion (4.2).
3589  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3590      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3591    return ImplicitConversionSequence::Indistinguishable;
3592
3593  // FIXME: the example in the standard doesn't use a qualification
3594  // conversion (!)
3595  QualType T1 = SCS1.getToType(2);
3596  QualType T2 = SCS2.getToType(2);
3597  T1 = S.Context.getCanonicalType(T1);
3598  T2 = S.Context.getCanonicalType(T2);
3599  Qualifiers T1Quals, T2Quals;
3600  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3601  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3602
3603  // If the types are the same, we won't learn anything by unwrapped
3604  // them.
3605  if (UnqualT1 == UnqualT2)
3606    return ImplicitConversionSequence::Indistinguishable;
3607
3608  // If the type is an array type, promote the element qualifiers to the type
3609  // for comparison.
3610  if (isa<ArrayType>(T1) && T1Quals)
3611    T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3612  if (isa<ArrayType>(T2) && T2Quals)
3613    T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3614
3615  ImplicitConversionSequence::CompareKind Result
3616    = ImplicitConversionSequence::Indistinguishable;
3617
3618  // Objective-C++ ARC:
3619  //   Prefer qualification conversions not involving a change in lifetime
3620  //   to qualification conversions that do not change lifetime.
3621  if (SCS1.QualificationIncludesObjCLifetime !=
3622                                      SCS2.QualificationIncludesObjCLifetime) {
3623    Result = SCS1.QualificationIncludesObjCLifetime
3624               ? ImplicitConversionSequence::Worse
3625               : ImplicitConversionSequence::Better;
3626  }
3627
3628  while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3629    // Within each iteration of the loop, we check the qualifiers to
3630    // determine if this still looks like a qualification
3631    // conversion. Then, if all is well, we unwrap one more level of
3632    // pointers or pointers-to-members and do it all again
3633    // until there are no more pointers or pointers-to-members left
3634    // to unwrap. This essentially mimics what
3635    // IsQualificationConversion does, but here we're checking for a
3636    // strict subset of qualifiers.
3637    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3638      // The qualifiers are the same, so this doesn't tell us anything
3639      // about how the sequences rank.
3640      ;
3641    else if (T2.isMoreQualifiedThan(T1)) {
3642      // T1 has fewer qualifiers, so it could be the better sequence.
3643      if (Result == ImplicitConversionSequence::Worse)
3644        // Neither has qualifiers that are a subset of the other's
3645        // qualifiers.
3646        return ImplicitConversionSequence::Indistinguishable;
3647
3648      Result = ImplicitConversionSequence::Better;
3649    } else if (T1.isMoreQualifiedThan(T2)) {
3650      // T2 has fewer qualifiers, so it could be the better sequence.
3651      if (Result == ImplicitConversionSequence::Better)
3652        // Neither has qualifiers that are a subset of the other's
3653        // qualifiers.
3654        return ImplicitConversionSequence::Indistinguishable;
3655
3656      Result = ImplicitConversionSequence::Worse;
3657    } else {
3658      // Qualifiers are disjoint.
3659      return ImplicitConversionSequence::Indistinguishable;
3660    }
3661
3662    // If the types after this point are equivalent, we're done.
3663    if (S.Context.hasSameUnqualifiedType(T1, T2))
3664      break;
3665  }
3666
3667  // Check that the winning standard conversion sequence isn't using
3668  // the deprecated string literal array to pointer conversion.
3669  switch (Result) {
3670  case ImplicitConversionSequence::Better:
3671    if (SCS1.DeprecatedStringLiteralToCharPtr)
3672      Result = ImplicitConversionSequence::Indistinguishable;
3673    break;
3674
3675  case ImplicitConversionSequence::Indistinguishable:
3676    break;
3677
3678  case ImplicitConversionSequence::Worse:
3679    if (SCS2.DeprecatedStringLiteralToCharPtr)
3680      Result = ImplicitConversionSequence::Indistinguishable;
3681    break;
3682  }
3683
3684  return Result;
3685}
3686
3687/// CompareDerivedToBaseConversions - Compares two standard conversion
3688/// sequences to determine whether they can be ranked based on their
3689/// various kinds of derived-to-base conversions (C++
3690/// [over.ics.rank]p4b3).  As part of these checks, we also look at
3691/// conversions between Objective-C interface types.
3692ImplicitConversionSequence::CompareKind
3693CompareDerivedToBaseConversions(Sema &S,
3694                                const StandardConversionSequence& SCS1,
3695                                const StandardConversionSequence& SCS2) {
3696  QualType FromType1 = SCS1.getFromType();
3697  QualType ToType1 = SCS1.getToType(1);
3698  QualType FromType2 = SCS2.getFromType();
3699  QualType ToType2 = SCS2.getToType(1);
3700
3701  // Adjust the types we're converting from via the array-to-pointer
3702  // conversion, if we need to.
3703  if (SCS1.First == ICK_Array_To_Pointer)
3704    FromType1 = S.Context.getArrayDecayedType(FromType1);
3705  if (SCS2.First == ICK_Array_To_Pointer)
3706    FromType2 = S.Context.getArrayDecayedType(FromType2);
3707
3708  // Canonicalize all of the types.
3709  FromType1 = S.Context.getCanonicalType(FromType1);
3710  ToType1 = S.Context.getCanonicalType(ToType1);
3711  FromType2 = S.Context.getCanonicalType(FromType2);
3712  ToType2 = S.Context.getCanonicalType(ToType2);
3713
3714  // C++ [over.ics.rank]p4b3:
3715  //
3716  //   If class B is derived directly or indirectly from class A and
3717  //   class C is derived directly or indirectly from B,
3718  //
3719  // Compare based on pointer conversions.
3720  if (SCS1.Second == ICK_Pointer_Conversion &&
3721      SCS2.Second == ICK_Pointer_Conversion &&
3722      /*FIXME: Remove if Objective-C id conversions get their own rank*/
3723      FromType1->isPointerType() && FromType2->isPointerType() &&
3724      ToType1->isPointerType() && ToType2->isPointerType()) {
3725    QualType FromPointee1
3726      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3727    QualType ToPointee1
3728      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3729    QualType FromPointee2
3730      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3731    QualType ToPointee2
3732      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3733
3734    //   -- conversion of C* to B* is better than conversion of C* to A*,
3735    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3736      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3737        return ImplicitConversionSequence::Better;
3738      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3739        return ImplicitConversionSequence::Worse;
3740    }
3741
3742    //   -- conversion of B* to A* is better than conversion of C* to A*,
3743    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3744      if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3745        return ImplicitConversionSequence::Better;
3746      else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3747        return ImplicitConversionSequence::Worse;
3748    }
3749  } else if (SCS1.Second == ICK_Pointer_Conversion &&
3750             SCS2.Second == ICK_Pointer_Conversion) {
3751    const ObjCObjectPointerType *FromPtr1
3752      = FromType1->getAs<ObjCObjectPointerType>();
3753    const ObjCObjectPointerType *FromPtr2
3754      = FromType2->getAs<ObjCObjectPointerType>();
3755    const ObjCObjectPointerType *ToPtr1
3756      = ToType1->getAs<ObjCObjectPointerType>();
3757    const ObjCObjectPointerType *ToPtr2
3758      = ToType2->getAs<ObjCObjectPointerType>();
3759
3760    if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3761      // Apply the same conversion ranking rules for Objective-C pointer types
3762      // that we do for C++ pointers to class types. However, we employ the
3763      // Objective-C pseudo-subtyping relationship used for assignment of
3764      // Objective-C pointer types.
3765      bool FromAssignLeft
3766        = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3767      bool FromAssignRight
3768        = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3769      bool ToAssignLeft
3770        = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3771      bool ToAssignRight
3772        = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3773
3774      // A conversion to an a non-id object pointer type or qualified 'id'
3775      // type is better than a conversion to 'id'.
3776      if (ToPtr1->isObjCIdType() &&
3777          (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3778        return ImplicitConversionSequence::Worse;
3779      if (ToPtr2->isObjCIdType() &&
3780          (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3781        return ImplicitConversionSequence::Better;
3782
3783      // A conversion to a non-id object pointer type is better than a
3784      // conversion to a qualified 'id' type
3785      if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3786        return ImplicitConversionSequence::Worse;
3787      if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3788        return ImplicitConversionSequence::Better;
3789
3790      // A conversion to an a non-Class object pointer type or qualified 'Class'
3791      // type is better than a conversion to 'Class'.
3792      if (ToPtr1->isObjCClassType() &&
3793          (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3794        return ImplicitConversionSequence::Worse;
3795      if (ToPtr2->isObjCClassType() &&
3796          (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3797        return ImplicitConversionSequence::Better;
3798
3799      // A conversion to a non-Class object pointer type is better than a
3800      // conversion to a qualified 'Class' type.
3801      if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3802        return ImplicitConversionSequence::Worse;
3803      if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3804        return ImplicitConversionSequence::Better;
3805
3806      //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3807      if (S.Context.hasSameType(FromType1, FromType2) &&
3808          !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3809          (ToAssignLeft != ToAssignRight))
3810        return ToAssignLeft? ImplicitConversionSequence::Worse
3811                           : ImplicitConversionSequence::Better;
3812
3813      //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3814      if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3815          (FromAssignLeft != FromAssignRight))
3816        return FromAssignLeft? ImplicitConversionSequence::Better
3817        : ImplicitConversionSequence::Worse;
3818    }
3819  }
3820
3821  // Ranking of member-pointer types.
3822  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3823      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3824      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3825    const MemberPointerType * FromMemPointer1 =
3826                                        FromType1->getAs<MemberPointerType>();
3827    const MemberPointerType * ToMemPointer1 =
3828                                          ToType1->getAs<MemberPointerType>();
3829    const MemberPointerType * FromMemPointer2 =
3830                                          FromType2->getAs<MemberPointerType>();
3831    const MemberPointerType * ToMemPointer2 =
3832                                          ToType2->getAs<MemberPointerType>();
3833    const Type *FromPointeeType1 = FromMemPointer1->getClass();
3834    const Type *ToPointeeType1 = ToMemPointer1->getClass();
3835    const Type *FromPointeeType2 = FromMemPointer2->getClass();
3836    const Type *ToPointeeType2 = ToMemPointer2->getClass();
3837    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3838    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3839    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3840    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3841    // conversion of A::* to B::* is better than conversion of A::* to C::*,
3842    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3843      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3844        return ImplicitConversionSequence::Worse;
3845      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3846        return ImplicitConversionSequence::Better;
3847    }
3848    // conversion of B::* to C::* is better than conversion of A::* to C::*
3849    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3850      if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3851        return ImplicitConversionSequence::Better;
3852      else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3853        return ImplicitConversionSequence::Worse;
3854    }
3855  }
3856
3857  if (SCS1.Second == ICK_Derived_To_Base) {
3858    //   -- conversion of C to B is better than conversion of C to A,
3859    //   -- binding of an expression of type C to a reference of type
3860    //      B& is better than binding an expression of type C to a
3861    //      reference of type A&,
3862    if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3863        !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3864      if (S.IsDerivedFrom(ToType1, ToType2))
3865        return ImplicitConversionSequence::Better;
3866      else if (S.IsDerivedFrom(ToType2, ToType1))
3867        return ImplicitConversionSequence::Worse;
3868    }
3869
3870    //   -- conversion of B to A is better than conversion of C to A.
3871    //   -- binding of an expression of type B to a reference of type
3872    //      A& is better than binding an expression of type C to a
3873    //      reference of type A&,
3874    if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3875        S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3876      if (S.IsDerivedFrom(FromType2, FromType1))
3877        return ImplicitConversionSequence::Better;
3878      else if (S.IsDerivedFrom(FromType1, FromType2))
3879        return ImplicitConversionSequence::Worse;
3880    }
3881  }
3882
3883  return ImplicitConversionSequence::Indistinguishable;
3884}
3885
3886/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3887/// determine whether they are reference-related,
3888/// reference-compatible, reference-compatible with added
3889/// qualification, or incompatible, for use in C++ initialization by
3890/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3891/// type, and the first type (T1) is the pointee type of the reference
3892/// type being initialized.
3893Sema::ReferenceCompareResult
3894Sema::CompareReferenceRelationship(SourceLocation Loc,
3895                                   QualType OrigT1, QualType OrigT2,
3896                                   bool &DerivedToBase,
3897                                   bool &ObjCConversion,
3898                                   bool &ObjCLifetimeConversion) {
3899  assert(!OrigT1->isReferenceType() &&
3900    "T1 must be the pointee type of the reference type");
3901  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3902
3903  QualType T1 = Context.getCanonicalType(OrigT1);
3904  QualType T2 = Context.getCanonicalType(OrigT2);
3905  Qualifiers T1Quals, T2Quals;
3906  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3907  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3908
3909  // C++ [dcl.init.ref]p4:
3910  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3911  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3912  //   T1 is a base class of T2.
3913  DerivedToBase = false;
3914  ObjCConversion = false;
3915  ObjCLifetimeConversion = false;
3916  if (UnqualT1 == UnqualT2) {
3917    // Nothing to do.
3918  } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3919           IsDerivedFrom(UnqualT2, UnqualT1))
3920    DerivedToBase = true;
3921  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3922           UnqualT2->isObjCObjectOrInterfaceType() &&
3923           Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3924    ObjCConversion = true;
3925  else
3926    return Ref_Incompatible;
3927
3928  // At this point, we know that T1 and T2 are reference-related (at
3929  // least).
3930
3931  // If the type is an array type, promote the element qualifiers to the type
3932  // for comparison.
3933  if (isa<ArrayType>(T1) && T1Quals)
3934    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3935  if (isa<ArrayType>(T2) && T2Quals)
3936    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3937
3938  // C++ [dcl.init.ref]p4:
3939  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3940  //   reference-related to T2 and cv1 is the same cv-qualification
3941  //   as, or greater cv-qualification than, cv2. For purposes of
3942  //   overload resolution, cases for which cv1 is greater
3943  //   cv-qualification than cv2 are identified as
3944  //   reference-compatible with added qualification (see 13.3.3.2).
3945  //
3946  // Note that we also require equivalence of Objective-C GC and address-space
3947  // qualifiers when performing these computations, so that e.g., an int in
3948  // address space 1 is not reference-compatible with an int in address
3949  // space 2.
3950  if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3951      T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3952    T1Quals.removeObjCLifetime();
3953    T2Quals.removeObjCLifetime();
3954    ObjCLifetimeConversion = true;
3955  }
3956
3957  if (T1Quals == T2Quals)
3958    return Ref_Compatible;
3959  else if (T1Quals.compatiblyIncludes(T2Quals))
3960    return Ref_Compatible_With_Added_Qualification;
3961  else
3962    return Ref_Related;
3963}
3964
3965/// \brief Look for a user-defined conversion to an value reference-compatible
3966///        with DeclType. Return true if something definite is found.
3967static bool
3968FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3969                         QualType DeclType, SourceLocation DeclLoc,
3970                         Expr *Init, QualType T2, bool AllowRvalues,
3971                         bool AllowExplicit) {
3972  assert(T2->isRecordType() && "Can only find conversions of record types.");
3973  CXXRecordDecl *T2RecordDecl
3974    = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3975
3976  OverloadCandidateSet CandidateSet(DeclLoc);
3977  std::pair<CXXRecordDecl::conversion_iterator,
3978            CXXRecordDecl::conversion_iterator>
3979    Conversions = T2RecordDecl->getVisibleConversionFunctions();
3980  for (CXXRecordDecl::conversion_iterator
3981         I = Conversions.first, E = Conversions.second; I != E; ++I) {
3982    NamedDecl *D = *I;
3983    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3984    if (isa<UsingShadowDecl>(D))
3985      D = cast<UsingShadowDecl>(D)->getTargetDecl();
3986
3987    FunctionTemplateDecl *ConvTemplate
3988      = dyn_cast<FunctionTemplateDecl>(D);
3989    CXXConversionDecl *Conv;
3990    if (ConvTemplate)
3991      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3992    else
3993      Conv = cast<CXXConversionDecl>(D);
3994
3995    // If this is an explicit conversion, and we're not allowed to consider
3996    // explicit conversions, skip it.
3997    if (!AllowExplicit && Conv->isExplicit())
3998      continue;
3999
4000    if (AllowRvalues) {
4001      bool DerivedToBase = false;
4002      bool ObjCConversion = false;
4003      bool ObjCLifetimeConversion = false;
4004
4005      // If we are initializing an rvalue reference, don't permit conversion
4006      // functions that return lvalues.
4007      if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4008        const ReferenceType *RefType
4009          = Conv->getConversionType()->getAs<LValueReferenceType>();
4010        if (RefType && !RefType->getPointeeType()->isFunctionType())
4011          continue;
4012      }
4013
4014      if (!ConvTemplate &&
4015          S.CompareReferenceRelationship(
4016            DeclLoc,
4017            Conv->getConversionType().getNonReferenceType()
4018              .getUnqualifiedType(),
4019            DeclType.getNonReferenceType().getUnqualifiedType(),
4020            DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4021          Sema::Ref_Incompatible)
4022        continue;
4023    } else {
4024      // If the conversion function doesn't return a reference type,
4025      // it can't be considered for this conversion. An rvalue reference
4026      // is only acceptable if its referencee is a function type.
4027
4028      const ReferenceType *RefType =
4029        Conv->getConversionType()->getAs<ReferenceType>();
4030      if (!RefType ||
4031          (!RefType->isLValueReferenceType() &&
4032           !RefType->getPointeeType()->isFunctionType()))
4033        continue;
4034    }
4035
4036    if (ConvTemplate)
4037      S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4038                                       Init, DeclType, CandidateSet);
4039    else
4040      S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4041                               DeclType, CandidateSet);
4042  }
4043
4044  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4045
4046  OverloadCandidateSet::iterator Best;
4047  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4048  case OR_Success:
4049    // C++ [over.ics.ref]p1:
4050    //
4051    //   [...] If the parameter binds directly to the result of
4052    //   applying a conversion function to the argument
4053    //   expression, the implicit conversion sequence is a
4054    //   user-defined conversion sequence (13.3.3.1.2), with the
4055    //   second standard conversion sequence either an identity
4056    //   conversion or, if the conversion function returns an
4057    //   entity of a type that is a derived class of the parameter
4058    //   type, a derived-to-base Conversion.
4059    if (!Best->FinalConversion.DirectBinding)
4060      return false;
4061
4062    ICS.setUserDefined();
4063    ICS.UserDefined.Before = Best->Conversions[0].Standard;
4064    ICS.UserDefined.After = Best->FinalConversion;
4065    ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4066    ICS.UserDefined.ConversionFunction = Best->Function;
4067    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4068    ICS.UserDefined.EllipsisConversion = false;
4069    assert(ICS.UserDefined.After.ReferenceBinding &&
4070           ICS.UserDefined.After.DirectBinding &&
4071           "Expected a direct reference binding!");
4072    return true;
4073
4074  case OR_Ambiguous:
4075    ICS.setAmbiguous();
4076    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4077         Cand != CandidateSet.end(); ++Cand)
4078      if (Cand->Viable)
4079        ICS.Ambiguous.addConversion(Cand->Function);
4080    return true;
4081
4082  case OR_No_Viable_Function:
4083  case OR_Deleted:
4084    // There was no suitable conversion, or we found a deleted
4085    // conversion; continue with other checks.
4086    return false;
4087  }
4088
4089  llvm_unreachable("Invalid OverloadResult!");
4090}
4091
4092/// \brief Compute an implicit conversion sequence for reference
4093/// initialization.
4094static ImplicitConversionSequence
4095TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4096                 SourceLocation DeclLoc,
4097                 bool SuppressUserConversions,
4098                 bool AllowExplicit) {
4099  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4100
4101  // Most paths end in a failed conversion.
4102  ImplicitConversionSequence ICS;
4103  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4104
4105  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4106  QualType T2 = Init->getType();
4107
4108  // If the initializer is the address of an overloaded function, try
4109  // to resolve the overloaded function. If all goes well, T2 is the
4110  // type of the resulting function.
4111  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4112    DeclAccessPair Found;
4113    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4114                                                                false, Found))
4115      T2 = Fn->getType();
4116  }
4117
4118  // Compute some basic properties of the types and the initializer.
4119  bool isRValRef = DeclType->isRValueReferenceType();
4120  bool DerivedToBase = false;
4121  bool ObjCConversion = false;
4122  bool ObjCLifetimeConversion = false;
4123  Expr::Classification InitCategory = Init->Classify(S.Context);
4124  Sema::ReferenceCompareResult RefRelationship
4125    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4126                                     ObjCConversion, ObjCLifetimeConversion);
4127
4128
4129  // C++0x [dcl.init.ref]p5:
4130  //   A reference to type "cv1 T1" is initialized by an expression
4131  //   of type "cv2 T2" as follows:
4132
4133  //     -- If reference is an lvalue reference and the initializer expression
4134  if (!isRValRef) {
4135    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4136    //        reference-compatible with "cv2 T2," or
4137    //
4138    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4139    if (InitCategory.isLValue() &&
4140        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4141      // C++ [over.ics.ref]p1:
4142      //   When a parameter of reference type binds directly (8.5.3)
4143      //   to an argument expression, the implicit conversion sequence
4144      //   is the identity conversion, unless the argument expression
4145      //   has a type that is a derived class of the parameter type,
4146      //   in which case the implicit conversion sequence is a
4147      //   derived-to-base Conversion (13.3.3.1).
4148      ICS.setStandard();
4149      ICS.Standard.First = ICK_Identity;
4150      ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4151                         : ObjCConversion? ICK_Compatible_Conversion
4152                         : ICK_Identity;
4153      ICS.Standard.Third = ICK_Identity;
4154      ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4155      ICS.Standard.setToType(0, T2);
4156      ICS.Standard.setToType(1, T1);
4157      ICS.Standard.setToType(2, T1);
4158      ICS.Standard.ReferenceBinding = true;
4159      ICS.Standard.DirectBinding = true;
4160      ICS.Standard.IsLvalueReference = !isRValRef;
4161      ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4162      ICS.Standard.BindsToRvalue = false;
4163      ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4164      ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4165      ICS.Standard.CopyConstructor = 0;
4166
4167      // Nothing more to do: the inaccessibility/ambiguity check for
4168      // derived-to-base conversions is suppressed when we're
4169      // computing the implicit conversion sequence (C++
4170      // [over.best.ics]p2).
4171      return ICS;
4172    }
4173
4174    //       -- has a class type (i.e., T2 is a class type), where T1 is
4175    //          not reference-related to T2, and can be implicitly
4176    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4177    //          is reference-compatible with "cv3 T3" 92) (this
4178    //          conversion is selected by enumerating the applicable
4179    //          conversion functions (13.3.1.6) and choosing the best
4180    //          one through overload resolution (13.3)),
4181    if (!SuppressUserConversions && T2->isRecordType() &&
4182        !S.RequireCompleteType(DeclLoc, T2, 0) &&
4183        RefRelationship == Sema::Ref_Incompatible) {
4184      if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4185                                   Init, T2, /*AllowRvalues=*/false,
4186                                   AllowExplicit))
4187        return ICS;
4188    }
4189  }
4190
4191  //     -- Otherwise, the reference shall be an lvalue reference to a
4192  //        non-volatile const type (i.e., cv1 shall be const), or the reference
4193  //        shall be an rvalue reference.
4194  //
4195  // We actually handle one oddity of C++ [over.ics.ref] at this
4196  // point, which is that, due to p2 (which short-circuits reference
4197  // binding by only attempting a simple conversion for non-direct
4198  // bindings) and p3's strange wording, we allow a const volatile
4199  // reference to bind to an rvalue. Hence the check for the presence
4200  // of "const" rather than checking for "const" being the only
4201  // qualifier.
4202  // This is also the point where rvalue references and lvalue inits no longer
4203  // go together.
4204  if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4205    return ICS;
4206
4207  //       -- If the initializer expression
4208  //
4209  //            -- is an xvalue, class prvalue, array prvalue or function
4210  //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4211  if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4212      (InitCategory.isXValue() ||
4213      (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4214      (InitCategory.isLValue() && T2->isFunctionType()))) {
4215    ICS.setStandard();
4216    ICS.Standard.First = ICK_Identity;
4217    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4218                      : ObjCConversion? ICK_Compatible_Conversion
4219                      : ICK_Identity;
4220    ICS.Standard.Third = ICK_Identity;
4221    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4222    ICS.Standard.setToType(0, T2);
4223    ICS.Standard.setToType(1, T1);
4224    ICS.Standard.setToType(2, T1);
4225    ICS.Standard.ReferenceBinding = true;
4226    // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4227    // binding unless we're binding to a class prvalue.
4228    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4229    // allow the use of rvalue references in C++98/03 for the benefit of
4230    // standard library implementors; therefore, we need the xvalue check here.
4231    ICS.Standard.DirectBinding =
4232      S.getLangOpts().CPlusPlus11 ||
4233      (InitCategory.isPRValue() && !T2->isRecordType());
4234    ICS.Standard.IsLvalueReference = !isRValRef;
4235    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4236    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4237    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4238    ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4239    ICS.Standard.CopyConstructor = 0;
4240    return ICS;
4241  }
4242
4243  //            -- has a class type (i.e., T2 is a class type), where T1 is not
4244  //               reference-related to T2, and can be implicitly converted to
4245  //               an xvalue, class prvalue, or function lvalue of type
4246  //               "cv3 T3", where "cv1 T1" is reference-compatible with
4247  //               "cv3 T3",
4248  //
4249  //          then the reference is bound to the value of the initializer
4250  //          expression in the first case and to the result of the conversion
4251  //          in the second case (or, in either case, to an appropriate base
4252  //          class subobject).
4253  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4254      T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4255      FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4256                               Init, T2, /*AllowRvalues=*/true,
4257                               AllowExplicit)) {
4258    // In the second case, if the reference is an rvalue reference
4259    // and the second standard conversion sequence of the
4260    // user-defined conversion sequence includes an lvalue-to-rvalue
4261    // conversion, the program is ill-formed.
4262    if (ICS.isUserDefined() && isRValRef &&
4263        ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4264      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4265
4266    return ICS;
4267  }
4268
4269  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4270  //          initialized from the initializer expression using the
4271  //          rules for a non-reference copy initialization (8.5). The
4272  //          reference is then bound to the temporary. If T1 is
4273  //          reference-related to T2, cv1 must be the same
4274  //          cv-qualification as, or greater cv-qualification than,
4275  //          cv2; otherwise, the program is ill-formed.
4276  if (RefRelationship == Sema::Ref_Related) {
4277    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4278    // we would be reference-compatible or reference-compatible with
4279    // added qualification. But that wasn't the case, so the reference
4280    // initialization fails.
4281    //
4282    // Note that we only want to check address spaces and cvr-qualifiers here.
4283    // ObjC GC and lifetime qualifiers aren't important.
4284    Qualifiers T1Quals = T1.getQualifiers();
4285    Qualifiers T2Quals = T2.getQualifiers();
4286    T1Quals.removeObjCGCAttr();
4287    T1Quals.removeObjCLifetime();
4288    T2Quals.removeObjCGCAttr();
4289    T2Quals.removeObjCLifetime();
4290    if (!T1Quals.compatiblyIncludes(T2Quals))
4291      return ICS;
4292  }
4293
4294  // If at least one of the types is a class type, the types are not
4295  // related, and we aren't allowed any user conversions, the
4296  // reference binding fails. This case is important for breaking
4297  // recursion, since TryImplicitConversion below will attempt to
4298  // create a temporary through the use of a copy constructor.
4299  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4300      (T1->isRecordType() || T2->isRecordType()))
4301    return ICS;
4302
4303  // If T1 is reference-related to T2 and the reference is an rvalue
4304  // reference, the initializer expression shall not be an lvalue.
4305  if (RefRelationship >= Sema::Ref_Related &&
4306      isRValRef && Init->Classify(S.Context).isLValue())
4307    return ICS;
4308
4309  // C++ [over.ics.ref]p2:
4310  //   When a parameter of reference type is not bound directly to
4311  //   an argument expression, the conversion sequence is the one
4312  //   required to convert the argument expression to the
4313  //   underlying type of the reference according to
4314  //   13.3.3.1. Conceptually, this conversion sequence corresponds
4315  //   to copy-initializing a temporary of the underlying type with
4316  //   the argument expression. Any difference in top-level
4317  //   cv-qualification is subsumed by the initialization itself
4318  //   and does not constitute a conversion.
4319  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4320                              /*AllowExplicit=*/false,
4321                              /*InOverloadResolution=*/false,
4322                              /*CStyle=*/false,
4323                              /*AllowObjCWritebackConversion=*/false);
4324
4325  // Of course, that's still a reference binding.
4326  if (ICS.isStandard()) {
4327    ICS.Standard.ReferenceBinding = true;
4328    ICS.Standard.IsLvalueReference = !isRValRef;
4329    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4330    ICS.Standard.BindsToRvalue = true;
4331    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4332    ICS.Standard.ObjCLifetimeConversionBinding = false;
4333  } else if (ICS.isUserDefined()) {
4334    // Don't allow rvalue references to bind to lvalues.
4335    if (DeclType->isRValueReferenceType()) {
4336      if (const ReferenceType *RefType
4337            = ICS.UserDefined.ConversionFunction->getResultType()
4338                ->getAs<LValueReferenceType>()) {
4339        if (!RefType->getPointeeType()->isFunctionType()) {
4340          ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4341                     DeclType);
4342          return ICS;
4343        }
4344      }
4345    }
4346
4347    ICS.UserDefined.After.ReferenceBinding = true;
4348    ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4349    ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4350    ICS.UserDefined.After.BindsToRvalue = true;
4351    ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4352    ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4353  }
4354
4355  return ICS;
4356}
4357
4358static ImplicitConversionSequence
4359TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4360                      bool SuppressUserConversions,
4361                      bool InOverloadResolution,
4362                      bool AllowObjCWritebackConversion,
4363                      bool AllowExplicit = false);
4364
4365/// TryListConversion - Try to copy-initialize a value of type ToType from the
4366/// initializer list From.
4367static ImplicitConversionSequence
4368TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4369                  bool SuppressUserConversions,
4370                  bool InOverloadResolution,
4371                  bool AllowObjCWritebackConversion) {
4372  // C++11 [over.ics.list]p1:
4373  //   When an argument is an initializer list, it is not an expression and
4374  //   special rules apply for converting it to a parameter type.
4375
4376  ImplicitConversionSequence Result;
4377  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4378  Result.setListInitializationSequence();
4379
4380  // We need a complete type for what follows. Incomplete types can never be
4381  // initialized from init lists.
4382  if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4383    return Result;
4384
4385  // C++11 [over.ics.list]p2:
4386  //   If the parameter type is std::initializer_list<X> or "array of X" and
4387  //   all the elements can be implicitly converted to X, the implicit
4388  //   conversion sequence is the worst conversion necessary to convert an
4389  //   element of the list to X.
4390  bool toStdInitializerList = false;
4391  QualType X;
4392  if (ToType->isArrayType())
4393    X = S.Context.getAsArrayType(ToType)->getElementType();
4394  else
4395    toStdInitializerList = S.isStdInitializerList(ToType, &X);
4396  if (!X.isNull()) {
4397    for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4398      Expr *Init = From->getInit(i);
4399      ImplicitConversionSequence ICS =
4400          TryCopyInitialization(S, Init, X, SuppressUserConversions,
4401                                InOverloadResolution,
4402                                AllowObjCWritebackConversion);
4403      // If a single element isn't convertible, fail.
4404      if (ICS.isBad()) {
4405        Result = ICS;
4406        break;
4407      }
4408      // Otherwise, look for the worst conversion.
4409      if (Result.isBad() ||
4410          CompareImplicitConversionSequences(S, ICS, Result) ==
4411              ImplicitConversionSequence::Worse)
4412        Result = ICS;
4413    }
4414
4415    // For an empty list, we won't have computed any conversion sequence.
4416    // Introduce the identity conversion sequence.
4417    if (From->getNumInits() == 0) {
4418      Result.setStandard();
4419      Result.Standard.setAsIdentityConversion();
4420      Result.Standard.setFromType(ToType);
4421      Result.Standard.setAllToTypes(ToType);
4422    }
4423
4424    Result.setListInitializationSequence();
4425    Result.setStdInitializerListElement(toStdInitializerList);
4426    return Result;
4427  }
4428
4429  // C++11 [over.ics.list]p3:
4430  //   Otherwise, if the parameter is a non-aggregate class X and overload
4431  //   resolution chooses a single best constructor [...] the implicit
4432  //   conversion sequence is a user-defined conversion sequence. If multiple
4433  //   constructors are viable but none is better than the others, the
4434  //   implicit conversion sequence is a user-defined conversion sequence.
4435  if (ToType->isRecordType() && !ToType->isAggregateType()) {
4436    // This function can deal with initializer lists.
4437    Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4438                                      /*AllowExplicit=*/false,
4439                                      InOverloadResolution, /*CStyle=*/false,
4440                                      AllowObjCWritebackConversion);
4441    Result.setListInitializationSequence();
4442    return Result;
4443  }
4444
4445  // C++11 [over.ics.list]p4:
4446  //   Otherwise, if the parameter has an aggregate type which can be
4447  //   initialized from the initializer list [...] the implicit conversion
4448  //   sequence is a user-defined conversion sequence.
4449  if (ToType->isAggregateType()) {
4450    // Type is an aggregate, argument is an init list. At this point it comes
4451    // down to checking whether the initialization works.
4452    // FIXME: Find out whether this parameter is consumed or not.
4453    InitializedEntity Entity =
4454        InitializedEntity::InitializeParameter(S.Context, ToType,
4455                                               /*Consumed=*/false);
4456    if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4457      Result.setUserDefined();
4458      Result.UserDefined.Before.setAsIdentityConversion();
4459      // Initializer lists don't have a type.
4460      Result.UserDefined.Before.setFromType(QualType());
4461      Result.UserDefined.Before.setAllToTypes(QualType());
4462
4463      Result.UserDefined.After.setAsIdentityConversion();
4464      Result.UserDefined.After.setFromType(ToType);
4465      Result.UserDefined.After.setAllToTypes(ToType);
4466      Result.UserDefined.ConversionFunction = 0;
4467    }
4468    return Result;
4469  }
4470
4471  // C++11 [over.ics.list]p5:
4472  //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4473  if (ToType->isReferenceType()) {
4474    // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4475    // mention initializer lists in any way. So we go by what list-
4476    // initialization would do and try to extrapolate from that.
4477
4478    QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4479
4480    // If the initializer list has a single element that is reference-related
4481    // to the parameter type, we initialize the reference from that.
4482    if (From->getNumInits() == 1) {
4483      Expr *Init = From->getInit(0);
4484
4485      QualType T2 = Init->getType();
4486
4487      // If the initializer is the address of an overloaded function, try
4488      // to resolve the overloaded function. If all goes well, T2 is the
4489      // type of the resulting function.
4490      if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4491        DeclAccessPair Found;
4492        if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4493                                   Init, ToType, false, Found))
4494          T2 = Fn->getType();
4495      }
4496
4497      // Compute some basic properties of the types and the initializer.
4498      bool dummy1 = false;
4499      bool dummy2 = false;
4500      bool dummy3 = false;
4501      Sema::ReferenceCompareResult RefRelationship
4502        = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4503                                         dummy2, dummy3);
4504
4505      if (RefRelationship >= Sema::Ref_Related)
4506        return TryReferenceInit(S, Init, ToType,
4507                                /*FIXME:*/From->getLocStart(),
4508                                SuppressUserConversions,
4509                                /*AllowExplicit=*/false);
4510    }
4511
4512    // Otherwise, we bind the reference to a temporary created from the
4513    // initializer list.
4514    Result = TryListConversion(S, From, T1, SuppressUserConversions,
4515                               InOverloadResolution,
4516                               AllowObjCWritebackConversion);
4517    if (Result.isFailure())
4518      return Result;
4519    assert(!Result.isEllipsis() &&
4520           "Sub-initialization cannot result in ellipsis conversion.");
4521
4522    // Can we even bind to a temporary?
4523    if (ToType->isRValueReferenceType() ||
4524        (T1.isConstQualified() && !T1.isVolatileQualified())) {
4525      StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4526                                            Result.UserDefined.After;
4527      SCS.ReferenceBinding = true;
4528      SCS.IsLvalueReference = ToType->isLValueReferenceType();
4529      SCS.BindsToRvalue = true;
4530      SCS.BindsToFunctionLvalue = false;
4531      SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4532      SCS.ObjCLifetimeConversionBinding = false;
4533    } else
4534      Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4535                    From, ToType);
4536    return Result;
4537  }
4538
4539  // C++11 [over.ics.list]p6:
4540  //   Otherwise, if the parameter type is not a class:
4541  if (!ToType->isRecordType()) {
4542    //    - if the initializer list has one element, the implicit conversion
4543    //      sequence is the one required to convert the element to the
4544    //      parameter type.
4545    unsigned NumInits = From->getNumInits();
4546    if (NumInits == 1)
4547      Result = TryCopyInitialization(S, From->getInit(0), ToType,
4548                                     SuppressUserConversions,
4549                                     InOverloadResolution,
4550                                     AllowObjCWritebackConversion);
4551    //    - if the initializer list has no elements, the implicit conversion
4552    //      sequence is the identity conversion.
4553    else if (NumInits == 0) {
4554      Result.setStandard();
4555      Result.Standard.setAsIdentityConversion();
4556      Result.Standard.setFromType(ToType);
4557      Result.Standard.setAllToTypes(ToType);
4558    }
4559    Result.setListInitializationSequence();
4560    return Result;
4561  }
4562
4563  // C++11 [over.ics.list]p7:
4564  //   In all cases other than those enumerated above, no conversion is possible
4565  return Result;
4566}
4567
4568/// TryCopyInitialization - Try to copy-initialize a value of type
4569/// ToType from the expression From. Return the implicit conversion
4570/// sequence required to pass this argument, which may be a bad
4571/// conversion sequence (meaning that the argument cannot be passed to
4572/// a parameter of this type). If @p SuppressUserConversions, then we
4573/// do not permit any user-defined conversion sequences.
4574static ImplicitConversionSequence
4575TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4576                      bool SuppressUserConversions,
4577                      bool InOverloadResolution,
4578                      bool AllowObjCWritebackConversion,
4579                      bool AllowExplicit) {
4580  if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4581    return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4582                             InOverloadResolution,AllowObjCWritebackConversion);
4583
4584  if (ToType->isReferenceType())
4585    return TryReferenceInit(S, From, ToType,
4586                            /*FIXME:*/From->getLocStart(),
4587                            SuppressUserConversions,
4588                            AllowExplicit);
4589
4590  return TryImplicitConversion(S, From, ToType,
4591                               SuppressUserConversions,
4592                               /*AllowExplicit=*/false,
4593                               InOverloadResolution,
4594                               /*CStyle=*/false,
4595                               AllowObjCWritebackConversion);
4596}
4597
4598static bool TryCopyInitialization(const CanQualType FromQTy,
4599                                  const CanQualType ToQTy,
4600                                  Sema &S,
4601                                  SourceLocation Loc,
4602                                  ExprValueKind FromVK) {
4603  OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4604  ImplicitConversionSequence ICS =
4605    TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4606
4607  return !ICS.isBad();
4608}
4609
4610/// TryObjectArgumentInitialization - Try to initialize the object
4611/// parameter of the given member function (@c Method) from the
4612/// expression @p From.
4613static ImplicitConversionSequence
4614TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
4615                                Expr::Classification FromClassification,
4616                                CXXMethodDecl *Method,
4617                                CXXRecordDecl *ActingContext) {
4618  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4619  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4620  //                 const volatile object.
4621  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4622    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4623  QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4624
4625  // Set up the conversion sequence as a "bad" conversion, to allow us
4626  // to exit early.
4627  ImplicitConversionSequence ICS;
4628
4629  // We need to have an object of class type.
4630  QualType FromType = OrigFromType;
4631  if (const PointerType *PT = FromType->getAs<PointerType>()) {
4632    FromType = PT->getPointeeType();
4633
4634    // When we had a pointer, it's implicitly dereferenced, so we
4635    // better have an lvalue.
4636    assert(FromClassification.isLValue());
4637  }
4638
4639  assert(FromType->isRecordType());
4640
4641  // C++0x [over.match.funcs]p4:
4642  //   For non-static member functions, the type of the implicit object
4643  //   parameter is
4644  //
4645  //     - "lvalue reference to cv X" for functions declared without a
4646  //        ref-qualifier or with the & ref-qualifier
4647  //     - "rvalue reference to cv X" for functions declared with the &&
4648  //        ref-qualifier
4649  //
4650  // where X is the class of which the function is a member and cv is the
4651  // cv-qualification on the member function declaration.
4652  //
4653  // However, when finding an implicit conversion sequence for the argument, we
4654  // are not allowed to create temporaries or perform user-defined conversions
4655  // (C++ [over.match.funcs]p5). We perform a simplified version of
4656  // reference binding here, that allows class rvalues to bind to
4657  // non-constant references.
4658
4659  // First check the qualifiers.
4660  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4661  if (ImplicitParamType.getCVRQualifiers()
4662                                    != FromTypeCanon.getLocalCVRQualifiers() &&
4663      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4664    ICS.setBad(BadConversionSequence::bad_qualifiers,
4665               OrigFromType, ImplicitParamType);
4666    return ICS;
4667  }
4668
4669  // Check that we have either the same type or a derived type. It
4670  // affects the conversion rank.
4671  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4672  ImplicitConversionKind SecondKind;
4673  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4674    SecondKind = ICK_Identity;
4675  } else if (S.IsDerivedFrom(FromType, ClassType))
4676    SecondKind = ICK_Derived_To_Base;
4677  else {
4678    ICS.setBad(BadConversionSequence::unrelated_class,
4679               FromType, ImplicitParamType);
4680    return ICS;
4681  }
4682
4683  // Check the ref-qualifier.
4684  switch (Method->getRefQualifier()) {
4685  case RQ_None:
4686    // Do nothing; we don't care about lvalueness or rvalueness.
4687    break;
4688
4689  case RQ_LValue:
4690    if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4691      // non-const lvalue reference cannot bind to an rvalue
4692      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4693                 ImplicitParamType);
4694      return ICS;
4695    }
4696    break;
4697
4698  case RQ_RValue:
4699    if (!FromClassification.isRValue()) {
4700      // rvalue reference cannot bind to an lvalue
4701      ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4702                 ImplicitParamType);
4703      return ICS;
4704    }
4705    break;
4706  }
4707
4708  // Success. Mark this as a reference binding.
4709  ICS.setStandard();
4710  ICS.Standard.setAsIdentityConversion();
4711  ICS.Standard.Second = SecondKind;
4712  ICS.Standard.setFromType(FromType);
4713  ICS.Standard.setAllToTypes(ImplicitParamType);
4714  ICS.Standard.ReferenceBinding = true;
4715  ICS.Standard.DirectBinding = true;
4716  ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4717  ICS.Standard.BindsToFunctionLvalue = false;
4718  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4719  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4720    = (Method->getRefQualifier() == RQ_None);
4721  return ICS;
4722}
4723
4724/// PerformObjectArgumentInitialization - Perform initialization of
4725/// the implicit object parameter for the given Method with the given
4726/// expression.
4727ExprResult
4728Sema::PerformObjectArgumentInitialization(Expr *From,
4729                                          NestedNameSpecifier *Qualifier,
4730                                          NamedDecl *FoundDecl,
4731                                          CXXMethodDecl *Method) {
4732  QualType FromRecordType, DestType;
4733  QualType ImplicitParamRecordType  =
4734    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4735
4736  Expr::Classification FromClassification;
4737  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4738    FromRecordType = PT->getPointeeType();
4739    DestType = Method->getThisType(Context);
4740    FromClassification = Expr::Classification::makeSimpleLValue();
4741  } else {
4742    FromRecordType = From->getType();
4743    DestType = ImplicitParamRecordType;
4744    FromClassification = From->Classify(Context);
4745  }
4746
4747  // Note that we always use the true parent context when performing
4748  // the actual argument initialization.
4749  ImplicitConversionSequence ICS
4750    = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4751                                      Method, Method->getParent());
4752  if (ICS.isBad()) {
4753    if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4754      Qualifiers FromQs = FromRecordType.getQualifiers();
4755      Qualifiers ToQs = DestType.getQualifiers();
4756      unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4757      if (CVR) {
4758        Diag(From->getLocStart(),
4759             diag::err_member_function_call_bad_cvr)
4760          << Method->getDeclName() << FromRecordType << (CVR - 1)
4761          << From->getSourceRange();
4762        Diag(Method->getLocation(), diag::note_previous_decl)
4763          << Method->getDeclName();
4764        return ExprError();
4765      }
4766    }
4767
4768    return Diag(From->getLocStart(),
4769                diag::err_implicit_object_parameter_init)
4770       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4771  }
4772
4773  if (ICS.Standard.Second == ICK_Derived_To_Base) {
4774    ExprResult FromRes =
4775      PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4776    if (FromRes.isInvalid())
4777      return ExprError();
4778    From = FromRes.take();
4779  }
4780
4781  if (!Context.hasSameType(From->getType(), DestType))
4782    From = ImpCastExprToType(From, DestType, CK_NoOp,
4783                             From->getValueKind()).take();
4784  return Owned(From);
4785}
4786
4787/// TryContextuallyConvertToBool - Attempt to contextually convert the
4788/// expression From to bool (C++0x [conv]p3).
4789static ImplicitConversionSequence
4790TryContextuallyConvertToBool(Sema &S, Expr *From) {
4791  // FIXME: This is pretty broken.
4792  return TryImplicitConversion(S, From, S.Context.BoolTy,
4793                               // FIXME: Are these flags correct?
4794                               /*SuppressUserConversions=*/false,
4795                               /*AllowExplicit=*/true,
4796                               /*InOverloadResolution=*/false,
4797                               /*CStyle=*/false,
4798                               /*AllowObjCWritebackConversion=*/false);
4799}
4800
4801/// PerformContextuallyConvertToBool - Perform a contextual conversion
4802/// of the expression From to bool (C++0x [conv]p3).
4803ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4804  if (checkPlaceholderForOverload(*this, From))
4805    return ExprError();
4806
4807  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4808  if (!ICS.isBad())
4809    return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4810
4811  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4812    return Diag(From->getLocStart(),
4813                diag::err_typecheck_bool_condition)
4814                  << From->getType() << From->getSourceRange();
4815  return ExprError();
4816}
4817
4818/// Check that the specified conversion is permitted in a converted constant
4819/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4820/// is acceptable.
4821static bool CheckConvertedConstantConversions(Sema &S,
4822                                              StandardConversionSequence &SCS) {
4823  // Since we know that the target type is an integral or unscoped enumeration
4824  // type, most conversion kinds are impossible. All possible First and Third
4825  // conversions are fine.
4826  switch (SCS.Second) {
4827  case ICK_Identity:
4828  case ICK_Integral_Promotion:
4829  case ICK_Integral_Conversion:
4830    return true;
4831
4832  case ICK_Boolean_Conversion:
4833    // Conversion from an integral or unscoped enumeration type to bool is
4834    // classified as ICK_Boolean_Conversion, but it's also an integral
4835    // conversion, so it's permitted in a converted constant expression.
4836    return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4837           SCS.getToType(2)->isBooleanType();
4838
4839  case ICK_Floating_Integral:
4840  case ICK_Complex_Real:
4841    return false;
4842
4843  case ICK_Lvalue_To_Rvalue:
4844  case ICK_Array_To_Pointer:
4845  case ICK_Function_To_Pointer:
4846  case ICK_NoReturn_Adjustment:
4847  case ICK_Qualification:
4848  case ICK_Compatible_Conversion:
4849  case ICK_Vector_Conversion:
4850  case ICK_Vector_Splat:
4851  case ICK_Derived_To_Base:
4852  case ICK_Pointer_Conversion:
4853  case ICK_Pointer_Member:
4854  case ICK_Block_Pointer_Conversion:
4855  case ICK_Writeback_Conversion:
4856  case ICK_Floating_Promotion:
4857  case ICK_Complex_Promotion:
4858  case ICK_Complex_Conversion:
4859  case ICK_Floating_Conversion:
4860  case ICK_TransparentUnionConversion:
4861    llvm_unreachable("unexpected second conversion kind");
4862
4863  case ICK_Num_Conversion_Kinds:
4864    break;
4865  }
4866
4867  llvm_unreachable("unknown conversion kind");
4868}
4869
4870/// CheckConvertedConstantExpression - Check that the expression From is a
4871/// converted constant expression of type T, perform the conversion and produce
4872/// the converted expression, per C++11 [expr.const]p3.
4873ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4874                                                  llvm::APSInt &Value,
4875                                                  CCEKind CCE) {
4876  assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4877  assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4878
4879  if (checkPlaceholderForOverload(*this, From))
4880    return ExprError();
4881
4882  // C++11 [expr.const]p3 with proposed wording fixes:
4883  //  A converted constant expression of type T is a core constant expression,
4884  //  implicitly converted to a prvalue of type T, where the converted
4885  //  expression is a literal constant expression and the implicit conversion
4886  //  sequence contains only user-defined conversions, lvalue-to-rvalue
4887  //  conversions, integral promotions, and integral conversions other than
4888  //  narrowing conversions.
4889  ImplicitConversionSequence ICS =
4890    TryImplicitConversion(From, T,
4891                          /*SuppressUserConversions=*/false,
4892                          /*AllowExplicit=*/false,
4893                          /*InOverloadResolution=*/false,
4894                          /*CStyle=*/false,
4895                          /*AllowObjcWritebackConversion=*/false);
4896  StandardConversionSequence *SCS = 0;
4897  switch (ICS.getKind()) {
4898  case ImplicitConversionSequence::StandardConversion:
4899    if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4900      return Diag(From->getLocStart(),
4901                  diag::err_typecheck_converted_constant_expression_disallowed)
4902               << From->getType() << From->getSourceRange() << T;
4903    SCS = &ICS.Standard;
4904    break;
4905  case ImplicitConversionSequence::UserDefinedConversion:
4906    // We are converting from class type to an integral or enumeration type, so
4907    // the Before sequence must be trivial.
4908    if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4909      return Diag(From->getLocStart(),
4910                  diag::err_typecheck_converted_constant_expression_disallowed)
4911               << From->getType() << From->getSourceRange() << T;
4912    SCS = &ICS.UserDefined.After;
4913    break;
4914  case ImplicitConversionSequence::AmbiguousConversion:
4915  case ImplicitConversionSequence::BadConversion:
4916    if (!DiagnoseMultipleUserDefinedConversion(From, T))
4917      return Diag(From->getLocStart(),
4918                  diag::err_typecheck_converted_constant_expression)
4919                    << From->getType() << From->getSourceRange() << T;
4920    return ExprError();
4921
4922  case ImplicitConversionSequence::EllipsisConversion:
4923    llvm_unreachable("ellipsis conversion in converted constant expression");
4924  }
4925
4926  ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4927  if (Result.isInvalid())
4928    return Result;
4929
4930  // Check for a narrowing implicit conversion.
4931  APValue PreNarrowingValue;
4932  QualType PreNarrowingType;
4933  switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4934                                PreNarrowingType)) {
4935  case NK_Variable_Narrowing:
4936    // Implicit conversion to a narrower type, and the value is not a constant
4937    // expression. We'll diagnose this in a moment.
4938  case NK_Not_Narrowing:
4939    break;
4940
4941  case NK_Constant_Narrowing:
4942    Diag(From->getLocStart(),
4943         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4944                             diag::err_cce_narrowing)
4945      << CCE << /*Constant*/1
4946      << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
4947    break;
4948
4949  case NK_Type_Narrowing:
4950    Diag(From->getLocStart(),
4951         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4952                             diag::err_cce_narrowing)
4953      << CCE << /*Constant*/0 << From->getType() << T;
4954    break;
4955  }
4956
4957  // Check the expression is a constant expression.
4958  SmallVector<PartialDiagnosticAt, 8> Notes;
4959  Expr::EvalResult Eval;
4960  Eval.Diag = &Notes;
4961
4962  if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4963    // The expression can't be folded, so we can't keep it at this position in
4964    // the AST.
4965    Result = ExprError();
4966  } else {
4967    Value = Eval.Val.getInt();
4968
4969    if (Notes.empty()) {
4970      // It's a constant expression.
4971      return Result;
4972    }
4973  }
4974
4975  // It's not a constant expression. Produce an appropriate diagnostic.
4976  if (Notes.size() == 1 &&
4977      Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4978    Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4979  else {
4980    Diag(From->getLocStart(), diag::err_expr_not_cce)
4981      << CCE << From->getSourceRange();
4982    for (unsigned I = 0; I < Notes.size(); ++I)
4983      Diag(Notes[I].first, Notes[I].second);
4984  }
4985  return Result;
4986}
4987
4988/// dropPointerConversions - If the given standard conversion sequence
4989/// involves any pointer conversions, remove them.  This may change
4990/// the result type of the conversion sequence.
4991static void dropPointerConversion(StandardConversionSequence &SCS) {
4992  if (SCS.Second == ICK_Pointer_Conversion) {
4993    SCS.Second = ICK_Identity;
4994    SCS.Third = ICK_Identity;
4995    SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4996  }
4997}
4998
4999/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5000/// convert the expression From to an Objective-C pointer type.
5001static ImplicitConversionSequence
5002TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5003  // Do an implicit conversion to 'id'.
5004  QualType Ty = S.Context.getObjCIdType();
5005  ImplicitConversionSequence ICS
5006    = TryImplicitConversion(S, From, Ty,
5007                            // FIXME: Are these flags correct?
5008                            /*SuppressUserConversions=*/false,
5009                            /*AllowExplicit=*/true,
5010                            /*InOverloadResolution=*/false,
5011                            /*CStyle=*/false,
5012                            /*AllowObjCWritebackConversion=*/false);
5013
5014  // Strip off any final conversions to 'id'.
5015  switch (ICS.getKind()) {
5016  case ImplicitConversionSequence::BadConversion:
5017  case ImplicitConversionSequence::AmbiguousConversion:
5018  case ImplicitConversionSequence::EllipsisConversion:
5019    break;
5020
5021  case ImplicitConversionSequence::UserDefinedConversion:
5022    dropPointerConversion(ICS.UserDefined.After);
5023    break;
5024
5025  case ImplicitConversionSequence::StandardConversion:
5026    dropPointerConversion(ICS.Standard);
5027    break;
5028  }
5029
5030  return ICS;
5031}
5032
5033/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5034/// conversion of the expression From to an Objective-C pointer type.
5035ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5036  if (checkPlaceholderForOverload(*this, From))
5037    return ExprError();
5038
5039  QualType Ty = Context.getObjCIdType();
5040  ImplicitConversionSequence ICS =
5041    TryContextuallyConvertToObjCPointer(*this, From);
5042  if (!ICS.isBad())
5043    return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5044  return ExprError();
5045}
5046
5047/// Determine whether the provided type is an integral type, or an enumeration
5048/// type of a permitted flavor.
5049static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5050  return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5051                         : T->isIntegralOrUnscopedEnumerationType();
5052}
5053
5054/// \brief Attempt to convert the given expression to an integral or
5055/// enumeration type.
5056///
5057/// This routine will attempt to convert an expression of class type to an
5058/// integral or enumeration type, if that class type only has a single
5059/// conversion to an integral or enumeration type.
5060///
5061/// \param Loc The source location of the construct that requires the
5062/// conversion.
5063///
5064/// \param From The expression we're converting from.
5065///
5066/// \param Diagnoser Used to output any diagnostics.
5067///
5068/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5069/// enumerations should be considered.
5070///
5071/// \returns The expression, converted to an integral or enumeration type if
5072/// successful.
5073ExprResult
5074Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
5075                                         ICEConvertDiagnoser &Diagnoser,
5076                                         bool AllowScopedEnumerations) {
5077  // We can't perform any more checking for type-dependent expressions.
5078  if (From->isTypeDependent())
5079    return Owned(From);
5080
5081  // Process placeholders immediately.
5082  if (From->hasPlaceholderType()) {
5083    ExprResult result = CheckPlaceholderExpr(From);
5084    if (result.isInvalid()) return result;
5085    From = result.take();
5086  }
5087
5088  // If the expression already has integral or enumeration type, we're golden.
5089  QualType T = From->getType();
5090  if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
5091    return DefaultLvalueConversion(From);
5092
5093  // FIXME: Check for missing '()' if T is a function type?
5094
5095  // If we don't have a class type in C++, there's no way we can get an
5096  // expression of integral or enumeration type.
5097  const RecordType *RecordTy = T->getAs<RecordType>();
5098  if (!RecordTy || !getLangOpts().CPlusPlus) {
5099    if (!Diagnoser.Suppress)
5100      Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
5101    return Owned(From);
5102  }
5103
5104  // We must have a complete class type.
5105  struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5106    ICEConvertDiagnoser &Diagnoser;
5107    Expr *From;
5108
5109    TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5110      : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
5111
5112    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5113      Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5114    }
5115  } IncompleteDiagnoser(Diagnoser, From);
5116
5117  if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5118    return Owned(From);
5119
5120  // Look for a conversion to an integral or enumeration type.
5121  UnresolvedSet<4> ViableConversions;
5122  UnresolvedSet<4> ExplicitConversions;
5123  std::pair<CXXRecordDecl::conversion_iterator,
5124            CXXRecordDecl::conversion_iterator> Conversions
5125    = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5126
5127  bool HadMultipleCandidates
5128    = (std::distance(Conversions.first, Conversions.second) > 1);
5129
5130  for (CXXRecordDecl::conversion_iterator
5131         I = Conversions.first, E = Conversions.second; I != E; ++I) {
5132    if (CXXConversionDecl *Conversion
5133          = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5134      if (isIntegralOrEnumerationType(
5135            Conversion->getConversionType().getNonReferenceType(),
5136            AllowScopedEnumerations)) {
5137        if (Conversion->isExplicit())
5138          ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5139        else
5140          ViableConversions.addDecl(I.getDecl(), I.getAccess());
5141      }
5142    }
5143  }
5144
5145  switch (ViableConversions.size()) {
5146  case 0:
5147    if (ExplicitConversions.size() == 1 && !Diagnoser.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
5155        = Conversion->getConversionType().getNonReferenceType();
5156      std::string TypeStr;
5157      ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
5158
5159      Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
5160        << FixItHint::CreateInsertion(From->getLocStart(),
5161                                      "static_cast<" + TypeStr + ">(")
5162        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5163                                      ")");
5164      Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
5165
5166      // If we aren't in a SFINAE context, build a call to the
5167      // explicit conversion function.
5168      if (isSFINAEContext())
5169        return ExprError();
5170
5171      CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5172      ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5173                                                 HadMultipleCandidates);
5174      if (Result.isInvalid())
5175        return ExprError();
5176      // Record usage of conversion in an implicit cast.
5177      From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5178                                      CK_UserDefinedConversion,
5179                                      Result.get(), 0,
5180                                      Result.get()->getValueKind());
5181    }
5182
5183    // We'll complain below about a non-integral condition type.
5184    break;
5185
5186  case 1: {
5187    // Apply this conversion.
5188    DeclAccessPair Found = ViableConversions[0];
5189    CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5190
5191    CXXConversionDecl *Conversion
5192      = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5193    QualType ConvTy
5194      = Conversion->getConversionType().getNonReferenceType();
5195    if (!Diagnoser.SuppressConversion) {
5196      if (isSFINAEContext())
5197        return ExprError();
5198
5199      Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5200        << From->getSourceRange();
5201    }
5202
5203    ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5204                                               HadMultipleCandidates);
5205    if (Result.isInvalid())
5206      return ExprError();
5207    // Record usage of conversion in an implicit cast.
5208    From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5209                                    CK_UserDefinedConversion,
5210                                    Result.get(), 0,
5211                                    Result.get()->getValueKind());
5212    break;
5213  }
5214
5215  default:
5216    if (Diagnoser.Suppress)
5217      return ExprError();
5218
5219    Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
5220    for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5221      CXXConversionDecl *Conv
5222        = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5223      QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5224      Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
5225    }
5226    return Owned(From);
5227  }
5228
5229  if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5230      !Diagnoser.Suppress) {
5231    Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5232      << From->getSourceRange();
5233  }
5234
5235  return DefaultLvalueConversion(From);
5236}
5237
5238/// AddOverloadCandidate - Adds the given function to the set of
5239/// candidate functions, using the given function call arguments.  If
5240/// @p SuppressUserConversions, then don't allow user-defined
5241/// conversions via constructors or conversion operators.
5242///
5243/// \param PartialOverloading true if we are performing "partial" overloading
5244/// based on an incomplete set of function arguments. This feature is used by
5245/// code completion.
5246void
5247Sema::AddOverloadCandidate(FunctionDecl *Function,
5248                           DeclAccessPair FoundDecl,
5249                           ArrayRef<Expr *> Args,
5250                           OverloadCandidateSet& CandidateSet,
5251                           bool SuppressUserConversions,
5252                           bool PartialOverloading,
5253                           bool AllowExplicit) {
5254  const FunctionProtoType* Proto
5255    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5256  assert(Proto && "Functions without a prototype cannot be overloaded");
5257  assert(!Function->getDescribedFunctionTemplate() &&
5258         "Use AddTemplateOverloadCandidate for function templates");
5259
5260  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5261    if (!isa<CXXConstructorDecl>(Method)) {
5262      // If we get here, it's because we're calling a member function
5263      // that is named without a member access expression (e.g.,
5264      // "this->f") that was either written explicitly or created
5265      // implicitly. This can happen with a qualified call to a member
5266      // function, e.g., X::f(). We use an empty type for the implied
5267      // object argument (C++ [over.call.func]p3), and the acting context
5268      // is irrelevant.
5269      AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5270                         QualType(), Expr::Classification::makeSimpleLValue(),
5271                         Args, CandidateSet, SuppressUserConversions);
5272      return;
5273    }
5274    // We treat a constructor like a non-member function, since its object
5275    // argument doesn't participate in overload resolution.
5276  }
5277
5278  if (!CandidateSet.isNewCandidate(Function))
5279    return;
5280
5281  // Overload resolution is always an unevaluated context.
5282  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5283
5284  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5285    // C++ [class.copy]p3:
5286    //   A member function template is never instantiated to perform the copy
5287    //   of a class object to an object of its class type.
5288    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5289    if (Args.size() == 1 &&
5290        Constructor->isSpecializationCopyingObject() &&
5291        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5292         IsDerivedFrom(Args[0]->getType(), ClassType)))
5293      return;
5294  }
5295
5296  // Add this candidate
5297  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5298  Candidate.FoundDecl = FoundDecl;
5299  Candidate.Function = Function;
5300  Candidate.Viable = true;
5301  Candidate.IsSurrogate = false;
5302  Candidate.IgnoreObjectArgument = false;
5303  Candidate.ExplicitCallArguments = Args.size();
5304
5305  unsigned NumArgsInProto = Proto->getNumArgs();
5306
5307  // (C++ 13.3.2p2): A candidate function having fewer than m
5308  // parameters is viable only if it has an ellipsis in its parameter
5309  // list (8.3.5).
5310  if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5311      !Proto->isVariadic()) {
5312    Candidate.Viable = false;
5313    Candidate.FailureKind = ovl_fail_too_many_arguments;
5314    return;
5315  }
5316
5317  // (C++ 13.3.2p2): A candidate function having more than m parameters
5318  // is viable only if the (m+1)st parameter has a default argument
5319  // (8.3.6). For the purposes of overload resolution, the
5320  // parameter list is truncated on the right, so that there are
5321  // exactly m parameters.
5322  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5323  if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5324    // Not enough arguments.
5325    Candidate.Viable = false;
5326    Candidate.FailureKind = ovl_fail_too_few_arguments;
5327    return;
5328  }
5329
5330  // (CUDA B.1): Check for invalid calls between targets.
5331  if (getLangOpts().CUDA)
5332    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5333      if (CheckCUDATarget(Caller, Function)) {
5334        Candidate.Viable = false;
5335        Candidate.FailureKind = ovl_fail_bad_target;
5336        return;
5337      }
5338
5339  // Determine the implicit conversion sequences for each of the
5340  // arguments.
5341  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5342    if (ArgIdx < NumArgsInProto) {
5343      // (C++ 13.3.2p3): for F to be a viable function, there shall
5344      // exist for each argument an implicit conversion sequence
5345      // (13.3.3.1) that converts that argument to the corresponding
5346      // parameter of F.
5347      QualType ParamType = Proto->getArgType(ArgIdx);
5348      Candidate.Conversions[ArgIdx]
5349        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5350                                SuppressUserConversions,
5351                                /*InOverloadResolution=*/true,
5352                                /*AllowObjCWritebackConversion=*/
5353                                  getLangOpts().ObjCAutoRefCount,
5354                                AllowExplicit);
5355      if (Candidate.Conversions[ArgIdx].isBad()) {
5356        Candidate.Viable = false;
5357        Candidate.FailureKind = ovl_fail_bad_conversion;
5358        break;
5359      }
5360    } else {
5361      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5362      // argument for which there is no corresponding parameter is
5363      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5364      Candidate.Conversions[ArgIdx].setEllipsis();
5365    }
5366  }
5367}
5368
5369/// \brief Add all of the function declarations in the given function set to
5370/// the overload canddiate set.
5371void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5372                                 ArrayRef<Expr *> Args,
5373                                 OverloadCandidateSet& CandidateSet,
5374                                 bool SuppressUserConversions,
5375                               TemplateArgumentListInfo *ExplicitTemplateArgs) {
5376  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5377    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5378    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5379      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5380        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5381                           cast<CXXMethodDecl>(FD)->getParent(),
5382                           Args[0]->getType(), Args[0]->Classify(Context),
5383                           Args.slice(1), CandidateSet,
5384                           SuppressUserConversions);
5385      else
5386        AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5387                             SuppressUserConversions);
5388    } else {
5389      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5390      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5391          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5392        AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5393                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5394                                   ExplicitTemplateArgs,
5395                                   Args[0]->getType(),
5396                                   Args[0]->Classify(Context), Args.slice(1),
5397                                   CandidateSet, SuppressUserConversions);
5398      else
5399        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5400                                     ExplicitTemplateArgs, Args,
5401                                     CandidateSet, SuppressUserConversions);
5402    }
5403  }
5404}
5405
5406/// AddMethodCandidate - Adds a named decl (which is some kind of
5407/// method) as a method candidate to the given overload set.
5408void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5409                              QualType ObjectType,
5410                              Expr::Classification ObjectClassification,
5411                              Expr **Args, unsigned NumArgs,
5412                              OverloadCandidateSet& CandidateSet,
5413                              bool SuppressUserConversions) {
5414  NamedDecl *Decl = FoundDecl.getDecl();
5415  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5416
5417  if (isa<UsingShadowDecl>(Decl))
5418    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5419
5420  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5421    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5422           "Expected a member function template");
5423    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5424                               /*ExplicitArgs*/ 0,
5425                               ObjectType, ObjectClassification,
5426                               llvm::makeArrayRef(Args, NumArgs), CandidateSet,
5427                               SuppressUserConversions);
5428  } else {
5429    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5430                       ObjectType, ObjectClassification,
5431                       llvm::makeArrayRef(Args, NumArgs),
5432                       CandidateSet, SuppressUserConversions);
5433  }
5434}
5435
5436/// AddMethodCandidate - Adds the given C++ member function to the set
5437/// of candidate functions, using the given function call arguments
5438/// and the object argument (@c Object). For example, in a call
5439/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5440/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5441/// allow user-defined conversions via constructors or conversion
5442/// operators.
5443void
5444Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5445                         CXXRecordDecl *ActingContext, QualType ObjectType,
5446                         Expr::Classification ObjectClassification,
5447                         ArrayRef<Expr *> Args,
5448                         OverloadCandidateSet& CandidateSet,
5449                         bool SuppressUserConversions) {
5450  const FunctionProtoType* Proto
5451    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5452  assert(Proto && "Methods without a prototype cannot be overloaded");
5453  assert(!isa<CXXConstructorDecl>(Method) &&
5454         "Use AddOverloadCandidate for constructors");
5455
5456  if (!CandidateSet.isNewCandidate(Method))
5457    return;
5458
5459  // Overload resolution is always an unevaluated context.
5460  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5461
5462  // Add this candidate
5463  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5464  Candidate.FoundDecl = FoundDecl;
5465  Candidate.Function = Method;
5466  Candidate.IsSurrogate = false;
5467  Candidate.IgnoreObjectArgument = false;
5468  Candidate.ExplicitCallArguments = Args.size();
5469
5470  unsigned NumArgsInProto = Proto->getNumArgs();
5471
5472  // (C++ 13.3.2p2): A candidate function having fewer than m
5473  // parameters is viable only if it has an ellipsis in its parameter
5474  // list (8.3.5).
5475  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5476    Candidate.Viable = false;
5477    Candidate.FailureKind = ovl_fail_too_many_arguments;
5478    return;
5479  }
5480
5481  // (C++ 13.3.2p2): A candidate function having more than m parameters
5482  // is viable only if the (m+1)st parameter has a default argument
5483  // (8.3.6). For the purposes of overload resolution, the
5484  // parameter list is truncated on the right, so that there are
5485  // exactly m parameters.
5486  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5487  if (Args.size() < MinRequiredArgs) {
5488    // Not enough arguments.
5489    Candidate.Viable = false;
5490    Candidate.FailureKind = ovl_fail_too_few_arguments;
5491    return;
5492  }
5493
5494  Candidate.Viable = true;
5495
5496  if (Method->isStatic() || ObjectType.isNull())
5497    // The implicit object argument is ignored.
5498    Candidate.IgnoreObjectArgument = true;
5499  else {
5500    // Determine the implicit conversion sequence for the object
5501    // parameter.
5502    Candidate.Conversions[0]
5503      = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5504                                        Method, ActingContext);
5505    if (Candidate.Conversions[0].isBad()) {
5506      Candidate.Viable = false;
5507      Candidate.FailureKind = ovl_fail_bad_conversion;
5508      return;
5509    }
5510  }
5511
5512  // Determine the implicit conversion sequences for each of the
5513  // arguments.
5514  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5515    if (ArgIdx < NumArgsInProto) {
5516      // (C++ 13.3.2p3): for F to be a viable function, there shall
5517      // exist for each argument an implicit conversion sequence
5518      // (13.3.3.1) that converts that argument to the corresponding
5519      // parameter of F.
5520      QualType ParamType = Proto->getArgType(ArgIdx);
5521      Candidate.Conversions[ArgIdx + 1]
5522        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5523                                SuppressUserConversions,
5524                                /*InOverloadResolution=*/true,
5525                                /*AllowObjCWritebackConversion=*/
5526                                  getLangOpts().ObjCAutoRefCount);
5527      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5528        Candidate.Viable = false;
5529        Candidate.FailureKind = ovl_fail_bad_conversion;
5530        break;
5531      }
5532    } else {
5533      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5534      // argument for which there is no corresponding parameter is
5535      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5536      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5537    }
5538  }
5539}
5540
5541/// \brief Add a C++ member function template as a candidate to the candidate
5542/// set, using template argument deduction to produce an appropriate member
5543/// function template specialization.
5544void
5545Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5546                                 DeclAccessPair FoundDecl,
5547                                 CXXRecordDecl *ActingContext,
5548                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5549                                 QualType ObjectType,
5550                                 Expr::Classification ObjectClassification,
5551                                 ArrayRef<Expr *> Args,
5552                                 OverloadCandidateSet& CandidateSet,
5553                                 bool SuppressUserConversions) {
5554  if (!CandidateSet.isNewCandidate(MethodTmpl))
5555    return;
5556
5557  // C++ [over.match.funcs]p7:
5558  //   In each case where a candidate is a function template, candidate
5559  //   function template specializations are generated using template argument
5560  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5561  //   candidate functions in the usual way.113) A given name can refer to one
5562  //   or more function templates and also to a set of overloaded non-template
5563  //   functions. In such a case, the candidate functions generated from each
5564  //   function template are combined with the set of non-template candidate
5565  //   functions.
5566  TemplateDeductionInfo Info(CandidateSet.getLocation());
5567  FunctionDecl *Specialization = 0;
5568  if (TemplateDeductionResult Result
5569      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5570                                Specialization, Info)) {
5571    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5572    Candidate.FoundDecl = FoundDecl;
5573    Candidate.Function = MethodTmpl->getTemplatedDecl();
5574    Candidate.Viable = false;
5575    Candidate.FailureKind = ovl_fail_bad_deduction;
5576    Candidate.IsSurrogate = false;
5577    Candidate.IgnoreObjectArgument = false;
5578    Candidate.ExplicitCallArguments = Args.size();
5579    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5580                                                          Info);
5581    return;
5582  }
5583
5584  // Add the function template specialization produced by template argument
5585  // deduction as a candidate.
5586  assert(Specialization && "Missing member function template specialization?");
5587  assert(isa<CXXMethodDecl>(Specialization) &&
5588         "Specialization is not a member function?");
5589  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5590                     ActingContext, ObjectType, ObjectClassification, Args,
5591                     CandidateSet, SuppressUserConversions);
5592}
5593
5594/// \brief Add a C++ function template specialization as a candidate
5595/// in the candidate set, using template argument deduction to produce
5596/// an appropriate function template specialization.
5597void
5598Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5599                                   DeclAccessPair FoundDecl,
5600                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
5601                                   ArrayRef<Expr *> Args,
5602                                   OverloadCandidateSet& CandidateSet,
5603                                   bool SuppressUserConversions) {
5604  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5605    return;
5606
5607  // C++ [over.match.funcs]p7:
5608  //   In each case where a candidate is a function template, candidate
5609  //   function template specializations are generated using template argument
5610  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5611  //   candidate functions in the usual way.113) A given name can refer to one
5612  //   or more function templates and also to a set of overloaded non-template
5613  //   functions. In such a case, the candidate functions generated from each
5614  //   function template are combined with the set of non-template candidate
5615  //   functions.
5616  TemplateDeductionInfo Info(CandidateSet.getLocation());
5617  FunctionDecl *Specialization = 0;
5618  if (TemplateDeductionResult Result
5619        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5620                                  Specialization, Info)) {
5621    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5622    Candidate.FoundDecl = FoundDecl;
5623    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5624    Candidate.Viable = false;
5625    Candidate.FailureKind = ovl_fail_bad_deduction;
5626    Candidate.IsSurrogate = false;
5627    Candidate.IgnoreObjectArgument = false;
5628    Candidate.ExplicitCallArguments = Args.size();
5629    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5630                                                          Info);
5631    return;
5632  }
5633
5634  // Add the function template specialization produced by template argument
5635  // deduction as a candidate.
5636  assert(Specialization && "Missing function template specialization?");
5637  AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5638                       SuppressUserConversions);
5639}
5640
5641/// AddConversionCandidate - Add a C++ conversion function as a
5642/// candidate in the candidate set (C++ [over.match.conv],
5643/// C++ [over.match.copy]). From is the expression we're converting from,
5644/// and ToType is the type that we're eventually trying to convert to
5645/// (which may or may not be the same type as the type that the
5646/// conversion function produces).
5647void
5648Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5649                             DeclAccessPair FoundDecl,
5650                             CXXRecordDecl *ActingContext,
5651                             Expr *From, QualType ToType,
5652                             OverloadCandidateSet& CandidateSet) {
5653  assert(!Conversion->getDescribedFunctionTemplate() &&
5654         "Conversion function templates use AddTemplateConversionCandidate");
5655  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5656  if (!CandidateSet.isNewCandidate(Conversion))
5657    return;
5658
5659  // Overload resolution is always an unevaluated context.
5660  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5661
5662  // Add this candidate
5663  OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5664  Candidate.FoundDecl = FoundDecl;
5665  Candidate.Function = Conversion;
5666  Candidate.IsSurrogate = false;
5667  Candidate.IgnoreObjectArgument = false;
5668  Candidate.FinalConversion.setAsIdentityConversion();
5669  Candidate.FinalConversion.setFromType(ConvType);
5670  Candidate.FinalConversion.setAllToTypes(ToType);
5671  Candidate.Viable = true;
5672  Candidate.ExplicitCallArguments = 1;
5673
5674  // C++ [over.match.funcs]p4:
5675  //   For conversion functions, the function is considered to be a member of
5676  //   the class of the implicit implied object argument for the purpose of
5677  //   defining the type of the implicit object parameter.
5678  //
5679  // Determine the implicit conversion sequence for the implicit
5680  // object parameter.
5681  QualType ImplicitParamType = From->getType();
5682  if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5683    ImplicitParamType = FromPtrType->getPointeeType();
5684  CXXRecordDecl *ConversionContext
5685    = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5686
5687  Candidate.Conversions[0]
5688    = TryObjectArgumentInitialization(*this, From->getType(),
5689                                      From->Classify(Context),
5690                                      Conversion, ConversionContext);
5691
5692  if (Candidate.Conversions[0].isBad()) {
5693    Candidate.Viable = false;
5694    Candidate.FailureKind = ovl_fail_bad_conversion;
5695    return;
5696  }
5697
5698  // We won't go through a user-define type conversion function to convert a
5699  // derived to base as such conversions are given Conversion Rank. They only
5700  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5701  QualType FromCanon
5702    = Context.getCanonicalType(From->getType().getUnqualifiedType());
5703  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5704  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5705    Candidate.Viable = false;
5706    Candidate.FailureKind = ovl_fail_trivial_conversion;
5707    return;
5708  }
5709
5710  // To determine what the conversion from the result of calling the
5711  // conversion function to the type we're eventually trying to
5712  // convert to (ToType), we need to synthesize a call to the
5713  // conversion function and attempt copy initialization from it. This
5714  // makes sure that we get the right semantics with respect to
5715  // lvalues/rvalues and the type. Fortunately, we can allocate this
5716  // call on the stack and we don't need its arguments to be
5717  // well-formed.
5718  DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5719                            VK_LValue, From->getLocStart());
5720  ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5721                                Context.getPointerType(Conversion->getType()),
5722                                CK_FunctionToPointerDecay,
5723                                &ConversionRef, VK_RValue);
5724
5725  QualType ConversionType = Conversion->getConversionType();
5726  if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5727    Candidate.Viable = false;
5728    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5729    return;
5730  }
5731
5732  ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5733
5734  // Note that it is safe to allocate CallExpr on the stack here because
5735  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5736  // allocator).
5737  QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5738  CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
5739                From->getLocStart());
5740  ImplicitConversionSequence ICS =
5741    TryCopyInitialization(*this, &Call, ToType,
5742                          /*SuppressUserConversions=*/true,
5743                          /*InOverloadResolution=*/false,
5744                          /*AllowObjCWritebackConversion=*/false);
5745
5746  switch (ICS.getKind()) {
5747  case ImplicitConversionSequence::StandardConversion:
5748    Candidate.FinalConversion = ICS.Standard;
5749
5750    // C++ [over.ics.user]p3:
5751    //   If the user-defined conversion is specified by a specialization of a
5752    //   conversion function template, the second standard conversion sequence
5753    //   shall have exact match rank.
5754    if (Conversion->getPrimaryTemplate() &&
5755        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5756      Candidate.Viable = false;
5757      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5758    }
5759
5760    // C++0x [dcl.init.ref]p5:
5761    //    In the second case, if the reference is an rvalue reference and
5762    //    the second standard conversion sequence of the user-defined
5763    //    conversion sequence includes an lvalue-to-rvalue conversion, the
5764    //    program is ill-formed.
5765    if (ToType->isRValueReferenceType() &&
5766        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5767      Candidate.Viable = false;
5768      Candidate.FailureKind = ovl_fail_bad_final_conversion;
5769    }
5770    break;
5771
5772  case ImplicitConversionSequence::BadConversion:
5773    Candidate.Viable = false;
5774    Candidate.FailureKind = ovl_fail_bad_final_conversion;
5775    break;
5776
5777  default:
5778    llvm_unreachable(
5779           "Can only end up with a standard conversion sequence or failure");
5780  }
5781}
5782
5783/// \brief Adds a conversion function template specialization
5784/// candidate to the overload set, using template argument deduction
5785/// to deduce the template arguments of the conversion function
5786/// template from the type that we are converting to (C++
5787/// [temp.deduct.conv]).
5788void
5789Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
5790                                     DeclAccessPair FoundDecl,
5791                                     CXXRecordDecl *ActingDC,
5792                                     Expr *From, QualType ToType,
5793                                     OverloadCandidateSet &CandidateSet) {
5794  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5795         "Only conversion function templates permitted here");
5796
5797  if (!CandidateSet.isNewCandidate(FunctionTemplate))
5798    return;
5799
5800  TemplateDeductionInfo Info(CandidateSet.getLocation());
5801  CXXConversionDecl *Specialization = 0;
5802  if (TemplateDeductionResult Result
5803        = DeduceTemplateArguments(FunctionTemplate, ToType,
5804                                  Specialization, Info)) {
5805    OverloadCandidate &Candidate = CandidateSet.addCandidate();
5806    Candidate.FoundDecl = FoundDecl;
5807    Candidate.Function = FunctionTemplate->getTemplatedDecl();
5808    Candidate.Viable = false;
5809    Candidate.FailureKind = ovl_fail_bad_deduction;
5810    Candidate.IsSurrogate = false;
5811    Candidate.IgnoreObjectArgument = false;
5812    Candidate.ExplicitCallArguments = 1;
5813    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5814                                                          Info);
5815    return;
5816  }
5817
5818  // Add the conversion function template specialization produced by
5819  // template argument deduction as a candidate.
5820  assert(Specialization && "Missing function template specialization?");
5821  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
5822                         CandidateSet);
5823}
5824
5825/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5826/// converts the given @c Object to a function pointer via the
5827/// conversion function @c Conversion, and then attempts to call it
5828/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5829/// the type of function that we'll eventually be calling.
5830void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
5831                                 DeclAccessPair FoundDecl,
5832                                 CXXRecordDecl *ActingContext,
5833                                 const FunctionProtoType *Proto,
5834                                 Expr *Object,
5835                                 ArrayRef<Expr *> Args,
5836                                 OverloadCandidateSet& CandidateSet) {
5837  if (!CandidateSet.isNewCandidate(Conversion))
5838    return;
5839
5840  // Overload resolution is always an unevaluated context.
5841  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5842
5843  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5844  Candidate.FoundDecl = FoundDecl;
5845  Candidate.Function = 0;
5846  Candidate.Surrogate = Conversion;
5847  Candidate.Viable = true;
5848  Candidate.IsSurrogate = true;
5849  Candidate.IgnoreObjectArgument = false;
5850  Candidate.ExplicitCallArguments = Args.size();
5851
5852  // Determine the implicit conversion sequence for the implicit
5853  // object parameter.
5854  ImplicitConversionSequence ObjectInit
5855    = TryObjectArgumentInitialization(*this, Object->getType(),
5856                                      Object->Classify(Context),
5857                                      Conversion, ActingContext);
5858  if (ObjectInit.isBad()) {
5859    Candidate.Viable = false;
5860    Candidate.FailureKind = ovl_fail_bad_conversion;
5861    Candidate.Conversions[0] = ObjectInit;
5862    return;
5863  }
5864
5865  // The first conversion is actually a user-defined conversion whose
5866  // first conversion is ObjectInit's standard conversion (which is
5867  // effectively a reference binding). Record it as such.
5868  Candidate.Conversions[0].setUserDefined();
5869  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
5870  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
5871  Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
5872  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
5873  Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
5874  Candidate.Conversions[0].UserDefined.After
5875    = Candidate.Conversions[0].UserDefined.Before;
5876  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5877
5878  // Find the
5879  unsigned NumArgsInProto = Proto->getNumArgs();
5880
5881  // (C++ 13.3.2p2): A candidate function having fewer than m
5882  // parameters is viable only if it has an ellipsis in its parameter
5883  // list (8.3.5).
5884  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5885    Candidate.Viable = false;
5886    Candidate.FailureKind = ovl_fail_too_many_arguments;
5887    return;
5888  }
5889
5890  // Function types don't have any default arguments, so just check if
5891  // we have enough arguments.
5892  if (Args.size() < NumArgsInProto) {
5893    // Not enough arguments.
5894    Candidate.Viable = false;
5895    Candidate.FailureKind = ovl_fail_too_few_arguments;
5896    return;
5897  }
5898
5899  // Determine the implicit conversion sequences for each of the
5900  // arguments.
5901  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5902    if (ArgIdx < NumArgsInProto) {
5903      // (C++ 13.3.2p3): for F to be a viable function, there shall
5904      // exist for each argument an implicit conversion sequence
5905      // (13.3.3.1) that converts that argument to the corresponding
5906      // parameter of F.
5907      QualType ParamType = Proto->getArgType(ArgIdx);
5908      Candidate.Conversions[ArgIdx + 1]
5909        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5910                                /*SuppressUserConversions=*/false,
5911                                /*InOverloadResolution=*/false,
5912                                /*AllowObjCWritebackConversion=*/
5913                                  getLangOpts().ObjCAutoRefCount);
5914      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5915        Candidate.Viable = false;
5916        Candidate.FailureKind = ovl_fail_bad_conversion;
5917        break;
5918      }
5919    } else {
5920      // (C++ 13.3.2p2): For the purposes of overload resolution, any
5921      // argument for which there is no corresponding parameter is
5922      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5923      Candidate.Conversions[ArgIdx + 1].setEllipsis();
5924    }
5925  }
5926}
5927
5928/// \brief Add overload candidates for overloaded operators that are
5929/// member functions.
5930///
5931/// Add the overloaded operator candidates that are member functions
5932/// for the operator Op that was used in an operator expression such
5933/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5934/// CandidateSet will store the added overload candidates. (C++
5935/// [over.match.oper]).
5936void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5937                                       SourceLocation OpLoc,
5938                                       Expr **Args, unsigned NumArgs,
5939                                       OverloadCandidateSet& CandidateSet,
5940                                       SourceRange OpRange) {
5941  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5942
5943  // C++ [over.match.oper]p3:
5944  //   For a unary operator @ with an operand of a type whose
5945  //   cv-unqualified version is T1, and for a binary operator @ with
5946  //   a left operand of a type whose cv-unqualified version is T1 and
5947  //   a right operand of a type whose cv-unqualified version is T2,
5948  //   three sets of candidate functions, designated member
5949  //   candidates, non-member candidates and built-in candidates, are
5950  //   constructed as follows:
5951  QualType T1 = Args[0]->getType();
5952
5953  //     -- If T1 is a class type, the set of member candidates is the
5954  //        result of the qualified lookup of T1::operator@
5955  //        (13.3.1.1.1); otherwise, the set of member candidates is
5956  //        empty.
5957  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
5958    // Complete the type if it can be completed. Otherwise, we're done.
5959    if (RequireCompleteType(OpLoc, T1, 0))
5960      return;
5961
5962    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5963    LookupQualifiedName(Operators, T1Rec->getDecl());
5964    Operators.suppressDiagnostics();
5965
5966    for (LookupResult::iterator Oper = Operators.begin(),
5967                             OperEnd = Operators.end();
5968         Oper != OperEnd;
5969         ++Oper)
5970      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
5971                         Args[0]->Classify(Context), Args + 1, NumArgs - 1,
5972                         CandidateSet,
5973                         /* SuppressUserConversions = */ false);
5974  }
5975}
5976
5977/// AddBuiltinCandidate - Add a candidate for a built-in
5978/// operator. ResultTy and ParamTys are the result and parameter types
5979/// of the built-in candidate, respectively. Args and NumArgs are the
5980/// arguments being passed to the candidate. IsAssignmentOperator
5981/// should be true when this built-in candidate is an assignment
5982/// operator. NumContextualBoolArguments is the number of arguments
5983/// (at the beginning of the argument list) that will be contextually
5984/// converted to bool.
5985void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
5986                               Expr **Args, unsigned NumArgs,
5987                               OverloadCandidateSet& CandidateSet,
5988                               bool IsAssignmentOperator,
5989                               unsigned NumContextualBoolArguments) {
5990  // Overload resolution is always an unevaluated context.
5991  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5992
5993  // Add this candidate
5994  OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
5995  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
5996  Candidate.Function = 0;
5997  Candidate.IsSurrogate = false;
5998  Candidate.IgnoreObjectArgument = false;
5999  Candidate.BuiltinTypes.ResultTy = ResultTy;
6000  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6001    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6002
6003  // Determine the implicit conversion sequences for each of the
6004  // arguments.
6005  Candidate.Viable = true;
6006  Candidate.ExplicitCallArguments = NumArgs;
6007  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6008    // C++ [over.match.oper]p4:
6009    //   For the built-in assignment operators, conversions of the
6010    //   left operand are restricted as follows:
6011    //     -- no temporaries are introduced to hold the left operand, and
6012    //     -- no user-defined conversions are applied to the left
6013    //        operand to achieve a type match with the left-most
6014    //        parameter of a built-in candidate.
6015    //
6016    // We block these conversions by turning off user-defined
6017    // conversions, since that is the only way that initialization of
6018    // a reference to a non-class type can occur from something that
6019    // is not of the same type.
6020    if (ArgIdx < NumContextualBoolArguments) {
6021      assert(ParamTys[ArgIdx] == Context.BoolTy &&
6022             "Contextual conversion to bool requires bool type");
6023      Candidate.Conversions[ArgIdx]
6024        = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6025    } else {
6026      Candidate.Conversions[ArgIdx]
6027        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6028                                ArgIdx == 0 && IsAssignmentOperator,
6029                                /*InOverloadResolution=*/false,
6030                                /*AllowObjCWritebackConversion=*/
6031                                  getLangOpts().ObjCAutoRefCount);
6032    }
6033    if (Candidate.Conversions[ArgIdx].isBad()) {
6034      Candidate.Viable = false;
6035      Candidate.FailureKind = ovl_fail_bad_conversion;
6036      break;
6037    }
6038  }
6039}
6040
6041/// BuiltinCandidateTypeSet - A set of types that will be used for the
6042/// candidate operator functions for built-in operators (C++
6043/// [over.built]). The types are separated into pointer types and
6044/// enumeration types.
6045class BuiltinCandidateTypeSet  {
6046  /// TypeSet - A set of types.
6047  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6048
6049  /// PointerTypes - The set of pointer types that will be used in the
6050  /// built-in candidates.
6051  TypeSet PointerTypes;
6052
6053  /// MemberPointerTypes - The set of member pointer types that will be
6054  /// used in the built-in candidates.
6055  TypeSet MemberPointerTypes;
6056
6057  /// EnumerationTypes - The set of enumeration types that will be
6058  /// used in the built-in candidates.
6059  TypeSet EnumerationTypes;
6060
6061  /// \brief The set of vector types that will be used in the built-in
6062  /// candidates.
6063  TypeSet VectorTypes;
6064
6065  /// \brief A flag indicating non-record types are viable candidates
6066  bool HasNonRecordTypes;
6067
6068  /// \brief A flag indicating whether either arithmetic or enumeration types
6069  /// were present in the candidate set.
6070  bool HasArithmeticOrEnumeralTypes;
6071
6072  /// \brief A flag indicating whether the nullptr type was present in the
6073  /// candidate set.
6074  bool HasNullPtrType;
6075
6076  /// Sema - The semantic analysis instance where we are building the
6077  /// candidate type set.
6078  Sema &SemaRef;
6079
6080  /// Context - The AST context in which we will build the type sets.
6081  ASTContext &Context;
6082
6083  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6084                                               const Qualifiers &VisibleQuals);
6085  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6086
6087public:
6088  /// iterator - Iterates through the types that are part of the set.
6089  typedef TypeSet::iterator iterator;
6090
6091  BuiltinCandidateTypeSet(Sema &SemaRef)
6092    : HasNonRecordTypes(false),
6093      HasArithmeticOrEnumeralTypes(false),
6094      HasNullPtrType(false),
6095      SemaRef(SemaRef),
6096      Context(SemaRef.Context) { }
6097
6098  void AddTypesConvertedFrom(QualType Ty,
6099                             SourceLocation Loc,
6100                             bool AllowUserConversions,
6101                             bool AllowExplicitConversions,
6102                             const Qualifiers &VisibleTypeConversionsQuals);
6103
6104  /// pointer_begin - First pointer type found;
6105  iterator pointer_begin() { return PointerTypes.begin(); }
6106
6107  /// pointer_end - Past the last pointer type found;
6108  iterator pointer_end() { return PointerTypes.end(); }
6109
6110  /// member_pointer_begin - First member pointer type found;
6111  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6112
6113  /// member_pointer_end - Past the last member pointer type found;
6114  iterator member_pointer_end() { return MemberPointerTypes.end(); }
6115
6116  /// enumeration_begin - First enumeration type found;
6117  iterator enumeration_begin() { return EnumerationTypes.begin(); }
6118
6119  /// enumeration_end - Past the last enumeration type found;
6120  iterator enumeration_end() { return EnumerationTypes.end(); }
6121
6122  iterator vector_begin() { return VectorTypes.begin(); }
6123  iterator vector_end() { return VectorTypes.end(); }
6124
6125  bool hasNonRecordTypes() { return HasNonRecordTypes; }
6126  bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6127  bool hasNullPtrType() const { return HasNullPtrType; }
6128};
6129
6130/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6131/// the set of pointer types along with any more-qualified variants of
6132/// that type. For example, if @p Ty is "int const *", this routine
6133/// will add "int const *", "int const volatile *", "int const
6134/// restrict *", and "int const volatile restrict *" to the set of
6135/// pointer types. Returns true if the add of @p Ty itself succeeded,
6136/// false otherwise.
6137///
6138/// FIXME: what to do about extended qualifiers?
6139bool
6140BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6141                                             const Qualifiers &VisibleQuals) {
6142
6143  // Insert this type.
6144  if (!PointerTypes.insert(Ty))
6145    return false;
6146
6147  QualType PointeeTy;
6148  const PointerType *PointerTy = Ty->getAs<PointerType>();
6149  bool buildObjCPtr = false;
6150  if (!PointerTy) {
6151    const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6152    PointeeTy = PTy->getPointeeType();
6153    buildObjCPtr = true;
6154  } else {
6155    PointeeTy = PointerTy->getPointeeType();
6156  }
6157
6158  // Don't add qualified variants of arrays. For one, they're not allowed
6159  // (the qualifier would sink to the element type), and for another, the
6160  // only overload situation where it matters is subscript or pointer +- int,
6161  // and those shouldn't have qualifier variants anyway.
6162  if (PointeeTy->isArrayType())
6163    return true;
6164
6165  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6166  bool hasVolatile = VisibleQuals.hasVolatile();
6167  bool hasRestrict = VisibleQuals.hasRestrict();
6168
6169  // Iterate through all strict supersets of BaseCVR.
6170  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6171    if ((CVR | BaseCVR) != CVR) continue;
6172    // Skip over volatile if no volatile found anywhere in the types.
6173    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6174
6175    // Skip over restrict if no restrict found anywhere in the types, or if
6176    // the type cannot be restrict-qualified.
6177    if ((CVR & Qualifiers::Restrict) &&
6178        (!hasRestrict ||
6179         (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6180      continue;
6181
6182    // Build qualified pointee type.
6183    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6184
6185    // Build qualified pointer type.
6186    QualType QPointerTy;
6187    if (!buildObjCPtr)
6188      QPointerTy = Context.getPointerType(QPointeeTy);
6189    else
6190      QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6191
6192    // Insert qualified pointer type.
6193    PointerTypes.insert(QPointerTy);
6194  }
6195
6196  return true;
6197}
6198
6199/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6200/// to the set of pointer types along with any more-qualified variants of
6201/// that type. For example, if @p Ty is "int const *", this routine
6202/// will add "int const *", "int const volatile *", "int const
6203/// restrict *", and "int const volatile restrict *" to the set of
6204/// pointer types. Returns true if the add of @p Ty itself succeeded,
6205/// false otherwise.
6206///
6207/// FIXME: what to do about extended qualifiers?
6208bool
6209BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6210    QualType Ty) {
6211  // Insert this type.
6212  if (!MemberPointerTypes.insert(Ty))
6213    return false;
6214
6215  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6216  assert(PointerTy && "type was not a member pointer type!");
6217
6218  QualType PointeeTy = PointerTy->getPointeeType();
6219  // Don't add qualified variants of arrays. For one, they're not allowed
6220  // (the qualifier would sink to the element type), and for another, the
6221  // only overload situation where it matters is subscript or pointer +- int,
6222  // and those shouldn't have qualifier variants anyway.
6223  if (PointeeTy->isArrayType())
6224    return true;
6225  const Type *ClassTy = PointerTy->getClass();
6226
6227  // Iterate through all strict supersets of the pointee type's CVR
6228  // qualifiers.
6229  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6230  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6231    if ((CVR | BaseCVR) != CVR) continue;
6232
6233    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6234    MemberPointerTypes.insert(
6235      Context.getMemberPointerType(QPointeeTy, ClassTy));
6236  }
6237
6238  return true;
6239}
6240
6241/// AddTypesConvertedFrom - Add each of the types to which the type @p
6242/// Ty can be implicit converted to the given set of @p Types. We're
6243/// primarily interested in pointer types and enumeration types. We also
6244/// take member pointer types, for the conditional operator.
6245/// AllowUserConversions is true if we should look at the conversion
6246/// functions of a class type, and AllowExplicitConversions if we
6247/// should also include the explicit conversion functions of a class
6248/// type.
6249void
6250BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6251                                               SourceLocation Loc,
6252                                               bool AllowUserConversions,
6253                                               bool AllowExplicitConversions,
6254                                               const Qualifiers &VisibleQuals) {
6255  // Only deal with canonical types.
6256  Ty = Context.getCanonicalType(Ty);
6257
6258  // Look through reference types; they aren't part of the type of an
6259  // expression for the purposes of conversions.
6260  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6261    Ty = RefTy->getPointeeType();
6262
6263  // If we're dealing with an array type, decay to the pointer.
6264  if (Ty->isArrayType())
6265    Ty = SemaRef.Context.getArrayDecayedType(Ty);
6266
6267  // Otherwise, we don't care about qualifiers on the type.
6268  Ty = Ty.getLocalUnqualifiedType();
6269
6270  // Flag if we ever add a non-record type.
6271  const RecordType *TyRec = Ty->getAs<RecordType>();
6272  HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6273
6274  // Flag if we encounter an arithmetic type.
6275  HasArithmeticOrEnumeralTypes =
6276    HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6277
6278  if (Ty->isObjCIdType() || Ty->isObjCClassType())
6279    PointerTypes.insert(Ty);
6280  else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6281    // Insert our type, and its more-qualified variants, into the set
6282    // of types.
6283    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6284      return;
6285  } else if (Ty->isMemberPointerType()) {
6286    // Member pointers are far easier, since the pointee can't be converted.
6287    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6288      return;
6289  } else if (Ty->isEnumeralType()) {
6290    HasArithmeticOrEnumeralTypes = true;
6291    EnumerationTypes.insert(Ty);
6292  } else if (Ty->isVectorType()) {
6293    // We treat vector types as arithmetic types in many contexts as an
6294    // extension.
6295    HasArithmeticOrEnumeralTypes = true;
6296    VectorTypes.insert(Ty);
6297  } else if (Ty->isNullPtrType()) {
6298    HasNullPtrType = true;
6299  } else if (AllowUserConversions && TyRec) {
6300    // No conversion functions in incomplete types.
6301    if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6302      return;
6303
6304    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6305    std::pair<CXXRecordDecl::conversion_iterator,
6306              CXXRecordDecl::conversion_iterator>
6307      Conversions = ClassDecl->getVisibleConversionFunctions();
6308    for (CXXRecordDecl::conversion_iterator
6309           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6310      NamedDecl *D = I.getDecl();
6311      if (isa<UsingShadowDecl>(D))
6312        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6313
6314      // Skip conversion function templates; they don't tell us anything
6315      // about which builtin types we can convert to.
6316      if (isa<FunctionTemplateDecl>(D))
6317        continue;
6318
6319      CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6320      if (AllowExplicitConversions || !Conv->isExplicit()) {
6321        AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6322                              VisibleQuals);
6323      }
6324    }
6325  }
6326}
6327
6328/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6329/// the volatile- and non-volatile-qualified assignment operators for the
6330/// given type to the candidate set.
6331static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6332                                                   QualType T,
6333                                                   Expr **Args,
6334                                                   unsigned NumArgs,
6335                                    OverloadCandidateSet &CandidateSet) {
6336  QualType ParamTypes[2];
6337
6338  // T& operator=(T&, T)
6339  ParamTypes[0] = S.Context.getLValueReferenceType(T);
6340  ParamTypes[1] = T;
6341  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6342                        /*IsAssignmentOperator=*/true);
6343
6344  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6345    // volatile T& operator=(volatile T&, T)
6346    ParamTypes[0]
6347      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6348    ParamTypes[1] = T;
6349    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6350                          /*IsAssignmentOperator=*/true);
6351  }
6352}
6353
6354/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6355/// if any, found in visible type conversion functions found in ArgExpr's type.
6356static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6357    Qualifiers VRQuals;
6358    const RecordType *TyRec;
6359    if (const MemberPointerType *RHSMPType =
6360        ArgExpr->getType()->getAs<MemberPointerType>())
6361      TyRec = RHSMPType->getClass()->getAs<RecordType>();
6362    else
6363      TyRec = ArgExpr->getType()->getAs<RecordType>();
6364    if (!TyRec) {
6365      // Just to be safe, assume the worst case.
6366      VRQuals.addVolatile();
6367      VRQuals.addRestrict();
6368      return VRQuals;
6369    }
6370
6371    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6372    if (!ClassDecl->hasDefinition())
6373      return VRQuals;
6374
6375    std::pair<CXXRecordDecl::conversion_iterator,
6376              CXXRecordDecl::conversion_iterator>
6377      Conversions = ClassDecl->getVisibleConversionFunctions();
6378
6379    for (CXXRecordDecl::conversion_iterator
6380           I = Conversions.first, E = Conversions.second; I != E; ++I) {
6381      NamedDecl *D = I.getDecl();
6382      if (isa<UsingShadowDecl>(D))
6383        D = cast<UsingShadowDecl>(D)->getTargetDecl();
6384      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6385        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6386        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6387          CanTy = ResTypeRef->getPointeeType();
6388        // Need to go down the pointer/mempointer chain and add qualifiers
6389        // as see them.
6390        bool done = false;
6391        while (!done) {
6392          if (CanTy.isRestrictQualified())
6393            VRQuals.addRestrict();
6394          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6395            CanTy = ResTypePtr->getPointeeType();
6396          else if (const MemberPointerType *ResTypeMPtr =
6397                CanTy->getAs<MemberPointerType>())
6398            CanTy = ResTypeMPtr->getPointeeType();
6399          else
6400            done = true;
6401          if (CanTy.isVolatileQualified())
6402            VRQuals.addVolatile();
6403          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6404            return VRQuals;
6405        }
6406      }
6407    }
6408    return VRQuals;
6409}
6410
6411namespace {
6412
6413/// \brief Helper class to manage the addition of builtin operator overload
6414/// candidates. It provides shared state and utility methods used throughout
6415/// the process, as well as a helper method to add each group of builtin
6416/// operator overloads from the standard to a candidate set.
6417class BuiltinOperatorOverloadBuilder {
6418  // Common instance state available to all overload candidate addition methods.
6419  Sema &S;
6420  Expr **Args;
6421  unsigned NumArgs;
6422  Qualifiers VisibleTypeConversionsQuals;
6423  bool HasArithmeticOrEnumeralCandidateType;
6424  SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6425  OverloadCandidateSet &CandidateSet;
6426
6427  // Define some constants used to index and iterate over the arithemetic types
6428  // provided via the getArithmeticType() method below.
6429  // The "promoted arithmetic types" are the arithmetic
6430  // types are that preserved by promotion (C++ [over.built]p2).
6431  static const unsigned FirstIntegralType = 3;
6432  static const unsigned LastIntegralType = 20;
6433  static const unsigned FirstPromotedIntegralType = 3,
6434                        LastPromotedIntegralType = 11;
6435  static const unsigned FirstPromotedArithmeticType = 0,
6436                        LastPromotedArithmeticType = 11;
6437  static const unsigned NumArithmeticTypes = 20;
6438
6439  /// \brief Get the canonical type for a given arithmetic type index.
6440  CanQualType getArithmeticType(unsigned index) {
6441    assert(index < NumArithmeticTypes);
6442    static CanQualType ASTContext::* const
6443      ArithmeticTypes[NumArithmeticTypes] = {
6444      // Start of promoted types.
6445      &ASTContext::FloatTy,
6446      &ASTContext::DoubleTy,
6447      &ASTContext::LongDoubleTy,
6448
6449      // Start of integral types.
6450      &ASTContext::IntTy,
6451      &ASTContext::LongTy,
6452      &ASTContext::LongLongTy,
6453      &ASTContext::Int128Ty,
6454      &ASTContext::UnsignedIntTy,
6455      &ASTContext::UnsignedLongTy,
6456      &ASTContext::UnsignedLongLongTy,
6457      &ASTContext::UnsignedInt128Ty,
6458      // End of promoted types.
6459
6460      &ASTContext::BoolTy,
6461      &ASTContext::CharTy,
6462      &ASTContext::WCharTy,
6463      &ASTContext::Char16Ty,
6464      &ASTContext::Char32Ty,
6465      &ASTContext::SignedCharTy,
6466      &ASTContext::ShortTy,
6467      &ASTContext::UnsignedCharTy,
6468      &ASTContext::UnsignedShortTy,
6469      // End of integral types.
6470      // FIXME: What about complex? What about half?
6471    };
6472    return S.Context.*ArithmeticTypes[index];
6473  }
6474
6475  /// \brief Gets the canonical type resulting from the usual arithemetic
6476  /// converions for the given arithmetic types.
6477  CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6478    // Accelerator table for performing the usual arithmetic conversions.
6479    // The rules are basically:
6480    //   - if either is floating-point, use the wider floating-point
6481    //   - if same signedness, use the higher rank
6482    //   - if same size, use unsigned of the higher rank
6483    //   - use the larger type
6484    // These rules, together with the axiom that higher ranks are
6485    // never smaller, are sufficient to precompute all of these results
6486    // *except* when dealing with signed types of higher rank.
6487    // (we could precompute SLL x UI for all known platforms, but it's
6488    // better not to make any assumptions).
6489    // We assume that int128 has a higher rank than long long on all platforms.
6490    enum PromotedType {
6491            Dep=-1,
6492            Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6493    };
6494    static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6495                                        [LastPromotedArithmeticType] = {
6496/* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6497/* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6498/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6499/*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6500/*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6501/* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6502/*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6503/*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6504/*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6505/* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6506/*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6507    };
6508
6509    assert(L < LastPromotedArithmeticType);
6510    assert(R < LastPromotedArithmeticType);
6511    int Idx = ConversionsTable[L][R];
6512
6513    // Fast path: the table gives us a concrete answer.
6514    if (Idx != Dep) return getArithmeticType(Idx);
6515
6516    // Slow path: we need to compare widths.
6517    // An invariant is that the signed type has higher rank.
6518    CanQualType LT = getArithmeticType(L),
6519                RT = getArithmeticType(R);
6520    unsigned LW = S.Context.getIntWidth(LT),
6521             RW = S.Context.getIntWidth(RT);
6522
6523    // If they're different widths, use the signed type.
6524    if (LW > RW) return LT;
6525    else if (LW < RW) return RT;
6526
6527    // Otherwise, use the unsigned type of the signed type's rank.
6528    if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6529    assert(L == SLL || R == SLL);
6530    return S.Context.UnsignedLongLongTy;
6531  }
6532
6533  /// \brief Helper method to factor out the common pattern of adding overloads
6534  /// for '++' and '--' builtin operators.
6535  void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6536                                           bool HasVolatile,
6537                                           bool HasRestrict) {
6538    QualType ParamTypes[2] = {
6539      S.Context.getLValueReferenceType(CandidateTy),
6540      S.Context.IntTy
6541    };
6542
6543    // Non-volatile version.
6544    if (NumArgs == 1)
6545      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6546    else
6547      S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6548
6549    // Use a heuristic to reduce number of builtin candidates in the set:
6550    // add volatile version only if there are conversions to a volatile type.
6551    if (HasVolatile) {
6552      ParamTypes[0] =
6553        S.Context.getLValueReferenceType(
6554          S.Context.getVolatileType(CandidateTy));
6555      if (NumArgs == 1)
6556        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6557      else
6558        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6559    }
6560
6561    // Add restrict version only if there are conversions to a restrict type
6562    // and our candidate type is a non-restrict-qualified pointer.
6563    if (HasRestrict && CandidateTy->isAnyPointerType() &&
6564        !CandidateTy.isRestrictQualified()) {
6565      ParamTypes[0]
6566        = S.Context.getLValueReferenceType(
6567            S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6568      if (NumArgs == 1)
6569        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6570      else
6571        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6572
6573      if (HasVolatile) {
6574        ParamTypes[0]
6575          = S.Context.getLValueReferenceType(
6576              S.Context.getCVRQualifiedType(CandidateTy,
6577                                            (Qualifiers::Volatile |
6578                                             Qualifiers::Restrict)));
6579        if (NumArgs == 1)
6580          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6581                                CandidateSet);
6582        else
6583          S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6584      }
6585    }
6586
6587  }
6588
6589public:
6590  BuiltinOperatorOverloadBuilder(
6591    Sema &S, Expr **Args, unsigned NumArgs,
6592    Qualifiers VisibleTypeConversionsQuals,
6593    bool HasArithmeticOrEnumeralCandidateType,
6594    SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6595    OverloadCandidateSet &CandidateSet)
6596    : S(S), Args(Args), NumArgs(NumArgs),
6597      VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6598      HasArithmeticOrEnumeralCandidateType(
6599        HasArithmeticOrEnumeralCandidateType),
6600      CandidateTypes(CandidateTypes),
6601      CandidateSet(CandidateSet) {
6602    // Validate some of our static helper constants in debug builds.
6603    assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6604           "Invalid first promoted integral type");
6605    assert(getArithmeticType(LastPromotedIntegralType - 1)
6606             == S.Context.UnsignedInt128Ty &&
6607           "Invalid last promoted integral type");
6608    assert(getArithmeticType(FirstPromotedArithmeticType)
6609             == S.Context.FloatTy &&
6610           "Invalid first promoted arithmetic type");
6611    assert(getArithmeticType(LastPromotedArithmeticType - 1)
6612             == S.Context.UnsignedInt128Ty &&
6613           "Invalid last promoted arithmetic type");
6614  }
6615
6616  // C++ [over.built]p3:
6617  //
6618  //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6619  //   is either volatile or empty, there exist candidate operator
6620  //   functions of the form
6621  //
6622  //       VQ T&      operator++(VQ T&);
6623  //       T          operator++(VQ T&, int);
6624  //
6625  // C++ [over.built]p4:
6626  //
6627  //   For every pair (T, VQ), where T is an arithmetic type other
6628  //   than bool, and VQ is either volatile or empty, there exist
6629  //   candidate operator functions of the form
6630  //
6631  //       VQ T&      operator--(VQ T&);
6632  //       T          operator--(VQ T&, int);
6633  void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6634    if (!HasArithmeticOrEnumeralCandidateType)
6635      return;
6636
6637    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6638         Arith < NumArithmeticTypes; ++Arith) {
6639      addPlusPlusMinusMinusStyleOverloads(
6640        getArithmeticType(Arith),
6641        VisibleTypeConversionsQuals.hasVolatile(),
6642        VisibleTypeConversionsQuals.hasRestrict());
6643    }
6644  }
6645
6646  // C++ [over.built]p5:
6647  //
6648  //   For every pair (T, VQ), where T is a cv-qualified or
6649  //   cv-unqualified object type, and VQ is either volatile or
6650  //   empty, there exist candidate operator functions of the form
6651  //
6652  //       T*VQ&      operator++(T*VQ&);
6653  //       T*VQ&      operator--(T*VQ&);
6654  //       T*         operator++(T*VQ&, int);
6655  //       T*         operator--(T*VQ&, int);
6656  void addPlusPlusMinusMinusPointerOverloads() {
6657    for (BuiltinCandidateTypeSet::iterator
6658              Ptr = CandidateTypes[0].pointer_begin(),
6659           PtrEnd = CandidateTypes[0].pointer_end();
6660         Ptr != PtrEnd; ++Ptr) {
6661      // Skip pointer types that aren't pointers to object types.
6662      if (!(*Ptr)->getPointeeType()->isObjectType())
6663        continue;
6664
6665      addPlusPlusMinusMinusStyleOverloads(*Ptr,
6666        (!(*Ptr).isVolatileQualified() &&
6667         VisibleTypeConversionsQuals.hasVolatile()),
6668        (!(*Ptr).isRestrictQualified() &&
6669         VisibleTypeConversionsQuals.hasRestrict()));
6670    }
6671  }
6672
6673  // C++ [over.built]p6:
6674  //   For every cv-qualified or cv-unqualified object type T, there
6675  //   exist candidate operator functions of the form
6676  //
6677  //       T&         operator*(T*);
6678  //
6679  // C++ [over.built]p7:
6680  //   For every function type T that does not have cv-qualifiers or a
6681  //   ref-qualifier, there exist candidate operator functions of the form
6682  //       T&         operator*(T*);
6683  void addUnaryStarPointerOverloads() {
6684    for (BuiltinCandidateTypeSet::iterator
6685              Ptr = CandidateTypes[0].pointer_begin(),
6686           PtrEnd = CandidateTypes[0].pointer_end();
6687         Ptr != PtrEnd; ++Ptr) {
6688      QualType ParamTy = *Ptr;
6689      QualType PointeeTy = ParamTy->getPointeeType();
6690      if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6691        continue;
6692
6693      if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6694        if (Proto->getTypeQuals() || Proto->getRefQualifier())
6695          continue;
6696
6697      S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6698                            &ParamTy, Args, 1, CandidateSet);
6699    }
6700  }
6701
6702  // C++ [over.built]p9:
6703  //  For every promoted arithmetic type T, there exist candidate
6704  //  operator functions of the form
6705  //
6706  //       T         operator+(T);
6707  //       T         operator-(T);
6708  void addUnaryPlusOrMinusArithmeticOverloads() {
6709    if (!HasArithmeticOrEnumeralCandidateType)
6710      return;
6711
6712    for (unsigned Arith = FirstPromotedArithmeticType;
6713         Arith < LastPromotedArithmeticType; ++Arith) {
6714      QualType ArithTy = getArithmeticType(Arith);
6715      S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6716    }
6717
6718    // Extension: We also add these operators for vector types.
6719    for (BuiltinCandidateTypeSet::iterator
6720              Vec = CandidateTypes[0].vector_begin(),
6721           VecEnd = CandidateTypes[0].vector_end();
6722         Vec != VecEnd; ++Vec) {
6723      QualType VecTy = *Vec;
6724      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6725    }
6726  }
6727
6728  // C++ [over.built]p8:
6729  //   For every type T, there exist candidate operator functions of
6730  //   the form
6731  //
6732  //       T*         operator+(T*);
6733  void addUnaryPlusPointerOverloads() {
6734    for (BuiltinCandidateTypeSet::iterator
6735              Ptr = CandidateTypes[0].pointer_begin(),
6736           PtrEnd = CandidateTypes[0].pointer_end();
6737         Ptr != PtrEnd; ++Ptr) {
6738      QualType ParamTy = *Ptr;
6739      S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6740    }
6741  }
6742
6743  // C++ [over.built]p10:
6744  //   For every promoted integral type T, there exist candidate
6745  //   operator functions of the form
6746  //
6747  //        T         operator~(T);
6748  void addUnaryTildePromotedIntegralOverloads() {
6749    if (!HasArithmeticOrEnumeralCandidateType)
6750      return;
6751
6752    for (unsigned Int = FirstPromotedIntegralType;
6753         Int < LastPromotedIntegralType; ++Int) {
6754      QualType IntTy = getArithmeticType(Int);
6755      S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6756    }
6757
6758    // Extension: We also add this operator for vector types.
6759    for (BuiltinCandidateTypeSet::iterator
6760              Vec = CandidateTypes[0].vector_begin(),
6761           VecEnd = CandidateTypes[0].vector_end();
6762         Vec != VecEnd; ++Vec) {
6763      QualType VecTy = *Vec;
6764      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6765    }
6766  }
6767
6768  // C++ [over.match.oper]p16:
6769  //   For every pointer to member type T, there exist candidate operator
6770  //   functions of the form
6771  //
6772  //        bool operator==(T,T);
6773  //        bool operator!=(T,T);
6774  void addEqualEqualOrNotEqualMemberPointerOverloads() {
6775    /// Set of (canonical) types that we've already handled.
6776    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6777
6778    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6779      for (BuiltinCandidateTypeSet::iterator
6780                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6781             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6782           MemPtr != MemPtrEnd;
6783           ++MemPtr) {
6784        // Don't add the same builtin candidate twice.
6785        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6786          continue;
6787
6788        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6789        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6790                              CandidateSet);
6791      }
6792    }
6793  }
6794
6795  // C++ [over.built]p15:
6796  //
6797  //   For every T, where T is an enumeration type, a pointer type, or
6798  //   std::nullptr_t, there exist candidate operator functions of the form
6799  //
6800  //        bool       operator<(T, T);
6801  //        bool       operator>(T, T);
6802  //        bool       operator<=(T, T);
6803  //        bool       operator>=(T, T);
6804  //        bool       operator==(T, T);
6805  //        bool       operator!=(T, T);
6806  void addRelationalPointerOrEnumeralOverloads() {
6807    // C++ [over.match.oper]p3:
6808    //   [...]the built-in candidates include all of the candidate operator
6809    //   functions defined in 13.6 that, compared to the given operator, [...]
6810    //   do not have the same parameter-type-list as any non-template non-member
6811    //   candidate.
6812    //
6813    // Note that in practice, this only affects enumeration types because there
6814    // aren't any built-in candidates of record type, and a user-defined operator
6815    // must have an operand of record or enumeration type. Also, the only other
6816    // overloaded operator with enumeration arguments, operator=,
6817    // cannot be overloaded for enumeration types, so this is the only place
6818    // where we must suppress candidates like this.
6819    llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6820      UserDefinedBinaryOperators;
6821
6822    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6823      if (CandidateTypes[ArgIdx].enumeration_begin() !=
6824          CandidateTypes[ArgIdx].enumeration_end()) {
6825        for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6826                                         CEnd = CandidateSet.end();
6827             C != CEnd; ++C) {
6828          if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6829            continue;
6830
6831          if (C->Function->isFunctionTemplateSpecialization())
6832            continue;
6833
6834          QualType FirstParamType =
6835            C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6836          QualType SecondParamType =
6837            C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6838
6839          // Skip if either parameter isn't of enumeral type.
6840          if (!FirstParamType->isEnumeralType() ||
6841              !SecondParamType->isEnumeralType())
6842            continue;
6843
6844          // Add this operator to the set of known user-defined operators.
6845          UserDefinedBinaryOperators.insert(
6846            std::make_pair(S.Context.getCanonicalType(FirstParamType),
6847                           S.Context.getCanonicalType(SecondParamType)));
6848        }
6849      }
6850    }
6851
6852    /// Set of (canonical) types that we've already handled.
6853    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6854
6855    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6856      for (BuiltinCandidateTypeSet::iterator
6857                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6858             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6859           Ptr != PtrEnd; ++Ptr) {
6860        // Don't add the same builtin candidate twice.
6861        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6862          continue;
6863
6864        QualType ParamTypes[2] = { *Ptr, *Ptr };
6865        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6866                              CandidateSet);
6867      }
6868      for (BuiltinCandidateTypeSet::iterator
6869                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6870             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6871           Enum != EnumEnd; ++Enum) {
6872        CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6873
6874        // Don't add the same builtin candidate twice, or if a user defined
6875        // candidate exists.
6876        if (!AddedTypes.insert(CanonType) ||
6877            UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6878                                                            CanonType)))
6879          continue;
6880
6881        QualType ParamTypes[2] = { *Enum, *Enum };
6882        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6883                              CandidateSet);
6884      }
6885
6886      if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6887        CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6888        if (AddedTypes.insert(NullPtrTy) &&
6889            !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6890                                                             NullPtrTy))) {
6891          QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6892          S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6893                                CandidateSet);
6894        }
6895      }
6896    }
6897  }
6898
6899  // C++ [over.built]p13:
6900  //
6901  //   For every cv-qualified or cv-unqualified object type T
6902  //   there exist candidate operator functions of the form
6903  //
6904  //      T*         operator+(T*, ptrdiff_t);
6905  //      T&         operator[](T*, ptrdiff_t);    [BELOW]
6906  //      T*         operator-(T*, ptrdiff_t);
6907  //      T*         operator+(ptrdiff_t, T*);
6908  //      T&         operator[](ptrdiff_t, T*);    [BELOW]
6909  //
6910  // C++ [over.built]p14:
6911  //
6912  //   For every T, where T is a pointer to object type, there
6913  //   exist candidate operator functions of the form
6914  //
6915  //      ptrdiff_t  operator-(T, T);
6916  void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6917    /// Set of (canonical) types that we've already handled.
6918    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6919
6920    for (int Arg = 0; Arg < 2; ++Arg) {
6921      QualType AsymetricParamTypes[2] = {
6922        S.Context.getPointerDiffType(),
6923        S.Context.getPointerDiffType(),
6924      };
6925      for (BuiltinCandidateTypeSet::iterator
6926                Ptr = CandidateTypes[Arg].pointer_begin(),
6927             PtrEnd = CandidateTypes[Arg].pointer_end();
6928           Ptr != PtrEnd; ++Ptr) {
6929        QualType PointeeTy = (*Ptr)->getPointeeType();
6930        if (!PointeeTy->isObjectType())
6931          continue;
6932
6933        AsymetricParamTypes[Arg] = *Ptr;
6934        if (Arg == 0 || Op == OO_Plus) {
6935          // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6936          // T* operator+(ptrdiff_t, T*);
6937          S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6938                                CandidateSet);
6939        }
6940        if (Op == OO_Minus) {
6941          // ptrdiff_t operator-(T, T);
6942          if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6943            continue;
6944
6945          QualType ParamTypes[2] = { *Ptr, *Ptr };
6946          S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6947                                Args, 2, CandidateSet);
6948        }
6949      }
6950    }
6951  }
6952
6953  // C++ [over.built]p12:
6954  //
6955  //   For every pair of promoted arithmetic types L and R, there
6956  //   exist candidate operator functions of the form
6957  //
6958  //        LR         operator*(L, R);
6959  //        LR         operator/(L, R);
6960  //        LR         operator+(L, R);
6961  //        LR         operator-(L, R);
6962  //        bool       operator<(L, R);
6963  //        bool       operator>(L, R);
6964  //        bool       operator<=(L, R);
6965  //        bool       operator>=(L, R);
6966  //        bool       operator==(L, R);
6967  //        bool       operator!=(L, R);
6968  //
6969  //   where LR is the result of the usual arithmetic conversions
6970  //   between types L and R.
6971  //
6972  // C++ [over.built]p24:
6973  //
6974  //   For every pair of promoted arithmetic types L and R, there exist
6975  //   candidate operator functions of the form
6976  //
6977  //        LR       operator?(bool, L, R);
6978  //
6979  //   where LR is the result of the usual arithmetic conversions
6980  //   between types L and R.
6981  // Our candidates ignore the first parameter.
6982  void addGenericBinaryArithmeticOverloads(bool isComparison) {
6983    if (!HasArithmeticOrEnumeralCandidateType)
6984      return;
6985
6986    for (unsigned Left = FirstPromotedArithmeticType;
6987         Left < LastPromotedArithmeticType; ++Left) {
6988      for (unsigned Right = FirstPromotedArithmeticType;
6989           Right < LastPromotedArithmeticType; ++Right) {
6990        QualType LandR[2] = { getArithmeticType(Left),
6991                              getArithmeticType(Right) };
6992        QualType Result =
6993          isComparison ? S.Context.BoolTy
6994                       : getUsualArithmeticConversions(Left, Right);
6995        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6996      }
6997    }
6998
6999    // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7000    // conditional operator for vector types.
7001    for (BuiltinCandidateTypeSet::iterator
7002              Vec1 = CandidateTypes[0].vector_begin(),
7003           Vec1End = CandidateTypes[0].vector_end();
7004         Vec1 != Vec1End; ++Vec1) {
7005      for (BuiltinCandidateTypeSet::iterator
7006                Vec2 = CandidateTypes[1].vector_begin(),
7007             Vec2End = CandidateTypes[1].vector_end();
7008           Vec2 != Vec2End; ++Vec2) {
7009        QualType LandR[2] = { *Vec1, *Vec2 };
7010        QualType Result = S.Context.BoolTy;
7011        if (!isComparison) {
7012          if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7013            Result = *Vec1;
7014          else
7015            Result = *Vec2;
7016        }
7017
7018        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7019      }
7020    }
7021  }
7022
7023  // C++ [over.built]p17:
7024  //
7025  //   For every pair of promoted integral types L and R, there
7026  //   exist candidate operator functions of the form
7027  //
7028  //      LR         operator%(L, R);
7029  //      LR         operator&(L, R);
7030  //      LR         operator^(L, R);
7031  //      LR         operator|(L, R);
7032  //      L          operator<<(L, R);
7033  //      L          operator>>(L, R);
7034  //
7035  //   where LR is the result of the usual arithmetic conversions
7036  //   between types L and R.
7037  void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7038    if (!HasArithmeticOrEnumeralCandidateType)
7039      return;
7040
7041    for (unsigned Left = FirstPromotedIntegralType;
7042         Left < LastPromotedIntegralType; ++Left) {
7043      for (unsigned Right = FirstPromotedIntegralType;
7044           Right < LastPromotedIntegralType; ++Right) {
7045        QualType LandR[2] = { getArithmeticType(Left),
7046                              getArithmeticType(Right) };
7047        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7048            ? LandR[0]
7049            : getUsualArithmeticConversions(Left, Right);
7050        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7051      }
7052    }
7053  }
7054
7055  // C++ [over.built]p20:
7056  //
7057  //   For every pair (T, VQ), where T is an enumeration or
7058  //   pointer to member type and VQ is either volatile or
7059  //   empty, there exist candidate operator functions of the form
7060  //
7061  //        VQ T&      operator=(VQ T&, T);
7062  void addAssignmentMemberPointerOrEnumeralOverloads() {
7063    /// Set of (canonical) types that we've already handled.
7064    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7065
7066    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7067      for (BuiltinCandidateTypeSet::iterator
7068                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7069             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7070           Enum != EnumEnd; ++Enum) {
7071        if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7072          continue;
7073
7074        AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7075                                               CandidateSet);
7076      }
7077
7078      for (BuiltinCandidateTypeSet::iterator
7079                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7080             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7081           MemPtr != MemPtrEnd; ++MemPtr) {
7082        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7083          continue;
7084
7085        AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7086                                               CandidateSet);
7087      }
7088    }
7089  }
7090
7091  // C++ [over.built]p19:
7092  //
7093  //   For every pair (T, VQ), where T is any type and VQ is either
7094  //   volatile or empty, there exist candidate operator functions
7095  //   of the form
7096  //
7097  //        T*VQ&      operator=(T*VQ&, T*);
7098  //
7099  // C++ [over.built]p21:
7100  //
7101  //   For every pair (T, VQ), where T is a cv-qualified or
7102  //   cv-unqualified object type and VQ is either volatile or
7103  //   empty, there exist candidate operator functions of the form
7104  //
7105  //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7106  //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7107  void addAssignmentPointerOverloads(bool isEqualOp) {
7108    /// Set of (canonical) types that we've already handled.
7109    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7110
7111    for (BuiltinCandidateTypeSet::iterator
7112              Ptr = CandidateTypes[0].pointer_begin(),
7113           PtrEnd = CandidateTypes[0].pointer_end();
7114         Ptr != PtrEnd; ++Ptr) {
7115      // If this is operator=, keep track of the builtin candidates we added.
7116      if (isEqualOp)
7117        AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7118      else if (!(*Ptr)->getPointeeType()->isObjectType())
7119        continue;
7120
7121      // non-volatile version
7122      QualType ParamTypes[2] = {
7123        S.Context.getLValueReferenceType(*Ptr),
7124        isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7125      };
7126      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7127                            /*IsAssigmentOperator=*/ isEqualOp);
7128
7129      bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7130                          VisibleTypeConversionsQuals.hasVolatile();
7131      if (NeedVolatile) {
7132        // volatile version
7133        ParamTypes[0] =
7134          S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7135        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7136                              /*IsAssigmentOperator=*/isEqualOp);
7137      }
7138
7139      if (!(*Ptr).isRestrictQualified() &&
7140          VisibleTypeConversionsQuals.hasRestrict()) {
7141        // restrict version
7142        ParamTypes[0]
7143          = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7144        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7145                              /*IsAssigmentOperator=*/isEqualOp);
7146
7147        if (NeedVolatile) {
7148          // volatile restrict version
7149          ParamTypes[0]
7150            = S.Context.getLValueReferenceType(
7151                S.Context.getCVRQualifiedType(*Ptr,
7152                                              (Qualifiers::Volatile |
7153                                               Qualifiers::Restrict)));
7154          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7155                                CandidateSet,
7156                                /*IsAssigmentOperator=*/isEqualOp);
7157        }
7158      }
7159    }
7160
7161    if (isEqualOp) {
7162      for (BuiltinCandidateTypeSet::iterator
7163                Ptr = CandidateTypes[1].pointer_begin(),
7164             PtrEnd = CandidateTypes[1].pointer_end();
7165           Ptr != PtrEnd; ++Ptr) {
7166        // Make sure we don't add the same candidate twice.
7167        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7168          continue;
7169
7170        QualType ParamTypes[2] = {
7171          S.Context.getLValueReferenceType(*Ptr),
7172          *Ptr,
7173        };
7174
7175        // non-volatile version
7176        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7177                              /*IsAssigmentOperator=*/true);
7178
7179        bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7180                           VisibleTypeConversionsQuals.hasVolatile();
7181        if (NeedVolatile) {
7182          // volatile version
7183          ParamTypes[0] =
7184            S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7185          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7186                                CandidateSet, /*IsAssigmentOperator=*/true);
7187        }
7188
7189        if (!(*Ptr).isRestrictQualified() &&
7190            VisibleTypeConversionsQuals.hasRestrict()) {
7191          // restrict version
7192          ParamTypes[0]
7193            = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7194          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7195                                CandidateSet, /*IsAssigmentOperator=*/true);
7196
7197          if (NeedVolatile) {
7198            // volatile restrict version
7199            ParamTypes[0]
7200              = S.Context.getLValueReferenceType(
7201                  S.Context.getCVRQualifiedType(*Ptr,
7202                                                (Qualifiers::Volatile |
7203                                                 Qualifiers::Restrict)));
7204            S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7205                                  CandidateSet, /*IsAssigmentOperator=*/true);
7206
7207          }
7208        }
7209      }
7210    }
7211  }
7212
7213  // C++ [over.built]p18:
7214  //
7215  //   For every triple (L, VQ, R), where L is an arithmetic type,
7216  //   VQ is either volatile or empty, and R is a promoted
7217  //   arithmetic type, there exist candidate operator functions of
7218  //   the form
7219  //
7220  //        VQ L&      operator=(VQ L&, R);
7221  //        VQ L&      operator*=(VQ L&, R);
7222  //        VQ L&      operator/=(VQ L&, R);
7223  //        VQ L&      operator+=(VQ L&, R);
7224  //        VQ L&      operator-=(VQ L&, R);
7225  void addAssignmentArithmeticOverloads(bool isEqualOp) {
7226    if (!HasArithmeticOrEnumeralCandidateType)
7227      return;
7228
7229    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7230      for (unsigned Right = FirstPromotedArithmeticType;
7231           Right < LastPromotedArithmeticType; ++Right) {
7232        QualType ParamTypes[2];
7233        ParamTypes[1] = getArithmeticType(Right);
7234
7235        // Add this built-in operator as a candidate (VQ is empty).
7236        ParamTypes[0] =
7237          S.Context.getLValueReferenceType(getArithmeticType(Left));
7238        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7239                              /*IsAssigmentOperator=*/isEqualOp);
7240
7241        // Add this built-in operator as a candidate (VQ is 'volatile').
7242        if (VisibleTypeConversionsQuals.hasVolatile()) {
7243          ParamTypes[0] =
7244            S.Context.getVolatileType(getArithmeticType(Left));
7245          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7246          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7247                                CandidateSet,
7248                                /*IsAssigmentOperator=*/isEqualOp);
7249        }
7250      }
7251    }
7252
7253    // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7254    for (BuiltinCandidateTypeSet::iterator
7255              Vec1 = CandidateTypes[0].vector_begin(),
7256           Vec1End = CandidateTypes[0].vector_end();
7257         Vec1 != Vec1End; ++Vec1) {
7258      for (BuiltinCandidateTypeSet::iterator
7259                Vec2 = CandidateTypes[1].vector_begin(),
7260             Vec2End = CandidateTypes[1].vector_end();
7261           Vec2 != Vec2End; ++Vec2) {
7262        QualType ParamTypes[2];
7263        ParamTypes[1] = *Vec2;
7264        // Add this built-in operator as a candidate (VQ is empty).
7265        ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7266        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7267                              /*IsAssigmentOperator=*/isEqualOp);
7268
7269        // Add this built-in operator as a candidate (VQ is 'volatile').
7270        if (VisibleTypeConversionsQuals.hasVolatile()) {
7271          ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7272          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7273          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7274                                CandidateSet,
7275                                /*IsAssigmentOperator=*/isEqualOp);
7276        }
7277      }
7278    }
7279  }
7280
7281  // C++ [over.built]p22:
7282  //
7283  //   For every triple (L, VQ, R), where L is an integral type, VQ
7284  //   is either volatile or empty, and R is a promoted integral
7285  //   type, there exist candidate operator functions of the form
7286  //
7287  //        VQ L&       operator%=(VQ L&, R);
7288  //        VQ L&       operator<<=(VQ L&, R);
7289  //        VQ L&       operator>>=(VQ L&, R);
7290  //        VQ L&       operator&=(VQ L&, R);
7291  //        VQ L&       operator^=(VQ L&, R);
7292  //        VQ L&       operator|=(VQ L&, R);
7293  void addAssignmentIntegralOverloads() {
7294    if (!HasArithmeticOrEnumeralCandidateType)
7295      return;
7296
7297    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7298      for (unsigned Right = FirstPromotedIntegralType;
7299           Right < LastPromotedIntegralType; ++Right) {
7300        QualType ParamTypes[2];
7301        ParamTypes[1] = getArithmeticType(Right);
7302
7303        // Add this built-in operator as a candidate (VQ is empty).
7304        ParamTypes[0] =
7305          S.Context.getLValueReferenceType(getArithmeticType(Left));
7306        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7307        if (VisibleTypeConversionsQuals.hasVolatile()) {
7308          // Add this built-in operator as a candidate (VQ is 'volatile').
7309          ParamTypes[0] = getArithmeticType(Left);
7310          ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7311          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7312          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7313                                CandidateSet);
7314        }
7315      }
7316    }
7317  }
7318
7319  // C++ [over.operator]p23:
7320  //
7321  //   There also exist candidate operator functions of the form
7322  //
7323  //        bool        operator!(bool);
7324  //        bool        operator&&(bool, bool);
7325  //        bool        operator||(bool, bool);
7326  void addExclaimOverload() {
7327    QualType ParamTy = S.Context.BoolTy;
7328    S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7329                          /*IsAssignmentOperator=*/false,
7330                          /*NumContextualBoolArguments=*/1);
7331  }
7332  void addAmpAmpOrPipePipeOverload() {
7333    QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7334    S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7335                          /*IsAssignmentOperator=*/false,
7336                          /*NumContextualBoolArguments=*/2);
7337  }
7338
7339  // C++ [over.built]p13:
7340  //
7341  //   For every cv-qualified or cv-unqualified object type T there
7342  //   exist candidate operator functions of the form
7343  //
7344  //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7345  //        T&         operator[](T*, ptrdiff_t);
7346  //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7347  //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7348  //        T&         operator[](ptrdiff_t, T*);
7349  void addSubscriptOverloads() {
7350    for (BuiltinCandidateTypeSet::iterator
7351              Ptr = CandidateTypes[0].pointer_begin(),
7352           PtrEnd = CandidateTypes[0].pointer_end();
7353         Ptr != PtrEnd; ++Ptr) {
7354      QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7355      QualType PointeeType = (*Ptr)->getPointeeType();
7356      if (!PointeeType->isObjectType())
7357        continue;
7358
7359      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7360
7361      // T& operator[](T*, ptrdiff_t)
7362      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7363    }
7364
7365    for (BuiltinCandidateTypeSet::iterator
7366              Ptr = CandidateTypes[1].pointer_begin(),
7367           PtrEnd = CandidateTypes[1].pointer_end();
7368         Ptr != PtrEnd; ++Ptr) {
7369      QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7370      QualType PointeeType = (*Ptr)->getPointeeType();
7371      if (!PointeeType->isObjectType())
7372        continue;
7373
7374      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7375
7376      // T& operator[](ptrdiff_t, T*)
7377      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7378    }
7379  }
7380
7381  // C++ [over.built]p11:
7382  //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7383  //    C1 is the same type as C2 or is a derived class of C2, T is an object
7384  //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7385  //    there exist candidate operator functions of the form
7386  //
7387  //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7388  //
7389  //    where CV12 is the union of CV1 and CV2.
7390  void addArrowStarOverloads() {
7391    for (BuiltinCandidateTypeSet::iterator
7392             Ptr = CandidateTypes[0].pointer_begin(),
7393           PtrEnd = CandidateTypes[0].pointer_end();
7394         Ptr != PtrEnd; ++Ptr) {
7395      QualType C1Ty = (*Ptr);
7396      QualType C1;
7397      QualifierCollector Q1;
7398      C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7399      if (!isa<RecordType>(C1))
7400        continue;
7401      // heuristic to reduce number of builtin candidates in the set.
7402      // Add volatile/restrict version only if there are conversions to a
7403      // volatile/restrict type.
7404      if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7405        continue;
7406      if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7407        continue;
7408      for (BuiltinCandidateTypeSet::iterator
7409                MemPtr = CandidateTypes[1].member_pointer_begin(),
7410             MemPtrEnd = CandidateTypes[1].member_pointer_end();
7411           MemPtr != MemPtrEnd; ++MemPtr) {
7412        const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7413        QualType C2 = QualType(mptr->getClass(), 0);
7414        C2 = C2.getUnqualifiedType();
7415        if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7416          break;
7417        QualType ParamTypes[2] = { *Ptr, *MemPtr };
7418        // build CV12 T&
7419        QualType T = mptr->getPointeeType();
7420        if (!VisibleTypeConversionsQuals.hasVolatile() &&
7421            T.isVolatileQualified())
7422          continue;
7423        if (!VisibleTypeConversionsQuals.hasRestrict() &&
7424            T.isRestrictQualified())
7425          continue;
7426        T = Q1.apply(S.Context, T);
7427        QualType ResultTy = S.Context.getLValueReferenceType(T);
7428        S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7429      }
7430    }
7431  }
7432
7433  // Note that we don't consider the first argument, since it has been
7434  // contextually converted to bool long ago. The candidates below are
7435  // therefore added as binary.
7436  //
7437  // C++ [over.built]p25:
7438  //   For every type T, where T is a pointer, pointer-to-member, or scoped
7439  //   enumeration type, there exist candidate operator functions of the form
7440  //
7441  //        T        operator?(bool, T, T);
7442  //
7443  void addConditionalOperatorOverloads() {
7444    /// Set of (canonical) types that we've already handled.
7445    llvm::SmallPtrSet<QualType, 8> AddedTypes;
7446
7447    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7448      for (BuiltinCandidateTypeSet::iterator
7449                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7450             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7451           Ptr != PtrEnd; ++Ptr) {
7452        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7453          continue;
7454
7455        QualType ParamTypes[2] = { *Ptr, *Ptr };
7456        S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7457      }
7458
7459      for (BuiltinCandidateTypeSet::iterator
7460                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7461             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7462           MemPtr != MemPtrEnd; ++MemPtr) {
7463        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7464          continue;
7465
7466        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7467        S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7468      }
7469
7470      if (S.getLangOpts().CPlusPlus11) {
7471        for (BuiltinCandidateTypeSet::iterator
7472                  Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7473               EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7474             Enum != EnumEnd; ++Enum) {
7475          if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7476            continue;
7477
7478          if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7479            continue;
7480
7481          QualType ParamTypes[2] = { *Enum, *Enum };
7482          S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7483        }
7484      }
7485    }
7486  }
7487};
7488
7489} // end anonymous namespace
7490
7491/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7492/// operator overloads to the candidate set (C++ [over.built]), based
7493/// on the operator @p Op and the arguments given. For example, if the
7494/// operator is a binary '+', this routine might add "int
7495/// operator+(int, int)" to cover integer addition.
7496void
7497Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7498                                   SourceLocation OpLoc,
7499                                   Expr **Args, unsigned NumArgs,
7500                                   OverloadCandidateSet& CandidateSet) {
7501  // Find all of the types that the arguments can convert to, but only
7502  // if the operator we're looking at has built-in operator candidates
7503  // that make use of these types. Also record whether we encounter non-record
7504  // candidate types or either arithmetic or enumeral candidate types.
7505  Qualifiers VisibleTypeConversionsQuals;
7506  VisibleTypeConversionsQuals.addConst();
7507  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7508    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7509
7510  bool HasNonRecordCandidateType = false;
7511  bool HasArithmeticOrEnumeralCandidateType = false;
7512  SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7513  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7514    CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7515    CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7516                                                 OpLoc,
7517                                                 true,
7518                                                 (Op == OO_Exclaim ||
7519                                                  Op == OO_AmpAmp ||
7520                                                  Op == OO_PipePipe),
7521                                                 VisibleTypeConversionsQuals);
7522    HasNonRecordCandidateType = HasNonRecordCandidateType ||
7523        CandidateTypes[ArgIdx].hasNonRecordTypes();
7524    HasArithmeticOrEnumeralCandidateType =
7525        HasArithmeticOrEnumeralCandidateType ||
7526        CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7527  }
7528
7529  // Exit early when no non-record types have been added to the candidate set
7530  // for any of the arguments to the operator.
7531  //
7532  // We can't exit early for !, ||, or &&, since there we have always have
7533  // 'bool' overloads.
7534  if (!HasNonRecordCandidateType &&
7535      !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7536    return;
7537
7538  // Setup an object to manage the common state for building overloads.
7539  BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7540                                           VisibleTypeConversionsQuals,
7541                                           HasArithmeticOrEnumeralCandidateType,
7542                                           CandidateTypes, CandidateSet);
7543
7544  // Dispatch over the operation to add in only those overloads which apply.
7545  switch (Op) {
7546  case OO_None:
7547  case NUM_OVERLOADED_OPERATORS:
7548    llvm_unreachable("Expected an overloaded operator");
7549
7550  case OO_New:
7551  case OO_Delete:
7552  case OO_Array_New:
7553  case OO_Array_Delete:
7554  case OO_Call:
7555    llvm_unreachable(
7556                    "Special operators don't use AddBuiltinOperatorCandidates");
7557
7558  case OO_Comma:
7559  case OO_Arrow:
7560    // C++ [over.match.oper]p3:
7561    //   -- For the operator ',', the unary operator '&', or the
7562    //      operator '->', the built-in candidates set is empty.
7563    break;
7564
7565  case OO_Plus: // '+' is either unary or binary
7566    if (NumArgs == 1)
7567      OpBuilder.addUnaryPlusPointerOverloads();
7568    // Fall through.
7569
7570  case OO_Minus: // '-' is either unary or binary
7571    if (NumArgs == 1) {
7572      OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7573    } else {
7574      OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7575      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7576    }
7577    break;
7578
7579  case OO_Star: // '*' is either unary or binary
7580    if (NumArgs == 1)
7581      OpBuilder.addUnaryStarPointerOverloads();
7582    else
7583      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7584    break;
7585
7586  case OO_Slash:
7587    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7588    break;
7589
7590  case OO_PlusPlus:
7591  case OO_MinusMinus:
7592    OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7593    OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7594    break;
7595
7596  case OO_EqualEqual:
7597  case OO_ExclaimEqual:
7598    OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7599    // Fall through.
7600
7601  case OO_Less:
7602  case OO_Greater:
7603  case OO_LessEqual:
7604  case OO_GreaterEqual:
7605    OpBuilder.addRelationalPointerOrEnumeralOverloads();
7606    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7607    break;
7608
7609  case OO_Percent:
7610  case OO_Caret:
7611  case OO_Pipe:
7612  case OO_LessLess:
7613  case OO_GreaterGreater:
7614    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7615    break;
7616
7617  case OO_Amp: // '&' is either unary or binary
7618    if (NumArgs == 1)
7619      // C++ [over.match.oper]p3:
7620      //   -- For the operator ',', the unary operator '&', or the
7621      //      operator '->', the built-in candidates set is empty.
7622      break;
7623
7624    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7625    break;
7626
7627  case OO_Tilde:
7628    OpBuilder.addUnaryTildePromotedIntegralOverloads();
7629    break;
7630
7631  case OO_Equal:
7632    OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7633    // Fall through.
7634
7635  case OO_PlusEqual:
7636  case OO_MinusEqual:
7637    OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7638    // Fall through.
7639
7640  case OO_StarEqual:
7641  case OO_SlashEqual:
7642    OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7643    break;
7644
7645  case OO_PercentEqual:
7646  case OO_LessLessEqual:
7647  case OO_GreaterGreaterEqual:
7648  case OO_AmpEqual:
7649  case OO_CaretEqual:
7650  case OO_PipeEqual:
7651    OpBuilder.addAssignmentIntegralOverloads();
7652    break;
7653
7654  case OO_Exclaim:
7655    OpBuilder.addExclaimOverload();
7656    break;
7657
7658  case OO_AmpAmp:
7659  case OO_PipePipe:
7660    OpBuilder.addAmpAmpOrPipePipeOverload();
7661    break;
7662
7663  case OO_Subscript:
7664    OpBuilder.addSubscriptOverloads();
7665    break;
7666
7667  case OO_ArrowStar:
7668    OpBuilder.addArrowStarOverloads();
7669    break;
7670
7671  case OO_Conditional:
7672    OpBuilder.addConditionalOperatorOverloads();
7673    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7674    break;
7675  }
7676}
7677
7678/// \brief Add function candidates found via argument-dependent lookup
7679/// to the set of overloading candidates.
7680///
7681/// This routine performs argument-dependent name lookup based on the
7682/// given function name (which may also be an operator name) and adds
7683/// all of the overload candidates found by ADL to the overload
7684/// candidate set (C++ [basic.lookup.argdep]).
7685void
7686Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7687                                           bool Operator, SourceLocation Loc,
7688                                           ArrayRef<Expr *> Args,
7689                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
7690                                           OverloadCandidateSet& CandidateSet,
7691                                           bool PartialOverloading) {
7692  ADLResult Fns;
7693
7694  // FIXME: This approach for uniquing ADL results (and removing
7695  // redundant candidates from the set) relies on pointer-equality,
7696  // which means we need to key off the canonical decl.  However,
7697  // always going back to the canonical decl might not get us the
7698  // right set of default arguments.  What default arguments are
7699  // we supposed to consider on ADL candidates, anyway?
7700
7701  // FIXME: Pass in the explicit template arguments?
7702  ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
7703
7704  // Erase all of the candidates we already knew about.
7705  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7706                                   CandEnd = CandidateSet.end();
7707       Cand != CandEnd; ++Cand)
7708    if (Cand->Function) {
7709      Fns.erase(Cand->Function);
7710      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7711        Fns.erase(FunTmpl);
7712    }
7713
7714  // For each of the ADL candidates we found, add it to the overload
7715  // set.
7716  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7717    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7718    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7719      if (ExplicitTemplateArgs)
7720        continue;
7721
7722      AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7723                           PartialOverloading);
7724    } else
7725      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7726                                   FoundDecl, ExplicitTemplateArgs,
7727                                   Args, CandidateSet);
7728  }
7729}
7730
7731/// isBetterOverloadCandidate - Determines whether the first overload
7732/// candidate is a better candidate than the second (C++ 13.3.3p1).
7733bool
7734isBetterOverloadCandidate(Sema &S,
7735                          const OverloadCandidate &Cand1,
7736                          const OverloadCandidate &Cand2,
7737                          SourceLocation Loc,
7738                          bool UserDefinedConversion) {
7739  // Define viable functions to be better candidates than non-viable
7740  // functions.
7741  if (!Cand2.Viable)
7742    return Cand1.Viable;
7743  else if (!Cand1.Viable)
7744    return false;
7745
7746  // C++ [over.match.best]p1:
7747  //
7748  //   -- if F is a static member function, ICS1(F) is defined such
7749  //      that ICS1(F) is neither better nor worse than ICS1(G) for
7750  //      any function G, and, symmetrically, ICS1(G) is neither
7751  //      better nor worse than ICS1(F).
7752  unsigned StartArg = 0;
7753  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7754    StartArg = 1;
7755
7756  // C++ [over.match.best]p1:
7757  //   A viable function F1 is defined to be a better function than another
7758  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
7759  //   conversion sequence than ICSi(F2), and then...
7760  unsigned NumArgs = Cand1.NumConversions;
7761  assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7762  bool HasBetterConversion = false;
7763  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7764    switch (CompareImplicitConversionSequences(S,
7765                                               Cand1.Conversions[ArgIdx],
7766                                               Cand2.Conversions[ArgIdx])) {
7767    case ImplicitConversionSequence::Better:
7768      // Cand1 has a better conversion sequence.
7769      HasBetterConversion = true;
7770      break;
7771
7772    case ImplicitConversionSequence::Worse:
7773      // Cand1 can't be better than Cand2.
7774      return false;
7775
7776    case ImplicitConversionSequence::Indistinguishable:
7777      // Do nothing.
7778      break;
7779    }
7780  }
7781
7782  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
7783  //       ICSj(F2), or, if not that,
7784  if (HasBetterConversion)
7785    return true;
7786
7787  //     - F1 is a non-template function and F2 is a function template
7788  //       specialization, or, if not that,
7789  if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
7790      Cand2.Function && Cand2.Function->getPrimaryTemplate())
7791    return true;
7792
7793  //   -- F1 and F2 are function template specializations, and the function
7794  //      template for F1 is more specialized than the template for F2
7795  //      according to the partial ordering rules described in 14.5.5.2, or,
7796  //      if not that,
7797  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
7798      Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
7799    if (FunctionTemplateDecl *BetterTemplate
7800          = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7801                                         Cand2.Function->getPrimaryTemplate(),
7802                                         Loc,
7803                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
7804                                                             : TPOC_Call,
7805                                         Cand1.ExplicitCallArguments))
7806      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
7807  }
7808
7809  //   -- the context is an initialization by user-defined conversion
7810  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
7811  //      from the return type of F1 to the destination type (i.e.,
7812  //      the type of the entity being initialized) is a better
7813  //      conversion sequence than the standard conversion sequence
7814  //      from the return type of F2 to the destination type.
7815  if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
7816      isa<CXXConversionDecl>(Cand1.Function) &&
7817      isa<CXXConversionDecl>(Cand2.Function)) {
7818    // First check whether we prefer one of the conversion functions over the
7819    // other. This only distinguishes the results in non-standard, extension
7820    // cases such as the conversion from a lambda closure type to a function
7821    // pointer or block.
7822    ImplicitConversionSequence::CompareKind FuncResult
7823      = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7824    if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7825      return FuncResult;
7826
7827    switch (CompareStandardConversionSequences(S,
7828                                               Cand1.FinalConversion,
7829                                               Cand2.FinalConversion)) {
7830    case ImplicitConversionSequence::Better:
7831      // Cand1 has a better conversion sequence.
7832      return true;
7833
7834    case ImplicitConversionSequence::Worse:
7835      // Cand1 can't be better than Cand2.
7836      return false;
7837
7838    case ImplicitConversionSequence::Indistinguishable:
7839      // Do nothing
7840      break;
7841    }
7842  }
7843
7844  return false;
7845}
7846
7847/// \brief Computes the best viable function (C++ 13.3.3)
7848/// within an overload candidate set.
7849///
7850/// \param Loc The location of the function name (or operator symbol) for
7851/// which overload resolution occurs.
7852///
7853/// \param Best If overload resolution was successful or found a deleted
7854/// function, \p Best points to the candidate function found.
7855///
7856/// \returns The result of overload resolution.
7857OverloadingResult
7858OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
7859                                         iterator &Best,
7860                                         bool UserDefinedConversion) {
7861  // Find the best viable function.
7862  Best = end();
7863  for (iterator Cand = begin(); Cand != end(); ++Cand) {
7864    if (Cand->Viable)
7865      if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
7866                                                     UserDefinedConversion))
7867        Best = Cand;
7868  }
7869
7870  // If we didn't find any viable functions, abort.
7871  if (Best == end())
7872    return OR_No_Viable_Function;
7873
7874  // Make sure that this function is better than every other viable
7875  // function. If not, we have an ambiguity.
7876  for (iterator Cand = begin(); Cand != end(); ++Cand) {
7877    if (Cand->Viable &&
7878        Cand != Best &&
7879        !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
7880                                   UserDefinedConversion)) {
7881      Best = end();
7882      return OR_Ambiguous;
7883    }
7884  }
7885
7886  // Best is the best viable function.
7887  if (Best->Function &&
7888      (Best->Function->isDeleted() ||
7889       S.isFunctionConsideredUnavailable(Best->Function)))
7890    return OR_Deleted;
7891
7892  return OR_Success;
7893}
7894
7895namespace {
7896
7897enum OverloadCandidateKind {
7898  oc_function,
7899  oc_method,
7900  oc_constructor,
7901  oc_function_template,
7902  oc_method_template,
7903  oc_constructor_template,
7904  oc_implicit_default_constructor,
7905  oc_implicit_copy_constructor,
7906  oc_implicit_move_constructor,
7907  oc_implicit_copy_assignment,
7908  oc_implicit_move_assignment,
7909  oc_implicit_inherited_constructor
7910};
7911
7912OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7913                                                FunctionDecl *Fn,
7914                                                std::string &Description) {
7915  bool isTemplate = false;
7916
7917  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7918    isTemplate = true;
7919    Description = S.getTemplateArgumentBindingsText(
7920      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7921  }
7922
7923  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
7924    if (!Ctor->isImplicit())
7925      return isTemplate ? oc_constructor_template : oc_constructor;
7926
7927    if (Ctor->getInheritedConstructor())
7928      return oc_implicit_inherited_constructor;
7929
7930    if (Ctor->isDefaultConstructor())
7931      return oc_implicit_default_constructor;
7932
7933    if (Ctor->isMoveConstructor())
7934      return oc_implicit_move_constructor;
7935
7936    assert(Ctor->isCopyConstructor() &&
7937           "unexpected sort of implicit constructor");
7938    return oc_implicit_copy_constructor;
7939  }
7940
7941  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7942    // This actually gets spelled 'candidate function' for now, but
7943    // it doesn't hurt to split it out.
7944    if (!Meth->isImplicit())
7945      return isTemplate ? oc_method_template : oc_method;
7946
7947    if (Meth->isMoveAssignmentOperator())
7948      return oc_implicit_move_assignment;
7949
7950    if (Meth->isCopyAssignmentOperator())
7951      return oc_implicit_copy_assignment;
7952
7953    assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7954    return oc_method;
7955  }
7956
7957  return isTemplate ? oc_function_template : oc_function;
7958}
7959
7960void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7961  const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7962  if (!Ctor) return;
7963
7964  Ctor = Ctor->getInheritedConstructor();
7965  if (!Ctor) return;
7966
7967  S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7968}
7969
7970} // end anonymous namespace
7971
7972// Notes the location of an overload candidate.
7973void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
7974  std::string FnDesc;
7975  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
7976  PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7977                             << (unsigned) K << FnDesc;
7978  HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7979  Diag(Fn->getLocation(), PD);
7980  MaybeEmitInheritedConstructorNote(*this, Fn);
7981}
7982
7983//Notes the location of all overload candidates designated through
7984// OverloadedExpr
7985void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
7986  assert(OverloadedExpr->getType() == Context.OverloadTy);
7987
7988  OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7989  OverloadExpr *OvlExpr = Ovl.Expression;
7990
7991  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7992                            IEnd = OvlExpr->decls_end();
7993       I != IEnd; ++I) {
7994    if (FunctionTemplateDecl *FunTmpl =
7995                dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
7996      NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
7997    } else if (FunctionDecl *Fun
7998                      = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
7999      NoteOverloadCandidate(Fun, DestType);
8000    }
8001  }
8002}
8003
8004/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8005/// "lead" diagnostic; it will be given two arguments, the source and
8006/// target types of the conversion.
8007void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8008                                 Sema &S,
8009                                 SourceLocation CaretLoc,
8010                                 const PartialDiagnostic &PDiag) const {
8011  S.Diag(CaretLoc, PDiag)
8012    << Ambiguous.getFromType() << Ambiguous.getToType();
8013  // FIXME: The note limiting machinery is borrowed from
8014  // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8015  // refactoring here.
8016  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8017  unsigned CandsShown = 0;
8018  AmbiguousConversionSequence::const_iterator I, E;
8019  for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8020    if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8021      break;
8022    ++CandsShown;
8023    S.NoteOverloadCandidate(*I);
8024  }
8025  if (I != E)
8026    S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8027}
8028
8029namespace {
8030
8031void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8032  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8033  assert(Conv.isBad());
8034  assert(Cand->Function && "for now, candidate must be a function");
8035  FunctionDecl *Fn = Cand->Function;
8036
8037  // There's a conversion slot for the object argument if this is a
8038  // non-constructor method.  Note that 'I' corresponds the
8039  // conversion-slot index.
8040  bool isObjectArgument = false;
8041  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8042    if (I == 0)
8043      isObjectArgument = true;
8044    else
8045      I--;
8046  }
8047
8048  std::string FnDesc;
8049  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8050
8051  Expr *FromExpr = Conv.Bad.FromExpr;
8052  QualType FromTy = Conv.Bad.getFromType();
8053  QualType ToTy = Conv.Bad.getToType();
8054
8055  if (FromTy == S.Context.OverloadTy) {
8056    assert(FromExpr && "overload set argument came from implicit argument?");
8057    Expr *E = FromExpr->IgnoreParens();
8058    if (isa<UnaryOperator>(E))
8059      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8060    DeclarationName Name = cast<OverloadExpr>(E)->getName();
8061
8062    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8063      << (unsigned) FnKind << FnDesc
8064      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8065      << ToTy << Name << I+1;
8066    MaybeEmitInheritedConstructorNote(S, Fn);
8067    return;
8068  }
8069
8070  // Do some hand-waving analysis to see if the non-viability is due
8071  // to a qualifier mismatch.
8072  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8073  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8074  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8075    CToTy = RT->getPointeeType();
8076  else {
8077    // TODO: detect and diagnose the full richness of const mismatches.
8078    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8079      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8080        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8081  }
8082
8083  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8084      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8085    Qualifiers FromQs = CFromTy.getQualifiers();
8086    Qualifiers ToQs = CToTy.getQualifiers();
8087
8088    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8089      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8090        << (unsigned) FnKind << FnDesc
8091        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8092        << FromTy
8093        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8094        << (unsigned) isObjectArgument << I+1;
8095      MaybeEmitInheritedConstructorNote(S, Fn);
8096      return;
8097    }
8098
8099    if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8100      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8101        << (unsigned) FnKind << FnDesc
8102        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8103        << FromTy
8104        << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8105        << (unsigned) isObjectArgument << I+1;
8106      MaybeEmitInheritedConstructorNote(S, Fn);
8107      return;
8108    }
8109
8110    if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8111      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8112      << (unsigned) FnKind << FnDesc
8113      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8114      << FromTy
8115      << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8116      << (unsigned) isObjectArgument << I+1;
8117      MaybeEmitInheritedConstructorNote(S, Fn);
8118      return;
8119    }
8120
8121    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8122    assert(CVR && "unexpected qualifiers mismatch");
8123
8124    if (isObjectArgument) {
8125      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8126        << (unsigned) FnKind << FnDesc
8127        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8128        << FromTy << (CVR - 1);
8129    } else {
8130      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8131        << (unsigned) FnKind << FnDesc
8132        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8133        << FromTy << (CVR - 1) << I+1;
8134    }
8135    MaybeEmitInheritedConstructorNote(S, Fn);
8136    return;
8137  }
8138
8139  // Special diagnostic for failure to convert an initializer list, since
8140  // telling the user that it has type void is not useful.
8141  if (FromExpr && isa<InitListExpr>(FromExpr)) {
8142    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8143      << (unsigned) FnKind << FnDesc
8144      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8145      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8146    MaybeEmitInheritedConstructorNote(S, Fn);
8147    return;
8148  }
8149
8150  // Diagnose references or pointers to incomplete types differently,
8151  // since it's far from impossible that the incompleteness triggered
8152  // the failure.
8153  QualType TempFromTy = FromTy.getNonReferenceType();
8154  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8155    TempFromTy = PTy->getPointeeType();
8156  if (TempFromTy->isIncompleteType()) {
8157    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8158      << (unsigned) FnKind << FnDesc
8159      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8160      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8161    MaybeEmitInheritedConstructorNote(S, Fn);
8162    return;
8163  }
8164
8165  // Diagnose base -> derived pointer conversions.
8166  unsigned BaseToDerivedConversion = 0;
8167  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8168    if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8169      if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8170                                               FromPtrTy->getPointeeType()) &&
8171          !FromPtrTy->getPointeeType()->isIncompleteType() &&
8172          !ToPtrTy->getPointeeType()->isIncompleteType() &&
8173          S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8174                          FromPtrTy->getPointeeType()))
8175        BaseToDerivedConversion = 1;
8176    }
8177  } else if (const ObjCObjectPointerType *FromPtrTy
8178                                    = FromTy->getAs<ObjCObjectPointerType>()) {
8179    if (const ObjCObjectPointerType *ToPtrTy
8180                                        = ToTy->getAs<ObjCObjectPointerType>())
8181      if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8182        if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8183          if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8184                                                FromPtrTy->getPointeeType()) &&
8185              FromIface->isSuperClassOf(ToIface))
8186            BaseToDerivedConversion = 2;
8187  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8188    if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8189        !FromTy->isIncompleteType() &&
8190        !ToRefTy->getPointeeType()->isIncompleteType() &&
8191        S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8192      BaseToDerivedConversion = 3;
8193    } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8194               ToTy.getNonReferenceType().getCanonicalType() ==
8195               FromTy.getNonReferenceType().getCanonicalType()) {
8196      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8197        << (unsigned) FnKind << FnDesc
8198        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8199        << (unsigned) isObjectArgument << I + 1;
8200      MaybeEmitInheritedConstructorNote(S, Fn);
8201      return;
8202    }
8203  }
8204
8205  if (BaseToDerivedConversion) {
8206    S.Diag(Fn->getLocation(),
8207           diag::note_ovl_candidate_bad_base_to_derived_conv)
8208      << (unsigned) FnKind << FnDesc
8209      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8210      << (BaseToDerivedConversion - 1)
8211      << FromTy << ToTy << I+1;
8212    MaybeEmitInheritedConstructorNote(S, Fn);
8213    return;
8214  }
8215
8216  if (isa<ObjCObjectPointerType>(CFromTy) &&
8217      isa<PointerType>(CToTy)) {
8218      Qualifiers FromQs = CFromTy.getQualifiers();
8219      Qualifiers ToQs = CToTy.getQualifiers();
8220      if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8221        S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8222        << (unsigned) FnKind << FnDesc
8223        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8224        << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8225        MaybeEmitInheritedConstructorNote(S, Fn);
8226        return;
8227      }
8228  }
8229
8230  // Emit the generic diagnostic and, optionally, add the hints to it.
8231  PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8232  FDiag << (unsigned) FnKind << FnDesc
8233    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8234    << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8235    << (unsigned) (Cand->Fix.Kind);
8236
8237  // If we can fix the conversion, suggest the FixIts.
8238  for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8239       HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8240    FDiag << *HI;
8241  S.Diag(Fn->getLocation(), FDiag);
8242
8243  MaybeEmitInheritedConstructorNote(S, Fn);
8244}
8245
8246void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8247                           unsigned NumFormalArgs) {
8248  // TODO: treat calls to a missing default constructor as a special case
8249
8250  FunctionDecl *Fn = Cand->Function;
8251  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8252
8253  unsigned MinParams = Fn->getMinRequiredArguments();
8254
8255  // With invalid overloaded operators, it's possible that we think we
8256  // have an arity mismatch when it fact it looks like we have the
8257  // right number of arguments, because only overloaded operators have
8258  // the weird behavior of overloading member and non-member functions.
8259  // Just don't report anything.
8260  if (Fn->isInvalidDecl() &&
8261      Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8262    return;
8263
8264  // at least / at most / exactly
8265  unsigned mode, modeCount;
8266  if (NumFormalArgs < MinParams) {
8267    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8268           (Cand->FailureKind == ovl_fail_bad_deduction &&
8269            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8270    if (MinParams != FnTy->getNumArgs() ||
8271        FnTy->isVariadic() || FnTy->isTemplateVariadic())
8272      mode = 0; // "at least"
8273    else
8274      mode = 2; // "exactly"
8275    modeCount = MinParams;
8276  } else {
8277    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8278           (Cand->FailureKind == ovl_fail_bad_deduction &&
8279            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8280    if (MinParams != FnTy->getNumArgs())
8281      mode = 1; // "at most"
8282    else
8283      mode = 2; // "exactly"
8284    modeCount = FnTy->getNumArgs();
8285  }
8286
8287  std::string Description;
8288  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8289
8290  if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8291    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8292      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8293      << Fn->getParamDecl(0) << NumFormalArgs;
8294  else
8295    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8296      << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8297      << modeCount << NumFormalArgs;
8298  MaybeEmitInheritedConstructorNote(S, Fn);
8299}
8300
8301/// Diagnose a failed template-argument deduction.
8302void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
8303                          unsigned NumArgs) {
8304  FunctionDecl *Fn = Cand->Function; // pattern
8305
8306  TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
8307  NamedDecl *ParamD;
8308  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8309  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8310  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8311  switch (Cand->DeductionFailure.Result) {
8312  case Sema::TDK_Success:
8313    llvm_unreachable("TDK_success while diagnosing bad deduction");
8314
8315  case Sema::TDK_Incomplete: {
8316    assert(ParamD && "no parameter found for incomplete deduction result");
8317    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8318      << ParamD->getDeclName();
8319    MaybeEmitInheritedConstructorNote(S, Fn);
8320    return;
8321  }
8322
8323  case Sema::TDK_Underqualified: {
8324    assert(ParamD && "no parameter found for bad qualifiers deduction result");
8325    TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8326
8327    QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8328
8329    // Param will have been canonicalized, but it should just be a
8330    // qualified version of ParamD, so move the qualifiers to that.
8331    QualifierCollector Qs;
8332    Qs.strip(Param);
8333    QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8334    assert(S.Context.hasSameType(Param, NonCanonParam));
8335
8336    // Arg has also been canonicalized, but there's nothing we can do
8337    // about that.  It also doesn't matter as much, because it won't
8338    // have any template parameters in it (because deduction isn't
8339    // done on dependent types).
8340    QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8341
8342    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8343      << ParamD->getDeclName() << Arg << NonCanonParam;
8344    MaybeEmitInheritedConstructorNote(S, Fn);
8345    return;
8346  }
8347
8348  case Sema::TDK_Inconsistent: {
8349    assert(ParamD && "no parameter found for inconsistent deduction result");
8350    int which = 0;
8351    if (isa<TemplateTypeParmDecl>(ParamD))
8352      which = 0;
8353    else if (isa<NonTypeTemplateParmDecl>(ParamD))
8354      which = 1;
8355    else {
8356      which = 2;
8357    }
8358
8359    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
8360      << which << ParamD->getDeclName()
8361      << *Cand->DeductionFailure.getFirstArg()
8362      << *Cand->DeductionFailure.getSecondArg();
8363    MaybeEmitInheritedConstructorNote(S, Fn);
8364    return;
8365  }
8366
8367  case Sema::TDK_InvalidExplicitArguments:
8368    assert(ParamD && "no parameter found for invalid explicit arguments");
8369    if (ParamD->getDeclName())
8370      S.Diag(Fn->getLocation(),
8371             diag::note_ovl_candidate_explicit_arg_mismatch_named)
8372        << ParamD->getDeclName();
8373    else {
8374      int index = 0;
8375      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8376        index = TTP->getIndex();
8377      else if (NonTypeTemplateParmDecl *NTTP
8378                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8379        index = NTTP->getIndex();
8380      else
8381        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8382      S.Diag(Fn->getLocation(),
8383             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8384        << (index + 1);
8385    }
8386    MaybeEmitInheritedConstructorNote(S, Fn);
8387    return;
8388
8389  case Sema::TDK_TooManyArguments:
8390  case Sema::TDK_TooFewArguments:
8391    DiagnoseArityMismatch(S, Cand, NumArgs);
8392    return;
8393
8394  case Sema::TDK_InstantiationDepth:
8395    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
8396    MaybeEmitInheritedConstructorNote(S, Fn);
8397    return;
8398
8399  case Sema::TDK_SubstitutionFailure: {
8400    // Format the template argument list into the argument string.
8401    SmallString<128> TemplateArgString;
8402    if (TemplateArgumentList *Args =
8403          Cand->DeductionFailure.getTemplateArgumentList()) {
8404      TemplateArgString = " ";
8405      TemplateArgString += S.getTemplateArgumentBindingsText(
8406          Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8407    }
8408
8409    // If this candidate was disabled by enable_if, say so.
8410    PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8411    if (PDiag && PDiag->second.getDiagID() ==
8412          diag::err_typename_nested_not_found_enable_if) {
8413      // FIXME: Use the source range of the condition, and the fully-qualified
8414      //        name of the enable_if template. These are both present in PDiag.
8415      S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8416        << "'enable_if'" << TemplateArgString;
8417      return;
8418    }
8419
8420    // Format the SFINAE diagnostic into the argument string.
8421    // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8422    //        formatted message in another diagnostic.
8423    SmallString<128> SFINAEArgString;
8424    SourceRange R;
8425    if (PDiag) {
8426      SFINAEArgString = ": ";
8427      R = SourceRange(PDiag->first, PDiag->first);
8428      PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8429    }
8430
8431    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8432      << TemplateArgString << SFINAEArgString << R;
8433    MaybeEmitInheritedConstructorNote(S, Fn);
8434    return;
8435  }
8436
8437  // TODO: diagnose these individually, then kill off
8438  // note_ovl_candidate_bad_deduction, which is uselessly vague.
8439  case Sema::TDK_NonDeducedMismatch:
8440  case Sema::TDK_FailedOverloadResolution:
8441    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
8442    MaybeEmitInheritedConstructorNote(S, Fn);
8443    return;
8444  }
8445}
8446
8447/// CUDA: diagnose an invalid call across targets.
8448void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8449  FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8450  FunctionDecl *Callee = Cand->Function;
8451
8452  Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8453                           CalleeTarget = S.IdentifyCUDATarget(Callee);
8454
8455  std::string FnDesc;
8456  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8457
8458  S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8459      << (unsigned) FnKind << CalleeTarget << CallerTarget;
8460}
8461
8462/// Generates a 'note' diagnostic for an overload candidate.  We've
8463/// already generated a primary error at the call site.
8464///
8465/// It really does need to be a single diagnostic with its caret
8466/// pointed at the candidate declaration.  Yes, this creates some
8467/// major challenges of technical writing.  Yes, this makes pointing
8468/// out problems with specific arguments quite awkward.  It's still
8469/// better than generating twenty screens of text for every failed
8470/// overload.
8471///
8472/// It would be great to be able to express per-candidate problems
8473/// more richly for those diagnostic clients that cared, but we'd
8474/// still have to be just as careful with the default diagnostics.
8475void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8476                           unsigned NumArgs) {
8477  FunctionDecl *Fn = Cand->Function;
8478
8479  // Note deleted candidates, but only if they're viable.
8480  if (Cand->Viable && (Fn->isDeleted() ||
8481      S.isFunctionConsideredUnavailable(Fn))) {
8482    std::string FnDesc;
8483    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8484
8485    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8486      << FnKind << FnDesc
8487      << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8488    MaybeEmitInheritedConstructorNote(S, Fn);
8489    return;
8490  }
8491
8492  // We don't really have anything else to say about viable candidates.
8493  if (Cand->Viable) {
8494    S.NoteOverloadCandidate(Fn);
8495    return;
8496  }
8497
8498  switch (Cand->FailureKind) {
8499  case ovl_fail_too_many_arguments:
8500  case ovl_fail_too_few_arguments:
8501    return DiagnoseArityMismatch(S, Cand, NumArgs);
8502
8503  case ovl_fail_bad_deduction:
8504    return DiagnoseBadDeduction(S, Cand, NumArgs);
8505
8506  case ovl_fail_trivial_conversion:
8507  case ovl_fail_bad_final_conversion:
8508  case ovl_fail_final_conversion_not_exact:
8509    return S.NoteOverloadCandidate(Fn);
8510
8511  case ovl_fail_bad_conversion: {
8512    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8513    for (unsigned N = Cand->NumConversions; I != N; ++I)
8514      if (Cand->Conversions[I].isBad())
8515        return DiagnoseBadConversion(S, Cand, I);
8516
8517    // FIXME: this currently happens when we're called from SemaInit
8518    // when user-conversion overload fails.  Figure out how to handle
8519    // those conditions and diagnose them well.
8520    return S.NoteOverloadCandidate(Fn);
8521  }
8522
8523  case ovl_fail_bad_target:
8524    return DiagnoseBadTarget(S, Cand);
8525  }
8526}
8527
8528void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8529  // Desugar the type of the surrogate down to a function type,
8530  // retaining as many typedefs as possible while still showing
8531  // the function type (and, therefore, its parameter types).
8532  QualType FnType = Cand->Surrogate->getConversionType();
8533  bool isLValueReference = false;
8534  bool isRValueReference = false;
8535  bool isPointer = false;
8536  if (const LValueReferenceType *FnTypeRef =
8537        FnType->getAs<LValueReferenceType>()) {
8538    FnType = FnTypeRef->getPointeeType();
8539    isLValueReference = true;
8540  } else if (const RValueReferenceType *FnTypeRef =
8541               FnType->getAs<RValueReferenceType>()) {
8542    FnType = FnTypeRef->getPointeeType();
8543    isRValueReference = true;
8544  }
8545  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8546    FnType = FnTypePtr->getPointeeType();
8547    isPointer = true;
8548  }
8549  // Desugar down to a function type.
8550  FnType = QualType(FnType->getAs<FunctionType>(), 0);
8551  // Reconstruct the pointer/reference as appropriate.
8552  if (isPointer) FnType = S.Context.getPointerType(FnType);
8553  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8554  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8555
8556  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8557    << FnType;
8558  MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8559}
8560
8561void NoteBuiltinOperatorCandidate(Sema &S,
8562                                  StringRef Opc,
8563                                  SourceLocation OpLoc,
8564                                  OverloadCandidate *Cand) {
8565  assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8566  std::string TypeStr("operator");
8567  TypeStr += Opc;
8568  TypeStr += "(";
8569  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8570  if (Cand->NumConversions == 1) {
8571    TypeStr += ")";
8572    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8573  } else {
8574    TypeStr += ", ";
8575    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8576    TypeStr += ")";
8577    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8578  }
8579}
8580
8581void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8582                                  OverloadCandidate *Cand) {
8583  unsigned NoOperands = Cand->NumConversions;
8584  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8585    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8586    if (ICS.isBad()) break; // all meaningless after first invalid
8587    if (!ICS.isAmbiguous()) continue;
8588
8589    ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8590                              S.PDiag(diag::note_ambiguous_type_conversion));
8591  }
8592}
8593
8594SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8595  if (Cand->Function)
8596    return Cand->Function->getLocation();
8597  if (Cand->IsSurrogate)
8598    return Cand->Surrogate->getLocation();
8599  return SourceLocation();
8600}
8601
8602static unsigned
8603RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
8604  switch ((Sema::TemplateDeductionResult)DFI.Result) {
8605  case Sema::TDK_Success:
8606    llvm_unreachable("TDK_success while diagnosing bad deduction");
8607
8608  case Sema::TDK_Invalid:
8609  case Sema::TDK_Incomplete:
8610    return 1;
8611
8612  case Sema::TDK_Underqualified:
8613  case Sema::TDK_Inconsistent:
8614    return 2;
8615
8616  case Sema::TDK_SubstitutionFailure:
8617  case Sema::TDK_NonDeducedMismatch:
8618    return 3;
8619
8620  case Sema::TDK_InstantiationDepth:
8621  case Sema::TDK_FailedOverloadResolution:
8622    return 4;
8623
8624  case Sema::TDK_InvalidExplicitArguments:
8625    return 5;
8626
8627  case Sema::TDK_TooManyArguments:
8628  case Sema::TDK_TooFewArguments:
8629    return 6;
8630  }
8631  llvm_unreachable("Unhandled deduction result");
8632}
8633
8634struct CompareOverloadCandidatesForDisplay {
8635  Sema &S;
8636  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8637
8638  bool operator()(const OverloadCandidate *L,
8639                  const OverloadCandidate *R) {
8640    // Fast-path this check.
8641    if (L == R) return false;
8642
8643    // Order first by viability.
8644    if (L->Viable) {
8645      if (!R->Viable) return true;
8646
8647      // TODO: introduce a tri-valued comparison for overload
8648      // candidates.  Would be more worthwhile if we had a sort
8649      // that could exploit it.
8650      if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8651      if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8652    } else if (R->Viable)
8653      return false;
8654
8655    assert(L->Viable == R->Viable);
8656
8657    // Criteria by which we can sort non-viable candidates:
8658    if (!L->Viable) {
8659      // 1. Arity mismatches come after other candidates.
8660      if (L->FailureKind == ovl_fail_too_many_arguments ||
8661          L->FailureKind == ovl_fail_too_few_arguments)
8662        return false;
8663      if (R->FailureKind == ovl_fail_too_many_arguments ||
8664          R->FailureKind == ovl_fail_too_few_arguments)
8665        return true;
8666
8667      // 2. Bad conversions come first and are ordered by the number
8668      // of bad conversions and quality of good conversions.
8669      if (L->FailureKind == ovl_fail_bad_conversion) {
8670        if (R->FailureKind != ovl_fail_bad_conversion)
8671          return true;
8672
8673        // The conversion that can be fixed with a smaller number of changes,
8674        // comes first.
8675        unsigned numLFixes = L->Fix.NumConversionsFixed;
8676        unsigned numRFixes = R->Fix.NumConversionsFixed;
8677        numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8678        numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8679        if (numLFixes != numRFixes) {
8680          if (numLFixes < numRFixes)
8681            return true;
8682          else
8683            return false;
8684        }
8685
8686        // If there's any ordering between the defined conversions...
8687        // FIXME: this might not be transitive.
8688        assert(L->NumConversions == R->NumConversions);
8689
8690        int leftBetter = 0;
8691        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8692        for (unsigned E = L->NumConversions; I != E; ++I) {
8693          switch (CompareImplicitConversionSequences(S,
8694                                                     L->Conversions[I],
8695                                                     R->Conversions[I])) {
8696          case ImplicitConversionSequence::Better:
8697            leftBetter++;
8698            break;
8699
8700          case ImplicitConversionSequence::Worse:
8701            leftBetter--;
8702            break;
8703
8704          case ImplicitConversionSequence::Indistinguishable:
8705            break;
8706          }
8707        }
8708        if (leftBetter > 0) return true;
8709        if (leftBetter < 0) return false;
8710
8711      } else if (R->FailureKind == ovl_fail_bad_conversion)
8712        return false;
8713
8714      if (L->FailureKind == ovl_fail_bad_deduction) {
8715        if (R->FailureKind != ovl_fail_bad_deduction)
8716          return true;
8717
8718        if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8719          return RankDeductionFailure(L->DeductionFailure)
8720               < RankDeductionFailure(R->DeductionFailure);
8721      } else if (R->FailureKind == ovl_fail_bad_deduction)
8722        return false;
8723
8724      // TODO: others?
8725    }
8726
8727    // Sort everything else by location.
8728    SourceLocation LLoc = GetLocationForCandidate(L);
8729    SourceLocation RLoc = GetLocationForCandidate(R);
8730
8731    // Put candidates without locations (e.g. builtins) at the end.
8732    if (LLoc.isInvalid()) return false;
8733    if (RLoc.isInvalid()) return true;
8734
8735    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8736  }
8737};
8738
8739/// CompleteNonViableCandidate - Normally, overload resolution only
8740/// computes up to the first. Produces the FixIt set if possible.
8741void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8742                                ArrayRef<Expr *> Args) {
8743  assert(!Cand->Viable);
8744
8745  // Don't do anything on failures other than bad conversion.
8746  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8747
8748  // We only want the FixIts if all the arguments can be corrected.
8749  bool Unfixable = false;
8750  // Use a implicit copy initialization to check conversion fixes.
8751  Cand->Fix.setConversionChecker(TryCopyInitialization);
8752
8753  // Skip forward to the first bad conversion.
8754  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
8755  unsigned ConvCount = Cand->NumConversions;
8756  while (true) {
8757    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8758    ConvIdx++;
8759    if (Cand->Conversions[ConvIdx - 1].isBad()) {
8760      Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
8761      break;
8762    }
8763  }
8764
8765  if (ConvIdx == ConvCount)
8766    return;
8767
8768  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8769         "remaining conversion is initialized?");
8770
8771  // FIXME: this should probably be preserved from the overload
8772  // operation somehow.
8773  bool SuppressUserConversions = false;
8774
8775  const FunctionProtoType* Proto;
8776  unsigned ArgIdx = ConvIdx;
8777
8778  if (Cand->IsSurrogate) {
8779    QualType ConvType
8780      = Cand->Surrogate->getConversionType().getNonReferenceType();
8781    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8782      ConvType = ConvPtrType->getPointeeType();
8783    Proto = ConvType->getAs<FunctionProtoType>();
8784    ArgIdx--;
8785  } else if (Cand->Function) {
8786    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8787    if (isa<CXXMethodDecl>(Cand->Function) &&
8788        !isa<CXXConstructorDecl>(Cand->Function))
8789      ArgIdx--;
8790  } else {
8791    // Builtin binary operator with a bad first conversion.
8792    assert(ConvCount <= 3);
8793    for (; ConvIdx != ConvCount; ++ConvIdx)
8794      Cand->Conversions[ConvIdx]
8795        = TryCopyInitialization(S, Args[ConvIdx],
8796                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
8797                                SuppressUserConversions,
8798                                /*InOverloadResolution*/ true,
8799                                /*AllowObjCWritebackConversion=*/
8800                                  S.getLangOpts().ObjCAutoRefCount);
8801    return;
8802  }
8803
8804  // Fill in the rest of the conversions.
8805  unsigned NumArgsInProto = Proto->getNumArgs();
8806  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
8807    if (ArgIdx < NumArgsInProto) {
8808      Cand->Conversions[ConvIdx]
8809        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
8810                                SuppressUserConversions,
8811                                /*InOverloadResolution=*/true,
8812                                /*AllowObjCWritebackConversion=*/
8813                                  S.getLangOpts().ObjCAutoRefCount);
8814      // Store the FixIt in the candidate if it exists.
8815      if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
8816        Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
8817    }
8818    else
8819      Cand->Conversions[ConvIdx].setEllipsis();
8820  }
8821}
8822
8823} // end anonymous namespace
8824
8825/// PrintOverloadCandidates - When overload resolution fails, prints
8826/// diagnostic messages containing the candidates in the candidate
8827/// set.
8828void OverloadCandidateSet::NoteCandidates(Sema &S,
8829                                          OverloadCandidateDisplayKind OCD,
8830                                          ArrayRef<Expr *> Args,
8831                                          StringRef Opc,
8832                                          SourceLocation OpLoc) {
8833  // Sort the candidates by viability and position.  Sorting directly would
8834  // be prohibitive, so we make a set of pointers and sort those.
8835  SmallVector<OverloadCandidate*, 32> Cands;
8836  if (OCD == OCD_AllCandidates) Cands.reserve(size());
8837  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
8838    if (Cand->Viable)
8839      Cands.push_back(Cand);
8840    else if (OCD == OCD_AllCandidates) {
8841      CompleteNonViableCandidate(S, Cand, Args);
8842      if (Cand->Function || Cand->IsSurrogate)
8843        Cands.push_back(Cand);
8844      // Otherwise, this a non-viable builtin candidate.  We do not, in general,
8845      // want to list every possible builtin candidate.
8846    }
8847  }
8848
8849  std::sort(Cands.begin(), Cands.end(),
8850            CompareOverloadCandidatesForDisplay(S));
8851
8852  bool ReportedAmbiguousConversions = false;
8853
8854  SmallVectorImpl<OverloadCandidate*>::iterator I, E;
8855  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8856  unsigned CandsShown = 0;
8857  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8858    OverloadCandidate *Cand = *I;
8859
8860    // Set an arbitrary limit on the number of candidate functions we'll spam
8861    // the user with.  FIXME: This limit should depend on details of the
8862    // candidate list.
8863    if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
8864      break;
8865    }
8866    ++CandsShown;
8867
8868    if (Cand->Function)
8869      NoteFunctionCandidate(S, Cand, Args.size());
8870    else if (Cand->IsSurrogate)
8871      NoteSurrogateCandidate(S, Cand);
8872    else {
8873      assert(Cand->Viable &&
8874             "Non-viable built-in candidates are not added to Cands.");
8875      // Generally we only see ambiguities including viable builtin
8876      // operators if overload resolution got screwed up by an
8877      // ambiguous user-defined conversion.
8878      //
8879      // FIXME: It's quite possible for different conversions to see
8880      // different ambiguities, though.
8881      if (!ReportedAmbiguousConversions) {
8882        NoteAmbiguousUserConversions(S, OpLoc, Cand);
8883        ReportedAmbiguousConversions = true;
8884      }
8885
8886      // If this is a viable builtin, print it.
8887      NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
8888    }
8889  }
8890
8891  if (I != E)
8892    S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
8893}
8894
8895// [PossiblyAFunctionType]  -->   [Return]
8896// NonFunctionType --> NonFunctionType
8897// R (A) --> R(A)
8898// R (*)(A) --> R (A)
8899// R (&)(A) --> R (A)
8900// R (S::*)(A) --> R (A)
8901QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8902  QualType Ret = PossiblyAFunctionType;
8903  if (const PointerType *ToTypePtr =
8904    PossiblyAFunctionType->getAs<PointerType>())
8905    Ret = ToTypePtr->getPointeeType();
8906  else if (const ReferenceType *ToTypeRef =
8907    PossiblyAFunctionType->getAs<ReferenceType>())
8908    Ret = ToTypeRef->getPointeeType();
8909  else if (const MemberPointerType *MemTypePtr =
8910    PossiblyAFunctionType->getAs<MemberPointerType>())
8911    Ret = MemTypePtr->getPointeeType();
8912  Ret =
8913    Context.getCanonicalType(Ret).getUnqualifiedType();
8914  return Ret;
8915}
8916
8917// A helper class to help with address of function resolution
8918// - allows us to avoid passing around all those ugly parameters
8919class AddressOfFunctionResolver
8920{
8921  Sema& S;
8922  Expr* SourceExpr;
8923  const QualType& TargetType;
8924  QualType TargetFunctionType; // Extracted function type from target type
8925
8926  bool Complain;
8927  //DeclAccessPair& ResultFunctionAccessPair;
8928  ASTContext& Context;
8929
8930  bool TargetTypeIsNonStaticMemberFunction;
8931  bool FoundNonTemplateFunction;
8932
8933  OverloadExpr::FindResult OvlExprInfo;
8934  OverloadExpr *OvlExpr;
8935  TemplateArgumentListInfo OvlExplicitTemplateArgs;
8936  SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
8937
8938public:
8939  AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8940                            const QualType& TargetType, bool Complain)
8941    : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8942      Complain(Complain), Context(S.getASTContext()),
8943      TargetTypeIsNonStaticMemberFunction(
8944                                    !!TargetType->getAs<MemberPointerType>()),
8945      FoundNonTemplateFunction(false),
8946      OvlExprInfo(OverloadExpr::find(SourceExpr)),
8947      OvlExpr(OvlExprInfo.Expression)
8948  {
8949    ExtractUnqualifiedFunctionTypeFromTargetType();
8950
8951    if (!TargetFunctionType->isFunctionType()) {
8952      if (OvlExpr->hasExplicitTemplateArgs()) {
8953        DeclAccessPair dap;
8954        if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
8955                                            OvlExpr, false, &dap) ) {
8956
8957          if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8958            if (!Method->isStatic()) {
8959              // If the target type is a non-function type and the function
8960              // found is a non-static member function, pretend as if that was
8961              // the target, it's the only possible type to end up with.
8962              TargetTypeIsNonStaticMemberFunction = true;
8963
8964              // And skip adding the function if its not in the proper form.
8965              // We'll diagnose this due to an empty set of functions.
8966              if (!OvlExprInfo.HasFormOfMemberPointer)
8967                return;
8968            }
8969          }
8970
8971          Matches.push_back(std::make_pair(dap,Fn));
8972        }
8973      }
8974      return;
8975    }
8976
8977    if (OvlExpr->hasExplicitTemplateArgs())
8978      OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
8979
8980    if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8981      // C++ [over.over]p4:
8982      //   If more than one function is selected, [...]
8983      if (Matches.size() > 1) {
8984        if (FoundNonTemplateFunction)
8985          EliminateAllTemplateMatches();
8986        else
8987          EliminateAllExceptMostSpecializedTemplate();
8988      }
8989    }
8990  }
8991
8992private:
8993  bool isTargetTypeAFunction() const {
8994    return TargetFunctionType->isFunctionType();
8995  }
8996
8997  // [ToType]     [Return]
8998
8999  // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9000  // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9001  // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9002  void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9003    TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9004  }
9005
9006  // return true if any matching specializations were found
9007  bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9008                                   const DeclAccessPair& CurAccessFunPair) {
9009    if (CXXMethodDecl *Method
9010              = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9011      // Skip non-static function templates when converting to pointer, and
9012      // static when converting to member pointer.
9013      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9014        return false;
9015    }
9016    else if (TargetTypeIsNonStaticMemberFunction)
9017      return false;
9018
9019    // C++ [over.over]p2:
9020    //   If the name is a function template, template argument deduction is
9021    //   done (14.8.2.2), and if the argument deduction succeeds, the
9022    //   resulting template argument list is used to generate a single
9023    //   function template specialization, which is added to the set of
9024    //   overloaded functions considered.
9025    FunctionDecl *Specialization = 0;
9026    TemplateDeductionInfo Info(OvlExpr->getNameLoc());
9027    if (Sema::TemplateDeductionResult Result
9028          = S.DeduceTemplateArguments(FunctionTemplate,
9029                                      &OvlExplicitTemplateArgs,
9030                                      TargetFunctionType, Specialization,
9031                                      Info)) {
9032      // FIXME: make a note of the failed deduction for diagnostics.
9033      (void)Result;
9034      return false;
9035    }
9036
9037    // Template argument deduction ensures that we have an exact match.
9038    // This function template specicalization works.
9039    Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9040    assert(TargetFunctionType
9041                      == Context.getCanonicalType(Specialization->getType()));
9042    Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9043    return true;
9044  }
9045
9046  bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9047                                      const DeclAccessPair& CurAccessFunPair) {
9048    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9049      // Skip non-static functions when converting to pointer, and static
9050      // when converting to member pointer.
9051      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9052        return false;
9053    }
9054    else if (TargetTypeIsNonStaticMemberFunction)
9055      return false;
9056
9057    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9058      if (S.getLangOpts().CUDA)
9059        if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9060          if (S.CheckCUDATarget(Caller, FunDecl))
9061            return false;
9062
9063      QualType ResultTy;
9064      if (Context.hasSameUnqualifiedType(TargetFunctionType,
9065                                         FunDecl->getType()) ||
9066          S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9067                                 ResultTy)) {
9068        Matches.push_back(std::make_pair(CurAccessFunPair,
9069          cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9070        FoundNonTemplateFunction = true;
9071        return true;
9072      }
9073    }
9074
9075    return false;
9076  }
9077
9078  bool FindAllFunctionsThatMatchTargetTypeExactly() {
9079    bool Ret = false;
9080
9081    // If the overload expression doesn't have the form of a pointer to
9082    // member, don't try to convert it to a pointer-to-member type.
9083    if (IsInvalidFormOfPointerToMemberFunction())
9084      return false;
9085
9086    for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9087                               E = OvlExpr->decls_end();
9088         I != E; ++I) {
9089      // Look through any using declarations to find the underlying function.
9090      NamedDecl *Fn = (*I)->getUnderlyingDecl();
9091
9092      // C++ [over.over]p3:
9093      //   Non-member functions and static member functions match
9094      //   targets of type "pointer-to-function" or "reference-to-function."
9095      //   Nonstatic member functions match targets of
9096      //   type "pointer-to-member-function."
9097      // Note that according to DR 247, the containing class does not matter.
9098      if (FunctionTemplateDecl *FunctionTemplate
9099                                        = dyn_cast<FunctionTemplateDecl>(Fn)) {
9100        if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9101          Ret = true;
9102      }
9103      // If we have explicit template arguments supplied, skip non-templates.
9104      else if (!OvlExpr->hasExplicitTemplateArgs() &&
9105               AddMatchingNonTemplateFunction(Fn, I.getPair()))
9106        Ret = true;
9107    }
9108    assert(Ret || Matches.empty());
9109    return Ret;
9110  }
9111
9112  void EliminateAllExceptMostSpecializedTemplate() {
9113    //   [...] and any given function template specialization F1 is
9114    //   eliminated if the set contains a second function template
9115    //   specialization whose function template is more specialized
9116    //   than the function template of F1 according to the partial
9117    //   ordering rules of 14.5.5.2.
9118
9119    // The algorithm specified above is quadratic. We instead use a
9120    // two-pass algorithm (similar to the one used to identify the
9121    // best viable function in an overload set) that identifies the
9122    // best function template (if it exists).
9123
9124    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9125    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9126      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9127
9128    UnresolvedSetIterator Result =
9129      S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9130                           TPOC_Other, 0, SourceExpr->getLocStart(),
9131                           S.PDiag(),
9132                           S.PDiag(diag::err_addr_ovl_ambiguous)
9133                             << Matches[0].second->getDeclName(),
9134                           S.PDiag(diag::note_ovl_candidate)
9135                             << (unsigned) oc_function_template,
9136                           Complain, TargetFunctionType);
9137
9138    if (Result != MatchesCopy.end()) {
9139      // Make it the first and only element
9140      Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9141      Matches[0].second = cast<FunctionDecl>(*Result);
9142      Matches.resize(1);
9143    }
9144  }
9145
9146  void EliminateAllTemplateMatches() {
9147    //   [...] any function template specializations in the set are
9148    //   eliminated if the set also contains a non-template function, [...]
9149    for (unsigned I = 0, N = Matches.size(); I != N; ) {
9150      if (Matches[I].second->getPrimaryTemplate() == 0)
9151        ++I;
9152      else {
9153        Matches[I] = Matches[--N];
9154        Matches.set_size(N);
9155      }
9156    }
9157  }
9158
9159public:
9160  void ComplainNoMatchesFound() const {
9161    assert(Matches.empty());
9162    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9163        << OvlExpr->getName() << TargetFunctionType
9164        << OvlExpr->getSourceRange();
9165    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9166  }
9167
9168  bool IsInvalidFormOfPointerToMemberFunction() const {
9169    return TargetTypeIsNonStaticMemberFunction &&
9170      !OvlExprInfo.HasFormOfMemberPointer;
9171  }
9172
9173  void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9174      // TODO: Should we condition this on whether any functions might
9175      // have matched, or is it more appropriate to do that in callers?
9176      // TODO: a fixit wouldn't hurt.
9177      S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9178        << TargetType << OvlExpr->getSourceRange();
9179  }
9180
9181  void ComplainOfInvalidConversion() const {
9182    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9183      << OvlExpr->getName() << TargetType;
9184  }
9185
9186  void ComplainMultipleMatchesFound() const {
9187    assert(Matches.size() > 1);
9188    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9189      << OvlExpr->getName()
9190      << OvlExpr->getSourceRange();
9191    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9192  }
9193
9194  bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9195
9196  int getNumMatches() const { return Matches.size(); }
9197
9198  FunctionDecl* getMatchingFunctionDecl() const {
9199    if (Matches.size() != 1) return 0;
9200    return Matches[0].second;
9201  }
9202
9203  const DeclAccessPair* getMatchingFunctionAccessPair() const {
9204    if (Matches.size() != 1) return 0;
9205    return &Matches[0].first;
9206  }
9207};
9208
9209/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9210/// an overloaded function (C++ [over.over]), where @p From is an
9211/// expression with overloaded function type and @p ToType is the type
9212/// we're trying to resolve to. For example:
9213///
9214/// @code
9215/// int f(double);
9216/// int f(int);
9217///
9218/// int (*pfd)(double) = f; // selects f(double)
9219/// @endcode
9220///
9221/// This routine returns the resulting FunctionDecl if it could be
9222/// resolved, and NULL otherwise. When @p Complain is true, this
9223/// routine will emit diagnostics if there is an error.
9224FunctionDecl *
9225Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9226                                         QualType TargetType,
9227                                         bool Complain,
9228                                         DeclAccessPair &FoundResult,
9229                                         bool *pHadMultipleCandidates) {
9230  assert(AddressOfExpr->getType() == Context.OverloadTy);
9231
9232  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9233                                     Complain);
9234  int NumMatches = Resolver.getNumMatches();
9235  FunctionDecl* Fn = 0;
9236  if (NumMatches == 0 && Complain) {
9237    if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9238      Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9239    else
9240      Resolver.ComplainNoMatchesFound();
9241  }
9242  else if (NumMatches > 1 && Complain)
9243    Resolver.ComplainMultipleMatchesFound();
9244  else if (NumMatches == 1) {
9245    Fn = Resolver.getMatchingFunctionDecl();
9246    assert(Fn);
9247    FoundResult = *Resolver.getMatchingFunctionAccessPair();
9248    if (Complain)
9249      CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9250  }
9251
9252  if (pHadMultipleCandidates)
9253    *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9254  return Fn;
9255}
9256
9257/// \brief Given an expression that refers to an overloaded function, try to
9258/// resolve that overloaded function expression down to a single function.
9259///
9260/// This routine can only resolve template-ids that refer to a single function
9261/// template, where that template-id refers to a single template whose template
9262/// arguments are either provided by the template-id or have defaults,
9263/// as described in C++0x [temp.arg.explicit]p3.
9264FunctionDecl *
9265Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9266                                                  bool Complain,
9267                                                  DeclAccessPair *FoundResult) {
9268  // C++ [over.over]p1:
9269  //   [...] [Note: any redundant set of parentheses surrounding the
9270  //   overloaded function name is ignored (5.1). ]
9271  // C++ [over.over]p1:
9272  //   [...] The overloaded function name can be preceded by the &
9273  //   operator.
9274
9275  // If we didn't actually find any template-ids, we're done.
9276  if (!ovl->hasExplicitTemplateArgs())
9277    return 0;
9278
9279  TemplateArgumentListInfo ExplicitTemplateArgs;
9280  ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9281
9282  // Look through all of the overloaded functions, searching for one
9283  // whose type matches exactly.
9284  FunctionDecl *Matched = 0;
9285  for (UnresolvedSetIterator I = ovl->decls_begin(),
9286         E = ovl->decls_end(); I != E; ++I) {
9287    // C++0x [temp.arg.explicit]p3:
9288    //   [...] In contexts where deduction is done and fails, or in contexts
9289    //   where deduction is not done, if a template argument list is
9290    //   specified and it, along with any default template arguments,
9291    //   identifies a single function template specialization, then the
9292    //   template-id is an lvalue for the function template specialization.
9293    FunctionTemplateDecl *FunctionTemplate
9294      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9295
9296    // C++ [over.over]p2:
9297    //   If the name is a function template, template argument deduction is
9298    //   done (14.8.2.2), and if the argument deduction succeeds, the
9299    //   resulting template argument list is used to generate a single
9300    //   function template specialization, which is added to the set of
9301    //   overloaded functions considered.
9302    FunctionDecl *Specialization = 0;
9303    TemplateDeductionInfo Info(ovl->getNameLoc());
9304    if (TemplateDeductionResult Result
9305          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9306                                    Specialization, Info)) {
9307      // FIXME: make a note of the failed deduction for diagnostics.
9308      (void)Result;
9309      continue;
9310    }
9311
9312    assert(Specialization && "no specialization and no error?");
9313
9314    // Multiple matches; we can't resolve to a single declaration.
9315    if (Matched) {
9316      if (Complain) {
9317        Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9318          << ovl->getName();
9319        NoteAllOverloadCandidates(ovl);
9320      }
9321      return 0;
9322    }
9323
9324    Matched = Specialization;
9325    if (FoundResult) *FoundResult = I.getPair();
9326  }
9327
9328  return Matched;
9329}
9330
9331
9332
9333
9334// Resolve and fix an overloaded expression that can be resolved
9335// because it identifies a single function template specialization.
9336//
9337// Last three arguments should only be supplied if Complain = true
9338//
9339// Return true if it was logically possible to so resolve the
9340// expression, regardless of whether or not it succeeded.  Always
9341// returns true if 'complain' is set.
9342bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9343                      ExprResult &SrcExpr, bool doFunctionPointerConverion,
9344                   bool complain, const SourceRange& OpRangeForComplaining,
9345                                           QualType DestTypeForComplaining,
9346                                            unsigned DiagIDForComplaining) {
9347  assert(SrcExpr.get()->getType() == Context.OverloadTy);
9348
9349  OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9350
9351  DeclAccessPair found;
9352  ExprResult SingleFunctionExpression;
9353  if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9354                           ovl.Expression, /*complain*/ false, &found)) {
9355    if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9356      SrcExpr = ExprError();
9357      return true;
9358    }
9359
9360    // It is only correct to resolve to an instance method if we're
9361    // resolving a form that's permitted to be a pointer to member.
9362    // Otherwise we'll end up making a bound member expression, which
9363    // is illegal in all the contexts we resolve like this.
9364    if (!ovl.HasFormOfMemberPointer &&
9365        isa<CXXMethodDecl>(fn) &&
9366        cast<CXXMethodDecl>(fn)->isInstance()) {
9367      if (!complain) return false;
9368
9369      Diag(ovl.Expression->getExprLoc(),
9370           diag::err_bound_member_function)
9371        << 0 << ovl.Expression->getSourceRange();
9372
9373      // TODO: I believe we only end up here if there's a mix of
9374      // static and non-static candidates (otherwise the expression
9375      // would have 'bound member' type, not 'overload' type).
9376      // Ideally we would note which candidate was chosen and why
9377      // the static candidates were rejected.
9378      SrcExpr = ExprError();
9379      return true;
9380    }
9381
9382    // Fix the expression to refer to 'fn'.
9383    SingleFunctionExpression =
9384      Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9385
9386    // If desired, do function-to-pointer decay.
9387    if (doFunctionPointerConverion) {
9388      SingleFunctionExpression =
9389        DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9390      if (SingleFunctionExpression.isInvalid()) {
9391        SrcExpr = ExprError();
9392        return true;
9393      }
9394    }
9395  }
9396
9397  if (!SingleFunctionExpression.isUsable()) {
9398    if (complain) {
9399      Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9400        << ovl.Expression->getName()
9401        << DestTypeForComplaining
9402        << OpRangeForComplaining
9403        << ovl.Expression->getQualifierLoc().getSourceRange();
9404      NoteAllOverloadCandidates(SrcExpr.get());
9405
9406      SrcExpr = ExprError();
9407      return true;
9408    }
9409
9410    return false;
9411  }
9412
9413  SrcExpr = SingleFunctionExpression;
9414  return true;
9415}
9416
9417/// \brief Add a single candidate to the overload set.
9418static void AddOverloadedCallCandidate(Sema &S,
9419                                       DeclAccessPair FoundDecl,
9420                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
9421                                       ArrayRef<Expr *> Args,
9422                                       OverloadCandidateSet &CandidateSet,
9423                                       bool PartialOverloading,
9424                                       bool KnownValid) {
9425  NamedDecl *Callee = FoundDecl.getDecl();
9426  if (isa<UsingShadowDecl>(Callee))
9427    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9428
9429  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9430    if (ExplicitTemplateArgs) {
9431      assert(!KnownValid && "Explicit template arguments?");
9432      return;
9433    }
9434    S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9435                           PartialOverloading);
9436    return;
9437  }
9438
9439  if (FunctionTemplateDecl *FuncTemplate
9440      = dyn_cast<FunctionTemplateDecl>(Callee)) {
9441    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9442                                   ExplicitTemplateArgs, Args, CandidateSet);
9443    return;
9444  }
9445
9446  assert(!KnownValid && "unhandled case in overloaded call candidate");
9447}
9448
9449/// \brief Add the overload candidates named by callee and/or found by argument
9450/// dependent lookup to the given overload set.
9451void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9452                                       ArrayRef<Expr *> Args,
9453                                       OverloadCandidateSet &CandidateSet,
9454                                       bool PartialOverloading) {
9455
9456#ifndef NDEBUG
9457  // Verify that ArgumentDependentLookup is consistent with the rules
9458  // in C++0x [basic.lookup.argdep]p3:
9459  //
9460  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9461  //   and let Y be the lookup set produced by argument dependent
9462  //   lookup (defined as follows). If X contains
9463  //
9464  //     -- a declaration of a class member, or
9465  //
9466  //     -- a block-scope function declaration that is not a
9467  //        using-declaration, or
9468  //
9469  //     -- a declaration that is neither a function or a function
9470  //        template
9471  //
9472  //   then Y is empty.
9473
9474  if (ULE->requiresADL()) {
9475    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9476           E = ULE->decls_end(); I != E; ++I) {
9477      assert(!(*I)->getDeclContext()->isRecord());
9478      assert(isa<UsingShadowDecl>(*I) ||
9479             !(*I)->getDeclContext()->isFunctionOrMethod());
9480      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9481    }
9482  }
9483#endif
9484
9485  // It would be nice to avoid this copy.
9486  TemplateArgumentListInfo TABuffer;
9487  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9488  if (ULE->hasExplicitTemplateArgs()) {
9489    ULE->copyTemplateArgumentsInto(TABuffer);
9490    ExplicitTemplateArgs = &TABuffer;
9491  }
9492
9493  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9494         E = ULE->decls_end(); I != E; ++I)
9495    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9496                               CandidateSet, PartialOverloading,
9497                               /*KnownValid*/ true);
9498
9499  if (ULE->requiresADL())
9500    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9501                                         ULE->getExprLoc(),
9502                                         Args, ExplicitTemplateArgs,
9503                                         CandidateSet, PartialOverloading);
9504}
9505
9506/// Attempt to recover from an ill-formed use of a non-dependent name in a
9507/// template, where the non-dependent name was declared after the template
9508/// was defined. This is common in code written for a compilers which do not
9509/// correctly implement two-stage name lookup.
9510///
9511/// Returns true if a viable candidate was found and a diagnostic was issued.
9512static bool
9513DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9514                       const CXXScopeSpec &SS, LookupResult &R,
9515                       TemplateArgumentListInfo *ExplicitTemplateArgs,
9516                       ArrayRef<Expr *> Args) {
9517  if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9518    return false;
9519
9520  for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9521    if (DC->isTransparentContext())
9522      continue;
9523
9524    SemaRef.LookupQualifiedName(R, DC);
9525
9526    if (!R.empty()) {
9527      R.suppressDiagnostics();
9528
9529      if (isa<CXXRecordDecl>(DC)) {
9530        // Don't diagnose names we find in classes; we get much better
9531        // diagnostics for these from DiagnoseEmptyLookup.
9532        R.clear();
9533        return false;
9534      }
9535
9536      OverloadCandidateSet Candidates(FnLoc);
9537      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9538        AddOverloadedCallCandidate(SemaRef, I.getPair(),
9539                                   ExplicitTemplateArgs, Args,
9540                                   Candidates, false, /*KnownValid*/ false);
9541
9542      OverloadCandidateSet::iterator Best;
9543      if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9544        // No viable functions. Don't bother the user with notes for functions
9545        // which don't work and shouldn't be found anyway.
9546        R.clear();
9547        return false;
9548      }
9549
9550      // Find the namespaces where ADL would have looked, and suggest
9551      // declaring the function there instead.
9552      Sema::AssociatedNamespaceSet AssociatedNamespaces;
9553      Sema::AssociatedClassSet AssociatedClasses;
9554      SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
9555                                                 AssociatedNamespaces,
9556                                                 AssociatedClasses);
9557      Sema::AssociatedNamespaceSet SuggestedNamespaces;
9558      DeclContext *Std = SemaRef.getStdNamespace();
9559      for (Sema::AssociatedNamespaceSet::iterator
9560             it = AssociatedNamespaces.begin(),
9561             end = AssociatedNamespaces.end(); it != end; ++it) {
9562        // Never suggest declaring a function within namespace 'std'.
9563        if (Std && Std->Encloses(*it))
9564          continue;
9565
9566        // Never suggest declaring a function within a namespace with a reserved
9567        // name, like __gnu_cxx.
9568        NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9569        if (NS &&
9570            NS->getQualifiedNameAsString().find("__") != std::string::npos)
9571          continue;
9572
9573        SuggestedNamespaces.insert(*it);
9574      }
9575
9576      SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9577        << R.getLookupName();
9578      if (SuggestedNamespaces.empty()) {
9579        SemaRef.Diag(Best->Function->getLocation(),
9580                     diag::note_not_found_by_two_phase_lookup)
9581          << R.getLookupName() << 0;
9582      } else if (SuggestedNamespaces.size() == 1) {
9583        SemaRef.Diag(Best->Function->getLocation(),
9584                     diag::note_not_found_by_two_phase_lookup)
9585          << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
9586      } else {
9587        // FIXME: It would be useful to list the associated namespaces here,
9588        // but the diagnostics infrastructure doesn't provide a way to produce
9589        // a localized representation of a list of items.
9590        SemaRef.Diag(Best->Function->getLocation(),
9591                     diag::note_not_found_by_two_phase_lookup)
9592          << R.getLookupName() << 2;
9593      }
9594
9595      // Try to recover by calling this function.
9596      return true;
9597    }
9598
9599    R.clear();
9600  }
9601
9602  return false;
9603}
9604
9605/// Attempt to recover from ill-formed use of a non-dependent operator in a
9606/// template, where the non-dependent operator was declared after the template
9607/// was defined.
9608///
9609/// Returns true if a viable candidate was found and a diagnostic was issued.
9610static bool
9611DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9612                               SourceLocation OpLoc,
9613                               ArrayRef<Expr *> Args) {
9614  DeclarationName OpName =
9615    SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9616  LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9617  return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9618                                /*ExplicitTemplateArgs=*/0, Args);
9619}
9620
9621namespace {
9622// Callback to limit the allowed keywords and to only accept typo corrections
9623// that are keywords or whose decls refer to functions (or template functions)
9624// that accept the given number of arguments.
9625class RecoveryCallCCC : public CorrectionCandidateCallback {
9626 public:
9627  RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9628      : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9629    WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
9630    WantRemainingKeywords = false;
9631  }
9632
9633  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9634    if (!candidate.getCorrectionDecl())
9635      return candidate.isKeyword();
9636
9637    for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9638           DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9639      FunctionDecl *FD = 0;
9640      NamedDecl *ND = (*DI)->getUnderlyingDecl();
9641      if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9642        FD = FTD->getTemplatedDecl();
9643      if (!HasExplicitTemplateArgs && !FD) {
9644        if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9645          // If the Decl is neither a function nor a template function,
9646          // determine if it is a pointer or reference to a function. If so,
9647          // check against the number of arguments expected for the pointee.
9648          QualType ValType = cast<ValueDecl>(ND)->getType();
9649          if (ValType->isAnyPointerType() || ValType->isReferenceType())
9650            ValType = ValType->getPointeeType();
9651          if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9652            if (FPT->getNumArgs() == NumArgs)
9653              return true;
9654        }
9655      }
9656      if (FD && FD->getNumParams() >= NumArgs &&
9657          FD->getMinRequiredArguments() <= NumArgs)
9658        return true;
9659    }
9660    return false;
9661  }
9662
9663 private:
9664  unsigned NumArgs;
9665  bool HasExplicitTemplateArgs;
9666};
9667
9668// Callback that effectively disabled typo correction
9669class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9670 public:
9671  NoTypoCorrectionCCC() {
9672    WantTypeSpecifiers = false;
9673    WantExpressionKeywords = false;
9674    WantCXXNamedCasts = false;
9675    WantRemainingKeywords = false;
9676  }
9677
9678  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9679    return false;
9680  }
9681};
9682
9683class BuildRecoveryCallExprRAII {
9684  Sema &SemaRef;
9685public:
9686  BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9687    assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9688    SemaRef.IsBuildingRecoveryCallExpr = true;
9689  }
9690
9691  ~BuildRecoveryCallExprRAII() {
9692    SemaRef.IsBuildingRecoveryCallExpr = false;
9693  }
9694};
9695
9696}
9697
9698/// Attempts to recover from a call where no functions were found.
9699///
9700/// Returns true if new candidates were found.
9701static ExprResult
9702BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9703                      UnresolvedLookupExpr *ULE,
9704                      SourceLocation LParenLoc,
9705                      llvm::MutableArrayRef<Expr *> Args,
9706                      SourceLocation RParenLoc,
9707                      bool EmptyLookup, bool AllowTypoCorrection) {
9708  // Do not try to recover if it is already building a recovery call.
9709  // This stops infinite loops for template instantiations like
9710  //
9711  // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9712  // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9713  //
9714  if (SemaRef.IsBuildingRecoveryCallExpr)
9715    return ExprError();
9716  BuildRecoveryCallExprRAII RCE(SemaRef);
9717
9718  CXXScopeSpec SS;
9719  SS.Adopt(ULE->getQualifierLoc());
9720  SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
9721
9722  TemplateArgumentListInfo TABuffer;
9723  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9724  if (ULE->hasExplicitTemplateArgs()) {
9725    ULE->copyTemplateArgumentsInto(TABuffer);
9726    ExplicitTemplateArgs = &TABuffer;
9727  }
9728
9729  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9730                 Sema::LookupOrdinaryName);
9731  RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
9732  NoTypoCorrectionCCC RejectAll;
9733  CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9734      (CorrectionCandidateCallback*)&Validator :
9735      (CorrectionCandidateCallback*)&RejectAll;
9736  if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9737                              ExplicitTemplateArgs, Args) &&
9738      (!EmptyLookup ||
9739       SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
9740                                   ExplicitTemplateArgs, Args)))
9741    return ExprError();
9742
9743  assert(!R.empty() && "lookup results empty despite recovery");
9744
9745  // Build an implicit member call if appropriate.  Just drop the
9746  // casts and such from the call, we don't really care.
9747  ExprResult NewFn = ExprError();
9748  if ((*R.begin())->isCXXClassMember())
9749    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9750                                                    R, ExplicitTemplateArgs);
9751  else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
9752    NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
9753                                        ExplicitTemplateArgs);
9754  else
9755    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9756
9757  if (NewFn.isInvalid())
9758    return ExprError();
9759
9760  // This shouldn't cause an infinite loop because we're giving it
9761  // an expression with viable lookup results, which should never
9762  // end up here.
9763  return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
9764                               MultiExprArg(Args.data(), Args.size()),
9765                               RParenLoc);
9766}
9767
9768/// \brief Constructs and populates an OverloadedCandidateSet from
9769/// the given function.
9770/// \returns true when an the ExprResult output parameter has been set.
9771bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9772                                  UnresolvedLookupExpr *ULE,
9773                                  Expr **Args, unsigned NumArgs,
9774                                  SourceLocation RParenLoc,
9775                                  OverloadCandidateSet *CandidateSet,
9776                                  ExprResult *Result) {
9777#ifndef NDEBUG
9778  if (ULE->requiresADL()) {
9779    // To do ADL, we must have found an unqualified name.
9780    assert(!ULE->getQualifier() && "qualified name with ADL");
9781
9782    // We don't perform ADL for implicit declarations of builtins.
9783    // Verify that this was correctly set up.
9784    FunctionDecl *F;
9785    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9786        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9787        F->getBuiltinID() && F->isImplicit())
9788      llvm_unreachable("performing ADL for builtin");
9789
9790    // We don't perform ADL in C.
9791    assert(getLangOpts().CPlusPlus && "ADL enabled in C");
9792  }
9793#endif
9794
9795  UnbridgedCastsSet UnbridgedCasts;
9796  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9797    *Result = ExprError();
9798    return true;
9799  }
9800
9801  // Add the functions denoted by the callee to the set of candidate
9802  // functions, including those from argument-dependent lookup.
9803  AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9804                              *CandidateSet);
9805
9806  // If we found nothing, try to recover.
9807  // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9808  // out if it fails.
9809  if (CandidateSet->empty()) {
9810    // In Microsoft mode, if we are inside a template class member function then
9811    // create a type dependent CallExpr. The goal is to postpone name lookup
9812    // to instantiation time to be able to search into type dependent base
9813    // classes.
9814    if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
9815        (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
9816      CallExpr *CE = new (Context) CallExpr(Context, Fn,
9817                                            llvm::makeArrayRef(Args, NumArgs),
9818                                            Context.DependentTy, VK_RValue,
9819                                            RParenLoc);
9820      CE->setTypeDependent(true);
9821      *Result = Owned(CE);
9822      return true;
9823    }
9824    return false;
9825  }
9826
9827  UnbridgedCasts.restore();
9828  return false;
9829}
9830
9831/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9832/// the completed call expression. If overload resolution fails, emits
9833/// diagnostics and returns ExprError()
9834static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9835                                           UnresolvedLookupExpr *ULE,
9836                                           SourceLocation LParenLoc,
9837                                           Expr **Args, unsigned NumArgs,
9838                                           SourceLocation RParenLoc,
9839                                           Expr *ExecConfig,
9840                                           OverloadCandidateSet *CandidateSet,
9841                                           OverloadCandidateSet::iterator *Best,
9842                                           OverloadingResult OverloadResult,
9843                                           bool AllowTypoCorrection) {
9844  if (CandidateSet->empty())
9845    return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9846                                 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9847                                 RParenLoc, /*EmptyLookup=*/true,
9848                                 AllowTypoCorrection);
9849
9850  switch (OverloadResult) {
9851  case OR_Success: {
9852    FunctionDecl *FDecl = (*Best)->Function;
9853    SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9854    SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9855    SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9856    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9857    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9858                                         RParenLoc, ExecConfig);
9859  }
9860
9861  case OR_No_Viable_Function: {
9862    // Try to recover by looking for viable functions which the user might
9863    // have meant to call.
9864    ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9865                                  llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9866                                                RParenLoc,
9867                                                /*EmptyLookup=*/false,
9868                                                AllowTypoCorrection);
9869    if (!Recovery.isInvalid())
9870      return Recovery;
9871
9872    SemaRef.Diag(Fn->getLocStart(),
9873         diag::err_ovl_no_viable_function_in_call)
9874      << ULE->getName() << Fn->getSourceRange();
9875    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9876                                 llvm::makeArrayRef(Args, NumArgs));
9877    break;
9878  }
9879
9880  case OR_Ambiguous:
9881    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
9882      << ULE->getName() << Fn->getSourceRange();
9883    CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9884                                 llvm::makeArrayRef(Args, NumArgs));
9885    break;
9886
9887  case OR_Deleted: {
9888    SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9889      << (*Best)->Function->isDeleted()
9890      << ULE->getName()
9891      << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9892      << Fn->getSourceRange();
9893    CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9894                                 llvm::makeArrayRef(Args, NumArgs));
9895
9896    // We emitted an error for the unvailable/deleted function call but keep
9897    // the call in the AST.
9898    FunctionDecl *FDecl = (*Best)->Function;
9899    Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9900    return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9901                                 RParenLoc, ExecConfig);
9902  }
9903  }
9904
9905  // Overload resolution failed.
9906  return ExprError();
9907}
9908
9909/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9910/// (which eventually refers to the declaration Func) and the call
9911/// arguments Args/NumArgs, attempt to resolve the function call down
9912/// to a specific function. If overload resolution succeeds, returns
9913/// the call expression produced by overload resolution.
9914/// Otherwise, emits diagnostics and returns ExprError.
9915ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9916                                         UnresolvedLookupExpr *ULE,
9917                                         SourceLocation LParenLoc,
9918                                         Expr **Args, unsigned NumArgs,
9919                                         SourceLocation RParenLoc,
9920                                         Expr *ExecConfig,
9921                                         bool AllowTypoCorrection) {
9922  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9923  ExprResult result;
9924
9925  if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9926                             &CandidateSet, &result))
9927    return result;
9928
9929  OverloadCandidateSet::iterator Best;
9930  OverloadingResult OverloadResult =
9931      CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9932
9933  return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9934                                  RParenLoc, ExecConfig, &CandidateSet,
9935                                  &Best, OverloadResult,
9936                                  AllowTypoCorrection);
9937}
9938
9939static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
9940  return Functions.size() > 1 ||
9941    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9942}
9943
9944/// \brief Create a unary operation that may resolve to an overloaded
9945/// operator.
9946///
9947/// \param OpLoc The location of the operator itself (e.g., '*').
9948///
9949/// \param OpcIn The UnaryOperator::Opcode that describes this
9950/// operator.
9951///
9952/// \param Fns The set of non-member functions that will be
9953/// considered by overload resolution. The caller needs to build this
9954/// set based on the context using, e.g.,
9955/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9956/// set should not contain any member functions; those will be added
9957/// by CreateOverloadedUnaryOp().
9958///
9959/// \param Input The input argument.
9960ExprResult
9961Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9962                              const UnresolvedSetImpl &Fns,
9963                              Expr *Input) {
9964  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
9965
9966  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9967  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9968  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9969  // TODO: provide better source location info.
9970  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
9971
9972  if (checkPlaceholderForOverload(*this, Input))
9973    return ExprError();
9974
9975  Expr *Args[2] = { Input, 0 };
9976  unsigned NumArgs = 1;
9977
9978  // For post-increment and post-decrement, add the implicit '0' as
9979  // the second argument, so that we know this is a post-increment or
9980  // post-decrement.
9981  if (Opc == UO_PostInc || Opc == UO_PostDec) {
9982    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
9983    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9984                                     SourceLocation());
9985    NumArgs = 2;
9986  }
9987
9988  if (Input->isTypeDependent()) {
9989    if (Fns.empty())
9990      return Owned(new (Context) UnaryOperator(Input,
9991                                               Opc,
9992                                               Context.DependentTy,
9993                                               VK_RValue, OK_Ordinary,
9994                                               OpLoc));
9995
9996    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
9997    UnresolvedLookupExpr *Fn
9998      = UnresolvedLookupExpr::Create(Context, NamingClass,
9999                                     NestedNameSpecifierLoc(), OpNameInfo,
10000                                     /*ADL*/ true, IsOverloaded(Fns),
10001                                     Fns.begin(), Fns.end());
10002    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
10003                                              llvm::makeArrayRef(Args, NumArgs),
10004                                                   Context.DependentTy,
10005                                                   VK_RValue,
10006                                                   OpLoc, false));
10007  }
10008
10009  // Build an empty overload set.
10010  OverloadCandidateSet CandidateSet(OpLoc);
10011
10012  // Add the candidates from the given function set.
10013  AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10014                        false);
10015
10016  // Add operator candidates that are member functions.
10017  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10018
10019  // Add candidates from ADL.
10020  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10021                                       OpLoc, llvm::makeArrayRef(Args, NumArgs),
10022                                       /*ExplicitTemplateArgs*/ 0,
10023                                       CandidateSet);
10024
10025  // Add builtin operator candidates.
10026  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10027
10028  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10029
10030  // Perform overload resolution.
10031  OverloadCandidateSet::iterator Best;
10032  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10033  case OR_Success: {
10034    // We found a built-in operator or an overloaded operator.
10035    FunctionDecl *FnDecl = Best->Function;
10036
10037    if (FnDecl) {
10038      // We matched an overloaded operator. Build a call to that
10039      // operator.
10040
10041      MarkFunctionReferenced(OpLoc, FnDecl);
10042
10043      // Convert the arguments.
10044      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10045        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
10046
10047        ExprResult InputRes =
10048          PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10049                                              Best->FoundDecl, Method);
10050        if (InputRes.isInvalid())
10051          return ExprError();
10052        Input = InputRes.take();
10053      } else {
10054        // Convert the arguments.
10055        ExprResult InputInit
10056          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10057                                                      Context,
10058                                                      FnDecl->getParamDecl(0)),
10059                                      SourceLocation(),
10060                                      Input);
10061        if (InputInit.isInvalid())
10062          return ExprError();
10063        Input = InputInit.take();
10064      }
10065
10066      DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10067
10068      // Determine the result type.
10069      QualType ResultTy = FnDecl->getResultType();
10070      ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10071      ResultTy = ResultTy.getNonLValueExprType(Context);
10072
10073      // Build the actual expression node.
10074      ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10075                                                HadMultipleCandidates, OpLoc);
10076      if (FnExpr.isInvalid())
10077        return ExprError();
10078
10079      Args[0] = Input;
10080      CallExpr *TheCall =
10081        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10082                                          llvm::makeArrayRef(Args, NumArgs),
10083                                          ResultTy, VK, OpLoc, false);
10084
10085      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10086                              FnDecl))
10087        return ExprError();
10088
10089      return MaybeBindToTemporary(TheCall);
10090    } else {
10091      // We matched a built-in operator. Convert the arguments, then
10092      // break out so that we will build the appropriate built-in
10093      // operator node.
10094      ExprResult InputRes =
10095        PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10096                                  Best->Conversions[0], AA_Passing);
10097      if (InputRes.isInvalid())
10098        return ExprError();
10099      Input = InputRes.take();
10100      break;
10101    }
10102  }
10103
10104  case OR_No_Viable_Function:
10105    // This is an erroneous use of an operator which can be overloaded by
10106    // a non-member function. Check for non-member operators which were
10107    // defined too late to be candidates.
10108    if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10109                                       llvm::makeArrayRef(Args, NumArgs)))
10110      // FIXME: Recover by calling the found function.
10111      return ExprError();
10112
10113    // No viable function; fall through to handling this as a
10114    // built-in operator, which will produce an error message for us.
10115    break;
10116
10117  case OR_Ambiguous:
10118    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10119        << UnaryOperator::getOpcodeStr(Opc)
10120        << Input->getType()
10121        << Input->getSourceRange();
10122    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10123                                llvm::makeArrayRef(Args, NumArgs),
10124                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10125    return ExprError();
10126
10127  case OR_Deleted:
10128    Diag(OpLoc, diag::err_ovl_deleted_oper)
10129      << Best->Function->isDeleted()
10130      << UnaryOperator::getOpcodeStr(Opc)
10131      << getDeletedOrUnavailableSuffix(Best->Function)
10132      << Input->getSourceRange();
10133    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10134                                llvm::makeArrayRef(Args, NumArgs),
10135                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
10136    return ExprError();
10137  }
10138
10139  // Either we found no viable overloaded operator or we matched a
10140  // built-in operator. In either case, fall through to trying to
10141  // build a built-in operation.
10142  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10143}
10144
10145/// \brief Create a binary operation that may resolve to an overloaded
10146/// operator.
10147///
10148/// \param OpLoc The location of the operator itself (e.g., '+').
10149///
10150/// \param OpcIn The BinaryOperator::Opcode that describes this
10151/// operator.
10152///
10153/// \param Fns The set of non-member functions that will be
10154/// considered by overload resolution. The caller needs to build this
10155/// set based on the context using, e.g.,
10156/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10157/// set should not contain any member functions; those will be added
10158/// by CreateOverloadedBinOp().
10159///
10160/// \param LHS Left-hand argument.
10161/// \param RHS Right-hand argument.
10162ExprResult
10163Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10164                            unsigned OpcIn,
10165                            const UnresolvedSetImpl &Fns,
10166                            Expr *LHS, Expr *RHS) {
10167  Expr *Args[2] = { LHS, RHS };
10168  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
10169
10170  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10171  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10172  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10173
10174  // If either side is type-dependent, create an appropriate dependent
10175  // expression.
10176  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10177    if (Fns.empty()) {
10178      // If there are no functions to store, just build a dependent
10179      // BinaryOperator or CompoundAssignment.
10180      if (Opc <= BO_Assign || Opc > BO_OrAssign)
10181        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
10182                                                  Context.DependentTy,
10183                                                  VK_RValue, OK_Ordinary,
10184                                                  OpLoc,
10185                                                  FPFeatures.fp_contract));
10186
10187      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10188                                                        Context.DependentTy,
10189                                                        VK_LValue,
10190                                                        OK_Ordinary,
10191                                                        Context.DependentTy,
10192                                                        Context.DependentTy,
10193                                                        OpLoc,
10194                                                        FPFeatures.fp_contract));
10195    }
10196
10197    // FIXME: save results of ADL from here?
10198    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10199    // TODO: provide better source location info in DNLoc component.
10200    DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10201    UnresolvedLookupExpr *Fn
10202      = UnresolvedLookupExpr::Create(Context, NamingClass,
10203                                     NestedNameSpecifierLoc(), OpNameInfo,
10204                                     /*ADL*/ true, IsOverloaded(Fns),
10205                                     Fns.begin(), Fns.end());
10206    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10207                                                Context.DependentTy, VK_RValue,
10208                                                OpLoc, FPFeatures.fp_contract));
10209  }
10210
10211  // Always do placeholder-like conversions on the RHS.
10212  if (checkPlaceholderForOverload(*this, Args[1]))
10213    return ExprError();
10214
10215  // Do placeholder-like conversion on the LHS; note that we should
10216  // not get here with a PseudoObject LHS.
10217  assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10218  if (checkPlaceholderForOverload(*this, Args[0]))
10219    return ExprError();
10220
10221  // If this is the assignment operator, we only perform overload resolution
10222  // if the left-hand side is a class or enumeration type. This is actually
10223  // a hack. The standard requires that we do overload resolution between the
10224  // various built-in candidates, but as DR507 points out, this can lead to
10225  // problems. So we do it this way, which pretty much follows what GCC does.
10226  // Note that we go the traditional code path for compound assignment forms.
10227  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10228    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10229
10230  // If this is the .* operator, which is not overloadable, just
10231  // create a built-in binary operator.
10232  if (Opc == BO_PtrMemD)
10233    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10234
10235  // Build an empty overload set.
10236  OverloadCandidateSet CandidateSet(OpLoc);
10237
10238  // Add the candidates from the given function set.
10239  AddFunctionCandidates(Fns, Args, CandidateSet, false);
10240
10241  // Add operator candidates that are member functions.
10242  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10243
10244  // Add candidates from ADL.
10245  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10246                                       OpLoc, Args,
10247                                       /*ExplicitTemplateArgs*/ 0,
10248                                       CandidateSet);
10249
10250  // Add builtin operator candidates.
10251  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10252
10253  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10254
10255  // Perform overload resolution.
10256  OverloadCandidateSet::iterator Best;
10257  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10258    case OR_Success: {
10259      // We found a built-in operator or an overloaded operator.
10260      FunctionDecl *FnDecl = Best->Function;
10261
10262      if (FnDecl) {
10263        // We matched an overloaded operator. Build a call to that
10264        // operator.
10265
10266        MarkFunctionReferenced(OpLoc, FnDecl);
10267
10268        // Convert the arguments.
10269        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10270          // Best->Access is only meaningful for class members.
10271          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10272
10273          ExprResult Arg1 =
10274            PerformCopyInitialization(
10275              InitializedEntity::InitializeParameter(Context,
10276                                                     FnDecl->getParamDecl(0)),
10277              SourceLocation(), Owned(Args[1]));
10278          if (Arg1.isInvalid())
10279            return ExprError();
10280
10281          ExprResult Arg0 =
10282            PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10283                                                Best->FoundDecl, Method);
10284          if (Arg0.isInvalid())
10285            return ExprError();
10286          Args[0] = Arg0.takeAs<Expr>();
10287          Args[1] = RHS = Arg1.takeAs<Expr>();
10288        } else {
10289          // Convert the arguments.
10290          ExprResult Arg0 = PerformCopyInitialization(
10291            InitializedEntity::InitializeParameter(Context,
10292                                                   FnDecl->getParamDecl(0)),
10293            SourceLocation(), Owned(Args[0]));
10294          if (Arg0.isInvalid())
10295            return ExprError();
10296
10297          ExprResult Arg1 =
10298            PerformCopyInitialization(
10299              InitializedEntity::InitializeParameter(Context,
10300                                                     FnDecl->getParamDecl(1)),
10301              SourceLocation(), Owned(Args[1]));
10302          if (Arg1.isInvalid())
10303            return ExprError();
10304          Args[0] = LHS = Arg0.takeAs<Expr>();
10305          Args[1] = RHS = Arg1.takeAs<Expr>();
10306        }
10307
10308        DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10309
10310        // Determine the result type.
10311        QualType ResultTy = FnDecl->getResultType();
10312        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10313        ResultTy = ResultTy.getNonLValueExprType(Context);
10314
10315        // Build the actual expression node.
10316        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10317                                                  HadMultipleCandidates, OpLoc);
10318        if (FnExpr.isInvalid())
10319          return ExprError();
10320
10321        CXXOperatorCallExpr *TheCall =
10322          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10323                                            Args, ResultTy, VK, OpLoc,
10324                                            FPFeatures.fp_contract);
10325
10326        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10327                                FnDecl))
10328          return ExprError();
10329
10330        return MaybeBindToTemporary(TheCall);
10331      } else {
10332        // We matched a built-in operator. Convert the arguments, then
10333        // break out so that we will build the appropriate built-in
10334        // operator node.
10335        ExprResult ArgsRes0 =
10336          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10337                                    Best->Conversions[0], AA_Passing);
10338        if (ArgsRes0.isInvalid())
10339          return ExprError();
10340        Args[0] = ArgsRes0.take();
10341
10342        ExprResult ArgsRes1 =
10343          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10344                                    Best->Conversions[1], AA_Passing);
10345        if (ArgsRes1.isInvalid())
10346          return ExprError();
10347        Args[1] = ArgsRes1.take();
10348        break;
10349      }
10350    }
10351
10352    case OR_No_Viable_Function: {
10353      // C++ [over.match.oper]p9:
10354      //   If the operator is the operator , [...] and there are no
10355      //   viable functions, then the operator is assumed to be the
10356      //   built-in operator and interpreted according to clause 5.
10357      if (Opc == BO_Comma)
10358        break;
10359
10360      // For class as left operand for assignment or compound assigment
10361      // operator do not fall through to handling in built-in, but report that
10362      // no overloaded assignment operator found
10363      ExprResult Result = ExprError();
10364      if (Args[0]->getType()->isRecordType() &&
10365          Opc >= BO_Assign && Opc <= BO_OrAssign) {
10366        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10367             << BinaryOperator::getOpcodeStr(Opc)
10368             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10369      } else {
10370        // This is an erroneous use of an operator which can be overloaded by
10371        // a non-member function. Check for non-member operators which were
10372        // defined too late to be candidates.
10373        if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10374          // FIXME: Recover by calling the found function.
10375          return ExprError();
10376
10377        // No viable function; try to create a built-in operation, which will
10378        // produce an error. Then, show the non-viable candidates.
10379        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10380      }
10381      assert(Result.isInvalid() &&
10382             "C++ binary operator overloading is missing candidates!");
10383      if (Result.isInvalid())
10384        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10385                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
10386      return Result;
10387    }
10388
10389    case OR_Ambiguous:
10390      Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10391          << BinaryOperator::getOpcodeStr(Opc)
10392          << Args[0]->getType() << Args[1]->getType()
10393          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10394      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10395                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10396      return ExprError();
10397
10398    case OR_Deleted:
10399      if (isImplicitlyDeleted(Best->Function)) {
10400        CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10401        Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10402          << Context.getRecordType(Method->getParent())
10403          << getSpecialMember(Method);
10404
10405        // The user probably meant to call this special member. Just
10406        // explain why it's deleted.
10407        NoteDeletedFunction(Method);
10408        return ExprError();
10409      } else {
10410        Diag(OpLoc, diag::err_ovl_deleted_oper)
10411          << Best->Function->isDeleted()
10412          << BinaryOperator::getOpcodeStr(Opc)
10413          << getDeletedOrUnavailableSuffix(Best->Function)
10414          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10415      }
10416      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10417                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
10418      return ExprError();
10419  }
10420
10421  // We matched a built-in operator; build it.
10422  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10423}
10424
10425ExprResult
10426Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10427                                         SourceLocation RLoc,
10428                                         Expr *Base, Expr *Idx) {
10429  Expr *Args[2] = { Base, Idx };
10430  DeclarationName OpName =
10431      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10432
10433  // If either side is type-dependent, create an appropriate dependent
10434  // expression.
10435  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10436
10437    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10438    // CHECKME: no 'operator' keyword?
10439    DeclarationNameInfo OpNameInfo(OpName, LLoc);
10440    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10441    UnresolvedLookupExpr *Fn
10442      = UnresolvedLookupExpr::Create(Context, NamingClass,
10443                                     NestedNameSpecifierLoc(), OpNameInfo,
10444                                     /*ADL*/ true, /*Overloaded*/ false,
10445                                     UnresolvedSetIterator(),
10446                                     UnresolvedSetIterator());
10447    // Can't add any actual overloads yet
10448
10449    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10450                                                   Args,
10451                                                   Context.DependentTy,
10452                                                   VK_RValue,
10453                                                   RLoc, false));
10454  }
10455
10456  // Handle placeholders on both operands.
10457  if (checkPlaceholderForOverload(*this, Args[0]))
10458    return ExprError();
10459  if (checkPlaceholderForOverload(*this, Args[1]))
10460    return ExprError();
10461
10462  // Build an empty overload set.
10463  OverloadCandidateSet CandidateSet(LLoc);
10464
10465  // Subscript can only be overloaded as a member function.
10466
10467  // Add operator candidates that are member functions.
10468  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10469
10470  // Add builtin operator candidates.
10471  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10472
10473  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10474
10475  // Perform overload resolution.
10476  OverloadCandidateSet::iterator Best;
10477  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10478    case OR_Success: {
10479      // We found a built-in operator or an overloaded operator.
10480      FunctionDecl *FnDecl = Best->Function;
10481
10482      if (FnDecl) {
10483        // We matched an overloaded operator. Build a call to that
10484        // operator.
10485
10486        MarkFunctionReferenced(LLoc, FnDecl);
10487
10488        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10489        DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
10490
10491        // Convert the arguments.
10492        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10493        ExprResult Arg0 =
10494          PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10495                                              Best->FoundDecl, Method);
10496        if (Arg0.isInvalid())
10497          return ExprError();
10498        Args[0] = Arg0.take();
10499
10500        // Convert the arguments.
10501        ExprResult InputInit
10502          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10503                                                      Context,
10504                                                      FnDecl->getParamDecl(0)),
10505                                      SourceLocation(),
10506                                      Owned(Args[1]));
10507        if (InputInit.isInvalid())
10508          return ExprError();
10509
10510        Args[1] = InputInit.takeAs<Expr>();
10511
10512        // Determine the result type
10513        QualType ResultTy = FnDecl->getResultType();
10514        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10515        ResultTy = ResultTy.getNonLValueExprType(Context);
10516
10517        // Build the actual expression node.
10518        DeclarationNameInfo OpLocInfo(OpName, LLoc);
10519        OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10520        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10521                                                  HadMultipleCandidates,
10522                                                  OpLocInfo.getLoc(),
10523                                                  OpLocInfo.getInfo());
10524        if (FnExpr.isInvalid())
10525          return ExprError();
10526
10527        CXXOperatorCallExpr *TheCall =
10528          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10529                                            FnExpr.take(), Args,
10530                                            ResultTy, VK, RLoc,
10531                                            false);
10532
10533        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10534                                FnDecl))
10535          return ExprError();
10536
10537        return MaybeBindToTemporary(TheCall);
10538      } else {
10539        // We matched a built-in operator. Convert the arguments, then
10540        // break out so that we will build the appropriate built-in
10541        // operator node.
10542        ExprResult ArgsRes0 =
10543          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10544                                    Best->Conversions[0], AA_Passing);
10545        if (ArgsRes0.isInvalid())
10546          return ExprError();
10547        Args[0] = ArgsRes0.take();
10548
10549        ExprResult ArgsRes1 =
10550          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10551                                    Best->Conversions[1], AA_Passing);
10552        if (ArgsRes1.isInvalid())
10553          return ExprError();
10554        Args[1] = ArgsRes1.take();
10555
10556        break;
10557      }
10558    }
10559
10560    case OR_No_Viable_Function: {
10561      if (CandidateSet.empty())
10562        Diag(LLoc, diag::err_ovl_no_oper)
10563          << Args[0]->getType() << /*subscript*/ 0
10564          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10565      else
10566        Diag(LLoc, diag::err_ovl_no_viable_subscript)
10567          << Args[0]->getType()
10568          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10569      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10570                                  "[]", LLoc);
10571      return ExprError();
10572    }
10573
10574    case OR_Ambiguous:
10575      Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10576          << "[]"
10577          << Args[0]->getType() << Args[1]->getType()
10578          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10579      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10580                                  "[]", LLoc);
10581      return ExprError();
10582
10583    case OR_Deleted:
10584      Diag(LLoc, diag::err_ovl_deleted_oper)
10585        << Best->Function->isDeleted() << "[]"
10586        << getDeletedOrUnavailableSuffix(Best->Function)
10587        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10588      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10589                                  "[]", LLoc);
10590      return ExprError();
10591    }
10592
10593  // We matched a built-in operator; build it.
10594  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10595}
10596
10597/// BuildCallToMemberFunction - Build a call to a member
10598/// function. MemExpr is the expression that refers to the member
10599/// function (and includes the object parameter), Args/NumArgs are the
10600/// arguments to the function call (not including the object
10601/// parameter). The caller needs to validate that the member
10602/// expression refers to a non-static member function or an overloaded
10603/// member function.
10604ExprResult
10605Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10606                                SourceLocation LParenLoc, Expr **Args,
10607                                unsigned NumArgs, SourceLocation RParenLoc) {
10608  assert(MemExprE->getType() == Context.BoundMemberTy ||
10609         MemExprE->getType() == Context.OverloadTy);
10610
10611  // Dig out the member expression. This holds both the object
10612  // argument and the member function we're referring to.
10613  Expr *NakedMemExpr = MemExprE->IgnoreParens();
10614
10615  // Determine whether this is a call to a pointer-to-member function.
10616  if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10617    assert(op->getType() == Context.BoundMemberTy);
10618    assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10619
10620    QualType fnType =
10621      op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10622
10623    const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10624    QualType resultType = proto->getCallResultType(Context);
10625    ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10626
10627    // Check that the object type isn't more qualified than the
10628    // member function we're calling.
10629    Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10630
10631    QualType objectType = op->getLHS()->getType();
10632    if (op->getOpcode() == BO_PtrMemI)
10633      objectType = objectType->castAs<PointerType>()->getPointeeType();
10634    Qualifiers objectQuals = objectType.getQualifiers();
10635
10636    Qualifiers difference = objectQuals - funcQuals;
10637    difference.removeObjCGCAttr();
10638    difference.removeAddressSpace();
10639    if (difference) {
10640      std::string qualsString = difference.getAsString();
10641      Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10642        << fnType.getUnqualifiedType()
10643        << qualsString
10644        << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10645    }
10646
10647    CXXMemberCallExpr *call
10648      = new (Context) CXXMemberCallExpr(Context, MemExprE,
10649                                        llvm::makeArrayRef(Args, NumArgs),
10650                                        resultType, valueKind, RParenLoc);
10651
10652    if (CheckCallReturnType(proto->getResultType(),
10653                            op->getRHS()->getLocStart(),
10654                            call, 0))
10655      return ExprError();
10656
10657    if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10658      return ExprError();
10659
10660    return MaybeBindToTemporary(call);
10661  }
10662
10663  UnbridgedCastsSet UnbridgedCasts;
10664  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10665    return ExprError();
10666
10667  MemberExpr *MemExpr;
10668  CXXMethodDecl *Method = 0;
10669  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
10670  NestedNameSpecifier *Qualifier = 0;
10671  if (isa<MemberExpr>(NakedMemExpr)) {
10672    MemExpr = cast<MemberExpr>(NakedMemExpr);
10673    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
10674    FoundDecl = MemExpr->getFoundDecl();
10675    Qualifier = MemExpr->getQualifier();
10676    UnbridgedCasts.restore();
10677  } else {
10678    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
10679    Qualifier = UnresExpr->getQualifier();
10680
10681    QualType ObjectType = UnresExpr->getBaseType();
10682    Expr::Classification ObjectClassification
10683      = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10684                            : UnresExpr->getBase()->Classify(Context);
10685
10686    // Add overload candidates
10687    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
10688
10689    // FIXME: avoid copy.
10690    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10691    if (UnresExpr->hasExplicitTemplateArgs()) {
10692      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10693      TemplateArgs = &TemplateArgsBuffer;
10694    }
10695
10696    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10697           E = UnresExpr->decls_end(); I != E; ++I) {
10698
10699      NamedDecl *Func = *I;
10700      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10701      if (isa<UsingShadowDecl>(Func))
10702        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10703
10704
10705      // Microsoft supports direct constructor calls.
10706      if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
10707        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10708                             llvm::makeArrayRef(Args, NumArgs), CandidateSet);
10709      } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
10710        // If explicit template arguments were provided, we can't call a
10711        // non-template member function.
10712        if (TemplateArgs)
10713          continue;
10714
10715        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
10716                           ObjectClassification,
10717                           llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10718                           /*SuppressUserConversions=*/false);
10719      } else {
10720        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
10721                                   I.getPair(), ActingDC, TemplateArgs,
10722                                   ObjectType,  ObjectClassification,
10723                                   llvm::makeArrayRef(Args, NumArgs),
10724                                   CandidateSet,
10725                                   /*SuppressUsedConversions=*/false);
10726      }
10727    }
10728
10729    DeclarationName DeclName = UnresExpr->getMemberName();
10730
10731    UnbridgedCasts.restore();
10732
10733    OverloadCandidateSet::iterator Best;
10734    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
10735                                            Best)) {
10736    case OR_Success:
10737      Method = cast<CXXMethodDecl>(Best->Function);
10738      MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
10739      FoundDecl = Best->FoundDecl;
10740      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
10741      DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
10742      break;
10743
10744    case OR_No_Viable_Function:
10745      Diag(UnresExpr->getMemberLoc(),
10746           diag::err_ovl_no_viable_member_function_in_call)
10747        << DeclName << MemExprE->getSourceRange();
10748      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10749                                  llvm::makeArrayRef(Args, NumArgs));
10750      // FIXME: Leaking incoming expressions!
10751      return ExprError();
10752
10753    case OR_Ambiguous:
10754      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
10755        << DeclName << MemExprE->getSourceRange();
10756      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10757                                  llvm::makeArrayRef(Args, NumArgs));
10758      // FIXME: Leaking incoming expressions!
10759      return ExprError();
10760
10761    case OR_Deleted:
10762      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
10763        << Best->Function->isDeleted()
10764        << DeclName
10765        << getDeletedOrUnavailableSuffix(Best->Function)
10766        << MemExprE->getSourceRange();
10767      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10768                                  llvm::makeArrayRef(Args, NumArgs));
10769      // FIXME: Leaking incoming expressions!
10770      return ExprError();
10771    }
10772
10773    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
10774
10775    // If overload resolution picked a static member, build a
10776    // non-member call based on that function.
10777    if (Method->isStatic()) {
10778      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10779                                   Args, NumArgs, RParenLoc);
10780    }
10781
10782    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
10783  }
10784
10785  QualType ResultType = Method->getResultType();
10786  ExprValueKind VK = Expr::getValueKindForType(ResultType);
10787  ResultType = ResultType.getNonLValueExprType(Context);
10788
10789  assert(Method && "Member call to something that isn't a method?");
10790  CXXMemberCallExpr *TheCall =
10791    new (Context) CXXMemberCallExpr(Context, MemExprE,
10792                                    llvm::makeArrayRef(Args, NumArgs),
10793                                    ResultType, VK, RParenLoc);
10794
10795  // Check for a valid return type.
10796  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
10797                          TheCall, Method))
10798    return ExprError();
10799
10800  // Convert the object argument (for a non-static member function call).
10801  // We only need to do this if there was actually an overload; otherwise
10802  // it was done at lookup.
10803  if (!Method->isStatic()) {
10804    ExprResult ObjectArg =
10805      PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10806                                          FoundDecl, Method);
10807    if (ObjectArg.isInvalid())
10808      return ExprError();
10809    MemExpr->setBase(ObjectArg.take());
10810  }
10811
10812  // Convert the rest of the arguments
10813  const FunctionProtoType *Proto =
10814    Method->getType()->getAs<FunctionProtoType>();
10815  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
10816                              RParenLoc))
10817    return ExprError();
10818
10819  DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10820
10821  if (CheckFunctionCall(Method, TheCall, Proto))
10822    return ExprError();
10823
10824  if ((isa<CXXConstructorDecl>(CurContext) ||
10825       isa<CXXDestructorDecl>(CurContext)) &&
10826      TheCall->getMethodDecl()->isPure()) {
10827    const CXXMethodDecl *MD = TheCall->getMethodDecl();
10828
10829    if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
10830      Diag(MemExpr->getLocStart(),
10831           diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10832        << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10833        << MD->getParent()->getDeclName();
10834
10835      Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
10836    }
10837  }
10838  return MaybeBindToTemporary(TheCall);
10839}
10840
10841/// BuildCallToObjectOfClassType - Build a call to an object of class
10842/// type (C++ [over.call.object]), which can end up invoking an
10843/// overloaded function call operator (@c operator()) or performing a
10844/// user-defined conversion on the object argument.
10845ExprResult
10846Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
10847                                   SourceLocation LParenLoc,
10848                                   Expr **Args, unsigned NumArgs,
10849                                   SourceLocation RParenLoc) {
10850  if (checkPlaceholderForOverload(*this, Obj))
10851    return ExprError();
10852  ExprResult Object = Owned(Obj);
10853
10854  UnbridgedCastsSet UnbridgedCasts;
10855  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10856    return ExprError();
10857
10858  assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10859  const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
10860
10861  // C++ [over.call.object]p1:
10862  //  If the primary-expression E in the function call syntax
10863  //  evaluates to a class object of type "cv T", then the set of
10864  //  candidate functions includes at least the function call
10865  //  operators of T. The function call operators of T are obtained by
10866  //  ordinary lookup of the name operator() in the context of
10867  //  (E).operator().
10868  OverloadCandidateSet CandidateSet(LParenLoc);
10869  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
10870
10871  if (RequireCompleteType(LParenLoc, Object.get()->getType(),
10872                          diag::err_incomplete_object_call, Object.get()))
10873    return true;
10874
10875  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10876  LookupQualifiedName(R, Record->getDecl());
10877  R.suppressDiagnostics();
10878
10879  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10880       Oper != OperEnd; ++Oper) {
10881    AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10882                       Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
10883                       /*SuppressUserConversions=*/ false);
10884  }
10885
10886  // C++ [over.call.object]p2:
10887  //   In addition, for each (non-explicit in C++0x) conversion function
10888  //   declared in T of the form
10889  //
10890  //        operator conversion-type-id () cv-qualifier;
10891  //
10892  //   where cv-qualifier is the same cv-qualification as, or a
10893  //   greater cv-qualification than, cv, and where conversion-type-id
10894  //   denotes the type "pointer to function of (P1,...,Pn) returning
10895  //   R", or the type "reference to pointer to function of
10896  //   (P1,...,Pn) returning R", or the type "reference to function
10897  //   of (P1,...,Pn) returning R", a surrogate call function [...]
10898  //   is also considered as a candidate function. Similarly,
10899  //   surrogate call functions are added to the set of candidate
10900  //   functions for each conversion function declared in an
10901  //   accessible base class provided the function is not hidden
10902  //   within T by another intervening declaration.
10903  std::pair<CXXRecordDecl::conversion_iterator,
10904            CXXRecordDecl::conversion_iterator> Conversions
10905    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
10906  for (CXXRecordDecl::conversion_iterator
10907         I = Conversions.first, E = Conversions.second; I != E; ++I) {
10908    NamedDecl *D = *I;
10909    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10910    if (isa<UsingShadowDecl>(D))
10911      D = cast<UsingShadowDecl>(D)->getTargetDecl();
10912
10913    // Skip over templated conversion functions; they aren't
10914    // surrogates.
10915    if (isa<FunctionTemplateDecl>(D))
10916      continue;
10917
10918    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
10919    if (!Conv->isExplicit()) {
10920      // Strip the reference type (if any) and then the pointer type (if
10921      // any) to get down to what might be a function type.
10922      QualType ConvType = Conv->getConversionType().getNonReferenceType();
10923      if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10924        ConvType = ConvPtrType->getPointeeType();
10925
10926      if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10927      {
10928        AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10929                              Object.get(), llvm::makeArrayRef(Args, NumArgs),
10930                              CandidateSet);
10931      }
10932    }
10933  }
10934
10935  bool HadMultipleCandidates = (CandidateSet.size() > 1);
10936
10937  // Perform overload resolution.
10938  OverloadCandidateSet::iterator Best;
10939  switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
10940                             Best)) {
10941  case OR_Success:
10942    // Overload resolution succeeded; we'll build the appropriate call
10943    // below.
10944    break;
10945
10946  case OR_No_Viable_Function:
10947    if (CandidateSet.empty())
10948      Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
10949        << Object.get()->getType() << /*call*/ 1
10950        << Object.get()->getSourceRange();
10951    else
10952      Diag(Object.get()->getLocStart(),
10953           diag::err_ovl_no_viable_object_call)
10954        << Object.get()->getType() << Object.get()->getSourceRange();
10955    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10956                                llvm::makeArrayRef(Args, NumArgs));
10957    break;
10958
10959  case OR_Ambiguous:
10960    Diag(Object.get()->getLocStart(),
10961         diag::err_ovl_ambiguous_object_call)
10962      << Object.get()->getType() << Object.get()->getSourceRange();
10963    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10964                                llvm::makeArrayRef(Args, NumArgs));
10965    break;
10966
10967  case OR_Deleted:
10968    Diag(Object.get()->getLocStart(),
10969         diag::err_ovl_deleted_object_call)
10970      << Best->Function->isDeleted()
10971      << Object.get()->getType()
10972      << getDeletedOrUnavailableSuffix(Best->Function)
10973      << Object.get()->getSourceRange();
10974    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10975                                llvm::makeArrayRef(Args, NumArgs));
10976    break;
10977  }
10978
10979  if (Best == CandidateSet.end())
10980    return true;
10981
10982  UnbridgedCasts.restore();
10983
10984  if (Best->Function == 0) {
10985    // Since there is no function declaration, this is one of the
10986    // surrogate candidates. Dig out the conversion function.
10987    CXXConversionDecl *Conv
10988      = cast<CXXConversionDecl>(
10989                         Best->Conversions[0].UserDefined.ConversionFunction);
10990
10991    CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
10992    DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
10993
10994    // We selected one of the surrogate functions that converts the
10995    // object parameter to a function pointer. Perform the conversion
10996    // on the object argument, then let ActOnCallExpr finish the job.
10997
10998    // Create an implicit member expr to refer to the conversion operator.
10999    // and then call it.
11000    ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11001                                             Conv, HadMultipleCandidates);
11002    if (Call.isInvalid())
11003      return ExprError();
11004    // Record usage of conversion in an implicit cast.
11005    Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11006                                          CK_UserDefinedConversion,
11007                                          Call.get(), 0, VK_RValue));
11008
11009    return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
11010                         RParenLoc);
11011  }
11012
11013  MarkFunctionReferenced(LParenLoc, Best->Function);
11014  CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11015  DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
11016
11017  // We found an overloaded operator(). Build a CXXOperatorCallExpr
11018  // that calls this method, using Object for the implicit object
11019  // parameter and passing along the remaining arguments.
11020  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11021
11022  // An error diagnostic has already been printed when parsing the declaration.
11023  if (Method->isInvalidDecl())
11024    return ExprError();
11025
11026  const FunctionProtoType *Proto =
11027    Method->getType()->getAs<FunctionProtoType>();
11028
11029  unsigned NumArgsInProto = Proto->getNumArgs();
11030  unsigned NumArgsToCheck = NumArgs;
11031
11032  // Build the full argument list for the method call (the
11033  // implicit object parameter is placed at the beginning of the
11034  // list).
11035  Expr **MethodArgs;
11036  if (NumArgs < NumArgsInProto) {
11037    NumArgsToCheck = NumArgsInProto;
11038    MethodArgs = new Expr*[NumArgsInProto + 1];
11039  } else {
11040    MethodArgs = new Expr*[NumArgs + 1];
11041  }
11042  MethodArgs[0] = Object.get();
11043  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11044    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
11045
11046  DeclarationNameInfo OpLocInfo(
11047               Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11048  OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11049  ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
11050                                           HadMultipleCandidates,
11051                                           OpLocInfo.getLoc(),
11052                                           OpLocInfo.getInfo());
11053  if (NewFn.isInvalid())
11054    return true;
11055
11056  // Once we've built TheCall, all of the expressions are properly
11057  // owned.
11058  QualType ResultTy = Method->getResultType();
11059  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11060  ResultTy = ResultTy.getNonLValueExprType(Context);
11061
11062  CXXOperatorCallExpr *TheCall =
11063    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11064                                      llvm::makeArrayRef(MethodArgs, NumArgs+1),
11065                                      ResultTy, VK, RParenLoc, false);
11066  delete [] MethodArgs;
11067
11068  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
11069                          Method))
11070    return true;
11071
11072  // We may have default arguments. If so, we need to allocate more
11073  // slots in the call for them.
11074  if (NumArgs < NumArgsInProto)
11075    TheCall->setNumArgs(Context, NumArgsInProto + 1);
11076  else if (NumArgs > NumArgsInProto)
11077    NumArgsToCheck = NumArgsInProto;
11078
11079  bool IsError = false;
11080
11081  // Initialize the implicit object parameter.
11082  ExprResult ObjRes =
11083    PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11084                                        Best->FoundDecl, Method);
11085  if (ObjRes.isInvalid())
11086    IsError = true;
11087  else
11088    Object = ObjRes;
11089  TheCall->setArg(0, Object.take());
11090
11091  // Check the argument types.
11092  for (unsigned i = 0; i != NumArgsToCheck; i++) {
11093    Expr *Arg;
11094    if (i < NumArgs) {
11095      Arg = Args[i];
11096
11097      // Pass the argument.
11098
11099      ExprResult InputInit
11100        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11101                                                    Context,
11102                                                    Method->getParamDecl(i)),
11103                                    SourceLocation(), Arg);
11104
11105      IsError |= InputInit.isInvalid();
11106      Arg = InputInit.takeAs<Expr>();
11107    } else {
11108      ExprResult DefArg
11109        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11110      if (DefArg.isInvalid()) {
11111        IsError = true;
11112        break;
11113      }
11114
11115      Arg = DefArg.takeAs<Expr>();
11116    }
11117
11118    TheCall->setArg(i + 1, Arg);
11119  }
11120
11121  // If this is a variadic call, handle args passed through "...".
11122  if (Proto->isVariadic()) {
11123    // Promote the arguments (C99 6.5.2.2p7).
11124    for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
11125      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11126      IsError |= Arg.isInvalid();
11127      TheCall->setArg(i + 1, Arg.take());
11128    }
11129  }
11130
11131  if (IsError) return true;
11132
11133  DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11134
11135  if (CheckFunctionCall(Method, TheCall, Proto))
11136    return true;
11137
11138  return MaybeBindToTemporary(TheCall);
11139}
11140
11141/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11142///  (if one exists), where @c Base is an expression of class type and
11143/// @c Member is the name of the member we're trying to find.
11144ExprResult
11145Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
11146  assert(Base->getType()->isRecordType() &&
11147         "left-hand side must have class type");
11148
11149  if (checkPlaceholderForOverload(*this, Base))
11150    return ExprError();
11151
11152  SourceLocation Loc = Base->getExprLoc();
11153
11154  // C++ [over.ref]p1:
11155  //
11156  //   [...] An expression x->m is interpreted as (x.operator->())->m
11157  //   for a class object x of type T if T::operator->() exists and if
11158  //   the operator is selected as the best match function by the
11159  //   overload resolution mechanism (13.3).
11160  DeclarationName OpName =
11161    Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11162  OverloadCandidateSet CandidateSet(Loc);
11163  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11164
11165  if (RequireCompleteType(Loc, Base->getType(),
11166                          diag::err_typecheck_incomplete_tag, Base))
11167    return ExprError();
11168
11169  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11170  LookupQualifiedName(R, BaseRecord->getDecl());
11171  R.suppressDiagnostics();
11172
11173  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11174       Oper != OperEnd; ++Oper) {
11175    AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11176                       0, 0, CandidateSet, /*SuppressUserConversions=*/false);
11177  }
11178
11179  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11180
11181  // Perform overload resolution.
11182  OverloadCandidateSet::iterator Best;
11183  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11184  case OR_Success:
11185    // Overload resolution succeeded; we'll build the call below.
11186    break;
11187
11188  case OR_No_Viable_Function:
11189    if (CandidateSet.empty())
11190      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11191        << Base->getType() << Base->getSourceRange();
11192    else
11193      Diag(OpLoc, diag::err_ovl_no_viable_oper)
11194        << "operator->" << Base->getSourceRange();
11195    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11196    return ExprError();
11197
11198  case OR_Ambiguous:
11199    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11200      << "->" << Base->getType() << Base->getSourceRange();
11201    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11202    return ExprError();
11203
11204  case OR_Deleted:
11205    Diag(OpLoc,  diag::err_ovl_deleted_oper)
11206      << Best->Function->isDeleted()
11207      << "->"
11208      << getDeletedOrUnavailableSuffix(Best->Function)
11209      << Base->getSourceRange();
11210    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11211    return ExprError();
11212  }
11213
11214  MarkFunctionReferenced(OpLoc, Best->Function);
11215  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11216  DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
11217
11218  // Convert the object parameter.
11219  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11220  ExprResult BaseResult =
11221    PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11222                                        Best->FoundDecl, Method);
11223  if (BaseResult.isInvalid())
11224    return ExprError();
11225  Base = BaseResult.take();
11226
11227  // Build the operator call.
11228  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
11229                                            HadMultipleCandidates, OpLoc);
11230  if (FnExpr.isInvalid())
11231    return ExprError();
11232
11233  QualType ResultTy = Method->getResultType();
11234  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11235  ResultTy = ResultTy.getNonLValueExprType(Context);
11236  CXXOperatorCallExpr *TheCall =
11237    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11238                                      Base, ResultTy, VK, OpLoc, false);
11239
11240  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11241                          Method))
11242          return ExprError();
11243
11244  return MaybeBindToTemporary(TheCall);
11245}
11246
11247/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11248/// a literal operator described by the provided lookup results.
11249ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11250                                          DeclarationNameInfo &SuffixInfo,
11251                                          ArrayRef<Expr*> Args,
11252                                          SourceLocation LitEndLoc,
11253                                       TemplateArgumentListInfo *TemplateArgs) {
11254  SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11255
11256  OverloadCandidateSet CandidateSet(UDSuffixLoc);
11257  AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11258                        TemplateArgs);
11259
11260  bool HadMultipleCandidates = (CandidateSet.size() > 1);
11261
11262  // Perform overload resolution. This will usually be trivial, but might need
11263  // to perform substitutions for a literal operator template.
11264  OverloadCandidateSet::iterator Best;
11265  switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11266  case OR_Success:
11267  case OR_Deleted:
11268    break;
11269
11270  case OR_No_Viable_Function:
11271    Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11272      << R.getLookupName();
11273    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11274    return ExprError();
11275
11276  case OR_Ambiguous:
11277    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11278    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11279    return ExprError();
11280  }
11281
11282  FunctionDecl *FD = Best->Function;
11283  MarkFunctionReferenced(UDSuffixLoc, FD);
11284  DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
11285
11286  ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11287                                        SuffixInfo.getLoc(),
11288                                        SuffixInfo.getInfo());
11289  if (Fn.isInvalid())
11290    return true;
11291
11292  // Check the argument types. This should almost always be a no-op, except
11293  // that array-to-pointer decay is applied to string literals.
11294  Expr *ConvArgs[2];
11295  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11296    ExprResult InputInit = PerformCopyInitialization(
11297      InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11298      SourceLocation(), Args[ArgIdx]);
11299    if (InputInit.isInvalid())
11300      return true;
11301    ConvArgs[ArgIdx] = InputInit.take();
11302  }
11303
11304  QualType ResultTy = FD->getResultType();
11305  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11306  ResultTy = ResultTy.getNonLValueExprType(Context);
11307
11308  UserDefinedLiteral *UDL =
11309    new (Context) UserDefinedLiteral(Context, Fn.take(),
11310                                     llvm::makeArrayRef(ConvArgs, Args.size()),
11311                                     ResultTy, VK, LitEndLoc, UDSuffixLoc);
11312
11313  if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11314    return ExprError();
11315
11316  if (CheckFunctionCall(FD, UDL, NULL))
11317    return ExprError();
11318
11319  return MaybeBindToTemporary(UDL);
11320}
11321
11322/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11323/// given LookupResult is non-empty, it is assumed to describe a member which
11324/// will be invoked. Otherwise, the function will be found via argument
11325/// dependent lookup.
11326/// CallExpr is set to a valid expression and FRS_Success returned on success,
11327/// otherwise CallExpr is set to ExprError() and some non-success value
11328/// is returned.
11329Sema::ForRangeStatus
11330Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11331                                SourceLocation RangeLoc, VarDecl *Decl,
11332                                BeginEndFunction BEF,
11333                                const DeclarationNameInfo &NameInfo,
11334                                LookupResult &MemberLookup,
11335                                OverloadCandidateSet *CandidateSet,
11336                                Expr *Range, ExprResult *CallExpr) {
11337  CandidateSet->clear();
11338  if (!MemberLookup.empty()) {
11339    ExprResult MemberRef =
11340        BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11341                                 /*IsPtr=*/false, CXXScopeSpec(),
11342                                 /*TemplateKWLoc=*/SourceLocation(),
11343                                 /*FirstQualifierInScope=*/0,
11344                                 MemberLookup,
11345                                 /*TemplateArgs=*/0);
11346    if (MemberRef.isInvalid()) {
11347      *CallExpr = ExprError();
11348      Diag(Range->getLocStart(), diag::note_in_for_range)
11349          << RangeLoc << BEF << Range->getType();
11350      return FRS_DiagnosticIssued;
11351    }
11352    *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11353    if (CallExpr->isInvalid()) {
11354      *CallExpr = ExprError();
11355      Diag(Range->getLocStart(), diag::note_in_for_range)
11356          << RangeLoc << BEF << Range->getType();
11357      return FRS_DiagnosticIssued;
11358    }
11359  } else {
11360    UnresolvedSet<0> FoundNames;
11361    UnresolvedLookupExpr *Fn =
11362      UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11363                                   NestedNameSpecifierLoc(), NameInfo,
11364                                   /*NeedsADL=*/true, /*Overloaded=*/false,
11365                                   FoundNames.begin(), FoundNames.end());
11366
11367    bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11368                                                    CandidateSet, CallExpr);
11369    if (CandidateSet->empty() || CandidateSetError) {
11370      *CallExpr = ExprError();
11371      return FRS_NoViableFunction;
11372    }
11373    OverloadCandidateSet::iterator Best;
11374    OverloadingResult OverloadResult =
11375        CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11376
11377    if (OverloadResult == OR_No_Viable_Function) {
11378      *CallExpr = ExprError();
11379      return FRS_NoViableFunction;
11380    }
11381    *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11382                                         Loc, 0, CandidateSet, &Best,
11383                                         OverloadResult,
11384                                         /*AllowTypoCorrection=*/false);
11385    if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11386      *CallExpr = ExprError();
11387      Diag(Range->getLocStart(), diag::note_in_for_range)
11388          << RangeLoc << BEF << Range->getType();
11389      return FRS_DiagnosticIssued;
11390    }
11391  }
11392  return FRS_Success;
11393}
11394
11395
11396/// FixOverloadedFunctionReference - E is an expression that refers to
11397/// a C++ overloaded function (possibly with some parentheses and
11398/// perhaps a '&' around it). We have resolved the overloaded function
11399/// to the function declaration Fn, so patch up the expression E to
11400/// refer (possibly indirectly) to Fn. Returns the new expr.
11401Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11402                                           FunctionDecl *Fn) {
11403  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11404    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11405                                                   Found, Fn);
11406    if (SubExpr == PE->getSubExpr())
11407      return PE;
11408
11409    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11410  }
11411
11412  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11413    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11414                                                   Found, Fn);
11415    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11416                               SubExpr->getType()) &&
11417           "Implicit cast type cannot be determined from overload");
11418    assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11419    if (SubExpr == ICE->getSubExpr())
11420      return ICE;
11421
11422    return ImplicitCastExpr::Create(Context, ICE->getType(),
11423                                    ICE->getCastKind(),
11424                                    SubExpr, 0,
11425                                    ICE->getValueKind());
11426  }
11427
11428  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11429    assert(UnOp->getOpcode() == UO_AddrOf &&
11430           "Can only take the address of an overloaded function");
11431    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11432      if (Method->isStatic()) {
11433        // Do nothing: static member functions aren't any different
11434        // from non-member functions.
11435      } else {
11436        // Fix the sub expression, which really has to be an
11437        // UnresolvedLookupExpr holding an overloaded member function
11438        // or template.
11439        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11440                                                       Found, Fn);
11441        if (SubExpr == UnOp->getSubExpr())
11442          return UnOp;
11443
11444        assert(isa<DeclRefExpr>(SubExpr)
11445               && "fixed to something other than a decl ref");
11446        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11447               && "fixed to a member ref with no nested name qualifier");
11448
11449        // We have taken the address of a pointer to member
11450        // function. Perform the computation here so that we get the
11451        // appropriate pointer to member type.
11452        QualType ClassType
11453          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11454        QualType MemPtrType
11455          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11456
11457        return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11458                                           VK_RValue, OK_Ordinary,
11459                                           UnOp->getOperatorLoc());
11460      }
11461    }
11462    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11463                                                   Found, Fn);
11464    if (SubExpr == UnOp->getSubExpr())
11465      return UnOp;
11466
11467    return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11468                                     Context.getPointerType(SubExpr->getType()),
11469                                       VK_RValue, OK_Ordinary,
11470                                       UnOp->getOperatorLoc());
11471  }
11472
11473  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11474    // FIXME: avoid copy.
11475    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11476    if (ULE->hasExplicitTemplateArgs()) {
11477      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11478      TemplateArgs = &TemplateArgsBuffer;
11479    }
11480
11481    DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11482                                           ULE->getQualifierLoc(),
11483                                           ULE->getTemplateKeywordLoc(),
11484                                           Fn,
11485                                           /*enclosing*/ false, // FIXME?
11486                                           ULE->getNameLoc(),
11487                                           Fn->getType(),
11488                                           VK_LValue,
11489                                           Found.getDecl(),
11490                                           TemplateArgs);
11491    MarkDeclRefReferenced(DRE);
11492    DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11493    return DRE;
11494  }
11495
11496  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11497    // FIXME: avoid copy.
11498    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11499    if (MemExpr->hasExplicitTemplateArgs()) {
11500      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11501      TemplateArgs = &TemplateArgsBuffer;
11502    }
11503
11504    Expr *Base;
11505
11506    // If we're filling in a static method where we used to have an
11507    // implicit member access, rewrite to a simple decl ref.
11508    if (MemExpr->isImplicitAccess()) {
11509      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11510        DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11511                                               MemExpr->getQualifierLoc(),
11512                                               MemExpr->getTemplateKeywordLoc(),
11513                                               Fn,
11514                                               /*enclosing*/ false,
11515                                               MemExpr->getMemberLoc(),
11516                                               Fn->getType(),
11517                                               VK_LValue,
11518                                               Found.getDecl(),
11519                                               TemplateArgs);
11520        MarkDeclRefReferenced(DRE);
11521        DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11522        return DRE;
11523      } else {
11524        SourceLocation Loc = MemExpr->getMemberLoc();
11525        if (MemExpr->getQualifier())
11526          Loc = MemExpr->getQualifierLoc().getBeginLoc();
11527        CheckCXXThisCapture(Loc);
11528        Base = new (Context) CXXThisExpr(Loc,
11529                                         MemExpr->getBaseType(),
11530                                         /*isImplicit=*/true);
11531      }
11532    } else
11533      Base = MemExpr->getBase();
11534
11535    ExprValueKind valueKind;
11536    QualType type;
11537    if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11538      valueKind = VK_LValue;
11539      type = Fn->getType();
11540    } else {
11541      valueKind = VK_RValue;
11542      type = Context.BoundMemberTy;
11543    }
11544
11545    MemberExpr *ME = MemberExpr::Create(Context, Base,
11546                                        MemExpr->isArrow(),
11547                                        MemExpr->getQualifierLoc(),
11548                                        MemExpr->getTemplateKeywordLoc(),
11549                                        Fn,
11550                                        Found,
11551                                        MemExpr->getMemberNameInfo(),
11552                                        TemplateArgs,
11553                                        type, valueKind, OK_Ordinary);
11554    ME->setHadMultipleCandidates(true);
11555    MarkMemberReferenced(ME);
11556    return ME;
11557  }
11558
11559  llvm_unreachable("Invalid reference to overloaded function");
11560}
11561
11562ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11563                                                DeclAccessPair Found,
11564                                                FunctionDecl *Fn) {
11565  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11566}
11567
11568} // end namespace clang
11569