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