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