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