SemaOverload.cpp revision 9b623639378d53a675921ddfa7316034d571881e
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]p24:
5259    //   For every type T, where T is a pointer or pointer-to-member type,
5260    //   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    goto Conditional;
5276  }
5277}
5278
5279/// \brief Add function candidates found via argument-dependent lookup
5280/// to the set of overloading candidates.
5281///
5282/// This routine performs argument-dependent name lookup based on the
5283/// given function name (which may also be an operator name) and adds
5284/// all of the overload candidates found by ADL to the overload
5285/// candidate set (C++ [basic.lookup.argdep]).
5286void
5287Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
5288                                           bool Operator,
5289                                           Expr **Args, unsigned NumArgs,
5290                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
5291                                           OverloadCandidateSet& CandidateSet,
5292                                           bool PartialOverloading) {
5293  ADLResult Fns;
5294
5295  // FIXME: This approach for uniquing ADL results (and removing
5296  // redundant candidates from the set) relies on pointer-equality,
5297  // which means we need to key off the canonical decl.  However,
5298  // always going back to the canonical decl might not get us the
5299  // right set of default arguments.  What default arguments are
5300  // we supposed to consider on ADL candidates, anyway?
5301
5302  // FIXME: Pass in the explicit template arguments?
5303  ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
5304
5305  // Erase all of the candidates we already knew about.
5306  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5307                                   CandEnd = CandidateSet.end();
5308       Cand != CandEnd; ++Cand)
5309    if (Cand->Function) {
5310      Fns.erase(Cand->Function);
5311      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
5312        Fns.erase(FunTmpl);
5313    }
5314
5315  // For each of the ADL candidates we found, add it to the overload
5316  // set.
5317  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
5318    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
5319    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
5320      if (ExplicitTemplateArgs)
5321        continue;
5322
5323      AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
5324                           false, PartialOverloading);
5325    } else
5326      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
5327                                   FoundDecl, ExplicitTemplateArgs,
5328                                   Args, NumArgs, CandidateSet);
5329  }
5330}
5331
5332/// isBetterOverloadCandidate - Determines whether the first overload
5333/// candidate is a better candidate than the second (C++ 13.3.3p1).
5334bool
5335isBetterOverloadCandidate(Sema &S,
5336                          const OverloadCandidate& Cand1,
5337                          const OverloadCandidate& Cand2,
5338                          SourceLocation Loc,
5339                          bool UserDefinedConversion) {
5340  // Define viable functions to be better candidates than non-viable
5341  // functions.
5342  if (!Cand2.Viable)
5343    return Cand1.Viable;
5344  else if (!Cand1.Viable)
5345    return false;
5346
5347  // C++ [over.match.best]p1:
5348  //
5349  //   -- if F is a static member function, ICS1(F) is defined such
5350  //      that ICS1(F) is neither better nor worse than ICS1(G) for
5351  //      any function G, and, symmetrically, ICS1(G) is neither
5352  //      better nor worse than ICS1(F).
5353  unsigned StartArg = 0;
5354  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5355    StartArg = 1;
5356
5357  // C++ [over.match.best]p1:
5358  //   A viable function F1 is defined to be a better function than another
5359  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
5360  //   conversion sequence than ICSi(F2), and then...
5361  unsigned NumArgs = Cand1.Conversions.size();
5362  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5363  bool HasBetterConversion = false;
5364  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
5365    switch (CompareImplicitConversionSequences(S,
5366                                               Cand1.Conversions[ArgIdx],
5367                                               Cand2.Conversions[ArgIdx])) {
5368    case ImplicitConversionSequence::Better:
5369      // Cand1 has a better conversion sequence.
5370      HasBetterConversion = true;
5371      break;
5372
5373    case ImplicitConversionSequence::Worse:
5374      // Cand1 can't be better than Cand2.
5375      return false;
5376
5377    case ImplicitConversionSequence::Indistinguishable:
5378      // Do nothing.
5379      break;
5380    }
5381  }
5382
5383  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
5384  //       ICSj(F2), or, if not that,
5385  if (HasBetterConversion)
5386    return true;
5387
5388  //     - F1 is a non-template function and F2 is a function template
5389  //       specialization, or, if not that,
5390  if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
5391      Cand2.Function && Cand2.Function->getPrimaryTemplate())
5392    return true;
5393
5394  //   -- F1 and F2 are function template specializations, and the function
5395  //      template for F1 is more specialized than the template for F2
5396  //      according to the partial ordering rules described in 14.5.5.2, or,
5397  //      if not that,
5398  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5399      Cand2.Function && Cand2.Function->getPrimaryTemplate())
5400    if (FunctionTemplateDecl *BetterTemplate
5401          = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5402                                         Cand2.Function->getPrimaryTemplate(),
5403                                         Loc,
5404                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5405                                                             : TPOC_Call))
5406      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
5407
5408  //   -- the context is an initialization by user-defined conversion
5409  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
5410  //      from the return type of F1 to the destination type (i.e.,
5411  //      the type of the entity being initialized) is a better
5412  //      conversion sequence than the standard conversion sequence
5413  //      from the return type of F2 to the destination type.
5414  if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
5415      isa<CXXConversionDecl>(Cand1.Function) &&
5416      isa<CXXConversionDecl>(Cand2.Function)) {
5417    switch (CompareStandardConversionSequences(S,
5418                                               Cand1.FinalConversion,
5419                                               Cand2.FinalConversion)) {
5420    case ImplicitConversionSequence::Better:
5421      // Cand1 has a better conversion sequence.
5422      return true;
5423
5424    case ImplicitConversionSequence::Worse:
5425      // Cand1 can't be better than Cand2.
5426      return false;
5427
5428    case ImplicitConversionSequence::Indistinguishable:
5429      // Do nothing
5430      break;
5431    }
5432  }
5433
5434  return false;
5435}
5436
5437/// \brief Computes the best viable function (C++ 13.3.3)
5438/// within an overload candidate set.
5439///
5440/// \param CandidateSet the set of candidate functions.
5441///
5442/// \param Loc the location of the function name (or operator symbol) for
5443/// which overload resolution occurs.
5444///
5445/// \param Best f overload resolution was successful or found a deleted
5446/// function, Best points to the candidate function found.
5447///
5448/// \returns The result of overload resolution.
5449OverloadingResult
5450OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
5451                                         iterator& Best,
5452                                         bool UserDefinedConversion) {
5453  // Find the best viable function.
5454  Best = end();
5455  for (iterator Cand = begin(); Cand != end(); ++Cand) {
5456    if (Cand->Viable)
5457      if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5458                                                     UserDefinedConversion))
5459        Best = Cand;
5460  }
5461
5462  // If we didn't find any viable functions, abort.
5463  if (Best == end())
5464    return OR_No_Viable_Function;
5465
5466  // Make sure that this function is better than every other viable
5467  // function. If not, we have an ambiguity.
5468  for (iterator Cand = begin(); Cand != end(); ++Cand) {
5469    if (Cand->Viable &&
5470        Cand != Best &&
5471        !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5472                                   UserDefinedConversion)) {
5473      Best = end();
5474      return OR_Ambiguous;
5475    }
5476  }
5477
5478  // Best is the best viable function.
5479  if (Best->Function &&
5480      (Best->Function->isDeleted() ||
5481       Best->Function->getAttr<UnavailableAttr>()))
5482    return OR_Deleted;
5483
5484  // C++ [basic.def.odr]p2:
5485  //   An overloaded function is used if it is selected by overload resolution
5486  //   when referred to from a potentially-evaluated expression. [Note: this
5487  //   covers calls to named functions (5.2.2), operator overloading
5488  //   (clause 13), user-defined conversions (12.3.2), allocation function for
5489  //   placement new (5.3.4), as well as non-default initialization (8.5).
5490  if (Best->Function)
5491    S.MarkDeclarationReferenced(Loc, Best->Function);
5492
5493  return OR_Success;
5494}
5495
5496namespace {
5497
5498enum OverloadCandidateKind {
5499  oc_function,
5500  oc_method,
5501  oc_constructor,
5502  oc_function_template,
5503  oc_method_template,
5504  oc_constructor_template,
5505  oc_implicit_default_constructor,
5506  oc_implicit_copy_constructor,
5507  oc_implicit_copy_assignment
5508};
5509
5510OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5511                                                FunctionDecl *Fn,
5512                                                std::string &Description) {
5513  bool isTemplate = false;
5514
5515  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5516    isTemplate = true;
5517    Description = S.getTemplateArgumentBindingsText(
5518      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5519  }
5520
5521  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
5522    if (!Ctor->isImplicit())
5523      return isTemplate ? oc_constructor_template : oc_constructor;
5524
5525    return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5526                                     : oc_implicit_default_constructor;
5527  }
5528
5529  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5530    // This actually gets spelled 'candidate function' for now, but
5531    // it doesn't hurt to split it out.
5532    if (!Meth->isImplicit())
5533      return isTemplate ? oc_method_template : oc_method;
5534
5535    assert(Meth->isCopyAssignmentOperator()
5536           && "implicit method is not copy assignment operator?");
5537    return oc_implicit_copy_assignment;
5538  }
5539
5540  return isTemplate ? oc_function_template : oc_function;
5541}
5542
5543} // end anonymous namespace
5544
5545// Notes the location of an overload candidate.
5546void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
5547  std::string FnDesc;
5548  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5549  Diag(Fn->getLocation(), diag::note_ovl_candidate)
5550    << (unsigned) K << FnDesc;
5551}
5552
5553/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
5554/// "lead" diagnostic; it will be given two arguments, the source and
5555/// target types of the conversion.
5556void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5557                                 Sema &S,
5558                                 SourceLocation CaretLoc,
5559                                 const PartialDiagnostic &PDiag) const {
5560  S.Diag(CaretLoc, PDiag)
5561    << Ambiguous.getFromType() << Ambiguous.getToType();
5562  for (AmbiguousConversionSequence::const_iterator
5563         I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5564    S.NoteOverloadCandidate(*I);
5565  }
5566}
5567
5568namespace {
5569
5570void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5571  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5572  assert(Conv.isBad());
5573  assert(Cand->Function && "for now, candidate must be a function");
5574  FunctionDecl *Fn = Cand->Function;
5575
5576  // There's a conversion slot for the object argument if this is a
5577  // non-constructor method.  Note that 'I' corresponds the
5578  // conversion-slot index.
5579  bool isObjectArgument = false;
5580  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
5581    if (I == 0)
5582      isObjectArgument = true;
5583    else
5584      I--;
5585  }
5586
5587  std::string FnDesc;
5588  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5589
5590  Expr *FromExpr = Conv.Bad.FromExpr;
5591  QualType FromTy = Conv.Bad.getFromType();
5592  QualType ToTy = Conv.Bad.getToType();
5593
5594  if (FromTy == S.Context.OverloadTy) {
5595    assert(FromExpr && "overload set argument came from implicit argument?");
5596    Expr *E = FromExpr->IgnoreParens();
5597    if (isa<UnaryOperator>(E))
5598      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
5599    DeclarationName Name = cast<OverloadExpr>(E)->getName();
5600
5601    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5602      << (unsigned) FnKind << FnDesc
5603      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5604      << ToTy << Name << I+1;
5605    return;
5606  }
5607
5608  // Do some hand-waving analysis to see if the non-viability is due
5609  // to a qualifier mismatch.
5610  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5611  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5612  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5613    CToTy = RT->getPointeeType();
5614  else {
5615    // TODO: detect and diagnose the full richness of const mismatches.
5616    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5617      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5618        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5619  }
5620
5621  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5622      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5623    // It is dumb that we have to do this here.
5624    while (isa<ArrayType>(CFromTy))
5625      CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5626    while (isa<ArrayType>(CToTy))
5627      CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5628
5629    Qualifiers FromQs = CFromTy.getQualifiers();
5630    Qualifiers ToQs = CToTy.getQualifiers();
5631
5632    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5633      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5634        << (unsigned) FnKind << FnDesc
5635        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5636        << FromTy
5637        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5638        << (unsigned) isObjectArgument << I+1;
5639      return;
5640    }
5641
5642    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5643    assert(CVR && "unexpected qualifiers mismatch");
5644
5645    if (isObjectArgument) {
5646      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5647        << (unsigned) FnKind << FnDesc
5648        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5649        << FromTy << (CVR - 1);
5650    } else {
5651      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5652        << (unsigned) FnKind << FnDesc
5653        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5654        << FromTy << (CVR - 1) << I+1;
5655    }
5656    return;
5657  }
5658
5659  // Diagnose references or pointers to incomplete types differently,
5660  // since it's far from impossible that the incompleteness triggered
5661  // the failure.
5662  QualType TempFromTy = FromTy.getNonReferenceType();
5663  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5664    TempFromTy = PTy->getPointeeType();
5665  if (TempFromTy->isIncompleteType()) {
5666    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5667      << (unsigned) FnKind << FnDesc
5668      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5669      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5670    return;
5671  }
5672
5673  // Diagnose base -> derived pointer conversions.
5674  unsigned BaseToDerivedConversion = 0;
5675  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5676    if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5677      if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5678                                               FromPtrTy->getPointeeType()) &&
5679          !FromPtrTy->getPointeeType()->isIncompleteType() &&
5680          !ToPtrTy->getPointeeType()->isIncompleteType() &&
5681          S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5682                          FromPtrTy->getPointeeType()))
5683        BaseToDerivedConversion = 1;
5684    }
5685  } else if (const ObjCObjectPointerType *FromPtrTy
5686                                    = FromTy->getAs<ObjCObjectPointerType>()) {
5687    if (const ObjCObjectPointerType *ToPtrTy
5688                                        = ToTy->getAs<ObjCObjectPointerType>())
5689      if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5690        if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5691          if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5692                                                FromPtrTy->getPointeeType()) &&
5693              FromIface->isSuperClassOf(ToIface))
5694            BaseToDerivedConversion = 2;
5695  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5696      if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5697          !FromTy->isIncompleteType() &&
5698          !ToRefTy->getPointeeType()->isIncompleteType() &&
5699          S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5700        BaseToDerivedConversion = 3;
5701    }
5702
5703  if (BaseToDerivedConversion) {
5704    S.Diag(Fn->getLocation(),
5705           diag::note_ovl_candidate_bad_base_to_derived_conv)
5706      << (unsigned) FnKind << FnDesc
5707      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5708      << (BaseToDerivedConversion - 1)
5709      << FromTy << ToTy << I+1;
5710    return;
5711  }
5712
5713  // TODO: specialize more based on the kind of mismatch
5714  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5715    << (unsigned) FnKind << FnDesc
5716    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5717    << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5718}
5719
5720void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5721                           unsigned NumFormalArgs) {
5722  // TODO: treat calls to a missing default constructor as a special case
5723
5724  FunctionDecl *Fn = Cand->Function;
5725  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5726
5727  unsigned MinParams = Fn->getMinRequiredArguments();
5728
5729  // at least / at most / exactly
5730  // FIXME: variadic templates "at most" should account for parameter packs
5731  unsigned mode, modeCount;
5732  if (NumFormalArgs < MinParams) {
5733    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5734           (Cand->FailureKind == ovl_fail_bad_deduction &&
5735            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
5736    if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5737      mode = 0; // "at least"
5738    else
5739      mode = 2; // "exactly"
5740    modeCount = MinParams;
5741  } else {
5742    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5743           (Cand->FailureKind == ovl_fail_bad_deduction &&
5744            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
5745    if (MinParams != FnTy->getNumArgs())
5746      mode = 1; // "at most"
5747    else
5748      mode = 2; // "exactly"
5749    modeCount = FnTy->getNumArgs();
5750  }
5751
5752  std::string Description;
5753  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5754
5755  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
5756    << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5757    << modeCount << NumFormalArgs;
5758}
5759
5760/// Diagnose a failed template-argument deduction.
5761void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5762                          Expr **Args, unsigned NumArgs) {
5763  FunctionDecl *Fn = Cand->Function; // pattern
5764
5765  TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
5766  NamedDecl *ParamD;
5767  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5768  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5769  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
5770  switch (Cand->DeductionFailure.Result) {
5771  case Sema::TDK_Success:
5772    llvm_unreachable("TDK_success while diagnosing bad deduction");
5773
5774  case Sema::TDK_Incomplete: {
5775    assert(ParamD && "no parameter found for incomplete deduction result");
5776    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5777      << ParamD->getDeclName();
5778    return;
5779  }
5780
5781  case Sema::TDK_Underqualified: {
5782    assert(ParamD && "no parameter found for bad qualifiers deduction result");
5783    TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5784
5785    QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5786
5787    // Param will have been canonicalized, but it should just be a
5788    // qualified version of ParamD, so move the qualifiers to that.
5789    QualifierCollector Qs(S.Context);
5790    Qs.strip(Param);
5791    QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5792    assert(S.Context.hasSameType(Param, NonCanonParam));
5793
5794    // Arg has also been canonicalized, but there's nothing we can do
5795    // about that.  It also doesn't matter as much, because it won't
5796    // have any template parameters in it (because deduction isn't
5797    // done on dependent types).
5798    QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5799
5800    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5801      << ParamD->getDeclName() << Arg << NonCanonParam;
5802    return;
5803  }
5804
5805  case Sema::TDK_Inconsistent: {
5806    assert(ParamD && "no parameter found for inconsistent deduction result");
5807    int which = 0;
5808    if (isa<TemplateTypeParmDecl>(ParamD))
5809      which = 0;
5810    else if (isa<NonTypeTemplateParmDecl>(ParamD))
5811      which = 1;
5812    else {
5813      which = 2;
5814    }
5815
5816    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5817      << which << ParamD->getDeclName()
5818      << *Cand->DeductionFailure.getFirstArg()
5819      << *Cand->DeductionFailure.getSecondArg();
5820    return;
5821  }
5822
5823  case Sema::TDK_InvalidExplicitArguments:
5824    assert(ParamD && "no parameter found for invalid explicit arguments");
5825    if (ParamD->getDeclName())
5826      S.Diag(Fn->getLocation(),
5827             diag::note_ovl_candidate_explicit_arg_mismatch_named)
5828        << ParamD->getDeclName();
5829    else {
5830      int index = 0;
5831      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5832        index = TTP->getIndex();
5833      else if (NonTypeTemplateParmDecl *NTTP
5834                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5835        index = NTTP->getIndex();
5836      else
5837        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5838      S.Diag(Fn->getLocation(),
5839             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5840        << (index + 1);
5841    }
5842    return;
5843
5844  case Sema::TDK_TooManyArguments:
5845  case Sema::TDK_TooFewArguments:
5846    DiagnoseArityMismatch(S, Cand, NumArgs);
5847    return;
5848
5849  case Sema::TDK_InstantiationDepth:
5850    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5851    return;
5852
5853  case Sema::TDK_SubstitutionFailure: {
5854    std::string ArgString;
5855    if (TemplateArgumentList *Args
5856                            = Cand->DeductionFailure.getTemplateArgumentList())
5857      ArgString = S.getTemplateArgumentBindingsText(
5858                    Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5859                                                    *Args);
5860    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5861      << ArgString;
5862    return;
5863  }
5864
5865  // TODO: diagnose these individually, then kill off
5866  // note_ovl_candidate_bad_deduction, which is uselessly vague.
5867  case Sema::TDK_NonDeducedMismatch:
5868  case Sema::TDK_FailedOverloadResolution:
5869    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5870    return;
5871  }
5872}
5873
5874/// Generates a 'note' diagnostic for an overload candidate.  We've
5875/// already generated a primary error at the call site.
5876///
5877/// It really does need to be a single diagnostic with its caret
5878/// pointed at the candidate declaration.  Yes, this creates some
5879/// major challenges of technical writing.  Yes, this makes pointing
5880/// out problems with specific arguments quite awkward.  It's still
5881/// better than generating twenty screens of text for every failed
5882/// overload.
5883///
5884/// It would be great to be able to express per-candidate problems
5885/// more richly for those diagnostic clients that cared, but we'd
5886/// still have to be just as careful with the default diagnostics.
5887void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5888                           Expr **Args, unsigned NumArgs) {
5889  FunctionDecl *Fn = Cand->Function;
5890
5891  // Note deleted candidates, but only if they're viable.
5892  if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
5893    std::string FnDesc;
5894    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5895
5896    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
5897      << FnKind << FnDesc << Fn->isDeleted();
5898    return;
5899  }
5900
5901  // We don't really have anything else to say about viable candidates.
5902  if (Cand->Viable) {
5903    S.NoteOverloadCandidate(Fn);
5904    return;
5905  }
5906
5907  switch (Cand->FailureKind) {
5908  case ovl_fail_too_many_arguments:
5909  case ovl_fail_too_few_arguments:
5910    return DiagnoseArityMismatch(S, Cand, NumArgs);
5911
5912  case ovl_fail_bad_deduction:
5913    return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5914
5915  case ovl_fail_trivial_conversion:
5916  case ovl_fail_bad_final_conversion:
5917  case ovl_fail_final_conversion_not_exact:
5918    return S.NoteOverloadCandidate(Fn);
5919
5920  case ovl_fail_bad_conversion: {
5921    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5922    for (unsigned N = Cand->Conversions.size(); I != N; ++I)
5923      if (Cand->Conversions[I].isBad())
5924        return DiagnoseBadConversion(S, Cand, I);
5925
5926    // FIXME: this currently happens when we're called from SemaInit
5927    // when user-conversion overload fails.  Figure out how to handle
5928    // those conditions and diagnose them well.
5929    return S.NoteOverloadCandidate(Fn);
5930  }
5931  }
5932}
5933
5934void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5935  // Desugar the type of the surrogate down to a function type,
5936  // retaining as many typedefs as possible while still showing
5937  // the function type (and, therefore, its parameter types).
5938  QualType FnType = Cand->Surrogate->getConversionType();
5939  bool isLValueReference = false;
5940  bool isRValueReference = false;
5941  bool isPointer = false;
5942  if (const LValueReferenceType *FnTypeRef =
5943        FnType->getAs<LValueReferenceType>()) {
5944    FnType = FnTypeRef->getPointeeType();
5945    isLValueReference = true;
5946  } else if (const RValueReferenceType *FnTypeRef =
5947               FnType->getAs<RValueReferenceType>()) {
5948    FnType = FnTypeRef->getPointeeType();
5949    isRValueReference = true;
5950  }
5951  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5952    FnType = FnTypePtr->getPointeeType();
5953    isPointer = true;
5954  }
5955  // Desugar down to a function type.
5956  FnType = QualType(FnType->getAs<FunctionType>(), 0);
5957  // Reconstruct the pointer/reference as appropriate.
5958  if (isPointer) FnType = S.Context.getPointerType(FnType);
5959  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5960  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5961
5962  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5963    << FnType;
5964}
5965
5966void NoteBuiltinOperatorCandidate(Sema &S,
5967                                  const char *Opc,
5968                                  SourceLocation OpLoc,
5969                                  OverloadCandidate *Cand) {
5970  assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5971  std::string TypeStr("operator");
5972  TypeStr += Opc;
5973  TypeStr += "(";
5974  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5975  if (Cand->Conversions.size() == 1) {
5976    TypeStr += ")";
5977    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5978  } else {
5979    TypeStr += ", ";
5980    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5981    TypeStr += ")";
5982    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5983  }
5984}
5985
5986void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5987                                  OverloadCandidate *Cand) {
5988  unsigned NoOperands = Cand->Conversions.size();
5989  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5990    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
5991    if (ICS.isBad()) break; // all meaningless after first invalid
5992    if (!ICS.isAmbiguous()) continue;
5993
5994    ICS.DiagnoseAmbiguousConversion(S, OpLoc,
5995                              S.PDiag(diag::note_ambiguous_type_conversion));
5996  }
5997}
5998
5999SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6000  if (Cand->Function)
6001    return Cand->Function->getLocation();
6002  if (Cand->IsSurrogate)
6003    return Cand->Surrogate->getLocation();
6004  return SourceLocation();
6005}
6006
6007struct CompareOverloadCandidatesForDisplay {
6008  Sema &S;
6009  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
6010
6011  bool operator()(const OverloadCandidate *L,
6012                  const OverloadCandidate *R) {
6013    // Fast-path this check.
6014    if (L == R) return false;
6015
6016    // Order first by viability.
6017    if (L->Viable) {
6018      if (!R->Viable) return true;
6019
6020      // TODO: introduce a tri-valued comparison for overload
6021      // candidates.  Would be more worthwhile if we had a sort
6022      // that could exploit it.
6023      if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6024      if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
6025    } else if (R->Viable)
6026      return false;
6027
6028    assert(L->Viable == R->Viable);
6029
6030    // Criteria by which we can sort non-viable candidates:
6031    if (!L->Viable) {
6032      // 1. Arity mismatches come after other candidates.
6033      if (L->FailureKind == ovl_fail_too_many_arguments ||
6034          L->FailureKind == ovl_fail_too_few_arguments)
6035        return false;
6036      if (R->FailureKind == ovl_fail_too_many_arguments ||
6037          R->FailureKind == ovl_fail_too_few_arguments)
6038        return true;
6039
6040      // 2. Bad conversions come first and are ordered by the number
6041      // of bad conversions and quality of good conversions.
6042      if (L->FailureKind == ovl_fail_bad_conversion) {
6043        if (R->FailureKind != ovl_fail_bad_conversion)
6044          return true;
6045
6046        // If there's any ordering between the defined conversions...
6047        // FIXME: this might not be transitive.
6048        assert(L->Conversions.size() == R->Conversions.size());
6049
6050        int leftBetter = 0;
6051        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6052        for (unsigned E = L->Conversions.size(); I != E; ++I) {
6053          switch (CompareImplicitConversionSequences(S,
6054                                                     L->Conversions[I],
6055                                                     R->Conversions[I])) {
6056          case ImplicitConversionSequence::Better:
6057            leftBetter++;
6058            break;
6059
6060          case ImplicitConversionSequence::Worse:
6061            leftBetter--;
6062            break;
6063
6064          case ImplicitConversionSequence::Indistinguishable:
6065            break;
6066          }
6067        }
6068        if (leftBetter > 0) return true;
6069        if (leftBetter < 0) return false;
6070
6071      } else if (R->FailureKind == ovl_fail_bad_conversion)
6072        return false;
6073
6074      // TODO: others?
6075    }
6076
6077    // Sort everything else by location.
6078    SourceLocation LLoc = GetLocationForCandidate(L);
6079    SourceLocation RLoc = GetLocationForCandidate(R);
6080
6081    // Put candidates without locations (e.g. builtins) at the end.
6082    if (LLoc.isInvalid()) return false;
6083    if (RLoc.isInvalid()) return true;
6084
6085    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
6086  }
6087};
6088
6089/// CompleteNonViableCandidate - Normally, overload resolution only
6090/// computes up to the first
6091void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6092                                Expr **Args, unsigned NumArgs) {
6093  assert(!Cand->Viable);
6094
6095  // Don't do anything on failures other than bad conversion.
6096  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6097
6098  // Skip forward to the first bad conversion.
6099  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
6100  unsigned ConvCount = Cand->Conversions.size();
6101  while (true) {
6102    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6103    ConvIdx++;
6104    if (Cand->Conversions[ConvIdx - 1].isBad())
6105      break;
6106  }
6107
6108  if (ConvIdx == ConvCount)
6109    return;
6110
6111  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6112         "remaining conversion is initialized?");
6113
6114  // FIXME: this should probably be preserved from the overload
6115  // operation somehow.
6116  bool SuppressUserConversions = false;
6117
6118  const FunctionProtoType* Proto;
6119  unsigned ArgIdx = ConvIdx;
6120
6121  if (Cand->IsSurrogate) {
6122    QualType ConvType
6123      = Cand->Surrogate->getConversionType().getNonReferenceType();
6124    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6125      ConvType = ConvPtrType->getPointeeType();
6126    Proto = ConvType->getAs<FunctionProtoType>();
6127    ArgIdx--;
6128  } else if (Cand->Function) {
6129    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6130    if (isa<CXXMethodDecl>(Cand->Function) &&
6131        !isa<CXXConstructorDecl>(Cand->Function))
6132      ArgIdx--;
6133  } else {
6134    // Builtin binary operator with a bad first conversion.
6135    assert(ConvCount <= 3);
6136    for (; ConvIdx != ConvCount; ++ConvIdx)
6137      Cand->Conversions[ConvIdx]
6138        = TryCopyInitialization(S, Args[ConvIdx],
6139                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
6140                                SuppressUserConversions,
6141                                /*InOverloadResolution*/ true);
6142    return;
6143  }
6144
6145  // Fill in the rest of the conversions.
6146  unsigned NumArgsInProto = Proto->getNumArgs();
6147  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6148    if (ArgIdx < NumArgsInProto)
6149      Cand->Conversions[ConvIdx]
6150        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6151                                SuppressUserConversions,
6152                                /*InOverloadResolution=*/true);
6153    else
6154      Cand->Conversions[ConvIdx].setEllipsis();
6155  }
6156}
6157
6158} // end anonymous namespace
6159
6160/// PrintOverloadCandidates - When overload resolution fails, prints
6161/// diagnostic messages containing the candidates in the candidate
6162/// set.
6163void OverloadCandidateSet::NoteCandidates(Sema &S,
6164                                          OverloadCandidateDisplayKind OCD,
6165                                          Expr **Args, unsigned NumArgs,
6166                                          const char *Opc,
6167                                          SourceLocation OpLoc) {
6168  // Sort the candidates by viability and position.  Sorting directly would
6169  // be prohibitive, so we make a set of pointers and sort those.
6170  llvm::SmallVector<OverloadCandidate*, 32> Cands;
6171  if (OCD == OCD_AllCandidates) Cands.reserve(size());
6172  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
6173    if (Cand->Viable)
6174      Cands.push_back(Cand);
6175    else if (OCD == OCD_AllCandidates) {
6176      CompleteNonViableCandidate(S, Cand, Args, NumArgs);
6177      if (Cand->Function || Cand->IsSurrogate)
6178        Cands.push_back(Cand);
6179      // Otherwise, this a non-viable builtin candidate.  We do not, in general,
6180      // want to list every possible builtin candidate.
6181    }
6182  }
6183
6184  std::sort(Cands.begin(), Cands.end(),
6185            CompareOverloadCandidatesForDisplay(S));
6186
6187  bool ReportedAmbiguousConversions = false;
6188
6189  llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
6190  const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
6191  unsigned CandsShown = 0;
6192  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6193    OverloadCandidate *Cand = *I;
6194
6195    // Set an arbitrary limit on the number of candidate functions we'll spam
6196    // the user with.  FIXME: This limit should depend on details of the
6197    // candidate list.
6198    if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6199      break;
6200    }
6201    ++CandsShown;
6202
6203    if (Cand->Function)
6204      NoteFunctionCandidate(S, Cand, Args, NumArgs);
6205    else if (Cand->IsSurrogate)
6206      NoteSurrogateCandidate(S, Cand);
6207    else {
6208      assert(Cand->Viable &&
6209             "Non-viable built-in candidates are not added to Cands.");
6210      // Generally we only see ambiguities including viable builtin
6211      // operators if overload resolution got screwed up by an
6212      // ambiguous user-defined conversion.
6213      //
6214      // FIXME: It's quite possible for different conversions to see
6215      // different ambiguities, though.
6216      if (!ReportedAmbiguousConversions) {
6217        NoteAmbiguousUserConversions(S, OpLoc, Cand);
6218        ReportedAmbiguousConversions = true;
6219      }
6220
6221      // If this is a viable builtin, print it.
6222      NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
6223    }
6224  }
6225
6226  if (I != E)
6227    S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
6228}
6229
6230static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
6231  if (isa<UnresolvedLookupExpr>(E))
6232    return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
6233
6234  return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
6235}
6236
6237/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6238/// an overloaded function (C++ [over.over]), where @p From is an
6239/// expression with overloaded function type and @p ToType is the type
6240/// we're trying to resolve to. For example:
6241///
6242/// @code
6243/// int f(double);
6244/// int f(int);
6245///
6246/// int (*pfd)(double) = f; // selects f(double)
6247/// @endcode
6248///
6249/// This routine returns the resulting FunctionDecl if it could be
6250/// resolved, and NULL otherwise. When @p Complain is true, this
6251/// routine will emit diagnostics if there is an error.
6252FunctionDecl *
6253Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
6254                                         bool Complain,
6255                                         DeclAccessPair &FoundResult) {
6256  QualType FunctionType = ToType;
6257  bool IsMember = false;
6258  if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
6259    FunctionType = ToTypePtr->getPointeeType();
6260  else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
6261    FunctionType = ToTypeRef->getPointeeType();
6262  else if (const MemberPointerType *MemTypePtr =
6263                    ToType->getAs<MemberPointerType>()) {
6264    FunctionType = MemTypePtr->getPointeeType();
6265    IsMember = true;
6266  }
6267
6268  // C++ [over.over]p1:
6269  //   [...] [Note: any redundant set of parentheses surrounding the
6270  //   overloaded function name is ignored (5.1). ]
6271  // C++ [over.over]p1:
6272  //   [...] The overloaded function name can be preceded by the &
6273  //   operator.
6274  // However, remember whether the expression has member-pointer form:
6275  // C++ [expr.unary.op]p4:
6276  //     A pointer to member is only formed when an explicit & is used
6277  //     and its operand is a qualified-id not enclosed in
6278  //     parentheses.
6279  OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6280  OverloadExpr *OvlExpr = Ovl.Expression;
6281
6282  // We expect a pointer or reference to function, or a function pointer.
6283  FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6284  if (!FunctionType->isFunctionType()) {
6285    if (Complain)
6286      Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6287        << OvlExpr->getName() << ToType;
6288
6289    return 0;
6290  }
6291
6292  // If the overload expression doesn't have the form of a pointer to
6293  // member, don't try to convert it to a pointer-to-member type.
6294  if (IsMember && !Ovl.HasFormOfMemberPointer) {
6295    if (!Complain) return 0;
6296
6297    // TODO: Should we condition this on whether any functions might
6298    // have matched, or is it more appropriate to do that in callers?
6299    // TODO: a fixit wouldn't hurt.
6300    Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6301      << ToType << OvlExpr->getSourceRange();
6302    return 0;
6303  }
6304
6305  TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6306  if (OvlExpr->hasExplicitTemplateArgs()) {
6307    OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6308    ExplicitTemplateArgs = &ETABuffer;
6309  }
6310
6311  assert(From->getType() == Context.OverloadTy);
6312
6313  // Look through all of the overloaded functions, searching for one
6314  // whose type matches exactly.
6315  llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
6316  llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6317
6318  bool FoundNonTemplateFunction = false;
6319  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6320         E = OvlExpr->decls_end(); I != E; ++I) {
6321    // Look through any using declarations to find the underlying function.
6322    NamedDecl *Fn = (*I)->getUnderlyingDecl();
6323
6324    // C++ [over.over]p3:
6325    //   Non-member functions and static member functions match
6326    //   targets of type "pointer-to-function" or "reference-to-function."
6327    //   Nonstatic member functions match targets of
6328    //   type "pointer-to-member-function."
6329    // Note that according to DR 247, the containing class does not matter.
6330
6331    if (FunctionTemplateDecl *FunctionTemplate
6332          = dyn_cast<FunctionTemplateDecl>(Fn)) {
6333      if (CXXMethodDecl *Method
6334            = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
6335        // Skip non-static function templates when converting to pointer, and
6336        // static when converting to member pointer.
6337        if (Method->isStatic() == IsMember)
6338          continue;
6339      } else if (IsMember)
6340        continue;
6341
6342      // C++ [over.over]p2:
6343      //   If the name is a function template, template argument deduction is
6344      //   done (14.8.2.2), and if the argument deduction succeeds, the
6345      //   resulting template argument list is used to generate a single
6346      //   function template specialization, which is added to the set of
6347      //   overloaded functions considered.
6348      FunctionDecl *Specialization = 0;
6349      TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
6350      if (TemplateDeductionResult Result
6351            = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
6352                                      FunctionType, Specialization, Info)) {
6353        // FIXME: make a note of the failed deduction for diagnostics.
6354        (void)Result;
6355      } else {
6356        // Template argument deduction ensures that we have an exact match.
6357        // This function template specicalization works.
6358        Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
6359        assert(FunctionType
6360                 == Context.getCanonicalType(Specialization->getType()));
6361        Matches.push_back(std::make_pair(I.getPair(), Specialization));
6362      }
6363
6364      continue;
6365    }
6366
6367    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6368      // Skip non-static functions when converting to pointer, and static
6369      // when converting to member pointer.
6370      if (Method->isStatic() == IsMember)
6371        continue;
6372
6373      // If we have explicit template arguments, skip non-templates.
6374      if (OvlExpr->hasExplicitTemplateArgs())
6375        continue;
6376    } else if (IsMember)
6377      continue;
6378
6379    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
6380      QualType ResultTy;
6381      if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6382          IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6383                               ResultTy)) {
6384        Matches.push_back(std::make_pair(I.getPair(),
6385                           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
6386        FoundNonTemplateFunction = true;
6387      }
6388    }
6389  }
6390
6391  // If there were 0 or 1 matches, we're done.
6392  if (Matches.empty()) {
6393    if (Complain) {
6394      Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6395        << OvlExpr->getName() << FunctionType;
6396      for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6397                                 E = OvlExpr->decls_end();
6398           I != E; ++I)
6399        if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6400          NoteOverloadCandidate(F);
6401    }
6402
6403    return 0;
6404  } else if (Matches.size() == 1) {
6405    FunctionDecl *Result = Matches[0].second;
6406    FoundResult = Matches[0].first;
6407    MarkDeclarationReferenced(From->getLocStart(), Result);
6408    if (Complain) {
6409      CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
6410    }
6411    return Result;
6412  }
6413
6414  // C++ [over.over]p4:
6415  //   If more than one function is selected, [...]
6416  if (!FoundNonTemplateFunction) {
6417    //   [...] and any given function template specialization F1 is
6418    //   eliminated if the set contains a second function template
6419    //   specialization whose function template is more specialized
6420    //   than the function template of F1 according to the partial
6421    //   ordering rules of 14.5.5.2.
6422
6423    // The algorithm specified above is quadratic. We instead use a
6424    // two-pass algorithm (similar to the one used to identify the
6425    // best viable function in an overload set) that identifies the
6426    // best function template (if it exists).
6427
6428    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6429    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6430      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
6431
6432    UnresolvedSetIterator Result =
6433        getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
6434                           TPOC_Other, From->getLocStart(),
6435                           PDiag(),
6436                           PDiag(diag::err_addr_ovl_ambiguous)
6437                               << Matches[0].second->getDeclName(),
6438                           PDiag(diag::note_ovl_candidate)
6439                               << (unsigned) oc_function_template);
6440    if (Result == MatchesCopy.end())
6441      return 0;
6442
6443    MarkDeclarationReferenced(From->getLocStart(), *Result);
6444    FoundResult = Matches[Result - MatchesCopy.begin()].first;
6445    if (Complain)
6446      CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
6447    return cast<FunctionDecl>(*Result);
6448  }
6449
6450  //   [...] any function template specializations in the set are
6451  //   eliminated if the set also contains a non-template function, [...]
6452  for (unsigned I = 0, N = Matches.size(); I != N; ) {
6453    if (Matches[I].second->getPrimaryTemplate() == 0)
6454      ++I;
6455    else {
6456      Matches[I] = Matches[--N];
6457      Matches.set_size(N);
6458    }
6459  }
6460
6461  // [...] After such eliminations, if any, there shall remain exactly one
6462  // selected function.
6463  if (Matches.size() == 1) {
6464    MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
6465    FoundResult = Matches[0].first;
6466    if (Complain)
6467      CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6468    return cast<FunctionDecl>(Matches[0].second);
6469  }
6470
6471  // FIXME: We should probably return the same thing that BestViableFunction
6472  // returns (even if we issue the diagnostics here).
6473  Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6474    << Matches[0].second->getDeclName();
6475  for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6476    NoteOverloadCandidate(Matches[I].second);
6477  return 0;
6478}
6479
6480/// \brief Given an expression that refers to an overloaded function, try to
6481/// resolve that overloaded function expression down to a single function.
6482///
6483/// This routine can only resolve template-ids that refer to a single function
6484/// template, where that template-id refers to a single template whose template
6485/// arguments are either provided by the template-id or have defaults,
6486/// as described in C++0x [temp.arg.explicit]p3.
6487FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6488  // C++ [over.over]p1:
6489  //   [...] [Note: any redundant set of parentheses surrounding the
6490  //   overloaded function name is ignored (5.1). ]
6491  // C++ [over.over]p1:
6492  //   [...] The overloaded function name can be preceded by the &
6493  //   operator.
6494
6495  if (From->getType() != Context.OverloadTy)
6496    return 0;
6497
6498  OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
6499
6500  // If we didn't actually find any template-ids, we're done.
6501  if (!OvlExpr->hasExplicitTemplateArgs())
6502    return 0;
6503
6504  TemplateArgumentListInfo ExplicitTemplateArgs;
6505  OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
6506
6507  // Look through all of the overloaded functions, searching for one
6508  // whose type matches exactly.
6509  FunctionDecl *Matched = 0;
6510  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6511         E = OvlExpr->decls_end(); I != E; ++I) {
6512    // C++0x [temp.arg.explicit]p3:
6513    //   [...] In contexts where deduction is done and fails, or in contexts
6514    //   where deduction is not done, if a template argument list is
6515    //   specified and it, along with any default template arguments,
6516    //   identifies a single function template specialization, then the
6517    //   template-id is an lvalue for the function template specialization.
6518    FunctionTemplateDecl *FunctionTemplate
6519      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
6520
6521    // C++ [over.over]p2:
6522    //   If the name is a function template, template argument deduction is
6523    //   done (14.8.2.2), and if the argument deduction succeeds, the
6524    //   resulting template argument list is used to generate a single
6525    //   function template specialization, which is added to the set of
6526    //   overloaded functions considered.
6527    FunctionDecl *Specialization = 0;
6528    TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
6529    if (TemplateDeductionResult Result
6530          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6531                                    Specialization, Info)) {
6532      // FIXME: make a note of the failed deduction for diagnostics.
6533      (void)Result;
6534      continue;
6535    }
6536
6537    // Multiple matches; we can't resolve to a single declaration.
6538    if (Matched)
6539      return 0;
6540
6541    Matched = Specialization;
6542  }
6543
6544  return Matched;
6545}
6546
6547/// \brief Add a single candidate to the overload set.
6548static void AddOverloadedCallCandidate(Sema &S,
6549                                       DeclAccessPair FoundDecl,
6550                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
6551                                       Expr **Args, unsigned NumArgs,
6552                                       OverloadCandidateSet &CandidateSet,
6553                                       bool PartialOverloading) {
6554  NamedDecl *Callee = FoundDecl.getDecl();
6555  if (isa<UsingShadowDecl>(Callee))
6556    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6557
6558  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
6559    assert(!ExplicitTemplateArgs && "Explicit template arguments?");
6560    S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
6561                           false, PartialOverloading);
6562    return;
6563  }
6564
6565  if (FunctionTemplateDecl *FuncTemplate
6566      = dyn_cast<FunctionTemplateDecl>(Callee)) {
6567    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6568                                   ExplicitTemplateArgs,
6569                                   Args, NumArgs, CandidateSet);
6570    return;
6571  }
6572
6573  assert(false && "unhandled case in overloaded call candidate");
6574
6575  // do nothing?
6576}
6577
6578/// \brief Add the overload candidates named by callee and/or found by argument
6579/// dependent lookup to the given overload set.
6580void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
6581                                       Expr **Args, unsigned NumArgs,
6582                                       OverloadCandidateSet &CandidateSet,
6583                                       bool PartialOverloading) {
6584
6585#ifndef NDEBUG
6586  // Verify that ArgumentDependentLookup is consistent with the rules
6587  // in C++0x [basic.lookup.argdep]p3:
6588  //
6589  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
6590  //   and let Y be the lookup set produced by argument dependent
6591  //   lookup (defined as follows). If X contains
6592  //
6593  //     -- a declaration of a class member, or
6594  //
6595  //     -- a block-scope function declaration that is not a
6596  //        using-declaration, or
6597  //
6598  //     -- a declaration that is neither a function or a function
6599  //        template
6600  //
6601  //   then Y is empty.
6602
6603  if (ULE->requiresADL()) {
6604    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6605           E = ULE->decls_end(); I != E; ++I) {
6606      assert(!(*I)->getDeclContext()->isRecord());
6607      assert(isa<UsingShadowDecl>(*I) ||
6608             !(*I)->getDeclContext()->isFunctionOrMethod());
6609      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
6610    }
6611  }
6612#endif
6613
6614  // It would be nice to avoid this copy.
6615  TemplateArgumentListInfo TABuffer;
6616  const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6617  if (ULE->hasExplicitTemplateArgs()) {
6618    ULE->copyTemplateArgumentsInto(TABuffer);
6619    ExplicitTemplateArgs = &TABuffer;
6620  }
6621
6622  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6623         E = ULE->decls_end(); I != E; ++I)
6624    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
6625                               Args, NumArgs, CandidateSet,
6626                               PartialOverloading);
6627
6628  if (ULE->requiresADL())
6629    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6630                                         Args, NumArgs,
6631                                         ExplicitTemplateArgs,
6632                                         CandidateSet,
6633                                         PartialOverloading);
6634}
6635
6636/// Attempts to recover from a call where no functions were found.
6637///
6638/// Returns true if new candidates were found.
6639static ExprResult
6640BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
6641                      UnresolvedLookupExpr *ULE,
6642                      SourceLocation LParenLoc,
6643                      Expr **Args, unsigned NumArgs,
6644                      SourceLocation RParenLoc) {
6645
6646  CXXScopeSpec SS;
6647  if (ULE->getQualifier()) {
6648    SS.setScopeRep(ULE->getQualifier());
6649    SS.setRange(ULE->getQualifierRange());
6650  }
6651
6652  TemplateArgumentListInfo TABuffer;
6653  const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6654  if (ULE->hasExplicitTemplateArgs()) {
6655    ULE->copyTemplateArgumentsInto(TABuffer);
6656    ExplicitTemplateArgs = &TABuffer;
6657  }
6658
6659  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6660                 Sema::LookupOrdinaryName);
6661  if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
6662    return ExprError();
6663
6664  assert(!R.empty() && "lookup results empty despite recovery");
6665
6666  // Build an implicit member call if appropriate.  Just drop the
6667  // casts and such from the call, we don't really care.
6668  ExprResult NewFn = ExprError();
6669  if ((*R.begin())->isCXXClassMember())
6670    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6671  else if (ExplicitTemplateArgs)
6672    NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6673  else
6674    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6675
6676  if (NewFn.isInvalid())
6677    return ExprError();
6678
6679  // This shouldn't cause an infinite loop because we're giving it
6680  // an expression with non-empty lookup results, which should never
6681  // end up here.
6682  return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
6683                               MultiExprArg(Args, NumArgs), RParenLoc);
6684}
6685
6686/// ResolveOverloadedCallFn - Given the call expression that calls Fn
6687/// (which eventually refers to the declaration Func) and the call
6688/// arguments Args/NumArgs, attempt to resolve the function call down
6689/// to a specific function. If overload resolution succeeds, returns
6690/// the function declaration produced by overload
6691/// resolution. Otherwise, emits diagnostics, deletes all of the
6692/// arguments and Fn, and returns NULL.
6693ExprResult
6694Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
6695                              SourceLocation LParenLoc,
6696                              Expr **Args, unsigned NumArgs,
6697                              SourceLocation RParenLoc) {
6698#ifndef NDEBUG
6699  if (ULE->requiresADL()) {
6700    // To do ADL, we must have found an unqualified name.
6701    assert(!ULE->getQualifier() && "qualified name with ADL");
6702
6703    // We don't perform ADL for implicit declarations of builtins.
6704    // Verify that this was correctly set up.
6705    FunctionDecl *F;
6706    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6707        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6708        F->getBuiltinID() && F->isImplicit())
6709      assert(0 && "performing ADL for builtin");
6710
6711    // We don't perform ADL in C.
6712    assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6713  }
6714#endif
6715
6716  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
6717
6718  // Add the functions denoted by the callee to the set of candidate
6719  // functions, including those from argument-dependent lookup.
6720  AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
6721
6722  // If we found nothing, try to recover.
6723  // AddRecoveryCallCandidates diagnoses the error itself, so we just
6724  // bailout out if it fails.
6725  if (CandidateSet.empty())
6726    return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
6727                                 RParenLoc);
6728
6729  OverloadCandidateSet::iterator Best;
6730  switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
6731  case OR_Success: {
6732    FunctionDecl *FDecl = Best->Function;
6733    CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
6734    DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl, ULE->getNameLoc());
6735    Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
6736    return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6737  }
6738
6739  case OR_No_Viable_Function:
6740    Diag(Fn->getSourceRange().getBegin(),
6741         diag::err_ovl_no_viable_function_in_call)
6742      << ULE->getName() << Fn->getSourceRange();
6743    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
6744    break;
6745
6746  case OR_Ambiguous:
6747    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
6748      << ULE->getName() << Fn->getSourceRange();
6749    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
6750    break;
6751
6752  case OR_Deleted:
6753    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6754      << Best->Function->isDeleted()
6755      << ULE->getName()
6756      << Fn->getSourceRange();
6757    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
6758    break;
6759  }
6760
6761  // Overload resolution failed.
6762  return ExprError();
6763}
6764
6765static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
6766  return Functions.size() > 1 ||
6767    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6768}
6769
6770/// \brief Create a unary operation that may resolve to an overloaded
6771/// operator.
6772///
6773/// \param OpLoc The location of the operator itself (e.g., '*').
6774///
6775/// \param OpcIn The UnaryOperator::Opcode that describes this
6776/// operator.
6777///
6778/// \param Functions The set of non-member functions that will be
6779/// considered by overload resolution. The caller needs to build this
6780/// set based on the context using, e.g.,
6781/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6782/// set should not contain any member functions; those will be added
6783/// by CreateOverloadedUnaryOp().
6784///
6785/// \param input The input argument.
6786ExprResult
6787Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6788                              const UnresolvedSetImpl &Fns,
6789                              Expr *Input) {
6790  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6791
6792  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6793  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6794  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6795  // TODO: provide better source location info.
6796  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
6797
6798  Expr *Args[2] = { Input, 0 };
6799  unsigned NumArgs = 1;
6800
6801  // For post-increment and post-decrement, add the implicit '0' as
6802  // the second argument, so that we know this is a post-increment or
6803  // post-decrement.
6804  if (Opc == UO_PostInc || Opc == UO_PostDec) {
6805    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
6806    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
6807                                     SourceLocation());
6808    NumArgs = 2;
6809  }
6810
6811  if (Input->isTypeDependent()) {
6812    if (Fns.empty())
6813      return Owned(new (Context) UnaryOperator(Input,
6814                                               Opc,
6815                                               Context.DependentTy,
6816                                               OpLoc));
6817
6818    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
6819    UnresolvedLookupExpr *Fn
6820      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
6821                                     0, SourceRange(), OpNameInfo,
6822                                     /*ADL*/ true, IsOverloaded(Fns),
6823                                     Fns.begin(), Fns.end());
6824    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6825                                                   &Args[0], NumArgs,
6826                                                   Context.DependentTy,
6827                                                   OpLoc));
6828  }
6829
6830  // Build an empty overload set.
6831  OverloadCandidateSet CandidateSet(OpLoc);
6832
6833  // Add the candidates from the given function set.
6834  AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
6835
6836  // Add operator candidates that are member functions.
6837  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6838
6839  // Add candidates from ADL.
6840  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6841                                       Args, NumArgs,
6842                                       /*ExplicitTemplateArgs*/ 0,
6843                                       CandidateSet);
6844
6845  // Add builtin operator candidates.
6846  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6847
6848  // Perform overload resolution.
6849  OverloadCandidateSet::iterator Best;
6850  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
6851  case OR_Success: {
6852    // We found a built-in operator or an overloaded operator.
6853    FunctionDecl *FnDecl = Best->Function;
6854
6855    if (FnDecl) {
6856      // We matched an overloaded operator. Build a call to that
6857      // operator.
6858
6859      // Convert the arguments.
6860      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
6861        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
6862
6863        if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6864                                                Best->FoundDecl, Method))
6865          return ExprError();
6866      } else {
6867        // Convert the arguments.
6868        ExprResult InputInit
6869          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6870                                                      Context,
6871                                                      FnDecl->getParamDecl(0)),
6872                                      SourceLocation(),
6873                                      Input);
6874        if (InputInit.isInvalid())
6875          return ExprError();
6876        Input = InputInit.take();
6877      }
6878
6879      DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6880
6881      // Determine the result type
6882      QualType ResultTy = FnDecl->getCallResultType();
6883
6884      // Build the actual expression node.
6885      Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6886                                               SourceLocation());
6887      UsualUnaryConversions(FnExpr);
6888
6889      Args[0] = Input;
6890      CallExpr *TheCall =
6891        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6892                                          Args, NumArgs, ResultTy, OpLoc);
6893
6894      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
6895                              FnDecl))
6896        return ExprError();
6897
6898      return MaybeBindToTemporary(TheCall);
6899    } else {
6900      // We matched a built-in operator. Convert the arguments, then
6901      // break out so that we will build the appropriate built-in
6902      // operator node.
6903        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
6904                                      Best->Conversions[0], AA_Passing))
6905          return ExprError();
6906
6907        break;
6908      }
6909    }
6910
6911    case OR_No_Viable_Function:
6912      // No viable function; fall through to handling this as a
6913      // built-in operator, which will produce an error message for us.
6914      break;
6915
6916    case OR_Ambiguous:
6917      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
6918          << UnaryOperator::getOpcodeStr(Opc)
6919          << Input->getSourceRange();
6920      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
6921                                  Args, NumArgs,
6922                                  UnaryOperator::getOpcodeStr(Opc), OpLoc);
6923      return ExprError();
6924
6925    case OR_Deleted:
6926      Diag(OpLoc, diag::err_ovl_deleted_oper)
6927        << Best->Function->isDeleted()
6928        << UnaryOperator::getOpcodeStr(Opc)
6929        << Input->getSourceRange();
6930      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
6931      return ExprError();
6932    }
6933
6934  // Either we found no viable overloaded operator or we matched a
6935  // built-in operator. In either case, fall through to trying to
6936  // build a built-in operation.
6937  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
6938}
6939
6940/// \brief Create a binary operation that may resolve to an overloaded
6941/// operator.
6942///
6943/// \param OpLoc The location of the operator itself (e.g., '+').
6944///
6945/// \param OpcIn The BinaryOperator::Opcode that describes this
6946/// operator.
6947///
6948/// \param Functions The set of non-member functions that will be
6949/// considered by overload resolution. The caller needs to build this
6950/// set based on the context using, e.g.,
6951/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6952/// set should not contain any member functions; those will be added
6953/// by CreateOverloadedBinOp().
6954///
6955/// \param LHS Left-hand argument.
6956/// \param RHS Right-hand argument.
6957ExprResult
6958Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
6959                            unsigned OpcIn,
6960                            const UnresolvedSetImpl &Fns,
6961                            Expr *LHS, Expr *RHS) {
6962  Expr *Args[2] = { LHS, RHS };
6963  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
6964
6965  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6966  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6967  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6968
6969  // If either side is type-dependent, create an appropriate dependent
6970  // expression.
6971  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6972    if (Fns.empty()) {
6973      // If there are no functions to store, just build a dependent
6974      // BinaryOperator or CompoundAssignment.
6975      if (Opc <= BO_Assign || Opc > BO_OrAssign)
6976        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6977                                                  Context.DependentTy, OpLoc));
6978
6979      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6980                                                        Context.DependentTy,
6981                                                        Context.DependentTy,
6982                                                        Context.DependentTy,
6983                                                        OpLoc));
6984    }
6985
6986    // FIXME: save results of ADL from here?
6987    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
6988    // TODO: provide better source location info in DNLoc component.
6989    DeclarationNameInfo OpNameInfo(OpName, OpLoc);
6990    UnresolvedLookupExpr *Fn
6991      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
6992                                     0, SourceRange(), OpNameInfo,
6993                                     /*ADL*/ true, IsOverloaded(Fns),
6994                                     Fns.begin(), Fns.end());
6995    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6996                                                   Args, 2,
6997                                                   Context.DependentTy,
6998                                                   OpLoc));
6999  }
7000
7001  // If this is the .* operator, which is not overloadable, just
7002  // create a built-in binary operator.
7003  if (Opc == BO_PtrMemD)
7004    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7005
7006  // If this is the assignment operator, we only perform overload resolution
7007  // if the left-hand side is a class or enumeration type. This is actually
7008  // a hack. The standard requires that we do overload resolution between the
7009  // various built-in candidates, but as DR507 points out, this can lead to
7010  // problems. So we do it this way, which pretty much follows what GCC does.
7011  // Note that we go the traditional code path for compound assignment forms.
7012  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
7013    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7014
7015  // Build an empty overload set.
7016  OverloadCandidateSet CandidateSet(OpLoc);
7017
7018  // Add the candidates from the given function set.
7019  AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
7020
7021  // Add operator candidates that are member functions.
7022  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7023
7024  // Add candidates from ADL.
7025  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7026                                       Args, 2,
7027                                       /*ExplicitTemplateArgs*/ 0,
7028                                       CandidateSet);
7029
7030  // Add builtin operator candidates.
7031  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7032
7033  // Perform overload resolution.
7034  OverloadCandidateSet::iterator Best;
7035  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
7036    case OR_Success: {
7037      // We found a built-in operator or an overloaded operator.
7038      FunctionDecl *FnDecl = Best->Function;
7039
7040      if (FnDecl) {
7041        // We matched an overloaded operator. Build a call to that
7042        // operator.
7043
7044        // Convert the arguments.
7045        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
7046          // Best->Access is only meaningful for class members.
7047          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
7048
7049          ExprResult Arg1
7050            = PerformCopyInitialization(
7051                                        InitializedEntity::InitializeParameter(
7052                                                        Context,
7053                                                        FnDecl->getParamDecl(0)),
7054                                        SourceLocation(),
7055                                        Owned(Args[1]));
7056          if (Arg1.isInvalid())
7057            return ExprError();
7058
7059          if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
7060                                                  Best->FoundDecl, Method))
7061            return ExprError();
7062
7063          Args[1] = RHS = Arg1.takeAs<Expr>();
7064        } else {
7065          // Convert the arguments.
7066          ExprResult Arg0
7067            = PerformCopyInitialization(
7068                                        InitializedEntity::InitializeParameter(
7069                                                        Context,
7070                                                        FnDecl->getParamDecl(0)),
7071                                        SourceLocation(),
7072                                        Owned(Args[0]));
7073          if (Arg0.isInvalid())
7074            return ExprError();
7075
7076          ExprResult Arg1
7077            = PerformCopyInitialization(
7078                                        InitializedEntity::InitializeParameter(
7079                                                        Context,
7080                                                        FnDecl->getParamDecl(1)),
7081                                        SourceLocation(),
7082                                        Owned(Args[1]));
7083          if (Arg1.isInvalid())
7084            return ExprError();
7085          Args[0] = LHS = Arg0.takeAs<Expr>();
7086          Args[1] = RHS = Arg1.takeAs<Expr>();
7087        }
7088
7089        DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7090
7091        // Determine the result type
7092        QualType ResultTy
7093          = FnDecl->getType()->getAs<FunctionType>()
7094                                                ->getCallResultType(Context);
7095
7096        // Build the actual expression node.
7097        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7098                                                 OpLoc);
7099        UsualUnaryConversions(FnExpr);
7100
7101        CXXOperatorCallExpr *TheCall =
7102          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7103                                            Args, 2, ResultTy, OpLoc);
7104
7105        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
7106                                FnDecl))
7107          return ExprError();
7108
7109        return MaybeBindToTemporary(TheCall);
7110      } else {
7111        // We matched a built-in operator. Convert the arguments, then
7112        // break out so that we will build the appropriate built-in
7113        // operator node.
7114        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
7115                                      Best->Conversions[0], AA_Passing) ||
7116            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
7117                                      Best->Conversions[1], AA_Passing))
7118          return ExprError();
7119
7120        break;
7121      }
7122    }
7123
7124    case OR_No_Viable_Function: {
7125      // C++ [over.match.oper]p9:
7126      //   If the operator is the operator , [...] and there are no
7127      //   viable functions, then the operator is assumed to be the
7128      //   built-in operator and interpreted according to clause 5.
7129      if (Opc == BO_Comma)
7130        break;
7131
7132      // For class as left operand for assignment or compound assigment operator
7133      // do not fall through to handling in built-in, but report that no overloaded
7134      // assignment operator found
7135      ExprResult Result = ExprError();
7136      if (Args[0]->getType()->isRecordType() &&
7137          Opc >= BO_Assign && Opc <= BO_OrAssign) {
7138        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
7139             << BinaryOperator::getOpcodeStr(Opc)
7140             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7141      } else {
7142        // No viable function; try to create a built-in operation, which will
7143        // produce an error. Then, show the non-viable candidates.
7144        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7145      }
7146      assert(Result.isInvalid() &&
7147             "C++ binary operator overloading is missing candidates!");
7148      if (Result.isInvalid())
7149        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7150                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
7151      return move(Result);
7152    }
7153
7154    case OR_Ambiguous:
7155      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
7156          << BinaryOperator::getOpcodeStr(Opc)
7157          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7158      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7159                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
7160      return ExprError();
7161
7162    case OR_Deleted:
7163      Diag(OpLoc, diag::err_ovl_deleted_oper)
7164        << Best->Function->isDeleted()
7165        << BinaryOperator::getOpcodeStr(Opc)
7166        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7167      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
7168      return ExprError();
7169  }
7170
7171  // We matched a built-in operator; build it.
7172  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7173}
7174
7175ExprResult
7176Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7177                                         SourceLocation RLoc,
7178                                         Expr *Base, Expr *Idx) {
7179  Expr *Args[2] = { Base, Idx };
7180  DeclarationName OpName =
7181      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7182
7183  // If either side is type-dependent, create an appropriate dependent
7184  // expression.
7185  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7186
7187    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
7188    // CHECKME: no 'operator' keyword?
7189    DeclarationNameInfo OpNameInfo(OpName, LLoc);
7190    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
7191    UnresolvedLookupExpr *Fn
7192      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
7193                                     0, SourceRange(), OpNameInfo,
7194                                     /*ADL*/ true, /*Overloaded*/ false,
7195                                     UnresolvedSetIterator(),
7196                                     UnresolvedSetIterator());
7197    // Can't add any actual overloads yet
7198
7199    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7200                                                   Args, 2,
7201                                                   Context.DependentTy,
7202                                                   RLoc));
7203  }
7204
7205  // Build an empty overload set.
7206  OverloadCandidateSet CandidateSet(LLoc);
7207
7208  // Subscript can only be overloaded as a member function.
7209
7210  // Add operator candidates that are member functions.
7211  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7212
7213  // Add builtin operator candidates.
7214  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7215
7216  // Perform overload resolution.
7217  OverloadCandidateSet::iterator Best;
7218  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
7219    case OR_Success: {
7220      // We found a built-in operator or an overloaded operator.
7221      FunctionDecl *FnDecl = Best->Function;
7222
7223      if (FnDecl) {
7224        // We matched an overloaded operator. Build a call to that
7225        // operator.
7226
7227        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
7228        DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
7229
7230        // Convert the arguments.
7231        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
7232        if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
7233                                                Best->FoundDecl, Method))
7234          return ExprError();
7235
7236        // Convert the arguments.
7237        ExprResult InputInit
7238          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7239                                                      Context,
7240                                                      FnDecl->getParamDecl(0)),
7241                                      SourceLocation(),
7242                                      Owned(Args[1]));
7243        if (InputInit.isInvalid())
7244          return ExprError();
7245
7246        Args[1] = InputInit.takeAs<Expr>();
7247
7248        // Determine the result type
7249        QualType ResultTy
7250          = FnDecl->getType()->getAs<FunctionType>()
7251                                                  ->getCallResultType(Context);
7252
7253        // Build the actual expression node.
7254        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7255                                                 LLoc);
7256        UsualUnaryConversions(FnExpr);
7257
7258        CXXOperatorCallExpr *TheCall =
7259          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7260                                            FnExpr, Args, 2,
7261                                            ResultTy, RLoc);
7262
7263        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
7264                                FnDecl))
7265          return ExprError();
7266
7267        return MaybeBindToTemporary(TheCall);
7268      } else {
7269        // We matched a built-in operator. Convert the arguments, then
7270        // break out so that we will build the appropriate built-in
7271        // operator node.
7272        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
7273                                      Best->Conversions[0], AA_Passing) ||
7274            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
7275                                      Best->Conversions[1], AA_Passing))
7276          return ExprError();
7277
7278        break;
7279      }
7280    }
7281
7282    case OR_No_Viable_Function: {
7283      if (CandidateSet.empty())
7284        Diag(LLoc, diag::err_ovl_no_oper)
7285          << Args[0]->getType() << /*subscript*/ 0
7286          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7287      else
7288        Diag(LLoc, diag::err_ovl_no_viable_subscript)
7289          << Args[0]->getType()
7290          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7291      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7292                                  "[]", LLoc);
7293      return ExprError();
7294    }
7295
7296    case OR_Ambiguous:
7297      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
7298          << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7299      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7300                                  "[]", LLoc);
7301      return ExprError();
7302
7303    case OR_Deleted:
7304      Diag(LLoc, diag::err_ovl_deleted_oper)
7305        << Best->Function->isDeleted() << "[]"
7306        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7307      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7308                                  "[]", LLoc);
7309      return ExprError();
7310    }
7311
7312  // We matched a built-in operator; build it.
7313  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
7314}
7315
7316/// BuildCallToMemberFunction - Build a call to a member
7317/// function. MemExpr is the expression that refers to the member
7318/// function (and includes the object parameter), Args/NumArgs are the
7319/// arguments to the function call (not including the object
7320/// parameter). The caller needs to validate that the member
7321/// expression refers to a member function or an overloaded member
7322/// function.
7323ExprResult
7324Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7325                                SourceLocation LParenLoc, Expr **Args,
7326                                unsigned NumArgs, SourceLocation RParenLoc) {
7327  // Dig out the member expression. This holds both the object
7328  // argument and the member function we're referring to.
7329  Expr *NakedMemExpr = MemExprE->IgnoreParens();
7330
7331  MemberExpr *MemExpr;
7332  CXXMethodDecl *Method = 0;
7333  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
7334  NestedNameSpecifier *Qualifier = 0;
7335  if (isa<MemberExpr>(NakedMemExpr)) {
7336    MemExpr = cast<MemberExpr>(NakedMemExpr);
7337    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
7338    FoundDecl = MemExpr->getFoundDecl();
7339    Qualifier = MemExpr->getQualifier();
7340  } else {
7341    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
7342    Qualifier = UnresExpr->getQualifier();
7343
7344    QualType ObjectType = UnresExpr->getBaseType();
7345
7346    // Add overload candidates
7347    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
7348
7349    // FIXME: avoid copy.
7350    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7351    if (UnresExpr->hasExplicitTemplateArgs()) {
7352      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7353      TemplateArgs = &TemplateArgsBuffer;
7354    }
7355
7356    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7357           E = UnresExpr->decls_end(); I != E; ++I) {
7358
7359      NamedDecl *Func = *I;
7360      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7361      if (isa<UsingShadowDecl>(Func))
7362        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7363
7364      if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
7365        // If explicit template arguments were provided, we can't call a
7366        // non-template member function.
7367        if (TemplateArgs)
7368          continue;
7369
7370        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
7371                           Args, NumArgs,
7372                           CandidateSet, /*SuppressUserConversions=*/false);
7373      } else {
7374        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
7375                                   I.getPair(), ActingDC, TemplateArgs,
7376                                   ObjectType, Args, NumArgs,
7377                                   CandidateSet,
7378                                   /*SuppressUsedConversions=*/false);
7379      }
7380    }
7381
7382    DeclarationName DeclName = UnresExpr->getMemberName();
7383
7384    OverloadCandidateSet::iterator Best;
7385    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
7386                               Best)) {
7387    case OR_Success:
7388      Method = cast<CXXMethodDecl>(Best->Function);
7389      FoundDecl = Best->FoundDecl;
7390      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
7391      DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
7392      break;
7393
7394    case OR_No_Viable_Function:
7395      Diag(UnresExpr->getMemberLoc(),
7396           diag::err_ovl_no_viable_member_function_in_call)
7397        << DeclName << MemExprE->getSourceRange();
7398      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7399      // FIXME: Leaking incoming expressions!
7400      return ExprError();
7401
7402    case OR_Ambiguous:
7403      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
7404        << DeclName << MemExprE->getSourceRange();
7405      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7406      // FIXME: Leaking incoming expressions!
7407      return ExprError();
7408
7409    case OR_Deleted:
7410      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
7411        << Best->Function->isDeleted()
7412        << DeclName << MemExprE->getSourceRange();
7413      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7414      // FIXME: Leaking incoming expressions!
7415      return ExprError();
7416    }
7417
7418    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
7419
7420    // If overload resolution picked a static member, build a
7421    // non-member call based on that function.
7422    if (Method->isStatic()) {
7423      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7424                                   Args, NumArgs, RParenLoc);
7425    }
7426
7427    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
7428  }
7429
7430  assert(Method && "Member call to something that isn't a method?");
7431  CXXMemberCallExpr *TheCall =
7432    new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7433                                    Method->getCallResultType(),
7434                                    RParenLoc);
7435
7436  // Check for a valid return type.
7437  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
7438                          TheCall, Method))
7439    return ExprError();
7440
7441  // Convert the object argument (for a non-static member function call).
7442  // We only need to do this if there was actually an overload; otherwise
7443  // it was done at lookup.
7444  Expr *ObjectArg = MemExpr->getBase();
7445  if (!Method->isStatic() &&
7446      PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7447                                          FoundDecl, Method))
7448    return ExprError();
7449  MemExpr->setBase(ObjectArg);
7450
7451  // Convert the rest of the arguments
7452  const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
7453  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
7454                              RParenLoc))
7455    return ExprError();
7456
7457  if (CheckFunctionCall(Method, TheCall))
7458    return ExprError();
7459
7460  return MaybeBindToTemporary(TheCall);
7461}
7462
7463/// BuildCallToObjectOfClassType - Build a call to an object of class
7464/// type (C++ [over.call.object]), which can end up invoking an
7465/// overloaded function call operator (@c operator()) or performing a
7466/// user-defined conversion on the object argument.
7467ExprResult
7468Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
7469                                   SourceLocation LParenLoc,
7470                                   Expr **Args, unsigned NumArgs,
7471                                   SourceLocation RParenLoc) {
7472  assert(Object->getType()->isRecordType() && "Requires object type argument");
7473  const RecordType *Record = Object->getType()->getAs<RecordType>();
7474
7475  // C++ [over.call.object]p1:
7476  //  If the primary-expression E in the function call syntax
7477  //  evaluates to a class object of type "cv T", then the set of
7478  //  candidate functions includes at least the function call
7479  //  operators of T. The function call operators of T are obtained by
7480  //  ordinary lookup of the name operator() in the context of
7481  //  (E).operator().
7482  OverloadCandidateSet CandidateSet(LParenLoc);
7483  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
7484
7485  if (RequireCompleteType(LParenLoc, Object->getType(),
7486                          PDiag(diag::err_incomplete_object_call)
7487                          << Object->getSourceRange()))
7488    return true;
7489
7490  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7491  LookupQualifiedName(R, Record->getDecl());
7492  R.suppressDiagnostics();
7493
7494  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
7495       Oper != OperEnd; ++Oper) {
7496    AddMethodCandidate(Oper.getPair(), Object->getType(),
7497                       Args, NumArgs, CandidateSet,
7498                       /*SuppressUserConversions=*/ false);
7499  }
7500
7501  // C++ [over.call.object]p2:
7502  //   In addition, for each conversion function declared in T of the
7503  //   form
7504  //
7505  //        operator conversion-type-id () cv-qualifier;
7506  //
7507  //   where cv-qualifier is the same cv-qualification as, or a
7508  //   greater cv-qualification than, cv, and where conversion-type-id
7509  //   denotes the type "pointer to function of (P1,...,Pn) returning
7510  //   R", or the type "reference to pointer to function of
7511  //   (P1,...,Pn) returning R", or the type "reference to function
7512  //   of (P1,...,Pn) returning R", a surrogate call function [...]
7513  //   is also considered as a candidate function. Similarly,
7514  //   surrogate call functions are added to the set of candidate
7515  //   functions for each conversion function declared in an
7516  //   accessible base class provided the function is not hidden
7517  //   within T by another intervening declaration.
7518  const UnresolvedSetImpl *Conversions
7519    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
7520  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
7521         E = Conversions->end(); I != E; ++I) {
7522    NamedDecl *D = *I;
7523    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7524    if (isa<UsingShadowDecl>(D))
7525      D = cast<UsingShadowDecl>(D)->getTargetDecl();
7526
7527    // Skip over templated conversion functions; they aren't
7528    // surrogates.
7529    if (isa<FunctionTemplateDecl>(D))
7530      continue;
7531
7532    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7533
7534    // Strip the reference type (if any) and then the pointer type (if
7535    // any) to get down to what might be a function type.
7536    QualType ConvType = Conv->getConversionType().getNonReferenceType();
7537    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7538      ConvType = ConvPtrType->getPointeeType();
7539
7540    if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
7541      AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
7542                            Object->getType(), Args, NumArgs,
7543                            CandidateSet);
7544  }
7545
7546  // Perform overload resolution.
7547  OverloadCandidateSet::iterator Best;
7548  switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7549                             Best)) {
7550  case OR_Success:
7551    // Overload resolution succeeded; we'll build the appropriate call
7552    // below.
7553    break;
7554
7555  case OR_No_Viable_Function:
7556    if (CandidateSet.empty())
7557      Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7558        << Object->getType() << /*call*/ 1
7559        << Object->getSourceRange();
7560    else
7561      Diag(Object->getSourceRange().getBegin(),
7562           diag::err_ovl_no_viable_object_call)
7563        << Object->getType() << Object->getSourceRange();
7564    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7565    break;
7566
7567  case OR_Ambiguous:
7568    Diag(Object->getSourceRange().getBegin(),
7569         diag::err_ovl_ambiguous_object_call)
7570      << Object->getType() << Object->getSourceRange();
7571    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
7572    break;
7573
7574  case OR_Deleted:
7575    Diag(Object->getSourceRange().getBegin(),
7576         diag::err_ovl_deleted_object_call)
7577      << Best->Function->isDeleted()
7578      << Object->getType() << Object->getSourceRange();
7579    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7580    break;
7581  }
7582
7583  if (Best == CandidateSet.end())
7584    return true;
7585
7586  if (Best->Function == 0) {
7587    // Since there is no function declaration, this is one of the
7588    // surrogate candidates. Dig out the conversion function.
7589    CXXConversionDecl *Conv
7590      = cast<CXXConversionDecl>(
7591                         Best->Conversions[0].UserDefined.ConversionFunction);
7592
7593    CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
7594    DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
7595
7596    // We selected one of the surrogate functions that converts the
7597    // object parameter to a function pointer. Perform the conversion
7598    // on the object argument, then let ActOnCallExpr finish the job.
7599
7600    // Create an implicit member expr to refer to the conversion operator.
7601    // and then call it.
7602    CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7603                                                   Conv);
7604
7605    return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
7606                         RParenLoc);
7607  }
7608
7609  CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
7610  DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
7611
7612  // We found an overloaded operator(). Build a CXXOperatorCallExpr
7613  // that calls this method, using Object for the implicit object
7614  // parameter and passing along the remaining arguments.
7615  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
7616  const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
7617
7618  unsigned NumArgsInProto = Proto->getNumArgs();
7619  unsigned NumArgsToCheck = NumArgs;
7620
7621  // Build the full argument list for the method call (the
7622  // implicit object parameter is placed at the beginning of the
7623  // list).
7624  Expr **MethodArgs;
7625  if (NumArgs < NumArgsInProto) {
7626    NumArgsToCheck = NumArgsInProto;
7627    MethodArgs = new Expr*[NumArgsInProto + 1];
7628  } else {
7629    MethodArgs = new Expr*[NumArgs + 1];
7630  }
7631  MethodArgs[0] = Object;
7632  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7633    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
7634
7635  Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
7636                                          SourceLocation());
7637  UsualUnaryConversions(NewFn);
7638
7639  // Once we've built TheCall, all of the expressions are properly
7640  // owned.
7641  QualType ResultTy = Method->getCallResultType();
7642  CXXOperatorCallExpr *TheCall =
7643    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7644                                      MethodArgs, NumArgs + 1,
7645                                      ResultTy, RParenLoc);
7646  delete [] MethodArgs;
7647
7648  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
7649                          Method))
7650    return true;
7651
7652  // We may have default arguments. If so, we need to allocate more
7653  // slots in the call for them.
7654  if (NumArgs < NumArgsInProto)
7655    TheCall->setNumArgs(Context, NumArgsInProto + 1);
7656  else if (NumArgs > NumArgsInProto)
7657    NumArgsToCheck = NumArgsInProto;
7658
7659  bool IsError = false;
7660
7661  // Initialize the implicit object parameter.
7662  IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
7663                                                 Best->FoundDecl, Method);
7664  TheCall->setArg(0, Object);
7665
7666
7667  // Check the argument types.
7668  for (unsigned i = 0; i != NumArgsToCheck; i++) {
7669    Expr *Arg;
7670    if (i < NumArgs) {
7671      Arg = Args[i];
7672
7673      // Pass the argument.
7674
7675      ExprResult InputInit
7676        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7677                                                    Context,
7678                                                    Method->getParamDecl(i)),
7679                                    SourceLocation(), Arg);
7680
7681      IsError |= InputInit.isInvalid();
7682      Arg = InputInit.takeAs<Expr>();
7683    } else {
7684      ExprResult DefArg
7685        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7686      if (DefArg.isInvalid()) {
7687        IsError = true;
7688        break;
7689      }
7690
7691      Arg = DefArg.takeAs<Expr>();
7692    }
7693
7694    TheCall->setArg(i + 1, Arg);
7695  }
7696
7697  // If this is a variadic call, handle args passed through "...".
7698  if (Proto->isVariadic()) {
7699    // Promote the arguments (C99 6.5.2.2p7).
7700    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7701      Expr *Arg = Args[i];
7702      IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
7703      TheCall->setArg(i + 1, Arg);
7704    }
7705  }
7706
7707  if (IsError) return true;
7708
7709  if (CheckFunctionCall(Method, TheCall))
7710    return true;
7711
7712  return MaybeBindToTemporary(TheCall);
7713}
7714
7715/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
7716///  (if one exists), where @c Base is an expression of class type and
7717/// @c Member is the name of the member we're trying to find.
7718ExprResult
7719Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
7720  assert(Base->getType()->isRecordType() && "left-hand side must have class type");
7721
7722  SourceLocation Loc = Base->getExprLoc();
7723
7724  // C++ [over.ref]p1:
7725  //
7726  //   [...] An expression x->m is interpreted as (x.operator->())->m
7727  //   for a class object x of type T if T::operator->() exists and if
7728  //   the operator is selected as the best match function by the
7729  //   overload resolution mechanism (13.3).
7730  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
7731  OverloadCandidateSet CandidateSet(Loc);
7732  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
7733
7734  if (RequireCompleteType(Loc, Base->getType(),
7735                          PDiag(diag::err_typecheck_incomplete_tag)
7736                            << Base->getSourceRange()))
7737    return ExprError();
7738
7739  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7740  LookupQualifiedName(R, BaseRecord->getDecl());
7741  R.suppressDiagnostics();
7742
7743  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
7744       Oper != OperEnd; ++Oper) {
7745    AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
7746                       /*SuppressUserConversions=*/false);
7747  }
7748
7749  // Perform overload resolution.
7750  OverloadCandidateSet::iterator Best;
7751  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
7752  case OR_Success:
7753    // Overload resolution succeeded; we'll build the call below.
7754    break;
7755
7756  case OR_No_Viable_Function:
7757    if (CandidateSet.empty())
7758      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7759        << Base->getType() << Base->getSourceRange();
7760    else
7761      Diag(OpLoc, diag::err_ovl_no_viable_oper)
7762        << "operator->" << Base->getSourceRange();
7763    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
7764    return ExprError();
7765
7766  case OR_Ambiguous:
7767    Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
7768      << "->" << Base->getSourceRange();
7769    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
7770    return ExprError();
7771
7772  case OR_Deleted:
7773    Diag(OpLoc,  diag::err_ovl_deleted_oper)
7774      << Best->Function->isDeleted()
7775      << "->" << Base->getSourceRange();
7776    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
7777    return ExprError();
7778  }
7779
7780  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
7781  DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7782
7783  // Convert the object parameter.
7784  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
7785  if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7786                                          Best->FoundDecl, Method))
7787    return ExprError();
7788
7789  // Build the operator call.
7790  Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7791                                           SourceLocation());
7792  UsualUnaryConversions(FnExpr);
7793
7794  QualType ResultTy = Method->getCallResultType();
7795  CXXOperatorCallExpr *TheCall =
7796    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7797                                      &Base, 1, ResultTy, OpLoc);
7798
7799  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
7800                          Method))
7801          return ExprError();
7802  return Owned(TheCall);
7803}
7804
7805/// FixOverloadedFunctionReference - E is an expression that refers to
7806/// a C++ overloaded function (possibly with some parentheses and
7807/// perhaps a '&' around it). We have resolved the overloaded function
7808/// to the function declaration Fn, so patch up the expression E to
7809/// refer (possibly indirectly) to Fn. Returns the new expr.
7810Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
7811                                           FunctionDecl *Fn) {
7812  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7813    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7814                                                   Found, Fn);
7815    if (SubExpr == PE->getSubExpr())
7816      return PE->Retain();
7817
7818    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7819  }
7820
7821  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7822    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7823                                                   Found, Fn);
7824    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
7825                               SubExpr->getType()) &&
7826           "Implicit cast type cannot be determined from overload");
7827    assert(ICE->path_empty() && "fixing up hierarchy conversion?");
7828    if (SubExpr == ICE->getSubExpr())
7829      return ICE->Retain();
7830
7831    return ImplicitCastExpr::Create(Context, ICE->getType(),
7832                                    ICE->getCastKind(),
7833                                    SubExpr, 0,
7834                                    ICE->getValueKind());
7835  }
7836
7837  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
7838    assert(UnOp->getOpcode() == UO_AddrOf &&
7839           "Can only take the address of an overloaded function");
7840    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7841      if (Method->isStatic()) {
7842        // Do nothing: static member functions aren't any different
7843        // from non-member functions.
7844      } else {
7845        // Fix the sub expression, which really has to be an
7846        // UnresolvedLookupExpr holding an overloaded member function
7847        // or template.
7848        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7849                                                       Found, Fn);
7850        if (SubExpr == UnOp->getSubExpr())
7851          return UnOp->Retain();
7852
7853        assert(isa<DeclRefExpr>(SubExpr)
7854               && "fixed to something other than a decl ref");
7855        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7856               && "fixed to a member ref with no nested name qualifier");
7857
7858        // We have taken the address of a pointer to member
7859        // function. Perform the computation here so that we get the
7860        // appropriate pointer to member type.
7861        QualType ClassType
7862          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7863        QualType MemPtrType
7864          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7865
7866        return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
7867                                           MemPtrType, UnOp->getOperatorLoc());
7868      }
7869    }
7870    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7871                                                   Found, Fn);
7872    if (SubExpr == UnOp->getSubExpr())
7873      return UnOp->Retain();
7874
7875    return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
7876                                     Context.getPointerType(SubExpr->getType()),
7877                                       UnOp->getOperatorLoc());
7878  }
7879
7880  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
7881    // FIXME: avoid copy.
7882    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7883    if (ULE->hasExplicitTemplateArgs()) {
7884      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7885      TemplateArgs = &TemplateArgsBuffer;
7886    }
7887
7888    return DeclRefExpr::Create(Context,
7889                               ULE->getQualifier(),
7890                               ULE->getQualifierRange(),
7891                               Fn,
7892                               ULE->getNameLoc(),
7893                               Fn->getType(),
7894                               TemplateArgs);
7895  }
7896
7897  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
7898    // FIXME: avoid copy.
7899    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7900    if (MemExpr->hasExplicitTemplateArgs()) {
7901      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7902      TemplateArgs = &TemplateArgsBuffer;
7903    }
7904
7905    Expr *Base;
7906
7907    // If we're filling in
7908    if (MemExpr->isImplicitAccess()) {
7909      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7910        return DeclRefExpr::Create(Context,
7911                                   MemExpr->getQualifier(),
7912                                   MemExpr->getQualifierRange(),
7913                                   Fn,
7914                                   MemExpr->getMemberLoc(),
7915                                   Fn->getType(),
7916                                   TemplateArgs);
7917      } else {
7918        SourceLocation Loc = MemExpr->getMemberLoc();
7919        if (MemExpr->getQualifier())
7920          Loc = MemExpr->getQualifierRange().getBegin();
7921        Base = new (Context) CXXThisExpr(Loc,
7922                                         MemExpr->getBaseType(),
7923                                         /*isImplicit=*/true);
7924      }
7925    } else
7926      Base = MemExpr->getBase()->Retain();
7927
7928    return MemberExpr::Create(Context, Base,
7929                              MemExpr->isArrow(),
7930                              MemExpr->getQualifier(),
7931                              MemExpr->getQualifierRange(),
7932                              Fn,
7933                              Found,
7934                              MemExpr->getMemberNameInfo(),
7935                              TemplateArgs,
7936                              Fn->getType());
7937  }
7938
7939  assert(false && "Invalid reference to overloaded function");
7940  return E->Retain();
7941}
7942
7943ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
7944                                                DeclAccessPair Found,
7945                                                FunctionDecl *Fn) {
7946  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
7947}
7948
7949} // end namespace clang
7950