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