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