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