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