SemaOverload.cpp revision f1991eab1e777634fb38758eafbbe0d303271d2f
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 "SemaInherit.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Expr.h"
19#include "llvm/Support/Compiler.h"
20#include <algorithm>
21
22namespace clang {
23
24/// GetConversionCategory - Retrieve the implicit conversion
25/// category corresponding to the given implicit conversion kind.
26ImplicitConversionCategory
27GetConversionCategory(ImplicitConversionKind Kind) {
28  static const ImplicitConversionCategory
29    Category[(int)ICK_Num_Conversion_Kinds] = {
30    ICC_Identity,
31    ICC_Lvalue_Transformation,
32    ICC_Lvalue_Transformation,
33    ICC_Lvalue_Transformation,
34    ICC_Qualification_Adjustment,
35    ICC_Promotion,
36    ICC_Promotion,
37    ICC_Conversion,
38    ICC_Conversion,
39    ICC_Conversion,
40    ICC_Conversion,
41    ICC_Conversion,
42    ICC_Conversion,
43    ICC_Conversion
44  };
45  return Category[(int)Kind];
46}
47
48/// GetConversionRank - Retrieve the implicit conversion rank
49/// corresponding to the given implicit conversion kind.
50ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
51  static const ImplicitConversionRank
52    Rank[(int)ICK_Num_Conversion_Kinds] = {
53    ICR_Exact_Match,
54    ICR_Exact_Match,
55    ICR_Exact_Match,
56    ICR_Exact_Match,
57    ICR_Exact_Match,
58    ICR_Promotion,
59    ICR_Promotion,
60    ICR_Conversion,
61    ICR_Conversion,
62    ICR_Conversion,
63    ICR_Conversion,
64    ICR_Conversion,
65    ICR_Conversion,
66    ICR_Conversion
67  };
68  return Rank[(int)Kind];
69}
70
71/// GetImplicitConversionName - Return the name of this kind of
72/// implicit conversion.
73const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
74  static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
75    "No conversion",
76    "Lvalue-to-rvalue",
77    "Array-to-pointer",
78    "Function-to-pointer",
79    "Qualification",
80    "Integral promotion",
81    "Floating point promotion",
82    "Integral conversion",
83    "Floating conversion",
84    "Floating-integral conversion",
85    "Pointer conversion",
86    "Pointer-to-member conversion",
87    "Boolean conversion",
88    "Derived-to-base conversion"
89  };
90  return Name[Kind];
91}
92
93/// StandardConversionSequence - Set the standard conversion
94/// sequence to the identity conversion.
95void StandardConversionSequence::setAsIdentityConversion() {
96  First = ICK_Identity;
97  Second = ICK_Identity;
98  Third = ICK_Identity;
99  Deprecated = false;
100  ReferenceBinding = false;
101  DirectBinding = false;
102  CopyConstructor = 0;
103}
104
105/// getRank - Retrieve the rank of this standard conversion sequence
106/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
107/// implicit conversions.
108ImplicitConversionRank StandardConversionSequence::getRank() const {
109  ImplicitConversionRank Rank = ICR_Exact_Match;
110  if  (GetConversionRank(First) > Rank)
111    Rank = GetConversionRank(First);
112  if  (GetConversionRank(Second) > Rank)
113    Rank = GetConversionRank(Second);
114  if  (GetConversionRank(Third) > Rank)
115    Rank = GetConversionRank(Third);
116  return Rank;
117}
118
119/// isPointerConversionToBool - Determines whether this conversion is
120/// a conversion of a pointer or pointer-to-member to bool. This is
121/// used as part of the ranking of standard conversion sequences
122/// (C++ 13.3.3.2p4).
123bool StandardConversionSequence::isPointerConversionToBool() const
124{
125  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
126  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
127
128  // Note that FromType has not necessarily been transformed by the
129  // array-to-pointer or function-to-pointer implicit conversions, so
130  // check for their presence as well as checking whether FromType is
131  // a pointer.
132  if (ToType->isBooleanType() &&
133      (FromType->isPointerType() ||
134       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
135    return true;
136
137  return false;
138}
139
140/// isPointerConversionToVoidPointer - Determines whether this
141/// conversion is a conversion of a pointer to a void pointer. This is
142/// used as part of the ranking of standard conversion sequences (C++
143/// 13.3.3.2p4).
144bool
145StandardConversionSequence::
146isPointerConversionToVoidPointer(ASTContext& Context) const
147{
148  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
149  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
150
151  // Note that FromType has not necessarily been transformed by the
152  // array-to-pointer implicit conversion, so check for its presence
153  // and redo the conversion to get a pointer.
154  if (First == ICK_Array_To_Pointer)
155    FromType = Context.getArrayDecayedType(FromType);
156
157  if (Second == ICK_Pointer_Conversion)
158    if (const PointerType* ToPtrType = ToType->getAsPointerType())
159      return ToPtrType->getPointeeType()->isVoidType();
160
161  return false;
162}
163
164/// DebugPrint - Print this standard conversion sequence to standard
165/// error. Useful for debugging overloading issues.
166void StandardConversionSequence::DebugPrint() const {
167  bool PrintedSomething = false;
168  if (First != ICK_Identity) {
169    fprintf(stderr, "%s", GetImplicitConversionName(First));
170    PrintedSomething = true;
171  }
172
173  if (Second != ICK_Identity) {
174    if (PrintedSomething) {
175      fprintf(stderr, " -> ");
176    }
177    fprintf(stderr, "%s", GetImplicitConversionName(Second));
178
179    if (CopyConstructor) {
180      fprintf(stderr, " (by copy constructor)");
181    } else if (DirectBinding) {
182      fprintf(stderr, " (direct reference binding)");
183    } else if (ReferenceBinding) {
184      fprintf(stderr, " (reference binding)");
185    }
186    PrintedSomething = true;
187  }
188
189  if (Third != ICK_Identity) {
190    if (PrintedSomething) {
191      fprintf(stderr, " -> ");
192    }
193    fprintf(stderr, "%s", GetImplicitConversionName(Third));
194    PrintedSomething = true;
195  }
196
197  if (!PrintedSomething) {
198    fprintf(stderr, "No conversions required");
199  }
200}
201
202/// DebugPrint - Print this user-defined conversion sequence to standard
203/// error. Useful for debugging overloading issues.
204void UserDefinedConversionSequence::DebugPrint() const {
205  if (Before.First || Before.Second || Before.Third) {
206    Before.DebugPrint();
207    fprintf(stderr, " -> ");
208  }
209  fprintf(stderr, "'%s'", ConversionFunction->getName());
210  if (After.First || After.Second || After.Third) {
211    fprintf(stderr, " -> ");
212    After.DebugPrint();
213  }
214}
215
216/// DebugPrint - Print this implicit conversion sequence to standard
217/// error. Useful for debugging overloading issues.
218void ImplicitConversionSequence::DebugPrint() const {
219  switch (ConversionKind) {
220  case StandardConversion:
221    fprintf(stderr, "Standard conversion: ");
222    Standard.DebugPrint();
223    break;
224  case UserDefinedConversion:
225    fprintf(stderr, "User-defined conversion: ");
226    UserDefined.DebugPrint();
227    break;
228  case EllipsisConversion:
229    fprintf(stderr, "Ellipsis conversion");
230    break;
231  case BadConversion:
232    fprintf(stderr, "Bad conversion");
233    break;
234  }
235
236  fprintf(stderr, "\n");
237}
238
239// IsOverload - Determine whether the given New declaration is an
240// overload of the Old declaration. This routine returns false if New
241// and Old cannot be overloaded, e.g., if they are functions with the
242// same signature (C++ 1.3.10) or if the Old declaration isn't a
243// function (or overload set). When it does return false and Old is an
244// OverloadedFunctionDecl, MatchedDecl will be set to point to the
245// FunctionDecl that New cannot be overloaded with.
246//
247// Example: Given the following input:
248//
249//   void f(int, float); // #1
250//   void f(int, int); // #2
251//   int f(int, int); // #3
252//
253// When we process #1, there is no previous declaration of "f",
254// so IsOverload will not be used.
255//
256// When we process #2, Old is a FunctionDecl for #1.  By comparing the
257// parameter types, we see that #1 and #2 are overloaded (since they
258// have different signatures), so this routine returns false;
259// MatchedDecl is unchanged.
260//
261// When we process #3, Old is an OverloadedFunctionDecl containing #1
262// and #2. We compare the signatures of #3 to #1 (they're overloaded,
263// so we do nothing) and then #3 to #2. Since the signatures of #3 and
264// #2 are identical (return types of functions are not part of the
265// signature), IsOverload returns false and MatchedDecl will be set to
266// point to the FunctionDecl for #2.
267bool
268Sema::IsOverload(FunctionDecl *New, Decl* OldD,
269                 OverloadedFunctionDecl::function_iterator& MatchedDecl)
270{
271  if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
272    // Is this new function an overload of every function in the
273    // overload set?
274    OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
275                                           FuncEnd = Ovl->function_end();
276    for (; Func != FuncEnd; ++Func) {
277      if (!IsOverload(New, *Func, MatchedDecl)) {
278        MatchedDecl = Func;
279        return false;
280      }
281    }
282
283    // This function overloads every function in the overload set.
284    return true;
285  } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
286    // Is the function New an overload of the function Old?
287    QualType OldQType = Context.getCanonicalType(Old->getType());
288    QualType NewQType = Context.getCanonicalType(New->getType());
289
290    // Compare the signatures (C++ 1.3.10) of the two functions to
291    // determine whether they are overloads. If we find any mismatch
292    // in the signature, they are overloads.
293
294    // If either of these functions is a K&R-style function (no
295    // prototype), then we consider them to have matching signatures.
296    if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
297        isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
298      return false;
299
300    FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
301    FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
302
303    // The signature of a function includes the types of its
304    // parameters (C++ 1.3.10), which includes the presence or absence
305    // of the ellipsis; see C++ DR 357).
306    if (OldQType != NewQType &&
307        (OldType->getNumArgs() != NewType->getNumArgs() ||
308         OldType->isVariadic() != NewType->isVariadic() ||
309         !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
310                     NewType->arg_type_begin())))
311      return true;
312
313    // If the function is a class member, its signature includes the
314    // cv-qualifiers (if any) on the function itself.
315    //
316    // As part of this, also check whether one of the member functions
317    // is static, in which case they are not overloads (C++
318    // 13.1p2). While not part of the definition of the signature,
319    // this check is important to determine whether these functions
320    // can be overloaded.
321    CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
322    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
323    if (OldMethod && NewMethod &&
324        !OldMethod->isStatic() && !NewMethod->isStatic() &&
325        OldQType.getCVRQualifiers() != NewQType.getCVRQualifiers())
326      return true;
327
328    // The signatures match; this is not an overload.
329    return false;
330  } else {
331    // (C++ 13p1):
332    //   Only function declarations can be overloaded; object and type
333    //   declarations cannot be overloaded.
334    return false;
335  }
336}
337
338/// TryImplicitConversion - Attempt to perform an implicit conversion
339/// from the given expression (Expr) to the given type (ToType). This
340/// function returns an implicit conversion sequence that can be used
341/// to perform the initialization. Given
342///
343///   void f(float f);
344///   void g(int i) { f(i); }
345///
346/// this routine would produce an implicit conversion sequence to
347/// describe the initialization of f from i, which will be a standard
348/// conversion sequence containing an lvalue-to-rvalue conversion (C++
349/// 4.1) followed by a floating-integral conversion (C++ 4.9).
350//
351/// Note that this routine only determines how the conversion can be
352/// performed; it does not actually perform the conversion. As such,
353/// it will not produce any diagnostics if no conversion is available,
354/// but will instead return an implicit conversion sequence of kind
355/// "BadConversion".
356///
357/// If @p SuppressUserConversions, then user-defined conversions are
358/// not permitted.
359ImplicitConversionSequence
360Sema::TryImplicitConversion(Expr* From, QualType ToType,
361                            bool SuppressUserConversions)
362{
363  ImplicitConversionSequence ICS;
364  if (IsStandardConversion(From, ToType, ICS.Standard))
365    ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
366  else if (!SuppressUserConversions &&
367           IsUserDefinedConversion(From, ToType, ICS.UserDefined)) {
368    ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
369    // C++ [over.ics.user]p4:
370    //   A conversion of an expression of class type to the same class
371    //   type is given Exact Match rank, and a conversion of an
372    //   expression of class type to a base class of that type is
373    //   given Conversion rank, in spite of the fact that a copy
374    //   constructor (i.e., a user-defined conversion function) is
375    //   called for those cases.
376    if (CXXConstructorDecl *Constructor
377          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
378      if (Constructor->isCopyConstructor(Context)) {
379        // Turn this into a "standard" conversion sequence, so that it
380        // gets ranked with standard conversion sequences.
381        ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
382        ICS.Standard.setAsIdentityConversion();
383        ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
384        ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
385        ICS.Standard.CopyConstructor = Constructor;
386        if (IsDerivedFrom(From->getType().getUnqualifiedType(),
387                          ToType.getUnqualifiedType()))
388          ICS.Standard.Second = ICK_Derived_To_Base;
389      }
390    }
391  } else
392    ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
393
394  return ICS;
395}
396
397/// IsStandardConversion - Determines whether there is a standard
398/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
399/// expression From to the type ToType. Standard conversion sequences
400/// only consider non-class types; for conversions that involve class
401/// types, use TryImplicitConversion. If a conversion exists, SCS will
402/// contain the standard conversion sequence required to perform this
403/// conversion and this routine will return true. Otherwise, this
404/// routine will return false and the value of SCS is unspecified.
405bool
406Sema::IsStandardConversion(Expr* From, QualType ToType,
407                           StandardConversionSequence &SCS)
408{
409  QualType FromType = From->getType();
410
411  // There are no standard conversions for class types, so abort early.
412  if (FromType->isRecordType() || ToType->isRecordType())
413    return false;
414
415  // Standard conversions (C++ [conv])
416  SCS.Deprecated = false;
417  SCS.FromTypePtr = FromType.getAsOpaquePtr();
418  SCS.CopyConstructor = 0;
419
420  // The first conversion can be an lvalue-to-rvalue conversion,
421  // array-to-pointer conversion, or function-to-pointer conversion
422  // (C++ 4p1).
423
424  // Lvalue-to-rvalue conversion (C++ 4.1):
425  //   An lvalue (3.10) of a non-function, non-array type T can be
426  //   converted to an rvalue.
427  Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
428  if (argIsLvalue == Expr::LV_Valid &&
429      !FromType->isFunctionType() && !FromType->isArrayType()) {
430    SCS.First = ICK_Lvalue_To_Rvalue;
431
432    // If T is a non-class type, the type of the rvalue is the
433    // cv-unqualified version of T. Otherwise, the type of the rvalue
434    // is T (C++ 4.1p1).
435    FromType = FromType.getUnqualifiedType();
436  }
437  // Array-to-pointer conversion (C++ 4.2)
438  else if (FromType->isArrayType()) {
439    SCS.First = ICK_Array_To_Pointer;
440
441    // An lvalue or rvalue of type "array of N T" or "array of unknown
442    // bound of T" can be converted to an rvalue of type "pointer to
443    // T" (C++ 4.2p1).
444    FromType = Context.getArrayDecayedType(FromType);
445
446    if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
447      // This conversion is deprecated. (C++ D.4).
448      SCS.Deprecated = true;
449
450      // For the purpose of ranking in overload resolution
451      // (13.3.3.1.1), this conversion is considered an
452      // array-to-pointer conversion followed by a qualification
453      // conversion (4.4). (C++ 4.2p2)
454      SCS.Second = ICK_Identity;
455      SCS.Third = ICK_Qualification;
456      SCS.ToTypePtr = ToType.getAsOpaquePtr();
457      return true;
458    }
459  }
460  // Function-to-pointer conversion (C++ 4.3).
461  else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
462    SCS.First = ICK_Function_To_Pointer;
463
464    // An lvalue of function type T can be converted to an rvalue of
465    // type "pointer to T." The result is a pointer to the
466    // function. (C++ 4.3p1).
467    FromType = Context.getPointerType(FromType);
468
469    // FIXME: Deal with overloaded functions here (C++ 4.3p2).
470  }
471  // We don't require any conversions for the first step.
472  else {
473    SCS.First = ICK_Identity;
474  }
475
476  // The second conversion can be an integral promotion, floating
477  // point promotion, integral conversion, floating point conversion,
478  // floating-integral conversion, pointer conversion,
479  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
480  if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
481      Context.getCanonicalType(ToType).getUnqualifiedType()) {
482    // The unqualified versions of the types are the same: there's no
483    // conversion to do.
484    SCS.Second = ICK_Identity;
485  }
486  // Integral promotion (C++ 4.5).
487  else if (IsIntegralPromotion(From, FromType, ToType)) {
488    SCS.Second = ICK_Integral_Promotion;
489    FromType = ToType.getUnqualifiedType();
490  }
491  // Floating point promotion (C++ 4.6).
492  else if (IsFloatingPointPromotion(FromType, ToType)) {
493    SCS.Second = ICK_Floating_Promotion;
494    FromType = ToType.getUnqualifiedType();
495  }
496  // Integral conversions (C++ 4.7).
497  // FIXME: isIntegralType shouldn't be true for enums in C++.
498  else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
499           (ToType->isIntegralType() && !ToType->isEnumeralType())) {
500    SCS.Second = ICK_Integral_Conversion;
501    FromType = ToType.getUnqualifiedType();
502  }
503  // Floating point conversions (C++ 4.8).
504  else if (FromType->isFloatingType() && ToType->isFloatingType()) {
505    SCS.Second = ICK_Floating_Conversion;
506    FromType = ToType.getUnqualifiedType();
507  }
508  // Floating-integral conversions (C++ 4.9).
509  // FIXME: isIntegralType shouldn't be true for enums in C++.
510  else if ((FromType->isFloatingType() &&
511            ToType->isIntegralType() && !ToType->isBooleanType() &&
512                                        !ToType->isEnumeralType()) ||
513           ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
514            ToType->isFloatingType())) {
515    SCS.Second = ICK_Floating_Integral;
516    FromType = ToType.getUnqualifiedType();
517  }
518  // Pointer conversions (C++ 4.10).
519  else if (IsPointerConversion(From, FromType, ToType, FromType)) {
520    SCS.Second = ICK_Pointer_Conversion;
521  }
522  // FIXME: Pointer to member conversions (4.11).
523  // Boolean conversions (C++ 4.12).
524  // FIXME: pointer-to-member type
525  else if (ToType->isBooleanType() &&
526           (FromType->isArithmeticType() ||
527            FromType->isEnumeralType() ||
528            FromType->isPointerType())) {
529    SCS.Second = ICK_Boolean_Conversion;
530    FromType = Context.BoolTy;
531  } else {
532    // No second conversion required.
533    SCS.Second = ICK_Identity;
534  }
535
536  QualType CanonFrom;
537  QualType CanonTo;
538  // The third conversion can be a qualification conversion (C++ 4p1).
539  if (IsQualificationConversion(FromType, ToType)) {
540    SCS.Third = ICK_Qualification;
541    FromType = ToType;
542    CanonFrom = Context.getCanonicalType(FromType);
543    CanonTo = Context.getCanonicalType(ToType);
544  } else {
545    // No conversion required
546    SCS.Third = ICK_Identity;
547
548    // C++ [over.best.ics]p6:
549    //   [...] Any difference in top-level cv-qualification is
550    //   subsumed by the initialization itself and does not constitute
551    //   a conversion. [...]
552    CanonFrom = Context.getCanonicalType(FromType);
553    CanonTo = Context.getCanonicalType(ToType);
554    if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
555        CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
556      FromType = ToType;
557      CanonFrom = CanonTo;
558    }
559  }
560
561  // If we have not converted the argument type to the parameter type,
562  // this is a bad conversion sequence.
563  if (CanonFrom != CanonTo)
564    return false;
565
566  SCS.ToTypePtr = FromType.getAsOpaquePtr();
567  return true;
568}
569
570/// IsIntegralPromotion - Determines whether the conversion from the
571/// expression From (whose potentially-adjusted type is FromType) to
572/// ToType is an integral promotion (C++ 4.5). If so, returns true and
573/// sets PromotedType to the promoted type.
574bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
575{
576  const BuiltinType *To = ToType->getAsBuiltinType();
577  // All integers are built-in.
578  if (!To) {
579    return false;
580  }
581
582  // An rvalue of type char, signed char, unsigned char, short int, or
583  // unsigned short int can be converted to an rvalue of type int if
584  // int can represent all the values of the source type; otherwise,
585  // the source rvalue can be converted to an rvalue of type unsigned
586  // int (C++ 4.5p1).
587  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
588    if (// We can promote any signed, promotable integer type to an int
589        (FromType->isSignedIntegerType() ||
590         // We can promote any unsigned integer type whose size is
591         // less than int to an int.
592         (!FromType->isSignedIntegerType() &&
593          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
594      return To->getKind() == BuiltinType::Int;
595    }
596
597    return To->getKind() == BuiltinType::UInt;
598  }
599
600  // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
601  // can be converted to an rvalue of the first of the following types
602  // that can represent all the values of its underlying type: int,
603  // unsigned int, long, or unsigned long (C++ 4.5p2).
604  if ((FromType->isEnumeralType() || FromType->isWideCharType())
605      && ToType->isIntegerType()) {
606    // Determine whether the type we're converting from is signed or
607    // unsigned.
608    bool FromIsSigned;
609    uint64_t FromSize = Context.getTypeSize(FromType);
610    if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
611      QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
612      FromIsSigned = UnderlyingType->isSignedIntegerType();
613    } else {
614      // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
615      FromIsSigned = true;
616    }
617
618    // The types we'll try to promote to, in the appropriate
619    // order. Try each of these types.
620    QualType PromoteTypes[4] = {
621      Context.IntTy, Context.UnsignedIntTy,
622      Context.LongTy, Context.UnsignedLongTy
623    };
624    for (int Idx = 0; Idx < 0; ++Idx) {
625      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
626      if (FromSize < ToSize ||
627          (FromSize == ToSize &&
628           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
629        // We found the type that we can promote to. If this is the
630        // type we wanted, we have a promotion. Otherwise, no
631        // promotion.
632        return Context.getCanonicalType(ToType).getUnqualifiedType()
633          == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
634      }
635    }
636  }
637
638  // An rvalue for an integral bit-field (9.6) can be converted to an
639  // rvalue of type int if int can represent all the values of the
640  // bit-field; otherwise, it can be converted to unsigned int if
641  // unsigned int can represent all the values of the bit-field. If
642  // the bit-field is larger yet, no integral promotion applies to
643  // it. If the bit-field has an enumerated type, it is treated as any
644  // other value of that type for promotion purposes (C++ 4.5p3).
645  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
646    using llvm::APSInt;
647    FieldDecl *MemberDecl = MemRef->getMemberDecl();
648    APSInt BitWidth;
649    if (MemberDecl->isBitField() &&
650        FromType->isIntegralType() && !FromType->isEnumeralType() &&
651        From->isIntegerConstantExpr(BitWidth, Context)) {
652      APSInt ToSize(Context.getTypeSize(ToType));
653
654      // Are we promoting to an int from a bitfield that fits in an int?
655      if (BitWidth < ToSize ||
656          (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
657        return To->getKind() == BuiltinType::Int;
658      }
659
660      // Are we promoting to an unsigned int from an unsigned bitfield
661      // that fits into an unsigned int?
662      if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
663        return To->getKind() == BuiltinType::UInt;
664      }
665
666      return false;
667    }
668  }
669
670  // An rvalue of type bool can be converted to an rvalue of type int,
671  // with false becoming zero and true becoming one (C++ 4.5p4).
672  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
673    return true;
674  }
675
676  return false;
677}
678
679/// IsFloatingPointPromotion - Determines whether the conversion from
680/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
681/// returns true and sets PromotedType to the promoted type.
682bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
683{
684  /// An rvalue of type float can be converted to an rvalue of type
685  /// double. (C++ 4.6p1).
686  if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
687    if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
688      if (FromBuiltin->getKind() == BuiltinType::Float &&
689          ToBuiltin->getKind() == BuiltinType::Double)
690        return true;
691
692  return false;
693}
694
695/// IsPointerConversion - Determines whether the conversion of the
696/// expression From, which has the (possibly adjusted) type FromType,
697/// can be converted to the type ToType via a pointer conversion (C++
698/// 4.10). If so, returns true and places the converted type (that
699/// might differ from ToType in its cv-qualifiers at some level) into
700/// ConvertedType.
701bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
702                               QualType& ConvertedType)
703{
704  const PointerType* ToTypePtr = ToType->getAsPointerType();
705  if (!ToTypePtr)
706    return false;
707
708  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
709  if (From->isNullPointerConstant(Context)) {
710    ConvertedType = ToType;
711    return true;
712  }
713
714  // An rvalue of type "pointer to cv T," where T is an object type,
715  // can be converted to an rvalue of type "pointer to cv void" (C++
716  // 4.10p2).
717  if (FromType->isPointerType() &&
718      FromType->getAsPointerType()->getPointeeType()->isObjectType() &&
719      ToTypePtr->getPointeeType()->isVoidType()) {
720    // We need to produce a pointer to cv void, where cv is the same
721    // set of cv-qualifiers as we had on the incoming pointee type.
722    QualType toPointee = ToTypePtr->getPointeeType();
723    unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType()
724                   ->getPointeeType().getCVRQualifiers();
725
726    if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers()
727	  == Quals) {
728      // ToType is exactly the type we want. Use it.
729      ConvertedType = ToType;
730    } else {
731      // Build a new type with the right qualifiers.
732      ConvertedType
733	= Context.getPointerType(Context.VoidTy.getQualifiedType(Quals));
734    }
735    return true;
736  }
737
738  // C++ [conv.ptr]p3:
739  //
740  //   An rvalue of type "pointer to cv D," where D is a class type,
741  //   can be converted to an rvalue of type "pointer to cv B," where
742  //   B is a base class (clause 10) of D. If B is an inaccessible
743  //   (clause 11) or ambiguous (10.2) base class of D, a program that
744  //   necessitates this conversion is ill-formed. The result of the
745  //   conversion is a pointer to the base class sub-object of the
746  //   derived class object. The null pointer value is converted to
747  //   the null pointer value of the destination type.
748  //
749  // Note that we do not check for ambiguity or inaccessibility
750  // here. That is handled by CheckPointerConversion.
751  if (const PointerType *FromPtrType = FromType->getAsPointerType())
752    if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
753      if (FromPtrType->getPointeeType()->isRecordType() &&
754          ToPtrType->getPointeeType()->isRecordType() &&
755          IsDerivedFrom(FromPtrType->getPointeeType(),
756                        ToPtrType->getPointeeType())) {
757        // The conversion is okay. Now, we need to produce the type
758        // that results from this conversion, which will have the same
759        // qualifiers as the incoming type.
760        QualType CanonFromPointee
761          = Context.getCanonicalType(FromPtrType->getPointeeType());
762        QualType ToPointee = ToPtrType->getPointeeType();
763        QualType CanonToPointee = Context.getCanonicalType(ToPointee);
764        unsigned Quals = CanonFromPointee.getCVRQualifiers();
765
766        if (CanonToPointee.getCVRQualifiers() == Quals) {
767          // ToType is exactly the type we want. Use it.
768          ConvertedType = ToType;
769        } else {
770          // Build a new type with the right qualifiers.
771          ConvertedType
772            = Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
773        }
774        return true;
775      }
776    }
777
778  return false;
779}
780
781/// CheckPointerConversion - Check the pointer conversion from the
782/// expression From to the type ToType. This routine checks for
783/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
784/// conversions for which IsPointerConversion has already returned
785/// true. It returns true and produces a diagnostic if there was an
786/// error, or returns false otherwise.
787bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
788  QualType FromType = From->getType();
789
790  if (const PointerType *FromPtrType = FromType->getAsPointerType())
791    if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
792      BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
793                      /*DetectVirtual=*/false);
794      QualType FromPointeeType = FromPtrType->getPointeeType(),
795               ToPointeeType   = ToPtrType->getPointeeType();
796      if (FromPointeeType->isRecordType() &&
797          ToPointeeType->isRecordType()) {
798        // We must have a derived-to-base conversion. Check an
799        // ambiguous or inaccessible conversion.
800        return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
801                                            From->getExprLoc(),
802                                            From->getSourceRange());
803      }
804    }
805
806  return false;
807}
808
809/// IsQualificationConversion - Determines whether the conversion from
810/// an rvalue of type FromType to ToType is a qualification conversion
811/// (C++ 4.4).
812bool
813Sema::IsQualificationConversion(QualType FromType, QualType ToType)
814{
815  FromType = Context.getCanonicalType(FromType);
816  ToType = Context.getCanonicalType(ToType);
817
818  // If FromType and ToType are the same type, this is not a
819  // qualification conversion.
820  if (FromType == ToType)
821    return false;
822
823  // (C++ 4.4p4):
824  //   A conversion can add cv-qualifiers at levels other than the first
825  //   in multi-level pointers, subject to the following rules: [...]
826  bool PreviousToQualsIncludeConst = true;
827  bool UnwrappedAnyPointer = false;
828  while (UnwrapSimilarPointerTypes(FromType, ToType)) {
829    // Within each iteration of the loop, we check the qualifiers to
830    // determine if this still looks like a qualification
831    // conversion. Then, if all is well, we unwrap one more level of
832    // pointers or pointers-to-members and do it all again
833    // until there are no more pointers or pointers-to-members left to
834    // unwrap.
835    UnwrappedAnyPointer = true;
836
837    //   -- for every j > 0, if const is in cv 1,j then const is in cv
838    //      2,j, and similarly for volatile.
839    if (!ToType.isAtLeastAsQualifiedAs(FromType))
840      return false;
841
842    //   -- if the cv 1,j and cv 2,j are different, then const is in
843    //      every cv for 0 < k < j.
844    if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
845        && !PreviousToQualsIncludeConst)
846      return false;
847
848    // Keep track of whether all prior cv-qualifiers in the "to" type
849    // include const.
850    PreviousToQualsIncludeConst
851      = PreviousToQualsIncludeConst && ToType.isConstQualified();
852  }
853
854  // We are left with FromType and ToType being the pointee types
855  // after unwrapping the original FromType and ToType the same number
856  // of types. If we unwrapped any pointers, and if FromType and
857  // ToType have the same unqualified type (since we checked
858  // qualifiers above), then this is a qualification conversion.
859  return UnwrappedAnyPointer &&
860    FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
861}
862
863/// IsUserDefinedConversion - Determines whether there is a
864/// user-defined conversion sequence (C++ [over.ics.user]) that
865/// converts expression From to the type ToType. If such a conversion
866/// exists, User will contain the user-defined conversion sequence
867/// that performs such a conversion and this routine will return
868/// true. Otherwise, this routine returns false and User is
869/// unspecified.
870bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
871                                   UserDefinedConversionSequence& User)
872{
873  OverloadCandidateSet CandidateSet;
874  if (const CXXRecordType *ToRecordType
875        = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
876    // C++ [over.match.ctor]p1:
877    //   When objects of class type are direct-initialized (8.5), or
878    //   copy-initialized from an expression of the same or a
879    //   derived class type (8.5), overload resolution selects the
880    //   constructor. [...] For copy-initialization, the candidate
881    //   functions are all the converting constructors (12.3.1) of
882    //   that class. The argument list is the expression-list within
883    //   the parentheses of the initializer.
884    CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
885    const OverloadedFunctionDecl *Constructors = ToRecordDecl->getConstructors();
886    for (OverloadedFunctionDecl::function_const_iterator func
887           = Constructors->function_begin();
888         func != Constructors->function_end(); ++func) {
889      CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func);
890      if (Constructor->isConvertingConstructor())
891        AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
892                             /*SuppressUserConversions=*/true);
893    }
894  }
895
896  if (const CXXRecordType *FromRecordType
897        = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
898    // Add all of the conversion functions as candidates.
899    // FIXME: Look for conversions in base classes!
900    CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
901    OverloadedFunctionDecl *Conversions
902      = FromRecordDecl->getConversionFunctions();
903    for (OverloadedFunctionDecl::function_iterator Func
904           = Conversions->function_begin();
905         Func != Conversions->function_end(); ++Func) {
906      CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
907      AddConversionCandidate(Conv, From, ToType, CandidateSet);
908    }
909  }
910
911  OverloadCandidateSet::iterator Best;
912  switch (BestViableFunction(CandidateSet, Best)) {
913    case OR_Success:
914      // Record the standard conversion we used and the conversion function.
915      // FIXME: Handle user-defined conversion operators.
916      if (CXXConstructorDecl *Constructor
917            = dyn_cast<CXXConstructorDecl>(Best->Function)) {
918        // C++ [over.ics.user]p1:
919        //   If the user-defined conversion is specified by a
920        //   constructor (12.3.1), the initial standard conversion
921        //   sequence converts the source type to the type required by
922        //   the argument of the constructor.
923        //
924        // FIXME: What about ellipsis conversions?
925        QualType ThisType = Constructor->getThisType(Context);
926        User.Before = Best->Conversions[0].Standard;
927        User.ConversionFunction = Constructor;
928        User.After.setAsIdentityConversion();
929        User.After.FromTypePtr
930          = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
931        User.After.ToTypePtr = ToType.getAsOpaquePtr();
932        return true;
933      } else if (CXXConversionDecl *Conversion
934                   = dyn_cast<CXXConversionDecl>(Best->Function)) {
935        // C++ [over.ics.user]p1:
936        //
937        //   [...] If the user-defined conversion is specified by a
938        //   conversion function (12.3.2), the initial standard
939        //   conversion sequence converts the source type to the
940        //   implicit object parameter of the conversion function.
941        User.Before = Best->Conversions[0].Standard;
942        User.ConversionFunction = Conversion;
943
944        // C++ [over.ics.user]p2:
945        //   The second standard conversion sequence converts the
946        //   result of the user-defined conversion to the target type
947        //   for the sequence. Since an implicit conversion sequence
948        //   is an initialization, the special rules for
949        //   initialization by user-defined conversion apply when
950        //   selecting the best user-defined conversion for a
951        //   user-defined conversion sequence (see 13.3.3 and
952        //   13.3.3.1).
953        User.After = Best->FinalConversion;
954        return true;
955      } else {
956        assert(false && "Not a constructor or conversion function?");
957        return false;
958      }
959
960    case OR_No_Viable_Function:
961      // No conversion here! We're done.
962      return false;
963
964    case OR_Ambiguous:
965      // FIXME: See C++ [over.best.ics]p10 for the handling of
966      // ambiguous conversion sequences.
967      return false;
968    }
969
970  return false;
971}
972
973/// CompareImplicitConversionSequences - Compare two implicit
974/// conversion sequences to determine whether one is better than the
975/// other or if they are indistinguishable (C++ 13.3.3.2).
976ImplicitConversionSequence::CompareKind
977Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
978                                         const ImplicitConversionSequence& ICS2)
979{
980  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
981  // conversion sequences (as defined in 13.3.3.1)
982  //   -- a standard conversion sequence (13.3.3.1.1) is a better
983  //      conversion sequence than a user-defined conversion sequence or
984  //      an ellipsis conversion sequence, and
985  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
986  //      conversion sequence than an ellipsis conversion sequence
987  //      (13.3.3.1.3).
988  //
989  if (ICS1.ConversionKind < ICS2.ConversionKind)
990    return ImplicitConversionSequence::Better;
991  else if (ICS2.ConversionKind < ICS1.ConversionKind)
992    return ImplicitConversionSequence::Worse;
993
994  // Two implicit conversion sequences of the same form are
995  // indistinguishable conversion sequences unless one of the
996  // following rules apply: (C++ 13.3.3.2p3):
997  if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
998    return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
999  else if (ICS1.ConversionKind ==
1000             ImplicitConversionSequence::UserDefinedConversion) {
1001    // User-defined conversion sequence U1 is a better conversion
1002    // sequence than another user-defined conversion sequence U2 if
1003    // they contain the same user-defined conversion function or
1004    // constructor and if the second standard conversion sequence of
1005    // U1 is better than the second standard conversion sequence of
1006    // U2 (C++ 13.3.3.2p3).
1007    if (ICS1.UserDefined.ConversionFunction ==
1008          ICS2.UserDefined.ConversionFunction)
1009      return CompareStandardConversionSequences(ICS1.UserDefined.After,
1010                                                ICS2.UserDefined.After);
1011  }
1012
1013  return ImplicitConversionSequence::Indistinguishable;
1014}
1015
1016/// CompareStandardConversionSequences - Compare two standard
1017/// conversion sequences to determine whether one is better than the
1018/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1019ImplicitConversionSequence::CompareKind
1020Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1021                                         const StandardConversionSequence& SCS2)
1022{
1023  // Standard conversion sequence S1 is a better conversion sequence
1024  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1025
1026  //  -- S1 is a proper subsequence of S2 (comparing the conversion
1027  //     sequences in the canonical form defined by 13.3.3.1.1,
1028  //     excluding any Lvalue Transformation; the identity conversion
1029  //     sequence is considered to be a subsequence of any
1030  //     non-identity conversion sequence) or, if not that,
1031  if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1032    // Neither is a proper subsequence of the other. Do nothing.
1033    ;
1034  else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1035           (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1036           (SCS1.Second == ICK_Identity &&
1037            SCS1.Third == ICK_Identity))
1038    // SCS1 is a proper subsequence of SCS2.
1039    return ImplicitConversionSequence::Better;
1040  else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1041           (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1042           (SCS2.Second == ICK_Identity &&
1043            SCS2.Third == ICK_Identity))
1044    // SCS2 is a proper subsequence of SCS1.
1045    return ImplicitConversionSequence::Worse;
1046
1047  //  -- the rank of S1 is better than the rank of S2 (by the rules
1048  //     defined below), or, if not that,
1049  ImplicitConversionRank Rank1 = SCS1.getRank();
1050  ImplicitConversionRank Rank2 = SCS2.getRank();
1051  if (Rank1 < Rank2)
1052    return ImplicitConversionSequence::Better;
1053  else if (Rank2 < Rank1)
1054    return ImplicitConversionSequence::Worse;
1055
1056  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1057  // are indistinguishable unless one of the following rules
1058  // applies:
1059
1060  //   A conversion that is not a conversion of a pointer, or
1061  //   pointer to member, to bool is better than another conversion
1062  //   that is such a conversion.
1063  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1064    return SCS2.isPointerConversionToBool()
1065             ? ImplicitConversionSequence::Better
1066             : ImplicitConversionSequence::Worse;
1067
1068  // C++ [over.ics.rank]p4b2:
1069  //
1070  //   If class B is derived directly or indirectly from class A,
1071  //   conversion of B* to A* is better than conversion of B* to
1072  //   void*, and conversion of A* to void* is better than conversion
1073  //   of B* to void*.
1074  bool SCS1ConvertsToVoid
1075    = SCS1.isPointerConversionToVoidPointer(Context);
1076  bool SCS2ConvertsToVoid
1077    = SCS2.isPointerConversionToVoidPointer(Context);
1078  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1079    // Exactly one of the conversion sequences is a conversion to
1080    // a void pointer; it's the worse conversion.
1081    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1082                              : ImplicitConversionSequence::Worse;
1083  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1084    // Neither conversion sequence converts to a void pointer; compare
1085    // their derived-to-base conversions.
1086    if (ImplicitConversionSequence::CompareKind DerivedCK
1087          = CompareDerivedToBaseConversions(SCS1, SCS2))
1088      return DerivedCK;
1089  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1090    // Both conversion sequences are conversions to void
1091    // pointers. Compare the source types to determine if there's an
1092    // inheritance relationship in their sources.
1093    QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1094    QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1095
1096    // Adjust the types we're converting from via the array-to-pointer
1097    // conversion, if we need to.
1098    if (SCS1.First == ICK_Array_To_Pointer)
1099      FromType1 = Context.getArrayDecayedType(FromType1);
1100    if (SCS2.First == ICK_Array_To_Pointer)
1101      FromType2 = Context.getArrayDecayedType(FromType2);
1102
1103    QualType FromPointee1
1104      = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1105    QualType FromPointee2
1106      = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1107
1108    if (IsDerivedFrom(FromPointee2, FromPointee1))
1109      return ImplicitConversionSequence::Better;
1110    else if (IsDerivedFrom(FromPointee1, FromPointee2))
1111      return ImplicitConversionSequence::Worse;
1112  }
1113
1114  // Compare based on qualification conversions (C++ 13.3.3.2p3,
1115  // bullet 3).
1116  if (ImplicitConversionSequence::CompareKind QualCK
1117        = CompareQualificationConversions(SCS1, SCS2))
1118    return QualCK;
1119
1120  // C++ [over.ics.rank]p3b4:
1121  //   -- S1 and S2 are reference bindings (8.5.3), and the types to
1122  //      which the references refer are the same type except for
1123  //      top-level cv-qualifiers, and the type to which the reference
1124  //      initialized by S2 refers is more cv-qualified than the type
1125  //      to which the reference initialized by S1 refers.
1126  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1127    QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1128    QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1129    T1 = Context.getCanonicalType(T1);
1130    T2 = Context.getCanonicalType(T2);
1131    if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1132      if (T2.isMoreQualifiedThan(T1))
1133        return ImplicitConversionSequence::Better;
1134      else if (T1.isMoreQualifiedThan(T2))
1135        return ImplicitConversionSequence::Worse;
1136    }
1137  }
1138
1139  return ImplicitConversionSequence::Indistinguishable;
1140}
1141
1142/// CompareQualificationConversions - Compares two standard conversion
1143/// sequences to determine whether they can be ranked based on their
1144/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1145ImplicitConversionSequence::CompareKind
1146Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1147                                      const StandardConversionSequence& SCS2)
1148{
1149  // C++ 13.3.3.2p3:
1150  //  -- S1 and S2 differ only in their qualification conversion and
1151  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
1152  //     cv-qualification signature of type T1 is a proper subset of
1153  //     the cv-qualification signature of type T2, and S1 is not the
1154  //     deprecated string literal array-to-pointer conversion (4.2).
1155  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1156      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1157    return ImplicitConversionSequence::Indistinguishable;
1158
1159  // FIXME: the example in the standard doesn't use a qualification
1160  // conversion (!)
1161  QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1162  QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1163  T1 = Context.getCanonicalType(T1);
1164  T2 = Context.getCanonicalType(T2);
1165
1166  // If the types are the same, we won't learn anything by unwrapped
1167  // them.
1168  if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1169    return ImplicitConversionSequence::Indistinguishable;
1170
1171  ImplicitConversionSequence::CompareKind Result
1172    = ImplicitConversionSequence::Indistinguishable;
1173  while (UnwrapSimilarPointerTypes(T1, T2)) {
1174    // Within each iteration of the loop, we check the qualifiers to
1175    // determine if this still looks like a qualification
1176    // conversion. Then, if all is well, we unwrap one more level of
1177    // pointers or pointers-to-members and do it all again
1178    // until there are no more pointers or pointers-to-members left
1179    // to unwrap. This essentially mimics what
1180    // IsQualificationConversion does, but here we're checking for a
1181    // strict subset of qualifiers.
1182    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1183      // The qualifiers are the same, so this doesn't tell us anything
1184      // about how the sequences rank.
1185      ;
1186    else if (T2.isMoreQualifiedThan(T1)) {
1187      // T1 has fewer qualifiers, so it could be the better sequence.
1188      if (Result == ImplicitConversionSequence::Worse)
1189        // Neither has qualifiers that are a subset of the other's
1190        // qualifiers.
1191        return ImplicitConversionSequence::Indistinguishable;
1192
1193      Result = ImplicitConversionSequence::Better;
1194    } else if (T1.isMoreQualifiedThan(T2)) {
1195      // T2 has fewer qualifiers, so it could be the better sequence.
1196      if (Result == ImplicitConversionSequence::Better)
1197        // Neither has qualifiers that are a subset of the other's
1198        // qualifiers.
1199        return ImplicitConversionSequence::Indistinguishable;
1200
1201      Result = ImplicitConversionSequence::Worse;
1202    } else {
1203      // Qualifiers are disjoint.
1204      return ImplicitConversionSequence::Indistinguishable;
1205    }
1206
1207    // If the types after this point are equivalent, we're done.
1208    if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1209      break;
1210  }
1211
1212  // Check that the winning standard conversion sequence isn't using
1213  // the deprecated string literal array to pointer conversion.
1214  switch (Result) {
1215  case ImplicitConversionSequence::Better:
1216    if (SCS1.Deprecated)
1217      Result = ImplicitConversionSequence::Indistinguishable;
1218    break;
1219
1220  case ImplicitConversionSequence::Indistinguishable:
1221    break;
1222
1223  case ImplicitConversionSequence::Worse:
1224    if (SCS2.Deprecated)
1225      Result = ImplicitConversionSequence::Indistinguishable;
1226    break;
1227  }
1228
1229  return Result;
1230}
1231
1232/// CompareDerivedToBaseConversions - Compares two standard conversion
1233/// sequences to determine whether they can be ranked based on their
1234/// various kinds of derived-to-base conversions (C++ [over.ics.rank]p4b3).
1235ImplicitConversionSequence::CompareKind
1236Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1237                                      const StandardConversionSequence& SCS2) {
1238  QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1239  QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1240  QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1241  QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1242
1243  // Adjust the types we're converting from via the array-to-pointer
1244  // conversion, if we need to.
1245  if (SCS1.First == ICK_Array_To_Pointer)
1246    FromType1 = Context.getArrayDecayedType(FromType1);
1247  if (SCS2.First == ICK_Array_To_Pointer)
1248    FromType2 = Context.getArrayDecayedType(FromType2);
1249
1250  // Canonicalize all of the types.
1251  FromType1 = Context.getCanonicalType(FromType1);
1252  ToType1 = Context.getCanonicalType(ToType1);
1253  FromType2 = Context.getCanonicalType(FromType2);
1254  ToType2 = Context.getCanonicalType(ToType2);
1255
1256  // C++ [over.ics.rank]p4b3:
1257  //
1258  //   If class B is derived directly or indirectly from class A and
1259  //   class C is derived directly or indirectly from B,
1260
1261  // Compare based on pointer conversions.
1262  if (SCS1.Second == ICK_Pointer_Conversion &&
1263      SCS2.Second == ICK_Pointer_Conversion) {
1264    QualType FromPointee1
1265      = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1266    QualType ToPointee1
1267      = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1268    QualType FromPointee2
1269      = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1270    QualType ToPointee2
1271      = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1272    //   -- conversion of C* to B* is better than conversion of C* to A*,
1273    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1274      if (IsDerivedFrom(ToPointee1, ToPointee2))
1275        return ImplicitConversionSequence::Better;
1276      else if (IsDerivedFrom(ToPointee2, ToPointee1))
1277        return ImplicitConversionSequence::Worse;
1278    }
1279
1280    //   -- conversion of B* to A* is better than conversion of C* to A*,
1281    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1282      if (IsDerivedFrom(FromPointee2, FromPointee1))
1283        return ImplicitConversionSequence::Better;
1284      else if (IsDerivedFrom(FromPointee1, FromPointee2))
1285        return ImplicitConversionSequence::Worse;
1286    }
1287  }
1288
1289  // Compare based on reference bindings.
1290  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1291      SCS1.Second == ICK_Derived_To_Base) {
1292    //   -- binding of an expression of type C to a reference of type
1293    //      B& is better than binding an expression of type C to a
1294    //      reference of type A&,
1295    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1296        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1297      if (IsDerivedFrom(ToType1, ToType2))
1298        return ImplicitConversionSequence::Better;
1299      else if (IsDerivedFrom(ToType2, ToType1))
1300        return ImplicitConversionSequence::Worse;
1301    }
1302
1303    //   -- binding of an expression of type B to a reference of type
1304    //      A& is better than binding an expression of type C to a
1305    //      reference of type A&,
1306    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1307        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1308      if (IsDerivedFrom(FromType2, FromType1))
1309        return ImplicitConversionSequence::Better;
1310      else if (IsDerivedFrom(FromType1, FromType2))
1311        return ImplicitConversionSequence::Worse;
1312    }
1313  }
1314
1315
1316  // FIXME: conversion of A::* to B::* is better than conversion of
1317  // A::* to C::*,
1318
1319  // FIXME: conversion of B::* to C::* is better than conversion of
1320  // A::* to C::*, and
1321
1322  if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1323      SCS1.Second == ICK_Derived_To_Base) {
1324    //   -- conversion of C to B is better than conversion of C to A,
1325    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1326        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1327      if (IsDerivedFrom(ToType1, ToType2))
1328        return ImplicitConversionSequence::Better;
1329      else if (IsDerivedFrom(ToType2, ToType1))
1330        return ImplicitConversionSequence::Worse;
1331    }
1332
1333    //   -- conversion of B to A is better than conversion of C to A.
1334    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1335        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1336      if (IsDerivedFrom(FromType2, FromType1))
1337        return ImplicitConversionSequence::Better;
1338      else if (IsDerivedFrom(FromType1, FromType2))
1339        return ImplicitConversionSequence::Worse;
1340    }
1341  }
1342
1343  return ImplicitConversionSequence::Indistinguishable;
1344}
1345
1346/// TryCopyInitialization - Try to copy-initialize a value of type
1347/// ToType from the expression From. Return the implicit conversion
1348/// sequence required to pass this argument, which may be a bad
1349/// conversion sequence (meaning that the argument cannot be passed to
1350/// a parameter of this type). If @p SuppressUserConversions, then we
1351/// do not permit any user-defined conversion sequences.
1352ImplicitConversionSequence
1353Sema::TryCopyInitialization(Expr *From, QualType ToType,
1354                            bool SuppressUserConversions) {
1355  if (!getLangOptions().CPlusPlus) {
1356    // In C, copy initialization is the same as performing an assignment.
1357    AssignConvertType ConvTy =
1358      CheckSingleAssignmentConstraints(ToType, From);
1359    ImplicitConversionSequence ICS;
1360    if (getLangOptions().NoExtensions? ConvTy != Compatible
1361                                     : ConvTy == Incompatible)
1362      ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1363    else
1364      ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1365    return ICS;
1366  } else if (ToType->isReferenceType()) {
1367    ImplicitConversionSequence ICS;
1368    CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
1369    return ICS;
1370  } else {
1371    return TryImplicitConversion(From, ToType, SuppressUserConversions);
1372  }
1373}
1374
1375/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1376/// type ToType. Returns true (and emits a diagnostic) if there was
1377/// an error, returns false if the initialization succeeded.
1378bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1379                                     const char* Flavor) {
1380  if (!getLangOptions().CPlusPlus) {
1381    // In C, argument passing is the same as performing an assignment.
1382    QualType FromType = From->getType();
1383    AssignConvertType ConvTy =
1384      CheckSingleAssignmentConstraints(ToType, From);
1385
1386    return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1387                                    FromType, From, Flavor);
1388  } else if (ToType->isReferenceType()) {
1389    return CheckReferenceInit(From, ToType);
1390  } else {
1391    if (PerformImplicitConversion(From, ToType))
1392      return Diag(From->getSourceRange().getBegin(),
1393                  diag::err_typecheck_convert_incompatible,
1394                  ToType.getAsString(), From->getType().getAsString(),
1395                  Flavor,
1396                  From->getSourceRange());
1397    else
1398      return false;
1399  }
1400}
1401
1402/// AddOverloadCandidate - Adds the given function to the set of
1403/// candidate functions, using the given function call arguments.  If
1404/// @p SuppressUserConversions, then don't allow user-defined
1405/// conversions via constructors or conversion operators.
1406void
1407Sema::AddOverloadCandidate(FunctionDecl *Function,
1408                           Expr **Args, unsigned NumArgs,
1409                           OverloadCandidateSet& CandidateSet,
1410                           bool SuppressUserConversions)
1411{
1412  const FunctionTypeProto* Proto
1413    = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1414  assert(Proto && "Functions without a prototype cannot be overloaded");
1415  assert(!isa<CXXConversionDecl>(Function) &&
1416         "Use AddConversionCandidate for conversion functions");
1417
1418  // Add this candidate
1419  CandidateSet.push_back(OverloadCandidate());
1420  OverloadCandidate& Candidate = CandidateSet.back();
1421  Candidate.Function = Function;
1422
1423  unsigned NumArgsInProto = Proto->getNumArgs();
1424
1425  // (C++ 13.3.2p2): A candidate function having fewer than m
1426  // parameters is viable only if it has an ellipsis in its parameter
1427  // list (8.3.5).
1428  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1429    Candidate.Viable = false;
1430    return;
1431  }
1432
1433  // (C++ 13.3.2p2): A candidate function having more than m parameters
1434  // is viable only if the (m+1)st parameter has a default argument
1435  // (8.3.6). For the purposes of overload resolution, the
1436  // parameter list is truncated on the right, so that there are
1437  // exactly m parameters.
1438  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1439  if (NumArgs < MinRequiredArgs) {
1440    // Not enough arguments.
1441    Candidate.Viable = false;
1442    return;
1443  }
1444
1445  // Determine the implicit conversion sequences for each of the
1446  // arguments.
1447  Candidate.Viable = true;
1448  Candidate.Conversions.resize(NumArgs);
1449  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1450    if (ArgIdx < NumArgsInProto) {
1451      // (C++ 13.3.2p3): for F to be a viable function, there shall
1452      // exist for each argument an implicit conversion sequence
1453      // (13.3.3.1) that converts that argument to the corresponding
1454      // parameter of F.
1455      QualType ParamType = Proto->getArgType(ArgIdx);
1456      Candidate.Conversions[ArgIdx]
1457        = TryCopyInitialization(Args[ArgIdx], ParamType,
1458                                SuppressUserConversions);
1459      if (Candidate.Conversions[ArgIdx].ConversionKind
1460            == ImplicitConversionSequence::BadConversion)
1461        Candidate.Viable = false;
1462    } else {
1463      // (C++ 13.3.2p2): For the purposes of overload resolution, any
1464      // argument for which there is no corresponding parameter is
1465      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1466      Candidate.Conversions[ArgIdx].ConversionKind
1467        = ImplicitConversionSequence::EllipsisConversion;
1468    }
1469  }
1470}
1471
1472/// AddConversionCandidate - Add a C++ conversion function as a
1473/// candidate in the candidate set (C++ [over.match.conv],
1474/// C++ [over.match.copy]). From is the expression we're converting from,
1475/// and ToType is the type that we're eventually trying to convert to
1476/// (which may or may not be the same type as the type that the
1477/// conversion function produces).
1478void
1479Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1480                             Expr *From, QualType ToType,
1481                             OverloadCandidateSet& CandidateSet) {
1482  // Add this candidate
1483  CandidateSet.push_back(OverloadCandidate());
1484  OverloadCandidate& Candidate = CandidateSet.back();
1485  Candidate.Function = Conversion;
1486  Candidate.FinalConversion.setAsIdentityConversion();
1487  Candidate.FinalConversion.FromTypePtr
1488    = Conversion->getConversionType().getAsOpaquePtr();
1489  Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1490
1491  // Determine the implicit conversion sequences for each of the
1492  // arguments.
1493  Candidate.Viable = true;
1494  Candidate.Conversions.resize(1);
1495
1496  // FIXME: We need to follow the rules for the implicit object
1497  // parameter.
1498  QualType ImplicitObjectType
1499    = Context.getTypeDeclType(Conversion->getParent());
1500  ImplicitObjectType
1501    = ImplicitObjectType.getQualifiedType(Conversion->getTypeQualifiers());
1502  ImplicitObjectType = Context.getReferenceType(ImplicitObjectType);
1503  Candidate.Conversions[0] = TryCopyInitialization(From, ImplicitObjectType,
1504                                                   true);
1505  if (Candidate.Conversions[0].ConversionKind
1506      == ImplicitConversionSequence::BadConversion) {
1507    Candidate.Viable = false;
1508    return;
1509  }
1510
1511  // To determine what the conversion from the result of calling the
1512  // conversion function to the type we're eventually trying to
1513  // convert to (ToType), we need to synthesize a call to the
1514  // conversion function and attempt copy initialization from it. This
1515  // makes sure that we get the right semantics with respect to
1516  // lvalues/rvalues and the type. Fortunately, we can allocate this
1517  // call on the stack and we don't need its arguments to be
1518  // well-formed.
1519  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1520                            SourceLocation());
1521  ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
1522                                &ConversionRef);
1523  CallExpr Call(&ConversionFn, 0, 0,
1524                Conversion->getConversionType().getNonReferenceType(),
1525                SourceLocation());
1526  ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1527  switch (ICS.ConversionKind) {
1528  case ImplicitConversionSequence::StandardConversion:
1529    Candidate.FinalConversion = ICS.Standard;
1530    break;
1531
1532  case ImplicitConversionSequence::BadConversion:
1533    Candidate.Viable = false;
1534    break;
1535
1536  default:
1537    assert(false &&
1538           "Can only end up with a standard conversion sequence or failure");
1539  }
1540}
1541
1542/// AddOverloadCandidates - Add all of the function overloads in Ovl
1543/// to the candidate set.
1544void
1545Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
1546                            Expr **Args, unsigned NumArgs,
1547                            OverloadCandidateSet& CandidateSet,
1548                            bool SuppressUserConversions)
1549{
1550  for (OverloadedFunctionDecl::function_const_iterator Func
1551         = Ovl->function_begin();
1552       Func != Ovl->function_end(); ++Func)
1553    AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
1554                         SuppressUserConversions);
1555}
1556
1557/// isBetterOverloadCandidate - Determines whether the first overload
1558/// candidate is a better candidate than the second (C++ 13.3.3p1).
1559bool
1560Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
1561                                const OverloadCandidate& Cand2)
1562{
1563  // Define viable functions to be better candidates than non-viable
1564  // functions.
1565  if (!Cand2.Viable)
1566    return Cand1.Viable;
1567  else if (!Cand1.Viable)
1568    return false;
1569
1570  // FIXME: Deal with the implicit object parameter for static member
1571  // functions. (C++ 13.3.3p1).
1572
1573  // (C++ 13.3.3p1): a viable function F1 is defined to be a better
1574  // function than another viable function F2 if for all arguments i,
1575  // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
1576  // then...
1577  unsigned NumArgs = Cand1.Conversions.size();
1578  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
1579  bool HasBetterConversion = false;
1580  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1581    switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
1582                                               Cand2.Conversions[ArgIdx])) {
1583    case ImplicitConversionSequence::Better:
1584      // Cand1 has a better conversion sequence.
1585      HasBetterConversion = true;
1586      break;
1587
1588    case ImplicitConversionSequence::Worse:
1589      // Cand1 can't be better than Cand2.
1590      return false;
1591
1592    case ImplicitConversionSequence::Indistinguishable:
1593      // Do nothing.
1594      break;
1595    }
1596  }
1597
1598  if (HasBetterConversion)
1599    return true;
1600
1601  // FIXME: Several other bullets in (C++ 13.3.3p1) need to be implemented.
1602
1603  // C++ [over.match.best]p1b4:
1604  //
1605  //   -- the context is an initialization by user-defined conversion
1606  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
1607  //      from the return type of F1 to the destination type (i.e.,
1608  //      the type of the entity being initialized) is a better
1609  //      conversion sequence than the standard conversion sequence
1610  //      from the return type of F2 to the destination type.
1611  if (isa<CXXConversionDecl>(Cand1.Function) &&
1612      isa<CXXConversionDecl>(Cand2.Function)) {
1613    switch (CompareStandardConversionSequences(Cand1.FinalConversion,
1614                                               Cand2.FinalConversion)) {
1615    case ImplicitConversionSequence::Better:
1616      // Cand1 has a better conversion sequence.
1617      return true;
1618
1619    case ImplicitConversionSequence::Worse:
1620      // Cand1 can't be better than Cand2.
1621      return false;
1622
1623    case ImplicitConversionSequence::Indistinguishable:
1624      // Do nothing
1625      break;
1626    }
1627  }
1628
1629  return false;
1630}
1631
1632/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
1633/// within an overload candidate set. If overloading is successful,
1634/// the result will be OR_Success and Best will be set to point to the
1635/// best viable function within the candidate set. Otherwise, one of
1636/// several kinds of errors will be returned; see
1637/// Sema::OverloadingResult.
1638Sema::OverloadingResult
1639Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
1640                         OverloadCandidateSet::iterator& Best)
1641{
1642  // Find the best viable function.
1643  Best = CandidateSet.end();
1644  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
1645       Cand != CandidateSet.end(); ++Cand) {
1646    if (Cand->Viable) {
1647      if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
1648        Best = Cand;
1649    }
1650  }
1651
1652  // If we didn't find any viable functions, abort.
1653  if (Best == CandidateSet.end())
1654    return OR_No_Viable_Function;
1655
1656  // Make sure that this function is better than every other viable
1657  // function. If not, we have an ambiguity.
1658  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
1659       Cand != CandidateSet.end(); ++Cand) {
1660    if (Cand->Viable &&
1661        Cand != Best &&
1662        !isBetterOverloadCandidate(*Best, *Cand))
1663      return OR_Ambiguous;
1664  }
1665
1666  // Best is the best viable function.
1667  return OR_Success;
1668}
1669
1670/// PrintOverloadCandidates - When overload resolution fails, prints
1671/// diagnostic messages containing the candidates in the candidate
1672/// set. If OnlyViable is true, only viable candidates will be printed.
1673void
1674Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
1675                              bool OnlyViable)
1676{
1677  OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1678                             LastCand = CandidateSet.end();
1679  for (; Cand != LastCand; ++Cand) {
1680    if (Cand->Viable ||!OnlyViable)
1681      Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
1682  }
1683}
1684
1685} // end namespace clang
1686