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