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