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