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