SemaOverload.cpp revision 78c057e5a16b3ba186cc6453ca26b15745f2b79d
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    if (Result == MatchesCopy.end())
6434      return 0;
6435
6436    MarkDeclarationReferenced(From->getLocStart(), *Result);
6437    FoundResult = Matches[Result - MatchesCopy.begin()].first;
6438    if (Complain) {
6439      CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
6440      DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6441    }
6442    return cast<FunctionDecl>(*Result);
6443  }
6444
6445  //   [...] any function template specializations in the set are
6446  //   eliminated if the set also contains a non-template function, [...]
6447  for (unsigned I = 0, N = Matches.size(); I != N; ) {
6448    if (Matches[I].second->getPrimaryTemplate() == 0)
6449      ++I;
6450    else {
6451      Matches[I] = Matches[--N];
6452      Matches.set_size(N);
6453    }
6454  }
6455
6456  // [...] After such eliminations, if any, there shall remain exactly one
6457  // selected function.
6458  if (Matches.size() == 1) {
6459    MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
6460    FoundResult = Matches[0].first;
6461    if (Complain) {
6462      CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6463      DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6464    }
6465    return cast<FunctionDecl>(Matches[0].second);
6466  }
6467
6468  // FIXME: We should probably return the same thing that BestViableFunction
6469  // returns (even if we issue the diagnostics here).
6470  Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6471    << Matches[0].second->getDeclName();
6472  for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6473    NoteOverloadCandidate(Matches[I].second);
6474  return 0;
6475}
6476
6477/// \brief Given an expression that refers to an overloaded function, try to
6478/// resolve that overloaded function expression down to a single function.
6479///
6480/// This routine can only resolve template-ids that refer to a single function
6481/// template, where that template-id refers to a single template whose template
6482/// arguments are either provided by the template-id or have defaults,
6483/// as described in C++0x [temp.arg.explicit]p3.
6484FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6485  // C++ [over.over]p1:
6486  //   [...] [Note: any redundant set of parentheses surrounding the
6487  //   overloaded function name is ignored (5.1). ]
6488  // C++ [over.over]p1:
6489  //   [...] The overloaded function name can be preceded by the &
6490  //   operator.
6491
6492  if (From->getType() != Context.OverloadTy)
6493    return 0;
6494
6495  OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
6496
6497  // If we didn't actually find any template-ids, we're done.
6498  if (!OvlExpr->hasExplicitTemplateArgs())
6499    return 0;
6500
6501  TemplateArgumentListInfo ExplicitTemplateArgs;
6502  OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
6503
6504  // Look through all of the overloaded functions, searching for one
6505  // whose type matches exactly.
6506  FunctionDecl *Matched = 0;
6507  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6508         E = OvlExpr->decls_end(); I != E; ++I) {
6509    // C++0x [temp.arg.explicit]p3:
6510    //   [...] In contexts where deduction is done and fails, or in contexts
6511    //   where deduction is not done, if a template argument list is
6512    //   specified and it, along with any default template arguments,
6513    //   identifies a single function template specialization, then the
6514    //   template-id is an lvalue for the function template specialization.
6515    FunctionTemplateDecl *FunctionTemplate
6516      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
6517
6518    // C++ [over.over]p2:
6519    //   If the name is a function template, template argument deduction is
6520    //   done (14.8.2.2), and if the argument deduction succeeds, the
6521    //   resulting template argument list is used to generate a single
6522    //   function template specialization, which is added to the set of
6523    //   overloaded functions considered.
6524    FunctionDecl *Specialization = 0;
6525    TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
6526    if (TemplateDeductionResult Result
6527          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6528                                    Specialization, Info)) {
6529      // FIXME: make a note of the failed deduction for diagnostics.
6530      (void)Result;
6531      continue;
6532    }
6533
6534    // Multiple matches; we can't resolve to a single declaration.
6535    if (Matched)
6536      return 0;
6537
6538    Matched = Specialization;
6539  }
6540
6541  return Matched;
6542}
6543
6544/// \brief Add a single candidate to the overload set.
6545static void AddOverloadedCallCandidate(Sema &S,
6546                                       DeclAccessPair FoundDecl,
6547                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
6548                                       Expr **Args, unsigned NumArgs,
6549                                       OverloadCandidateSet &CandidateSet,
6550                                       bool PartialOverloading) {
6551  NamedDecl *Callee = FoundDecl.getDecl();
6552  if (isa<UsingShadowDecl>(Callee))
6553    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6554
6555  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
6556    assert(!ExplicitTemplateArgs && "Explicit template arguments?");
6557    S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
6558                           false, PartialOverloading);
6559    return;
6560  }
6561
6562  if (FunctionTemplateDecl *FuncTemplate
6563      = dyn_cast<FunctionTemplateDecl>(Callee)) {
6564    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6565                                   ExplicitTemplateArgs,
6566                                   Args, NumArgs, CandidateSet);
6567    return;
6568  }
6569
6570  assert(false && "unhandled case in overloaded call candidate");
6571
6572  // do nothing?
6573}
6574
6575/// \brief Add the overload candidates named by callee and/or found by argument
6576/// dependent lookup to the given overload set.
6577void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
6578                                       Expr **Args, unsigned NumArgs,
6579                                       OverloadCandidateSet &CandidateSet,
6580                                       bool PartialOverloading) {
6581
6582#ifndef NDEBUG
6583  // Verify that ArgumentDependentLookup is consistent with the rules
6584  // in C++0x [basic.lookup.argdep]p3:
6585  //
6586  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
6587  //   and let Y be the lookup set produced by argument dependent
6588  //   lookup (defined as follows). If X contains
6589  //
6590  //     -- a declaration of a class member, or
6591  //
6592  //     -- a block-scope function declaration that is not a
6593  //        using-declaration, or
6594  //
6595  //     -- a declaration that is neither a function or a function
6596  //        template
6597  //
6598  //   then Y is empty.
6599
6600  if (ULE->requiresADL()) {
6601    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6602           E = ULE->decls_end(); I != E; ++I) {
6603      assert(!(*I)->getDeclContext()->isRecord());
6604      assert(isa<UsingShadowDecl>(*I) ||
6605             !(*I)->getDeclContext()->isFunctionOrMethod());
6606      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
6607    }
6608  }
6609#endif
6610
6611  // It would be nice to avoid this copy.
6612  TemplateArgumentListInfo TABuffer;
6613  const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6614  if (ULE->hasExplicitTemplateArgs()) {
6615    ULE->copyTemplateArgumentsInto(TABuffer);
6616    ExplicitTemplateArgs = &TABuffer;
6617  }
6618
6619  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6620         E = ULE->decls_end(); I != E; ++I)
6621    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
6622                               Args, NumArgs, CandidateSet,
6623                               PartialOverloading);
6624
6625  if (ULE->requiresADL())
6626    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6627                                         Args, NumArgs,
6628                                         ExplicitTemplateArgs,
6629                                         CandidateSet,
6630                                         PartialOverloading);
6631}
6632
6633/// Attempts to recover from a call where no functions were found.
6634///
6635/// Returns true if new candidates were found.
6636static ExprResult
6637BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
6638                      UnresolvedLookupExpr *ULE,
6639                      SourceLocation LParenLoc,
6640                      Expr **Args, unsigned NumArgs,
6641                      SourceLocation RParenLoc) {
6642
6643  CXXScopeSpec SS;
6644  if (ULE->getQualifier()) {
6645    SS.setScopeRep(ULE->getQualifier());
6646    SS.setRange(ULE->getQualifierRange());
6647  }
6648
6649  TemplateArgumentListInfo TABuffer;
6650  const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6651  if (ULE->hasExplicitTemplateArgs()) {
6652    ULE->copyTemplateArgumentsInto(TABuffer);
6653    ExplicitTemplateArgs = &TABuffer;
6654  }
6655
6656  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6657                 Sema::LookupOrdinaryName);
6658  if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
6659    return ExprError();
6660
6661  assert(!R.empty() && "lookup results empty despite recovery");
6662
6663  // Build an implicit member call if appropriate.  Just drop the
6664  // casts and such from the call, we don't really care.
6665  ExprResult NewFn = ExprError();
6666  if ((*R.begin())->isCXXClassMember())
6667    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6668  else if (ExplicitTemplateArgs)
6669    NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6670  else
6671    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6672
6673  if (NewFn.isInvalid())
6674    return ExprError();
6675
6676  // This shouldn't cause an infinite loop because we're giving it
6677  // an expression with non-empty lookup results, which should never
6678  // end up here.
6679  return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
6680                               MultiExprArg(Args, NumArgs), RParenLoc);
6681}
6682
6683/// ResolveOverloadedCallFn - Given the call expression that calls Fn
6684/// (which eventually refers to the declaration Func) and the call
6685/// arguments Args/NumArgs, attempt to resolve the function call down
6686/// to a specific function. If overload resolution succeeds, returns
6687/// the function declaration produced by overload
6688/// resolution. Otherwise, emits diagnostics, deletes all of the
6689/// arguments and Fn, and returns NULL.
6690ExprResult
6691Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
6692                              SourceLocation LParenLoc,
6693                              Expr **Args, unsigned NumArgs,
6694                              SourceLocation RParenLoc) {
6695#ifndef NDEBUG
6696  if (ULE->requiresADL()) {
6697    // To do ADL, we must have found an unqualified name.
6698    assert(!ULE->getQualifier() && "qualified name with ADL");
6699
6700    // We don't perform ADL for implicit declarations of builtins.
6701    // Verify that this was correctly set up.
6702    FunctionDecl *F;
6703    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6704        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6705        F->getBuiltinID() && F->isImplicit())
6706      assert(0 && "performing ADL for builtin");
6707
6708    // We don't perform ADL in C.
6709    assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6710  }
6711#endif
6712
6713  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
6714
6715  // Add the functions denoted by the callee to the set of candidate
6716  // functions, including those from argument-dependent lookup.
6717  AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
6718
6719  // If we found nothing, try to recover.
6720  // AddRecoveryCallCandidates diagnoses the error itself, so we just
6721  // bailout out if it fails.
6722  if (CandidateSet.empty())
6723    return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
6724                                 RParenLoc);
6725
6726  OverloadCandidateSet::iterator Best;
6727  switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
6728  case OR_Success: {
6729    FunctionDecl *FDecl = Best->Function;
6730    CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
6731    DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
6732    Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
6733    return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6734  }
6735
6736  case OR_No_Viable_Function:
6737    Diag(Fn->getSourceRange().getBegin(),
6738         diag::err_ovl_no_viable_function_in_call)
6739      << ULE->getName() << Fn->getSourceRange();
6740    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
6741    break;
6742
6743  case OR_Ambiguous:
6744    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
6745      << ULE->getName() << Fn->getSourceRange();
6746    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
6747    break;
6748
6749  case OR_Deleted:
6750    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6751      << Best->Function->isDeleted()
6752      << ULE->getName()
6753      << Fn->getSourceRange();
6754    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
6755    break;
6756  }
6757
6758  // Overload resolution failed.
6759  return ExprError();
6760}
6761
6762static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
6763  return Functions.size() > 1 ||
6764    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6765}
6766
6767/// \brief Create a unary operation that may resolve to an overloaded
6768/// operator.
6769///
6770/// \param OpLoc The location of the operator itself (e.g., '*').
6771///
6772/// \param OpcIn The UnaryOperator::Opcode that describes this
6773/// operator.
6774///
6775/// \param Functions The set of non-member functions that will be
6776/// considered by overload resolution. The caller needs to build this
6777/// set based on the context using, e.g.,
6778/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6779/// set should not contain any member functions; those will be added
6780/// by CreateOverloadedUnaryOp().
6781///
6782/// \param input The input argument.
6783ExprResult
6784Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6785                              const UnresolvedSetImpl &Fns,
6786                              Expr *Input) {
6787  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6788
6789  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6790  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6791  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6792  // TODO: provide better source location info.
6793  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
6794
6795  Expr *Args[2] = { Input, 0 };
6796  unsigned NumArgs = 1;
6797
6798  // For post-increment and post-decrement, add the implicit '0' as
6799  // the second argument, so that we know this is a post-increment or
6800  // post-decrement.
6801  if (Opc == UO_PostInc || Opc == UO_PostDec) {
6802    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
6803    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
6804                                     SourceLocation());
6805    NumArgs = 2;
6806  }
6807
6808  if (Input->isTypeDependent()) {
6809    if (Fns.empty())
6810      return Owned(new (Context) UnaryOperator(Input,
6811                                               Opc,
6812                                               Context.DependentTy,
6813                                               OpLoc));
6814
6815    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
6816    UnresolvedLookupExpr *Fn
6817      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
6818                                     0, SourceRange(), OpNameInfo,
6819                                     /*ADL*/ true, IsOverloaded(Fns),
6820                                     Fns.begin(), Fns.end());
6821    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6822                                                   &Args[0], NumArgs,
6823                                                   Context.DependentTy,
6824                                                   OpLoc));
6825  }
6826
6827  // Build an empty overload set.
6828  OverloadCandidateSet CandidateSet(OpLoc);
6829
6830  // Add the candidates from the given function set.
6831  AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
6832
6833  // Add operator candidates that are member functions.
6834  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6835
6836  // Add candidates from ADL.
6837  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6838                                       Args, NumArgs,
6839                                       /*ExplicitTemplateArgs*/ 0,
6840                                       CandidateSet);
6841
6842  // Add builtin operator candidates.
6843  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6844
6845  // Perform overload resolution.
6846  OverloadCandidateSet::iterator Best;
6847  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
6848  case OR_Success: {
6849    // We found a built-in operator or an overloaded operator.
6850    FunctionDecl *FnDecl = Best->Function;
6851
6852    if (FnDecl) {
6853      // We matched an overloaded operator. Build a call to that
6854      // operator.
6855
6856      // Convert the arguments.
6857      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
6858        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
6859
6860        if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6861                                                Best->FoundDecl, Method))
6862          return ExprError();
6863      } else {
6864        // Convert the arguments.
6865        ExprResult InputInit
6866          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6867                                                      FnDecl->getParamDecl(0)),
6868                                      SourceLocation(),
6869                                      Input);
6870        if (InputInit.isInvalid())
6871          return ExprError();
6872        Input = InputInit.take();
6873      }
6874
6875      DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6876
6877      // Determine the result type
6878      QualType ResultTy = FnDecl->getCallResultType();
6879
6880      // Build the actual expression node.
6881      Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6882                                               SourceLocation());
6883      UsualUnaryConversions(FnExpr);
6884
6885      Args[0] = Input;
6886      CallExpr *TheCall =
6887        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6888                                          Args, NumArgs, ResultTy, OpLoc);
6889
6890      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
6891                              FnDecl))
6892        return ExprError();
6893
6894      return MaybeBindToTemporary(TheCall);
6895    } else {
6896      // We matched a built-in operator. Convert the arguments, then
6897      // break out so that we will build the appropriate built-in
6898      // operator node.
6899        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
6900                                      Best->Conversions[0], AA_Passing))
6901          return ExprError();
6902
6903        break;
6904      }
6905    }
6906
6907    case OR_No_Viable_Function:
6908      // No viable function; fall through to handling this as a
6909      // built-in operator, which will produce an error message for us.
6910      break;
6911
6912    case OR_Ambiguous:
6913      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
6914          << UnaryOperator::getOpcodeStr(Opc)
6915          << Input->getSourceRange();
6916      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
6917                                  Args, NumArgs,
6918                                  UnaryOperator::getOpcodeStr(Opc), OpLoc);
6919      return ExprError();
6920
6921    case OR_Deleted:
6922      Diag(OpLoc, diag::err_ovl_deleted_oper)
6923        << Best->Function->isDeleted()
6924        << UnaryOperator::getOpcodeStr(Opc)
6925        << Input->getSourceRange();
6926      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
6927      return ExprError();
6928    }
6929
6930  // Either we found no viable overloaded operator or we matched a
6931  // built-in operator. In either case, fall through to trying to
6932  // build a built-in operation.
6933  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
6934}
6935
6936/// \brief Create a binary operation that may resolve to an overloaded
6937/// operator.
6938///
6939/// \param OpLoc The location of the operator itself (e.g., '+').
6940///
6941/// \param OpcIn The BinaryOperator::Opcode that describes this
6942/// operator.
6943///
6944/// \param Functions The set of non-member functions that will be
6945/// considered by overload resolution. The caller needs to build this
6946/// set based on the context using, e.g.,
6947/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6948/// set should not contain any member functions; those will be added
6949/// by CreateOverloadedBinOp().
6950///
6951/// \param LHS Left-hand argument.
6952/// \param RHS Right-hand argument.
6953ExprResult
6954Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
6955                            unsigned OpcIn,
6956                            const UnresolvedSetImpl &Fns,
6957                            Expr *LHS, Expr *RHS) {
6958  Expr *Args[2] = { LHS, RHS };
6959  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
6960
6961  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6962  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6963  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6964
6965  // If either side is type-dependent, create an appropriate dependent
6966  // expression.
6967  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6968    if (Fns.empty()) {
6969      // If there are no functions to store, just build a dependent
6970      // BinaryOperator or CompoundAssignment.
6971      if (Opc <= BO_Assign || Opc > BO_OrAssign)
6972        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6973                                                  Context.DependentTy, OpLoc));
6974
6975      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6976                                                        Context.DependentTy,
6977                                                        Context.DependentTy,
6978                                                        Context.DependentTy,
6979                                                        OpLoc));
6980    }
6981
6982    // FIXME: save results of ADL from here?
6983    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
6984    // TODO: provide better source location info in DNLoc component.
6985    DeclarationNameInfo OpNameInfo(OpName, OpLoc);
6986    UnresolvedLookupExpr *Fn
6987      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
6988                                     0, SourceRange(), OpNameInfo,
6989                                     /*ADL*/ true, IsOverloaded(Fns),
6990                                     Fns.begin(), Fns.end());
6991    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6992                                                   Args, 2,
6993                                                   Context.DependentTy,
6994                                                   OpLoc));
6995  }
6996
6997  // If this is the .* operator, which is not overloadable, just
6998  // create a built-in binary operator.
6999  if (Opc == BO_PtrMemD)
7000    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7001
7002  // If this is the assignment operator, we only perform overload resolution
7003  // if the left-hand side is a class or enumeration type. This is actually
7004  // a hack. The standard requires that we do overload resolution between the
7005  // various built-in candidates, but as DR507 points out, this can lead to
7006  // problems. So we do it this way, which pretty much follows what GCC does.
7007  // Note that we go the traditional code path for compound assignment forms.
7008  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
7009    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7010
7011  // Build an empty overload set.
7012  OverloadCandidateSet CandidateSet(OpLoc);
7013
7014  // Add the candidates from the given function set.
7015  AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
7016
7017  // Add operator candidates that are member functions.
7018  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7019
7020  // Add candidates from ADL.
7021  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7022                                       Args, 2,
7023                                       /*ExplicitTemplateArgs*/ 0,
7024                                       CandidateSet);
7025
7026  // Add builtin operator candidates.
7027  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7028
7029  // Perform overload resolution.
7030  OverloadCandidateSet::iterator Best;
7031  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
7032    case OR_Success: {
7033      // We found a built-in operator or an overloaded operator.
7034      FunctionDecl *FnDecl = Best->Function;
7035
7036      if (FnDecl) {
7037        // We matched an overloaded operator. Build a call to that
7038        // operator.
7039
7040        // Convert the arguments.
7041        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
7042          // Best->Access is only meaningful for class members.
7043          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
7044
7045          ExprResult Arg1
7046            = PerformCopyInitialization(
7047                                        InitializedEntity::InitializeParameter(
7048                                                        FnDecl->getParamDecl(0)),
7049                                        SourceLocation(),
7050                                        Owned(Args[1]));
7051          if (Arg1.isInvalid())
7052            return ExprError();
7053
7054          if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
7055                                                  Best->FoundDecl, Method))
7056            return ExprError();
7057
7058          Args[1] = RHS = Arg1.takeAs<Expr>();
7059        } else {
7060          // Convert the arguments.
7061          ExprResult Arg0
7062            = PerformCopyInitialization(
7063                                        InitializedEntity::InitializeParameter(
7064                                                        FnDecl->getParamDecl(0)),
7065                                        SourceLocation(),
7066                                        Owned(Args[0]));
7067          if (Arg0.isInvalid())
7068            return ExprError();
7069
7070          ExprResult Arg1
7071            = PerformCopyInitialization(
7072                                        InitializedEntity::InitializeParameter(
7073                                                        FnDecl->getParamDecl(1)),
7074                                        SourceLocation(),
7075                                        Owned(Args[1]));
7076          if (Arg1.isInvalid())
7077            return ExprError();
7078          Args[0] = LHS = Arg0.takeAs<Expr>();
7079          Args[1] = RHS = Arg1.takeAs<Expr>();
7080        }
7081
7082        DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7083
7084        // Determine the result type
7085        QualType ResultTy
7086          = FnDecl->getType()->getAs<FunctionType>()
7087                                                ->getCallResultType(Context);
7088
7089        // Build the actual expression node.
7090        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7091                                                 OpLoc);
7092        UsualUnaryConversions(FnExpr);
7093
7094        CXXOperatorCallExpr *TheCall =
7095          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7096                                            Args, 2, ResultTy, OpLoc);
7097
7098        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
7099                                FnDecl))
7100          return ExprError();
7101
7102        return MaybeBindToTemporary(TheCall);
7103      } else {
7104        // We matched a built-in operator. Convert the arguments, then
7105        // break out so that we will build the appropriate built-in
7106        // operator node.
7107        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
7108                                      Best->Conversions[0], AA_Passing) ||
7109            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
7110                                      Best->Conversions[1], AA_Passing))
7111          return ExprError();
7112
7113        break;
7114      }
7115    }
7116
7117    case OR_No_Viable_Function: {
7118      // C++ [over.match.oper]p9:
7119      //   If the operator is the operator , [...] and there are no
7120      //   viable functions, then the operator is assumed to be the
7121      //   built-in operator and interpreted according to clause 5.
7122      if (Opc == BO_Comma)
7123        break;
7124
7125      // For class as left operand for assignment or compound assigment operator
7126      // do not fall through to handling in built-in, but report that no overloaded
7127      // assignment operator found
7128      ExprResult Result = ExprError();
7129      if (Args[0]->getType()->isRecordType() &&
7130          Opc >= BO_Assign && Opc <= BO_OrAssign) {
7131        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
7132             << BinaryOperator::getOpcodeStr(Opc)
7133             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7134      } else {
7135        // No viable function; try to create a built-in operation, which will
7136        // produce an error. Then, show the non-viable candidates.
7137        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7138      }
7139      assert(Result.isInvalid() &&
7140             "C++ binary operator overloading is missing candidates!");
7141      if (Result.isInvalid())
7142        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7143                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
7144      return move(Result);
7145    }
7146
7147    case OR_Ambiguous:
7148      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
7149          << BinaryOperator::getOpcodeStr(Opc)
7150          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7151      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7152                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
7153      return ExprError();
7154
7155    case OR_Deleted:
7156      Diag(OpLoc, diag::err_ovl_deleted_oper)
7157        << Best->Function->isDeleted()
7158        << BinaryOperator::getOpcodeStr(Opc)
7159        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7160      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
7161      return ExprError();
7162  }
7163
7164  // We matched a built-in operator; build it.
7165  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7166}
7167
7168ExprResult
7169Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7170                                         SourceLocation RLoc,
7171                                         Expr *Base, Expr *Idx) {
7172  Expr *Args[2] = { Base, Idx };
7173  DeclarationName OpName =
7174      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7175
7176  // If either side is type-dependent, create an appropriate dependent
7177  // expression.
7178  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7179
7180    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
7181    // CHECKME: no 'operator' keyword?
7182    DeclarationNameInfo OpNameInfo(OpName, LLoc);
7183    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
7184    UnresolvedLookupExpr *Fn
7185      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
7186                                     0, SourceRange(), OpNameInfo,
7187                                     /*ADL*/ true, /*Overloaded*/ false,
7188                                     UnresolvedSetIterator(),
7189                                     UnresolvedSetIterator());
7190    // Can't add any actual overloads yet
7191
7192    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7193                                                   Args, 2,
7194                                                   Context.DependentTy,
7195                                                   RLoc));
7196  }
7197
7198  // Build an empty overload set.
7199  OverloadCandidateSet CandidateSet(LLoc);
7200
7201  // Subscript can only be overloaded as a member function.
7202
7203  // Add operator candidates that are member functions.
7204  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7205
7206  // Add builtin operator candidates.
7207  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7208
7209  // Perform overload resolution.
7210  OverloadCandidateSet::iterator Best;
7211  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
7212    case OR_Success: {
7213      // We found a built-in operator or an overloaded operator.
7214      FunctionDecl *FnDecl = Best->Function;
7215
7216      if (FnDecl) {
7217        // We matched an overloaded operator. Build a call to that
7218        // operator.
7219
7220        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
7221        DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
7222
7223        // Convert the arguments.
7224        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
7225        if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
7226                                                Best->FoundDecl, Method))
7227          return ExprError();
7228
7229        // Convert the arguments.
7230        ExprResult InputInit
7231          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7232                                                      FnDecl->getParamDecl(0)),
7233                                      SourceLocation(),
7234                                      Owned(Args[1]));
7235        if (InputInit.isInvalid())
7236          return ExprError();
7237
7238        Args[1] = InputInit.takeAs<Expr>();
7239
7240        // Determine the result type
7241        QualType ResultTy
7242          = FnDecl->getType()->getAs<FunctionType>()
7243                                                  ->getCallResultType(Context);
7244
7245        // Build the actual expression node.
7246        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7247                                                 LLoc);
7248        UsualUnaryConversions(FnExpr);
7249
7250        CXXOperatorCallExpr *TheCall =
7251          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7252                                            FnExpr, Args, 2,
7253                                            ResultTy, RLoc);
7254
7255        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
7256                                FnDecl))
7257          return ExprError();
7258
7259        return MaybeBindToTemporary(TheCall);
7260      } else {
7261        // We matched a built-in operator. Convert the arguments, then
7262        // break out so that we will build the appropriate built-in
7263        // operator node.
7264        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
7265                                      Best->Conversions[0], AA_Passing) ||
7266            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
7267                                      Best->Conversions[1], AA_Passing))
7268          return ExprError();
7269
7270        break;
7271      }
7272    }
7273
7274    case OR_No_Viable_Function: {
7275      if (CandidateSet.empty())
7276        Diag(LLoc, diag::err_ovl_no_oper)
7277          << Args[0]->getType() << /*subscript*/ 0
7278          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7279      else
7280        Diag(LLoc, diag::err_ovl_no_viable_subscript)
7281          << Args[0]->getType()
7282          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7283      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7284                                  "[]", LLoc);
7285      return ExprError();
7286    }
7287
7288    case OR_Ambiguous:
7289      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
7290          << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7291      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7292                                  "[]", LLoc);
7293      return ExprError();
7294
7295    case OR_Deleted:
7296      Diag(LLoc, diag::err_ovl_deleted_oper)
7297        << Best->Function->isDeleted() << "[]"
7298        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7299      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7300                                  "[]", LLoc);
7301      return ExprError();
7302    }
7303
7304  // We matched a built-in operator; build it.
7305  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
7306}
7307
7308/// BuildCallToMemberFunction - Build a call to a member
7309/// function. MemExpr is the expression that refers to the member
7310/// function (and includes the object parameter), Args/NumArgs are the
7311/// arguments to the function call (not including the object
7312/// parameter). The caller needs to validate that the member
7313/// expression refers to a member function or an overloaded member
7314/// function.
7315ExprResult
7316Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7317                                SourceLocation LParenLoc, Expr **Args,
7318                                unsigned NumArgs, SourceLocation RParenLoc) {
7319  // Dig out the member expression. This holds both the object
7320  // argument and the member function we're referring to.
7321  Expr *NakedMemExpr = MemExprE->IgnoreParens();
7322
7323  MemberExpr *MemExpr;
7324  CXXMethodDecl *Method = 0;
7325  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
7326  NestedNameSpecifier *Qualifier = 0;
7327  if (isa<MemberExpr>(NakedMemExpr)) {
7328    MemExpr = cast<MemberExpr>(NakedMemExpr);
7329    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
7330    FoundDecl = MemExpr->getFoundDecl();
7331    Qualifier = MemExpr->getQualifier();
7332  } else {
7333    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
7334    Qualifier = UnresExpr->getQualifier();
7335
7336    QualType ObjectType = UnresExpr->getBaseType();
7337
7338    // Add overload candidates
7339    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
7340
7341    // FIXME: avoid copy.
7342    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7343    if (UnresExpr->hasExplicitTemplateArgs()) {
7344      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7345      TemplateArgs = &TemplateArgsBuffer;
7346    }
7347
7348    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7349           E = UnresExpr->decls_end(); I != E; ++I) {
7350
7351      NamedDecl *Func = *I;
7352      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7353      if (isa<UsingShadowDecl>(Func))
7354        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7355
7356      if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
7357        // If explicit template arguments were provided, we can't call a
7358        // non-template member function.
7359        if (TemplateArgs)
7360          continue;
7361
7362        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
7363                           Args, NumArgs,
7364                           CandidateSet, /*SuppressUserConversions=*/false);
7365      } else {
7366        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
7367                                   I.getPair(), ActingDC, TemplateArgs,
7368                                   ObjectType, Args, NumArgs,
7369                                   CandidateSet,
7370                                   /*SuppressUsedConversions=*/false);
7371      }
7372    }
7373
7374    DeclarationName DeclName = UnresExpr->getMemberName();
7375
7376    OverloadCandidateSet::iterator Best;
7377    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
7378                               Best)) {
7379    case OR_Success:
7380      Method = cast<CXXMethodDecl>(Best->Function);
7381      FoundDecl = Best->FoundDecl;
7382      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
7383      DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
7384      break;
7385
7386    case OR_No_Viable_Function:
7387      Diag(UnresExpr->getMemberLoc(),
7388           diag::err_ovl_no_viable_member_function_in_call)
7389        << DeclName << MemExprE->getSourceRange();
7390      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7391      // FIXME: Leaking incoming expressions!
7392      return ExprError();
7393
7394    case OR_Ambiguous:
7395      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
7396        << DeclName << MemExprE->getSourceRange();
7397      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7398      // FIXME: Leaking incoming expressions!
7399      return ExprError();
7400
7401    case OR_Deleted:
7402      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
7403        << Best->Function->isDeleted()
7404        << DeclName << MemExprE->getSourceRange();
7405      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7406      // FIXME: Leaking incoming expressions!
7407      return ExprError();
7408    }
7409
7410    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
7411
7412    // If overload resolution picked a static member, build a
7413    // non-member call based on that function.
7414    if (Method->isStatic()) {
7415      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7416                                   Args, NumArgs, RParenLoc);
7417    }
7418
7419    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
7420  }
7421
7422  assert(Method && "Member call to something that isn't a method?");
7423  CXXMemberCallExpr *TheCall =
7424    new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7425                                    Method->getCallResultType(),
7426                                    RParenLoc);
7427
7428  // Check for a valid return type.
7429  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
7430                          TheCall, Method))
7431    return ExprError();
7432
7433  // Convert the object argument (for a non-static member function call).
7434  // We only need to do this if there was actually an overload; otherwise
7435  // it was done at lookup.
7436  Expr *ObjectArg = MemExpr->getBase();
7437  if (!Method->isStatic() &&
7438      PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7439                                          FoundDecl, Method))
7440    return ExprError();
7441  MemExpr->setBase(ObjectArg);
7442
7443  // Convert the rest of the arguments
7444  const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
7445  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
7446                              RParenLoc))
7447    return ExprError();
7448
7449  if (CheckFunctionCall(Method, TheCall))
7450    return ExprError();
7451
7452  return MaybeBindToTemporary(TheCall);
7453}
7454
7455/// BuildCallToObjectOfClassType - Build a call to an object of class
7456/// type (C++ [over.call.object]), which can end up invoking an
7457/// overloaded function call operator (@c operator()) or performing a
7458/// user-defined conversion on the object argument.
7459ExprResult
7460Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
7461                                   SourceLocation LParenLoc,
7462                                   Expr **Args, unsigned NumArgs,
7463                                   SourceLocation RParenLoc) {
7464  assert(Object->getType()->isRecordType() && "Requires object type argument");
7465  const RecordType *Record = Object->getType()->getAs<RecordType>();
7466
7467  // C++ [over.call.object]p1:
7468  //  If the primary-expression E in the function call syntax
7469  //  evaluates to a class object of type "cv T", then the set of
7470  //  candidate functions includes at least the function call
7471  //  operators of T. The function call operators of T are obtained by
7472  //  ordinary lookup of the name operator() in the context of
7473  //  (E).operator().
7474  OverloadCandidateSet CandidateSet(LParenLoc);
7475  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
7476
7477  if (RequireCompleteType(LParenLoc, Object->getType(),
7478                          PDiag(diag::err_incomplete_object_call)
7479                          << Object->getSourceRange()))
7480    return true;
7481
7482  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7483  LookupQualifiedName(R, Record->getDecl());
7484  R.suppressDiagnostics();
7485
7486  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
7487       Oper != OperEnd; ++Oper) {
7488    AddMethodCandidate(Oper.getPair(), Object->getType(),
7489                       Args, NumArgs, CandidateSet,
7490                       /*SuppressUserConversions=*/ false);
7491  }
7492
7493  // C++ [over.call.object]p2:
7494  //   In addition, for each conversion function declared in T of the
7495  //   form
7496  //
7497  //        operator conversion-type-id () cv-qualifier;
7498  //
7499  //   where cv-qualifier is the same cv-qualification as, or a
7500  //   greater cv-qualification than, cv, and where conversion-type-id
7501  //   denotes the type "pointer to function of (P1,...,Pn) returning
7502  //   R", or the type "reference to pointer to function of
7503  //   (P1,...,Pn) returning R", or the type "reference to function
7504  //   of (P1,...,Pn) returning R", a surrogate call function [...]
7505  //   is also considered as a candidate function. Similarly,
7506  //   surrogate call functions are added to the set of candidate
7507  //   functions for each conversion function declared in an
7508  //   accessible base class provided the function is not hidden
7509  //   within T by another intervening declaration.
7510  const UnresolvedSetImpl *Conversions
7511    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
7512  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
7513         E = Conversions->end(); I != E; ++I) {
7514    NamedDecl *D = *I;
7515    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7516    if (isa<UsingShadowDecl>(D))
7517      D = cast<UsingShadowDecl>(D)->getTargetDecl();
7518
7519    // Skip over templated conversion functions; they aren't
7520    // surrogates.
7521    if (isa<FunctionTemplateDecl>(D))
7522      continue;
7523
7524    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7525
7526    // Strip the reference type (if any) and then the pointer type (if
7527    // any) to get down to what might be a function type.
7528    QualType ConvType = Conv->getConversionType().getNonReferenceType();
7529    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7530      ConvType = ConvPtrType->getPointeeType();
7531
7532    if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
7533      AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
7534                            Object->getType(), Args, NumArgs,
7535                            CandidateSet);
7536  }
7537
7538  // Perform overload resolution.
7539  OverloadCandidateSet::iterator Best;
7540  switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7541                             Best)) {
7542  case OR_Success:
7543    // Overload resolution succeeded; we'll build the appropriate call
7544    // below.
7545    break;
7546
7547  case OR_No_Viable_Function:
7548    if (CandidateSet.empty())
7549      Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7550        << Object->getType() << /*call*/ 1
7551        << Object->getSourceRange();
7552    else
7553      Diag(Object->getSourceRange().getBegin(),
7554           diag::err_ovl_no_viable_object_call)
7555        << Object->getType() << Object->getSourceRange();
7556    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7557    break;
7558
7559  case OR_Ambiguous:
7560    Diag(Object->getSourceRange().getBegin(),
7561         diag::err_ovl_ambiguous_object_call)
7562      << Object->getType() << Object->getSourceRange();
7563    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
7564    break;
7565
7566  case OR_Deleted:
7567    Diag(Object->getSourceRange().getBegin(),
7568         diag::err_ovl_deleted_object_call)
7569      << Best->Function->isDeleted()
7570      << Object->getType() << Object->getSourceRange();
7571    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7572    break;
7573  }
7574
7575  if (Best == CandidateSet.end())
7576    return true;
7577
7578  if (Best->Function == 0) {
7579    // Since there is no function declaration, this is one of the
7580    // surrogate candidates. Dig out the conversion function.
7581    CXXConversionDecl *Conv
7582      = cast<CXXConversionDecl>(
7583                         Best->Conversions[0].UserDefined.ConversionFunction);
7584
7585    CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
7586    DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
7587
7588    // We selected one of the surrogate functions that converts the
7589    // object parameter to a function pointer. Perform the conversion
7590    // on the object argument, then let ActOnCallExpr finish the job.
7591
7592    // Create an implicit member expr to refer to the conversion operator.
7593    // and then call it.
7594    CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7595                                                   Conv);
7596
7597    return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
7598                         RParenLoc);
7599  }
7600
7601  CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
7602  DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
7603
7604  // We found an overloaded operator(). Build a CXXOperatorCallExpr
7605  // that calls this method, using Object for the implicit object
7606  // parameter and passing along the remaining arguments.
7607  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
7608  const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
7609
7610  unsigned NumArgsInProto = Proto->getNumArgs();
7611  unsigned NumArgsToCheck = NumArgs;
7612
7613  // Build the full argument list for the method call (the
7614  // implicit object parameter is placed at the beginning of the
7615  // list).
7616  Expr **MethodArgs;
7617  if (NumArgs < NumArgsInProto) {
7618    NumArgsToCheck = NumArgsInProto;
7619    MethodArgs = new Expr*[NumArgsInProto + 1];
7620  } else {
7621    MethodArgs = new Expr*[NumArgs + 1];
7622  }
7623  MethodArgs[0] = Object;
7624  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7625    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
7626
7627  Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
7628                                          SourceLocation());
7629  UsualUnaryConversions(NewFn);
7630
7631  // Once we've built TheCall, all of the expressions are properly
7632  // owned.
7633  QualType ResultTy = Method->getCallResultType();
7634  CXXOperatorCallExpr *TheCall =
7635    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7636                                      MethodArgs, NumArgs + 1,
7637                                      ResultTy, RParenLoc);
7638  delete [] MethodArgs;
7639
7640  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
7641                          Method))
7642    return true;
7643
7644  // We may have default arguments. If so, we need to allocate more
7645  // slots in the call for them.
7646  if (NumArgs < NumArgsInProto)
7647    TheCall->setNumArgs(Context, NumArgsInProto + 1);
7648  else if (NumArgs > NumArgsInProto)
7649    NumArgsToCheck = NumArgsInProto;
7650
7651  bool IsError = false;
7652
7653  // Initialize the implicit object parameter.
7654  IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
7655                                                 Best->FoundDecl, Method);
7656  TheCall->setArg(0, Object);
7657
7658
7659  // Check the argument types.
7660  for (unsigned i = 0; i != NumArgsToCheck; i++) {
7661    Expr *Arg;
7662    if (i < NumArgs) {
7663      Arg = Args[i];
7664
7665      // Pass the argument.
7666
7667      ExprResult InputInit
7668        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7669                                                    Method->getParamDecl(i)),
7670                                    SourceLocation(), Arg);
7671
7672      IsError |= InputInit.isInvalid();
7673      Arg = InputInit.takeAs<Expr>();
7674    } else {
7675      ExprResult DefArg
7676        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7677      if (DefArg.isInvalid()) {
7678        IsError = true;
7679        break;
7680      }
7681
7682      Arg = DefArg.takeAs<Expr>();
7683    }
7684
7685    TheCall->setArg(i + 1, Arg);
7686  }
7687
7688  // If this is a variadic call, handle args passed through "...".
7689  if (Proto->isVariadic()) {
7690    // Promote the arguments (C99 6.5.2.2p7).
7691    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7692      Expr *Arg = Args[i];
7693      IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
7694      TheCall->setArg(i + 1, Arg);
7695    }
7696  }
7697
7698  if (IsError) return true;
7699
7700  if (CheckFunctionCall(Method, TheCall))
7701    return true;
7702
7703  return MaybeBindToTemporary(TheCall);
7704}
7705
7706/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
7707///  (if one exists), where @c Base is an expression of class type and
7708/// @c Member is the name of the member we're trying to find.
7709ExprResult
7710Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
7711  assert(Base->getType()->isRecordType() && "left-hand side must have class type");
7712
7713  SourceLocation Loc = Base->getExprLoc();
7714
7715  // C++ [over.ref]p1:
7716  //
7717  //   [...] An expression x->m is interpreted as (x.operator->())->m
7718  //   for a class object x of type T if T::operator->() exists and if
7719  //   the operator is selected as the best match function by the
7720  //   overload resolution mechanism (13.3).
7721  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
7722  OverloadCandidateSet CandidateSet(Loc);
7723  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
7724
7725  if (RequireCompleteType(Loc, Base->getType(),
7726                          PDiag(diag::err_typecheck_incomplete_tag)
7727                            << Base->getSourceRange()))
7728    return ExprError();
7729
7730  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7731  LookupQualifiedName(R, BaseRecord->getDecl());
7732  R.suppressDiagnostics();
7733
7734  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
7735       Oper != OperEnd; ++Oper) {
7736    AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
7737                       /*SuppressUserConversions=*/false);
7738  }
7739
7740  // Perform overload resolution.
7741  OverloadCandidateSet::iterator Best;
7742  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
7743  case OR_Success:
7744    // Overload resolution succeeded; we'll build the call below.
7745    break;
7746
7747  case OR_No_Viable_Function:
7748    if (CandidateSet.empty())
7749      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7750        << Base->getType() << Base->getSourceRange();
7751    else
7752      Diag(OpLoc, diag::err_ovl_no_viable_oper)
7753        << "operator->" << Base->getSourceRange();
7754    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
7755    return ExprError();
7756
7757  case OR_Ambiguous:
7758    Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
7759      << "->" << Base->getSourceRange();
7760    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
7761    return ExprError();
7762
7763  case OR_Deleted:
7764    Diag(OpLoc,  diag::err_ovl_deleted_oper)
7765      << Best->Function->isDeleted()
7766      << "->" << Base->getSourceRange();
7767    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
7768    return ExprError();
7769  }
7770
7771  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
7772  DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7773
7774  // Convert the object parameter.
7775  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
7776  if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7777                                          Best->FoundDecl, Method))
7778    return ExprError();
7779
7780  // Build the operator call.
7781  Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7782                                           SourceLocation());
7783  UsualUnaryConversions(FnExpr);
7784
7785  QualType ResultTy = Method->getCallResultType();
7786  CXXOperatorCallExpr *TheCall =
7787    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7788                                      &Base, 1, ResultTy, OpLoc);
7789
7790  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
7791                          Method))
7792          return ExprError();
7793  return Owned(TheCall);
7794}
7795
7796/// FixOverloadedFunctionReference - E is an expression that refers to
7797/// a C++ overloaded function (possibly with some parentheses and
7798/// perhaps a '&' around it). We have resolved the overloaded function
7799/// to the function declaration Fn, so patch up the expression E to
7800/// refer (possibly indirectly) to Fn. Returns the new expr.
7801Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
7802                                           FunctionDecl *Fn) {
7803  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7804    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7805                                                   Found, Fn);
7806    if (SubExpr == PE->getSubExpr())
7807      return PE->Retain();
7808
7809    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7810  }
7811
7812  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7813    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7814                                                   Found, Fn);
7815    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
7816                               SubExpr->getType()) &&
7817           "Implicit cast type cannot be determined from overload");
7818    assert(ICE->path_empty() && "fixing up hierarchy conversion?");
7819    if (SubExpr == ICE->getSubExpr())
7820      return ICE->Retain();
7821
7822    return ImplicitCastExpr::Create(Context, ICE->getType(),
7823                                    ICE->getCastKind(),
7824                                    SubExpr, 0,
7825                                    ICE->getValueKind());
7826  }
7827
7828  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
7829    assert(UnOp->getOpcode() == UO_AddrOf &&
7830           "Can only take the address of an overloaded function");
7831    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7832      if (Method->isStatic()) {
7833        // Do nothing: static member functions aren't any different
7834        // from non-member functions.
7835      } else {
7836        // Fix the sub expression, which really has to be an
7837        // UnresolvedLookupExpr holding an overloaded member function
7838        // or template.
7839        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7840                                                       Found, Fn);
7841        if (SubExpr == UnOp->getSubExpr())
7842          return UnOp->Retain();
7843
7844        assert(isa<DeclRefExpr>(SubExpr)
7845               && "fixed to something other than a decl ref");
7846        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7847               && "fixed to a member ref with no nested name qualifier");
7848
7849        // We have taken the address of a pointer to member
7850        // function. Perform the computation here so that we get the
7851        // appropriate pointer to member type.
7852        QualType ClassType
7853          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7854        QualType MemPtrType
7855          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7856
7857        return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
7858                                           MemPtrType, UnOp->getOperatorLoc());
7859      }
7860    }
7861    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7862                                                   Found, Fn);
7863    if (SubExpr == UnOp->getSubExpr())
7864      return UnOp->Retain();
7865
7866    return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
7867                                     Context.getPointerType(SubExpr->getType()),
7868                                       UnOp->getOperatorLoc());
7869  }
7870
7871  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
7872    // FIXME: avoid copy.
7873    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7874    if (ULE->hasExplicitTemplateArgs()) {
7875      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7876      TemplateArgs = &TemplateArgsBuffer;
7877    }
7878
7879    return DeclRefExpr::Create(Context,
7880                               ULE->getQualifier(),
7881                               ULE->getQualifierRange(),
7882                               Fn,
7883                               ULE->getNameLoc(),
7884                               Fn->getType(),
7885                               TemplateArgs);
7886  }
7887
7888  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
7889    // FIXME: avoid copy.
7890    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7891    if (MemExpr->hasExplicitTemplateArgs()) {
7892      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7893      TemplateArgs = &TemplateArgsBuffer;
7894    }
7895
7896    Expr *Base;
7897
7898    // If we're filling in
7899    if (MemExpr->isImplicitAccess()) {
7900      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7901        return DeclRefExpr::Create(Context,
7902                                   MemExpr->getQualifier(),
7903                                   MemExpr->getQualifierRange(),
7904                                   Fn,
7905                                   MemExpr->getMemberLoc(),
7906                                   Fn->getType(),
7907                                   TemplateArgs);
7908      } else {
7909        SourceLocation Loc = MemExpr->getMemberLoc();
7910        if (MemExpr->getQualifier())
7911          Loc = MemExpr->getQualifierRange().getBegin();
7912        Base = new (Context) CXXThisExpr(Loc,
7913                                         MemExpr->getBaseType(),
7914                                         /*isImplicit=*/true);
7915      }
7916    } else
7917      Base = MemExpr->getBase()->Retain();
7918
7919    return MemberExpr::Create(Context, Base,
7920                              MemExpr->isArrow(),
7921                              MemExpr->getQualifier(),
7922                              MemExpr->getQualifierRange(),
7923                              Fn,
7924                              Found,
7925                              MemExpr->getMemberNameInfo(),
7926                              TemplateArgs,
7927                              Fn->getType());
7928  }
7929
7930  assert(false && "Invalid reference to overloaded function");
7931  return E->Retain();
7932}
7933
7934ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
7935                                                DeclAccessPair Found,
7936                                                FunctionDecl *Fn) {
7937  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
7938}
7939
7940} // end namespace clang
7941