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