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