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