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