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