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