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