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