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