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