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