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