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