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