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