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