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