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