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