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