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