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