]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaOverload.cpp
Merge ACPICA 20141107 and 20150204.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaOverload.cpp
1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
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/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include <algorithm>
36 #include <cstdlib>
37
38 namespace clang {
39 using namespace sema;
40
41 /// A convenience routine for creating a decayed reference to a function.
42 static ExprResult
43 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44                       bool HadMultipleCandidates,
45                       SourceLocation Loc = SourceLocation(), 
46                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
47   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
48     return ExprError(); 
49   // If FoundDecl is different from Fn (such as if one is a template
50   // and the other a specialization), make sure DiagnoseUseOfDecl is 
51   // called on both.
52   // FIXME: This would be more comprehensively addressed by modifying
53   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
54   // being used.
55   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
56     return ExprError();
57   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
58                                                  VK_LValue, Loc, LocInfo);
59   if (HadMultipleCandidates)
60     DRE->setHadMultipleCandidates(true);
61
62   S.MarkDeclRefReferenced(DRE);
63
64   ExprResult E = DRE;
65   E = S.DefaultFunctionArrayConversion(E.get());
66   if (E.isInvalid())
67     return ExprError();
68   return E;
69 }
70
71 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72                                  bool InOverloadResolution,
73                                  StandardConversionSequence &SCS,
74                                  bool CStyle,
75                                  bool AllowObjCWritebackConversion);
76
77 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 
78                                                  QualType &ToType,
79                                                  bool InOverloadResolution,
80                                                  StandardConversionSequence &SCS,
81                                                  bool CStyle);
82 static OverloadingResult
83 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84                         UserDefinedConversionSequence& User,
85                         OverloadCandidateSet& Conversions,
86                         bool AllowExplicit,
87                         bool AllowObjCConversionOnExplicit);
88
89
90 static ImplicitConversionSequence::CompareKind
91 CompareStandardConversionSequences(Sema &S,
92                                    const StandardConversionSequence& SCS1,
93                                    const StandardConversionSequence& SCS2);
94
95 static ImplicitConversionSequence::CompareKind
96 CompareQualificationConversions(Sema &S,
97                                 const StandardConversionSequence& SCS1,
98                                 const StandardConversionSequence& SCS2);
99
100 static ImplicitConversionSequence::CompareKind
101 CompareDerivedToBaseConversions(Sema &S,
102                                 const StandardConversionSequence& SCS1,
103                                 const StandardConversionSequence& SCS2);
104
105
106
107 /// GetConversionCategory - Retrieve the implicit conversion
108 /// category corresponding to the given implicit conversion kind.
109 ImplicitConversionCategory
110 GetConversionCategory(ImplicitConversionKind Kind) {
111   static const ImplicitConversionCategory
112     Category[(int)ICK_Num_Conversion_Kinds] = {
113     ICC_Identity,
114     ICC_Lvalue_Transformation,
115     ICC_Lvalue_Transformation,
116     ICC_Lvalue_Transformation,
117     ICC_Identity,
118     ICC_Qualification_Adjustment,
119     ICC_Promotion,
120     ICC_Promotion,
121     ICC_Promotion,
122     ICC_Conversion,
123     ICC_Conversion,
124     ICC_Conversion,
125     ICC_Conversion,
126     ICC_Conversion,
127     ICC_Conversion,
128     ICC_Conversion,
129     ICC_Conversion,
130     ICC_Conversion,
131     ICC_Conversion,
132     ICC_Conversion,
133     ICC_Conversion,
134     ICC_Conversion
135   };
136   return Category[(int)Kind];
137 }
138
139 /// GetConversionRank - Retrieve the implicit conversion rank
140 /// corresponding to the given implicit conversion kind.
141 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
142   static const ImplicitConversionRank
143     Rank[(int)ICK_Num_Conversion_Kinds] = {
144     ICR_Exact_Match,
145     ICR_Exact_Match,
146     ICR_Exact_Match,
147     ICR_Exact_Match,
148     ICR_Exact_Match,
149     ICR_Exact_Match,
150     ICR_Promotion,
151     ICR_Promotion,
152     ICR_Promotion,
153     ICR_Conversion,
154     ICR_Conversion,
155     ICR_Conversion,
156     ICR_Conversion,
157     ICR_Conversion,
158     ICR_Conversion,
159     ICR_Conversion,
160     ICR_Conversion,
161     ICR_Conversion,
162     ICR_Conversion,
163     ICR_Conversion,
164     ICR_Complex_Real_Conversion,
165     ICR_Conversion,
166     ICR_Conversion,
167     ICR_Writeback_Conversion
168   };
169   return Rank[(int)Kind];
170 }
171
172 /// GetImplicitConversionName - Return the name of this kind of
173 /// implicit conversion.
174 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
175   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
176     "No conversion",
177     "Lvalue-to-rvalue",
178     "Array-to-pointer",
179     "Function-to-pointer",
180     "Noreturn adjustment",
181     "Qualification",
182     "Integral promotion",
183     "Floating point promotion",
184     "Complex promotion",
185     "Integral conversion",
186     "Floating conversion",
187     "Complex conversion",
188     "Floating-integral conversion",
189     "Pointer conversion",
190     "Pointer-to-member conversion",
191     "Boolean conversion",
192     "Compatible-types conversion",
193     "Derived-to-base conversion",
194     "Vector conversion",
195     "Vector splat",
196     "Complex-real conversion",
197     "Block Pointer conversion",
198     "Transparent Union Conversion"
199     "Writeback conversion"
200   };
201   return Name[Kind];
202 }
203
204 /// StandardConversionSequence - Set the standard conversion
205 /// sequence to the identity conversion.
206 void StandardConversionSequence::setAsIdentityConversion() {
207   First = ICK_Identity;
208   Second = ICK_Identity;
209   Third = ICK_Identity;
210   DeprecatedStringLiteralToCharPtr = false;
211   QualificationIncludesObjCLifetime = false;
212   ReferenceBinding = false;
213   DirectBinding = false;
214   IsLvalueReference = true;
215   BindsToFunctionLvalue = false;
216   BindsToRvalue = false;
217   BindsImplicitObjectArgumentWithoutRefQualifier = false;
218   ObjCLifetimeConversionBinding = false;
219   CopyConstructor = nullptr;
220 }
221
222 /// getRank - Retrieve the rank of this standard conversion sequence
223 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
224 /// implicit conversions.
225 ImplicitConversionRank StandardConversionSequence::getRank() const {
226   ImplicitConversionRank Rank = ICR_Exact_Match;
227   if  (GetConversionRank(First) > Rank)
228     Rank = GetConversionRank(First);
229   if  (GetConversionRank(Second) > Rank)
230     Rank = GetConversionRank(Second);
231   if  (GetConversionRank(Third) > Rank)
232     Rank = GetConversionRank(Third);
233   return Rank;
234 }
235
236 /// isPointerConversionToBool - Determines whether this conversion is
237 /// a conversion of a pointer or pointer-to-member to bool. This is
238 /// used as part of the ranking of standard conversion sequences
239 /// (C++ 13.3.3.2p4).
240 bool StandardConversionSequence::isPointerConversionToBool() const {
241   // Note that FromType has not necessarily been transformed by the
242   // array-to-pointer or function-to-pointer implicit conversions, so
243   // check for their presence as well as checking whether FromType is
244   // a pointer.
245   if (getToType(1)->isBooleanType() &&
246       (getFromType()->isPointerType() ||
247        getFromType()->isObjCObjectPointerType() ||
248        getFromType()->isBlockPointerType() ||
249        getFromType()->isNullPtrType() ||
250        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
251     return true;
252
253   return false;
254 }
255
256 /// isPointerConversionToVoidPointer - Determines whether this
257 /// conversion is a conversion of a pointer to a void pointer. This is
258 /// used as part of the ranking of standard conversion sequences (C++
259 /// 13.3.3.2p4).
260 bool
261 StandardConversionSequence::
262 isPointerConversionToVoidPointer(ASTContext& Context) const {
263   QualType FromType = getFromType();
264   QualType ToType = getToType(1);
265
266   // Note that FromType has not necessarily been transformed by the
267   // array-to-pointer implicit conversion, so check for its presence
268   // and redo the conversion to get a pointer.
269   if (First == ICK_Array_To_Pointer)
270     FromType = Context.getArrayDecayedType(FromType);
271
272   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
273     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
274       return ToPtrType->getPointeeType()->isVoidType();
275
276   return false;
277 }
278
279 /// Skip any implicit casts which could be either part of a narrowing conversion
280 /// or after one in an implicit conversion.
281 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
282   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
283     switch (ICE->getCastKind()) {
284     case CK_NoOp:
285     case CK_IntegralCast:
286     case CK_IntegralToBoolean:
287     case CK_IntegralToFloating:
288     case CK_FloatingToIntegral:
289     case CK_FloatingToBoolean:
290     case CK_FloatingCast:
291       Converted = ICE->getSubExpr();
292       continue;
293
294     default:
295       return Converted;
296     }
297   }
298
299   return Converted;
300 }
301
302 /// Check if this standard conversion sequence represents a narrowing
303 /// conversion, according to C++11 [dcl.init.list]p7.
304 ///
305 /// \param Ctx  The AST context.
306 /// \param Converted  The result of applying this standard conversion sequence.
307 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
308 ///        value of the expression prior to the narrowing conversion.
309 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
310 ///        type of the expression prior to the narrowing conversion.
311 NarrowingKind
312 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
313                                              const Expr *Converted,
314                                              APValue &ConstantValue,
315                                              QualType &ConstantType) const {
316   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
317
318   // C++11 [dcl.init.list]p7:
319   //   A narrowing conversion is an implicit conversion ...
320   QualType FromType = getToType(0);
321   QualType ToType = getToType(1);
322   switch (Second) {
323   // -- from a floating-point type to an integer type, or
324   //
325   // -- from an integer type or unscoped enumeration type to a floating-point
326   //    type, except where the source is a constant expression and the actual
327   //    value after conversion will fit into the target type and will produce
328   //    the original value when converted back to the original type, or
329   case ICK_Floating_Integral:
330     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
331       return NK_Type_Narrowing;
332     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
333       llvm::APSInt IntConstantValue;
334       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
335       if (Initializer &&
336           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
337         // Convert the integer to the floating type.
338         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
339         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
340                                 llvm::APFloat::rmNearestTiesToEven);
341         // And back.
342         llvm::APSInt ConvertedValue = IntConstantValue;
343         bool ignored;
344         Result.convertToInteger(ConvertedValue,
345                                 llvm::APFloat::rmTowardZero, &ignored);
346         // If the resulting value is different, this was a narrowing conversion.
347         if (IntConstantValue != ConvertedValue) {
348           ConstantValue = APValue(IntConstantValue);
349           ConstantType = Initializer->getType();
350           return NK_Constant_Narrowing;
351         }
352       } else {
353         // Variables are always narrowings.
354         return NK_Variable_Narrowing;
355       }
356     }
357     return NK_Not_Narrowing;
358
359   // -- from long double to double or float, or from double to float, except
360   //    where the source is a constant expression and the actual value after
361   //    conversion is within the range of values that can be represented (even
362   //    if it cannot be represented exactly), or
363   case ICK_Floating_Conversion:
364     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
365         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
366       // FromType is larger than ToType.
367       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
368       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
369         // Constant!
370         assert(ConstantValue.isFloat());
371         llvm::APFloat FloatVal = ConstantValue.getFloat();
372         // Convert the source value into the target type.
373         bool ignored;
374         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
375           Ctx.getFloatTypeSemantics(ToType),
376           llvm::APFloat::rmNearestTiesToEven, &ignored);
377         // If there was no overflow, the source value is within the range of
378         // values that can be represented.
379         if (ConvertStatus & llvm::APFloat::opOverflow) {
380           ConstantType = Initializer->getType();
381           return NK_Constant_Narrowing;
382         }
383       } else {
384         return NK_Variable_Narrowing;
385       }
386     }
387     return NK_Not_Narrowing;
388
389   // -- from an integer type or unscoped enumeration type to an integer type
390   //    that cannot represent all the values of the original type, except where
391   //    the source is a constant expression and the actual value after
392   //    conversion will fit into the target type and will produce the original
393   //    value when converted back to the original type.
394   case ICK_Boolean_Conversion:  // Bools are integers too.
395     if (!FromType->isIntegralOrUnscopedEnumerationType()) {
396       // Boolean conversions can be from pointers and pointers to members
397       // [conv.bool], and those aren't considered narrowing conversions.
398       return NK_Not_Narrowing;
399     }  // Otherwise, fall through to the integral case.
400   case ICK_Integral_Conversion: {
401     assert(FromType->isIntegralOrUnscopedEnumerationType());
402     assert(ToType->isIntegralOrUnscopedEnumerationType());
403     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
404     const unsigned FromWidth = Ctx.getIntWidth(FromType);
405     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
406     const unsigned ToWidth = Ctx.getIntWidth(ToType);
407
408     if (FromWidth > ToWidth ||
409         (FromWidth == ToWidth && FromSigned != ToSigned) ||
410         (FromSigned && !ToSigned)) {
411       // Not all values of FromType can be represented in ToType.
412       llvm::APSInt InitializerValue;
413       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
414       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
415         // Such conversions on variables are always narrowing.
416         return NK_Variable_Narrowing;
417       }
418       bool Narrowing = false;
419       if (FromWidth < ToWidth) {
420         // Negative -> unsigned is narrowing. Otherwise, more bits is never
421         // narrowing.
422         if (InitializerValue.isSigned() && InitializerValue.isNegative())
423           Narrowing = true;
424       } else {
425         // Add a bit to the InitializerValue so we don't have to worry about
426         // signed vs. unsigned comparisons.
427         InitializerValue = InitializerValue.extend(
428           InitializerValue.getBitWidth() + 1);
429         // Convert the initializer to and from the target width and signed-ness.
430         llvm::APSInt ConvertedValue = InitializerValue;
431         ConvertedValue = ConvertedValue.trunc(ToWidth);
432         ConvertedValue.setIsSigned(ToSigned);
433         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
434         ConvertedValue.setIsSigned(InitializerValue.isSigned());
435         // If the result is different, this was a narrowing conversion.
436         if (ConvertedValue != InitializerValue)
437           Narrowing = true;
438       }
439       if (Narrowing) {
440         ConstantType = Initializer->getType();
441         ConstantValue = APValue(InitializerValue);
442         return NK_Constant_Narrowing;
443       }
444     }
445     return NK_Not_Narrowing;
446   }
447
448   default:
449     // Other kinds of conversions are not narrowings.
450     return NK_Not_Narrowing;
451   }
452 }
453
454 /// dump - Print this standard conversion sequence to standard
455 /// error. Useful for debugging overloading issues.
456 void StandardConversionSequence::dump() const {
457   raw_ostream &OS = llvm::errs();
458   bool PrintedSomething = false;
459   if (First != ICK_Identity) {
460     OS << GetImplicitConversionName(First);
461     PrintedSomething = true;
462   }
463
464   if (Second != ICK_Identity) {
465     if (PrintedSomething) {
466       OS << " -> ";
467     }
468     OS << GetImplicitConversionName(Second);
469
470     if (CopyConstructor) {
471       OS << " (by copy constructor)";
472     } else if (DirectBinding) {
473       OS << " (direct reference binding)";
474     } else if (ReferenceBinding) {
475       OS << " (reference binding)";
476     }
477     PrintedSomething = true;
478   }
479
480   if (Third != ICK_Identity) {
481     if (PrintedSomething) {
482       OS << " -> ";
483     }
484     OS << GetImplicitConversionName(Third);
485     PrintedSomething = true;
486   }
487
488   if (!PrintedSomething) {
489     OS << "No conversions required";
490   }
491 }
492
493 /// dump - Print this user-defined conversion sequence to standard
494 /// error. Useful for debugging overloading issues.
495 void UserDefinedConversionSequence::dump() const {
496   raw_ostream &OS = llvm::errs();
497   if (Before.First || Before.Second || Before.Third) {
498     Before.dump();
499     OS << " -> ";
500   }
501   if (ConversionFunction)
502     OS << '\'' << *ConversionFunction << '\'';
503   else
504     OS << "aggregate initialization";
505   if (After.First || After.Second || After.Third) {
506     OS << " -> ";
507     After.dump();
508   }
509 }
510
511 /// dump - Print this implicit conversion sequence to standard
512 /// error. Useful for debugging overloading issues.
513 void ImplicitConversionSequence::dump() const {
514   raw_ostream &OS = llvm::errs();
515   if (isStdInitializerListElement())
516     OS << "Worst std::initializer_list element conversion: ";
517   switch (ConversionKind) {
518   case StandardConversion:
519     OS << "Standard conversion: ";
520     Standard.dump();
521     break;
522   case UserDefinedConversion:
523     OS << "User-defined conversion: ";
524     UserDefined.dump();
525     break;
526   case EllipsisConversion:
527     OS << "Ellipsis conversion";
528     break;
529   case AmbiguousConversion:
530     OS << "Ambiguous conversion";
531     break;
532   case BadConversion:
533     OS << "Bad conversion";
534     break;
535   }
536
537   OS << "\n";
538 }
539
540 void AmbiguousConversionSequence::construct() {
541   new (&conversions()) ConversionSet();
542 }
543
544 void AmbiguousConversionSequence::destruct() {
545   conversions().~ConversionSet();
546 }
547
548 void
549 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
550   FromTypePtr = O.FromTypePtr;
551   ToTypePtr = O.ToTypePtr;
552   new (&conversions()) ConversionSet(O.conversions());
553 }
554
555 namespace {
556   // Structure used by DeductionFailureInfo to store
557   // template argument information.
558   struct DFIArguments {
559     TemplateArgument FirstArg;
560     TemplateArgument SecondArg;
561   };
562   // Structure used by DeductionFailureInfo to store
563   // template parameter and template argument information.
564   struct DFIParamWithArguments : DFIArguments {
565     TemplateParameter Param;
566   };
567 }
568
569 /// \brief Convert from Sema's representation of template deduction information
570 /// to the form used in overload-candidate information.
571 DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
572                                               Sema::TemplateDeductionResult TDK,
573                                               TemplateDeductionInfo &Info) {
574   DeductionFailureInfo Result;
575   Result.Result = static_cast<unsigned>(TDK);
576   Result.HasDiagnostic = false;
577   Result.Data = nullptr;
578   switch (TDK) {
579   case Sema::TDK_Success:
580   case Sema::TDK_Invalid:
581   case Sema::TDK_InstantiationDepth:
582   case Sema::TDK_TooManyArguments:
583   case Sema::TDK_TooFewArguments:
584     break;
585
586   case Sema::TDK_Incomplete:
587   case Sema::TDK_InvalidExplicitArguments:
588     Result.Data = Info.Param.getOpaqueValue();
589     break;
590
591   case Sema::TDK_NonDeducedMismatch: {
592     // FIXME: Should allocate from normal heap so that we can free this later.
593     DFIArguments *Saved = new (Context) DFIArguments;
594     Saved->FirstArg = Info.FirstArg;
595     Saved->SecondArg = Info.SecondArg;
596     Result.Data = Saved;
597     break;
598   }
599
600   case Sema::TDK_Inconsistent:
601   case Sema::TDK_Underqualified: {
602     // FIXME: Should allocate from normal heap so that we can free this later.
603     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
604     Saved->Param = Info.Param;
605     Saved->FirstArg = Info.FirstArg;
606     Saved->SecondArg = Info.SecondArg;
607     Result.Data = Saved;
608     break;
609   }
610
611   case Sema::TDK_SubstitutionFailure:
612     Result.Data = Info.take();
613     if (Info.hasSFINAEDiagnostic()) {
614       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
615           SourceLocation(), PartialDiagnostic::NullDiagnostic());
616       Info.takeSFINAEDiagnostic(*Diag);
617       Result.HasDiagnostic = true;
618     }
619     break;
620
621   case Sema::TDK_FailedOverloadResolution:
622     Result.Data = Info.Expression;
623     break;
624
625   case Sema::TDK_MiscellaneousDeductionFailure:
626     break;
627   }
628
629   return Result;
630 }
631
632 void DeductionFailureInfo::Destroy() {
633   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
634   case Sema::TDK_Success:
635   case Sema::TDK_Invalid:
636   case Sema::TDK_InstantiationDepth:
637   case Sema::TDK_Incomplete:
638   case Sema::TDK_TooManyArguments:
639   case Sema::TDK_TooFewArguments:
640   case Sema::TDK_InvalidExplicitArguments:
641   case Sema::TDK_FailedOverloadResolution:
642     break;
643
644   case Sema::TDK_Inconsistent:
645   case Sema::TDK_Underqualified:
646   case Sema::TDK_NonDeducedMismatch:
647     // FIXME: Destroy the data?
648     Data = nullptr;
649     break;
650
651   case Sema::TDK_SubstitutionFailure:
652     // FIXME: Destroy the template argument list?
653     Data = nullptr;
654     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
655       Diag->~PartialDiagnosticAt();
656       HasDiagnostic = false;
657     }
658     break;
659
660   // Unhandled
661   case Sema::TDK_MiscellaneousDeductionFailure:
662     break;
663   }
664 }
665
666 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
667   if (HasDiagnostic)
668     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
669   return nullptr;
670 }
671
672 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
673   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
674   case Sema::TDK_Success:
675   case Sema::TDK_Invalid:
676   case Sema::TDK_InstantiationDepth:
677   case Sema::TDK_TooManyArguments:
678   case Sema::TDK_TooFewArguments:
679   case Sema::TDK_SubstitutionFailure:
680   case Sema::TDK_NonDeducedMismatch:
681   case Sema::TDK_FailedOverloadResolution:
682     return TemplateParameter();
683
684   case Sema::TDK_Incomplete:
685   case Sema::TDK_InvalidExplicitArguments:
686     return TemplateParameter::getFromOpaqueValue(Data);
687
688   case Sema::TDK_Inconsistent:
689   case Sema::TDK_Underqualified:
690     return static_cast<DFIParamWithArguments*>(Data)->Param;
691
692   // Unhandled
693   case Sema::TDK_MiscellaneousDeductionFailure:
694     break;
695   }
696
697   return TemplateParameter();
698 }
699
700 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
701   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702   case Sema::TDK_Success:
703   case Sema::TDK_Invalid:
704   case Sema::TDK_InstantiationDepth:
705   case Sema::TDK_TooManyArguments:
706   case Sema::TDK_TooFewArguments:
707   case Sema::TDK_Incomplete:
708   case Sema::TDK_InvalidExplicitArguments:
709   case Sema::TDK_Inconsistent:
710   case Sema::TDK_Underqualified:
711   case Sema::TDK_NonDeducedMismatch:
712   case Sema::TDK_FailedOverloadResolution:
713     return nullptr;
714
715   case Sema::TDK_SubstitutionFailure:
716     return static_cast<TemplateArgumentList*>(Data);
717
718   // Unhandled
719   case Sema::TDK_MiscellaneousDeductionFailure:
720     break;
721   }
722
723   return nullptr;
724 }
725
726 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
727   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
728   case Sema::TDK_Success:
729   case Sema::TDK_Invalid:
730   case Sema::TDK_InstantiationDepth:
731   case Sema::TDK_Incomplete:
732   case Sema::TDK_TooManyArguments:
733   case Sema::TDK_TooFewArguments:
734   case Sema::TDK_InvalidExplicitArguments:
735   case Sema::TDK_SubstitutionFailure:
736   case Sema::TDK_FailedOverloadResolution:
737     return nullptr;
738
739   case Sema::TDK_Inconsistent:
740   case Sema::TDK_Underqualified:
741   case Sema::TDK_NonDeducedMismatch:
742     return &static_cast<DFIArguments*>(Data)->FirstArg;
743
744   // Unhandled
745   case Sema::TDK_MiscellaneousDeductionFailure:
746     break;
747   }
748
749   return nullptr;
750 }
751
752 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
753   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
754   case Sema::TDK_Success:
755   case Sema::TDK_Invalid:
756   case Sema::TDK_InstantiationDepth:
757   case Sema::TDK_Incomplete:
758   case Sema::TDK_TooManyArguments:
759   case Sema::TDK_TooFewArguments:
760   case Sema::TDK_InvalidExplicitArguments:
761   case Sema::TDK_SubstitutionFailure:
762   case Sema::TDK_FailedOverloadResolution:
763     return nullptr;
764
765   case Sema::TDK_Inconsistent:
766   case Sema::TDK_Underqualified:
767   case Sema::TDK_NonDeducedMismatch:
768     return &static_cast<DFIArguments*>(Data)->SecondArg;
769
770   // Unhandled
771   case Sema::TDK_MiscellaneousDeductionFailure:
772     break;
773   }
774
775   return nullptr;
776 }
777
778 Expr *DeductionFailureInfo::getExpr() {
779   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
780         Sema::TDK_FailedOverloadResolution)
781     return static_cast<Expr*>(Data);
782
783   return nullptr;
784 }
785
786 void OverloadCandidateSet::destroyCandidates() {
787   for (iterator i = begin(), e = end(); i != e; ++i) {
788     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
789       i->Conversions[ii].~ImplicitConversionSequence();
790     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
791       i->DeductionFailure.Destroy();
792   }
793 }
794
795 void OverloadCandidateSet::clear() {
796   destroyCandidates();
797   NumInlineSequences = 0;
798   Candidates.clear();
799   Functions.clear();
800 }
801
802 namespace {
803   class UnbridgedCastsSet {
804     struct Entry {
805       Expr **Addr;
806       Expr *Saved;
807     };
808     SmallVector<Entry, 2> Entries;
809     
810   public:
811     void save(Sema &S, Expr *&E) {
812       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
813       Entry entry = { &E, E };
814       Entries.push_back(entry);
815       E = S.stripARCUnbridgedCast(E);
816     }
817
818     void restore() {
819       for (SmallVectorImpl<Entry>::iterator
820              i = Entries.begin(), e = Entries.end(); i != e; ++i) 
821         *i->Addr = i->Saved;
822     }
823   };
824 }
825
826 /// checkPlaceholderForOverload - Do any interesting placeholder-like
827 /// preprocessing on the given expression.
828 ///
829 /// \param unbridgedCasts a collection to which to add unbridged casts;
830 ///   without this, they will be immediately diagnosed as errors
831 ///
832 /// Return true on unrecoverable error.
833 static bool
834 checkPlaceholderForOverload(Sema &S, Expr *&E,
835                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
836   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
837     // We can't handle overloaded expressions here because overload
838     // resolution might reasonably tweak them.
839     if (placeholder->getKind() == BuiltinType::Overload) return false;
840
841     // If the context potentially accepts unbridged ARC casts, strip
842     // the unbridged cast and add it to the collection for later restoration.
843     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
844         unbridgedCasts) {
845       unbridgedCasts->save(S, E);
846       return false;
847     }
848
849     // Go ahead and check everything else.
850     ExprResult result = S.CheckPlaceholderExpr(E);
851     if (result.isInvalid())
852       return true;
853
854     E = result.get();
855     return false;
856   }
857
858   // Nothing to do.
859   return false;
860 }
861
862 /// checkArgPlaceholdersForOverload - Check a set of call operands for
863 /// placeholders.
864 static bool checkArgPlaceholdersForOverload(Sema &S,
865                                             MultiExprArg Args,
866                                             UnbridgedCastsSet &unbridged) {
867   for (unsigned i = 0, e = Args.size(); i != e; ++i)
868     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
869       return true;
870
871   return false;
872 }
873
874 // IsOverload - Determine whether the given New declaration is an
875 // overload of the declarations in Old. This routine returns false if
876 // New and Old cannot be overloaded, e.g., if New has the same
877 // signature as some function in Old (C++ 1.3.10) or if the Old
878 // declarations aren't functions (or function templates) at all. When
879 // it does return false, MatchedDecl will point to the decl that New
880 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
881 // top of the underlying declaration.
882 //
883 // Example: Given the following input:
884 //
885 //   void f(int, float); // #1
886 //   void f(int, int); // #2
887 //   int f(int, int); // #3
888 //
889 // When we process #1, there is no previous declaration of "f",
890 // so IsOverload will not be used.
891 //
892 // When we process #2, Old contains only the FunctionDecl for #1.  By
893 // comparing the parameter types, we see that #1 and #2 are overloaded
894 // (since they have different signatures), so this routine returns
895 // false; MatchedDecl is unchanged.
896 //
897 // When we process #3, Old is an overload set containing #1 and #2. We
898 // compare the signatures of #3 to #1 (they're overloaded, so we do
899 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
900 // identical (return types of functions are not part of the
901 // signature), IsOverload returns false and MatchedDecl will be set to
902 // point to the FunctionDecl for #2.
903 //
904 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
905 // into a class by a using declaration.  The rules for whether to hide
906 // shadow declarations ignore some properties which otherwise figure
907 // into a function template's signature.
908 Sema::OverloadKind
909 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
910                     NamedDecl *&Match, bool NewIsUsingDecl) {
911   for (LookupResult::iterator I = Old.begin(), E = Old.end();
912          I != E; ++I) {
913     NamedDecl *OldD = *I;
914
915     bool OldIsUsingDecl = false;
916     if (isa<UsingShadowDecl>(OldD)) {
917       OldIsUsingDecl = true;
918
919       // We can always introduce two using declarations into the same
920       // context, even if they have identical signatures.
921       if (NewIsUsingDecl) continue;
922
923       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
924     }
925
926     // If either declaration was introduced by a using declaration,
927     // we'll need to use slightly different rules for matching.
928     // Essentially, these rules are the normal rules, except that
929     // function templates hide function templates with different
930     // return types or template parameter lists.
931     bool UseMemberUsingDeclRules =
932       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
933       !New->getFriendObjectKind();
934
935     if (FunctionDecl *OldF = OldD->getAsFunction()) {
936       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
937         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
938           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
939           continue;
940         }
941
942         if (!isa<FunctionTemplateDecl>(OldD) &&
943             !shouldLinkPossiblyHiddenDecl(*I, New))
944           continue;
945
946         Match = *I;
947         return Ovl_Match;
948       }
949     } else if (isa<UsingDecl>(OldD)) {
950       // We can overload with these, which can show up when doing
951       // redeclaration checks for UsingDecls.
952       assert(Old.getLookupKind() == LookupUsingDeclName);
953     } else if (isa<TagDecl>(OldD)) {
954       // We can always overload with tags by hiding them.
955     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
956       // Optimistically assume that an unresolved using decl will
957       // overload; if it doesn't, we'll have to diagnose during
958       // template instantiation.
959     } else {
960       // (C++ 13p1):
961       //   Only function declarations can be overloaded; object and type
962       //   declarations cannot be overloaded.
963       Match = *I;
964       return Ovl_NonFunction;
965     }
966   }
967
968   return Ovl_Overload;
969 }
970
971 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
972                       bool UseUsingDeclRules) {
973   // C++ [basic.start.main]p2: This function shall not be overloaded.
974   if (New->isMain())
975     return false;
976
977   // MSVCRT user defined entry points cannot be overloaded.
978   if (New->isMSVCRTEntryPoint())
979     return false;
980
981   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
982   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
983
984   // C++ [temp.fct]p2:
985   //   A function template can be overloaded with other function templates
986   //   and with normal (non-template) functions.
987   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
988     return true;
989
990   // Is the function New an overload of the function Old?
991   QualType OldQType = Context.getCanonicalType(Old->getType());
992   QualType NewQType = Context.getCanonicalType(New->getType());
993
994   // Compare the signatures (C++ 1.3.10) of the two functions to
995   // determine whether they are overloads. If we find any mismatch
996   // in the signature, they are overloads.
997
998   // If either of these functions is a K&R-style function (no
999   // prototype), then we consider them to have matching signatures.
1000   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1001       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1002     return false;
1003
1004   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1005   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1006
1007   // The signature of a function includes the types of its
1008   // parameters (C++ 1.3.10), which includes the presence or absence
1009   // of the ellipsis; see C++ DR 357).
1010   if (OldQType != NewQType &&
1011       (OldType->getNumParams() != NewType->getNumParams() ||
1012        OldType->isVariadic() != NewType->isVariadic() ||
1013        !FunctionParamTypesAreEqual(OldType, NewType)))
1014     return true;
1015
1016   // C++ [temp.over.link]p4:
1017   //   The signature of a function template consists of its function
1018   //   signature, its return type and its template parameter list. The names
1019   //   of the template parameters are significant only for establishing the
1020   //   relationship between the template parameters and the rest of the
1021   //   signature.
1022   //
1023   // We check the return type and template parameter lists for function
1024   // templates first; the remaining checks follow.
1025   //
1026   // However, we don't consider either of these when deciding whether
1027   // a member introduced by a shadow declaration is hidden.
1028   if (!UseUsingDeclRules && NewTemplate &&
1029       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1030                                        OldTemplate->getTemplateParameters(),
1031                                        false, TPL_TemplateMatch) ||
1032        OldType->getReturnType() != NewType->getReturnType()))
1033     return true;
1034
1035   // If the function is a class member, its signature includes the
1036   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1037   //
1038   // As part of this, also check whether one of the member functions
1039   // is static, in which case they are not overloads (C++
1040   // 13.1p2). While not part of the definition of the signature,
1041   // this check is important to determine whether these functions
1042   // can be overloaded.
1043   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1044   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1045   if (OldMethod && NewMethod &&
1046       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1047     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1048       if (!UseUsingDeclRules &&
1049           (OldMethod->getRefQualifier() == RQ_None ||
1050            NewMethod->getRefQualifier() == RQ_None)) {
1051         // C++0x [over.load]p2:
1052         //   - Member function declarations with the same name and the same
1053         //     parameter-type-list as well as member function template
1054         //     declarations with the same name, the same parameter-type-list, and
1055         //     the same template parameter lists cannot be overloaded if any of
1056         //     them, but not all, have a ref-qualifier (8.3.5).
1057         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1058           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1059         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1060       }
1061       return true;
1062     }
1063
1064     // We may not have applied the implicit const for a constexpr member
1065     // function yet (because we haven't yet resolved whether this is a static
1066     // or non-static member function). Add it now, on the assumption that this
1067     // is a redeclaration of OldMethod.
1068     unsigned OldQuals = OldMethod->getTypeQualifiers();
1069     unsigned NewQuals = NewMethod->getTypeQualifiers();
1070     if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
1071         !isa<CXXConstructorDecl>(NewMethod))
1072       NewQuals |= Qualifiers::Const;
1073
1074     // We do not allow overloading based off of '__restrict'.
1075     OldQuals &= ~Qualifiers::Restrict;
1076     NewQuals &= ~Qualifiers::Restrict;
1077     if (OldQuals != NewQuals)
1078       return true;
1079   }
1080
1081   // enable_if attributes are an order-sensitive part of the signature.
1082   for (specific_attr_iterator<EnableIfAttr>
1083          NewI = New->specific_attr_begin<EnableIfAttr>(),
1084          NewE = New->specific_attr_end<EnableIfAttr>(),
1085          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1086          OldE = Old->specific_attr_end<EnableIfAttr>();
1087        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1088     if (NewI == NewE || OldI == OldE)
1089       return true;
1090     llvm::FoldingSetNodeID NewID, OldID;
1091     NewI->getCond()->Profile(NewID, Context, true);
1092     OldI->getCond()->Profile(OldID, Context, true);
1093     if (NewID != OldID)
1094       return true;
1095   }
1096
1097   // The signatures match; this is not an overload.
1098   return false;
1099 }
1100
1101 /// \brief Checks availability of the function depending on the current
1102 /// function context. Inside an unavailable function, unavailability is ignored.
1103 ///
1104 /// \returns true if \arg FD is unavailable and current context is inside
1105 /// an available function, false otherwise.
1106 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1107   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1108 }
1109
1110 /// \brief Tries a user-defined conversion from From to ToType.
1111 ///
1112 /// Produces an implicit conversion sequence for when a standard conversion
1113 /// is not an option. See TryImplicitConversion for more information.
1114 static ImplicitConversionSequence
1115 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1116                          bool SuppressUserConversions,
1117                          bool AllowExplicit,
1118                          bool InOverloadResolution,
1119                          bool CStyle,
1120                          bool AllowObjCWritebackConversion,
1121                          bool AllowObjCConversionOnExplicit) {
1122   ImplicitConversionSequence ICS;
1123
1124   if (SuppressUserConversions) {
1125     // We're not in the case above, so there is no conversion that
1126     // we can perform.
1127     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1128     return ICS;
1129   }
1130
1131   // Attempt user-defined conversion.
1132   OverloadCandidateSet Conversions(From->getExprLoc(),
1133                                    OverloadCandidateSet::CSK_Normal);
1134   OverloadingResult UserDefResult
1135     = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1136                               AllowExplicit, AllowObjCConversionOnExplicit);
1137
1138   if (UserDefResult == OR_Success) {
1139     ICS.setUserDefined();
1140     ICS.UserDefined.Before.setAsIdentityConversion();
1141     // C++ [over.ics.user]p4:
1142     //   A conversion of an expression of class type to the same class
1143     //   type is given Exact Match rank, and a conversion of an
1144     //   expression of class type to a base class of that type is
1145     //   given Conversion rank, in spite of the fact that a copy
1146     //   constructor (i.e., a user-defined conversion function) is
1147     //   called for those cases.
1148     if (CXXConstructorDecl *Constructor
1149           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1150       QualType FromCanon
1151         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1152       QualType ToCanon
1153         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1154       if (Constructor->isCopyConstructor() &&
1155           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1156         // Turn this into a "standard" conversion sequence, so that it
1157         // gets ranked with standard conversion sequences.
1158         ICS.setStandard();
1159         ICS.Standard.setAsIdentityConversion();
1160         ICS.Standard.setFromType(From->getType());
1161         ICS.Standard.setAllToTypes(ToType);
1162         ICS.Standard.CopyConstructor = Constructor;
1163         if (ToCanon != FromCanon)
1164           ICS.Standard.Second = ICK_Derived_To_Base;
1165       }
1166     }
1167   } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1168     ICS.setAmbiguous();
1169     ICS.Ambiguous.setFromType(From->getType());
1170     ICS.Ambiguous.setToType(ToType);
1171     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1172          Cand != Conversions.end(); ++Cand)
1173       if (Cand->Viable)
1174         ICS.Ambiguous.addConversion(Cand->Function);
1175   } else {
1176     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1177   }
1178
1179   return ICS;
1180 }
1181
1182 /// TryImplicitConversion - Attempt to perform an implicit conversion
1183 /// from the given expression (Expr) to the given type (ToType). This
1184 /// function returns an implicit conversion sequence that can be used
1185 /// to perform the initialization. Given
1186 ///
1187 ///   void f(float f);
1188 ///   void g(int i) { f(i); }
1189 ///
1190 /// this routine would produce an implicit conversion sequence to
1191 /// describe the initialization of f from i, which will be a standard
1192 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1193 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1194 //
1195 /// Note that this routine only determines how the conversion can be
1196 /// performed; it does not actually perform the conversion. As such,
1197 /// it will not produce any diagnostics if no conversion is available,
1198 /// but will instead return an implicit conversion sequence of kind
1199 /// "BadConversion".
1200 ///
1201 /// If @p SuppressUserConversions, then user-defined conversions are
1202 /// not permitted.
1203 /// If @p AllowExplicit, then explicit user-defined conversions are
1204 /// permitted.
1205 ///
1206 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1207 /// writeback conversion, which allows __autoreleasing id* parameters to
1208 /// be initialized with __strong id* or __weak id* arguments.
1209 static ImplicitConversionSequence
1210 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1211                       bool SuppressUserConversions,
1212                       bool AllowExplicit,
1213                       bool InOverloadResolution,
1214                       bool CStyle,
1215                       bool AllowObjCWritebackConversion,
1216                       bool AllowObjCConversionOnExplicit) {
1217   ImplicitConversionSequence ICS;
1218   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1219                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1220     ICS.setStandard();
1221     return ICS;
1222   }
1223
1224   if (!S.getLangOpts().CPlusPlus) {
1225     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1226     return ICS;
1227   }
1228
1229   // C++ [over.ics.user]p4:
1230   //   A conversion of an expression of class type to the same class
1231   //   type is given Exact Match rank, and a conversion of an
1232   //   expression of class type to a base class of that type is
1233   //   given Conversion rank, in spite of the fact that a copy/move
1234   //   constructor (i.e., a user-defined conversion function) is
1235   //   called for those cases.
1236   QualType FromType = From->getType();
1237   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1238       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1239        S.IsDerivedFrom(FromType, ToType))) {
1240     ICS.setStandard();
1241     ICS.Standard.setAsIdentityConversion();
1242     ICS.Standard.setFromType(FromType);
1243     ICS.Standard.setAllToTypes(ToType);
1244
1245     // We don't actually check at this point whether there is a valid
1246     // copy/move constructor, since overloading just assumes that it
1247     // exists. When we actually perform initialization, we'll find the
1248     // appropriate constructor to copy the returned object, if needed.
1249     ICS.Standard.CopyConstructor = nullptr;
1250
1251     // Determine whether this is considered a derived-to-base conversion.
1252     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1253       ICS.Standard.Second = ICK_Derived_To_Base;
1254
1255     return ICS;
1256   }
1257
1258   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1259                                   AllowExplicit, InOverloadResolution, CStyle,
1260                                   AllowObjCWritebackConversion,
1261                                   AllowObjCConversionOnExplicit);
1262 }
1263
1264 ImplicitConversionSequence
1265 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1266                             bool SuppressUserConversions,
1267                             bool AllowExplicit,
1268                             bool InOverloadResolution,
1269                             bool CStyle,
1270                             bool AllowObjCWritebackConversion) {
1271   return clang::TryImplicitConversion(*this, From, ToType, 
1272                                       SuppressUserConversions, AllowExplicit,
1273                                       InOverloadResolution, CStyle, 
1274                                       AllowObjCWritebackConversion,
1275                                       /*AllowObjCConversionOnExplicit=*/false);
1276 }
1277
1278 /// PerformImplicitConversion - Perform an implicit conversion of the
1279 /// expression From to the type ToType. Returns the
1280 /// converted expression. Flavor is the kind of conversion we're
1281 /// performing, used in the error message. If @p AllowExplicit,
1282 /// explicit user-defined conversions are permitted.
1283 ExprResult
1284 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1285                                 AssignmentAction Action, bool AllowExplicit) {
1286   ImplicitConversionSequence ICS;
1287   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1288 }
1289
1290 ExprResult
1291 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1292                                 AssignmentAction Action, bool AllowExplicit,
1293                                 ImplicitConversionSequence& ICS) {
1294   if (checkPlaceholderForOverload(*this, From))
1295     return ExprError();
1296
1297   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1298   bool AllowObjCWritebackConversion
1299     = getLangOpts().ObjCAutoRefCount && 
1300       (Action == AA_Passing || Action == AA_Sending);
1301   if (getLangOpts().ObjC1)
1302     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1303                                       ToType, From->getType(), From);
1304   ICS = clang::TryImplicitConversion(*this, From, ToType,
1305                                      /*SuppressUserConversions=*/false,
1306                                      AllowExplicit,
1307                                      /*InOverloadResolution=*/false,
1308                                      /*CStyle=*/false,
1309                                      AllowObjCWritebackConversion,
1310                                      /*AllowObjCConversionOnExplicit=*/false);
1311   return PerformImplicitConversion(From, ToType, ICS, Action);
1312 }
1313
1314 /// \brief Determine whether the conversion from FromType to ToType is a valid
1315 /// conversion that strips "noreturn" off the nested function type.
1316 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1317                                 QualType &ResultTy) {
1318   if (Context.hasSameUnqualifiedType(FromType, ToType))
1319     return false;
1320
1321   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1322   // where F adds one of the following at most once:
1323   //   - a pointer
1324   //   - a member pointer
1325   //   - a block pointer
1326   CanQualType CanTo = Context.getCanonicalType(ToType);
1327   CanQualType CanFrom = Context.getCanonicalType(FromType);
1328   Type::TypeClass TyClass = CanTo->getTypeClass();
1329   if (TyClass != CanFrom->getTypeClass()) return false;
1330   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1331     if (TyClass == Type::Pointer) {
1332       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1333       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1334     } else if (TyClass == Type::BlockPointer) {
1335       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1336       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1337     } else if (TyClass == Type::MemberPointer) {
1338       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1339       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1340     } else {
1341       return false;
1342     }
1343
1344     TyClass = CanTo->getTypeClass();
1345     if (TyClass != CanFrom->getTypeClass()) return false;
1346     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1347       return false;
1348   }
1349
1350   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1351   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1352   if (!EInfo.getNoReturn()) return false;
1353
1354   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1355   assert(QualType(FromFn, 0).isCanonical());
1356   if (QualType(FromFn, 0) != CanTo) return false;
1357
1358   ResultTy = ToType;
1359   return true;
1360 }
1361
1362 /// \brief Determine whether the conversion from FromType to ToType is a valid
1363 /// vector conversion.
1364 ///
1365 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1366 /// conversion.
1367 static bool IsVectorConversion(Sema &S, QualType FromType,
1368                                QualType ToType, ImplicitConversionKind &ICK) {
1369   // We need at least one of these types to be a vector type to have a vector
1370   // conversion.
1371   if (!ToType->isVectorType() && !FromType->isVectorType())
1372     return false;
1373
1374   // Identical types require no conversions.
1375   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1376     return false;
1377
1378   // There are no conversions between extended vector types, only identity.
1379   if (ToType->isExtVectorType()) {
1380     // There are no conversions between extended vector types other than the
1381     // identity conversion.
1382     if (FromType->isExtVectorType())
1383       return false;
1384
1385     // Vector splat from any arithmetic type to a vector.
1386     if (FromType->isArithmeticType()) {
1387       ICK = ICK_Vector_Splat;
1388       return true;
1389     }
1390   }
1391
1392   // We can perform the conversion between vector types in the following cases:
1393   // 1)vector types are equivalent AltiVec and GCC vector types
1394   // 2)lax vector conversions are permitted and the vector types are of the
1395   //   same size
1396   if (ToType->isVectorType() && FromType->isVectorType()) {
1397     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1398         S.isLaxVectorConversion(FromType, ToType)) {
1399       ICK = ICK_Vector_Conversion;
1400       return true;
1401     }
1402   }
1403
1404   return false;
1405 }
1406
1407 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1408                                 bool InOverloadResolution,
1409                                 StandardConversionSequence &SCS,
1410                                 bool CStyle);
1411   
1412 /// IsStandardConversion - Determines whether there is a standard
1413 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1414 /// expression From to the type ToType. Standard conversion sequences
1415 /// only consider non-class types; for conversions that involve class
1416 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1417 /// contain the standard conversion sequence required to perform this
1418 /// conversion and this routine will return true. Otherwise, this
1419 /// routine will return false and the value of SCS is unspecified.
1420 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1421                                  bool InOverloadResolution,
1422                                  StandardConversionSequence &SCS,
1423                                  bool CStyle,
1424                                  bool AllowObjCWritebackConversion) {
1425   QualType FromType = From->getType();
1426
1427   // Standard conversions (C++ [conv])
1428   SCS.setAsIdentityConversion();
1429   SCS.IncompatibleObjC = false;
1430   SCS.setFromType(FromType);
1431   SCS.CopyConstructor = nullptr;
1432
1433   // There are no standard conversions for class types in C++, so
1434   // abort early. When overloading in C, however, we do permit
1435   if (FromType->isRecordType() || ToType->isRecordType()) {
1436     if (S.getLangOpts().CPlusPlus)
1437       return false;
1438
1439     // When we're overloading in C, we allow, as standard conversions,
1440   }
1441
1442   // The first conversion can be an lvalue-to-rvalue conversion,
1443   // array-to-pointer conversion, or function-to-pointer conversion
1444   // (C++ 4p1).
1445
1446   if (FromType == S.Context.OverloadTy) {
1447     DeclAccessPair AccessPair;
1448     if (FunctionDecl *Fn
1449           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1450                                                  AccessPair)) {
1451       // We were able to resolve the address of the overloaded function,
1452       // so we can convert to the type of that function.
1453       FromType = Fn->getType();
1454
1455       // we can sometimes resolve &foo<int> regardless of ToType, so check
1456       // if the type matches (identity) or we are converting to bool
1457       if (!S.Context.hasSameUnqualifiedType(
1458                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1459         QualType resultTy;
1460         // if the function type matches except for [[noreturn]], it's ok
1461         if (!S.IsNoReturnConversion(FromType,
1462               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1463           // otherwise, only a boolean conversion is standard   
1464           if (!ToType->isBooleanType()) 
1465             return false; 
1466       }
1467
1468       // Check if the "from" expression is taking the address of an overloaded
1469       // function and recompute the FromType accordingly. Take advantage of the
1470       // fact that non-static member functions *must* have such an address-of
1471       // expression. 
1472       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1473       if (Method && !Method->isStatic()) {
1474         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1475                "Non-unary operator on non-static member address");
1476         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1477                == UO_AddrOf &&
1478                "Non-address-of operator on non-static member address");
1479         const Type *ClassType
1480           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1481         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1482       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1483         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1484                UO_AddrOf &&
1485                "Non-address-of operator for overloaded function expression");
1486         FromType = S.Context.getPointerType(FromType);
1487       }
1488
1489       // Check that we've computed the proper type after overload resolution.
1490       assert(S.Context.hasSameType(
1491         FromType,
1492         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1493     } else {
1494       return false;
1495     }
1496   }
1497   // Lvalue-to-rvalue conversion (C++11 4.1):
1498   //   A glvalue (3.10) of a non-function, non-array type T can
1499   //   be converted to a prvalue.
1500   bool argIsLValue = From->isGLValue();
1501   if (argIsLValue &&
1502       !FromType->isFunctionType() && !FromType->isArrayType() &&
1503       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1504     SCS.First = ICK_Lvalue_To_Rvalue;
1505
1506     // C11 6.3.2.1p2:
1507     //   ... if the lvalue has atomic type, the value has the non-atomic version 
1508     //   of the type of the lvalue ...
1509     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1510       FromType = Atomic->getValueType();
1511
1512     // If T is a non-class type, the type of the rvalue is the
1513     // cv-unqualified version of T. Otherwise, the type of the rvalue
1514     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1515     // just strip the qualifiers because they don't matter.
1516     FromType = FromType.getUnqualifiedType();
1517   } else if (FromType->isArrayType()) {
1518     // Array-to-pointer conversion (C++ 4.2)
1519     SCS.First = ICK_Array_To_Pointer;
1520
1521     // An lvalue or rvalue of type "array of N T" or "array of unknown
1522     // bound of T" can be converted to an rvalue of type "pointer to
1523     // T" (C++ 4.2p1).
1524     FromType = S.Context.getArrayDecayedType(FromType);
1525
1526     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1527       // This conversion is deprecated in C++03 (D.4)
1528       SCS.DeprecatedStringLiteralToCharPtr = true;
1529
1530       // For the purpose of ranking in overload resolution
1531       // (13.3.3.1.1), this conversion is considered an
1532       // array-to-pointer conversion followed by a qualification
1533       // conversion (4.4). (C++ 4.2p2)
1534       SCS.Second = ICK_Identity;
1535       SCS.Third = ICK_Qualification;
1536       SCS.QualificationIncludesObjCLifetime = false;
1537       SCS.setAllToTypes(FromType);
1538       return true;
1539     }
1540   } else if (FromType->isFunctionType() && argIsLValue) {
1541     // Function-to-pointer conversion (C++ 4.3).
1542     SCS.First = ICK_Function_To_Pointer;
1543
1544     // An lvalue of function type T can be converted to an rvalue of
1545     // type "pointer to T." The result is a pointer to the
1546     // function. (C++ 4.3p1).
1547     FromType = S.Context.getPointerType(FromType);
1548   } else {
1549     // We don't require any conversions for the first step.
1550     SCS.First = ICK_Identity;
1551   }
1552   SCS.setToType(0, FromType);
1553
1554   // The second conversion can be an integral promotion, floating
1555   // point promotion, integral conversion, floating point conversion,
1556   // floating-integral conversion, pointer conversion,
1557   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1558   // For overloading in C, this can also be a "compatible-type"
1559   // conversion.
1560   bool IncompatibleObjC = false;
1561   ImplicitConversionKind SecondICK = ICK_Identity;
1562   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1563     // The unqualified versions of the types are the same: there's no
1564     // conversion to do.
1565     SCS.Second = ICK_Identity;
1566   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1567     // Integral promotion (C++ 4.5).
1568     SCS.Second = ICK_Integral_Promotion;
1569     FromType = ToType.getUnqualifiedType();
1570   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1571     // Floating point promotion (C++ 4.6).
1572     SCS.Second = ICK_Floating_Promotion;
1573     FromType = ToType.getUnqualifiedType();
1574   } else if (S.IsComplexPromotion(FromType, ToType)) {
1575     // Complex promotion (Clang extension)
1576     SCS.Second = ICK_Complex_Promotion;
1577     FromType = ToType.getUnqualifiedType();
1578   } else if (ToType->isBooleanType() &&
1579              (FromType->isArithmeticType() ||
1580               FromType->isAnyPointerType() ||
1581               FromType->isBlockPointerType() ||
1582               FromType->isMemberPointerType() ||
1583               FromType->isNullPtrType())) {
1584     // Boolean conversions (C++ 4.12).
1585     SCS.Second = ICK_Boolean_Conversion;
1586     FromType = S.Context.BoolTy;
1587   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1588              ToType->isIntegralType(S.Context)) {
1589     // Integral conversions (C++ 4.7).
1590     SCS.Second = ICK_Integral_Conversion;
1591     FromType = ToType.getUnqualifiedType();
1592   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1593     // Complex conversions (C99 6.3.1.6)
1594     SCS.Second = ICK_Complex_Conversion;
1595     FromType = ToType.getUnqualifiedType();
1596   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1597              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1598     // Complex-real conversions (C99 6.3.1.7)
1599     SCS.Second = ICK_Complex_Real;
1600     FromType = ToType.getUnqualifiedType();
1601   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1602     // Floating point conversions (C++ 4.8).
1603     SCS.Second = ICK_Floating_Conversion;
1604     FromType = ToType.getUnqualifiedType();
1605   } else if ((FromType->isRealFloatingType() &&
1606               ToType->isIntegralType(S.Context)) ||
1607              (FromType->isIntegralOrUnscopedEnumerationType() &&
1608               ToType->isRealFloatingType())) {
1609     // Floating-integral conversions (C++ 4.9).
1610     SCS.Second = ICK_Floating_Integral;
1611     FromType = ToType.getUnqualifiedType();
1612   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1613     SCS.Second = ICK_Block_Pointer_Conversion;
1614   } else if (AllowObjCWritebackConversion &&
1615              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1616     SCS.Second = ICK_Writeback_Conversion;
1617   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1618                                    FromType, IncompatibleObjC)) {
1619     // Pointer conversions (C++ 4.10).
1620     SCS.Second = ICK_Pointer_Conversion;
1621     SCS.IncompatibleObjC = IncompatibleObjC;
1622     FromType = FromType.getUnqualifiedType();
1623   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1624                                          InOverloadResolution, FromType)) {
1625     // Pointer to member conversions (4.11).
1626     SCS.Second = ICK_Pointer_Member;
1627   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1628     SCS.Second = SecondICK;
1629     FromType = ToType.getUnqualifiedType();
1630   } else if (!S.getLangOpts().CPlusPlus &&
1631              S.Context.typesAreCompatible(ToType, FromType)) {
1632     // Compatible conversions (Clang extension for C function overloading)
1633     SCS.Second = ICK_Compatible_Conversion;
1634     FromType = ToType.getUnqualifiedType();
1635   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1636     // Treat a conversion that strips "noreturn" as an identity conversion.
1637     SCS.Second = ICK_NoReturn_Adjustment;
1638   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1639                                              InOverloadResolution,
1640                                              SCS, CStyle)) {
1641     SCS.Second = ICK_TransparentUnionConversion;
1642     FromType = ToType;
1643   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1644                                  CStyle)) {
1645     // tryAtomicConversion has updated the standard conversion sequence
1646     // appropriately.
1647     return true;
1648   } else if (ToType->isEventT() && 
1649              From->isIntegerConstantExpr(S.getASTContext()) &&
1650              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1651     SCS.Second = ICK_Zero_Event_Conversion;
1652     FromType = ToType;
1653   } else {
1654     // No second conversion required.
1655     SCS.Second = ICK_Identity;
1656   }
1657   SCS.setToType(1, FromType);
1658
1659   QualType CanonFrom;
1660   QualType CanonTo;
1661   // The third conversion can be a qualification conversion (C++ 4p1).
1662   bool ObjCLifetimeConversion;
1663   if (S.IsQualificationConversion(FromType, ToType, CStyle, 
1664                                   ObjCLifetimeConversion)) {
1665     SCS.Third = ICK_Qualification;
1666     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1667     FromType = ToType;
1668     CanonFrom = S.Context.getCanonicalType(FromType);
1669     CanonTo = S.Context.getCanonicalType(ToType);
1670   } else {
1671     // No conversion required
1672     SCS.Third = ICK_Identity;
1673
1674     // C++ [over.best.ics]p6:
1675     //   [...] Any difference in top-level cv-qualification is
1676     //   subsumed by the initialization itself and does not constitute
1677     //   a conversion. [...]
1678     CanonFrom = S.Context.getCanonicalType(FromType);
1679     CanonTo = S.Context.getCanonicalType(ToType);
1680     if (CanonFrom.getLocalUnqualifiedType()
1681                                        == CanonTo.getLocalUnqualifiedType() &&
1682         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1683       FromType = ToType;
1684       CanonFrom = CanonTo;
1685     }
1686   }
1687   SCS.setToType(2, FromType);
1688
1689   // If we have not converted the argument type to the parameter type,
1690   // this is a bad conversion sequence.
1691   if (CanonFrom != CanonTo)
1692     return false;
1693
1694   return true;
1695 }
1696   
1697 static bool
1698 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 
1699                                      QualType &ToType,
1700                                      bool InOverloadResolution,
1701                                      StandardConversionSequence &SCS,
1702                                      bool CStyle) {
1703     
1704   const RecordType *UT = ToType->getAsUnionType();
1705   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1706     return false;
1707   // The field to initialize within the transparent union.
1708   RecordDecl *UD = UT->getDecl();
1709   // It's compatible if the expression matches any of the fields.
1710   for (const auto *it : UD->fields()) {
1711     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1712                              CStyle, /*ObjCWritebackConversion=*/false)) {
1713       ToType = it->getType();
1714       return true;
1715     }
1716   }
1717   return false;
1718 }
1719
1720 /// IsIntegralPromotion - Determines whether the conversion from the
1721 /// expression From (whose potentially-adjusted type is FromType) to
1722 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1723 /// sets PromotedType to the promoted type.
1724 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1725   const BuiltinType *To = ToType->getAs<BuiltinType>();
1726   // All integers are built-in.
1727   if (!To) {
1728     return false;
1729   }
1730
1731   // An rvalue of type char, signed char, unsigned char, short int, or
1732   // unsigned short int can be converted to an rvalue of type int if
1733   // int can represent all the values of the source type; otherwise,
1734   // the source rvalue can be converted to an rvalue of type unsigned
1735   // int (C++ 4.5p1).
1736   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1737       !FromType->isEnumeralType()) {
1738     if (// We can promote any signed, promotable integer type to an int
1739         (FromType->isSignedIntegerType() ||
1740          // We can promote any unsigned integer type whose size is
1741          // less than int to an int.
1742          (!FromType->isSignedIntegerType() &&
1743           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1744       return To->getKind() == BuiltinType::Int;
1745     }
1746
1747     return To->getKind() == BuiltinType::UInt;
1748   }
1749
1750   // C++11 [conv.prom]p3:
1751   //   A prvalue of an unscoped enumeration type whose underlying type is not
1752   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1753   //   following types that can represent all the values of the enumeration
1754   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1755   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1756   //   long long int. If none of the types in that list can represent all the
1757   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1758   //   type can be converted to an rvalue a prvalue of the extended integer type
1759   //   with lowest integer conversion rank (4.13) greater than the rank of long
1760   //   long in which all the values of the enumeration can be represented. If
1761   //   there are two such extended types, the signed one is chosen.
1762   // C++11 [conv.prom]p4:
1763   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1764   //   can be converted to a prvalue of its underlying type. Moreover, if
1765   //   integral promotion can be applied to its underlying type, a prvalue of an
1766   //   unscoped enumeration type whose underlying type is fixed can also be
1767   //   converted to a prvalue of the promoted underlying type.
1768   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1769     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1770     // provided for a scoped enumeration.
1771     if (FromEnumType->getDecl()->isScoped())
1772       return false;
1773
1774     // We can perform an integral promotion to the underlying type of the enum,
1775     // even if that's not the promoted type.
1776     if (FromEnumType->getDecl()->isFixed()) {
1777       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1778       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1779              IsIntegralPromotion(From, Underlying, ToType);
1780     }
1781
1782     // We have already pre-calculated the promotion type, so this is trivial.
1783     if (ToType->isIntegerType() &&
1784         !RequireCompleteType(From->getLocStart(), FromType, 0))
1785       return Context.hasSameUnqualifiedType(ToType,
1786                                 FromEnumType->getDecl()->getPromotionType());
1787   }
1788
1789   // C++0x [conv.prom]p2:
1790   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1791   //   to an rvalue a prvalue of the first of the following types that can
1792   //   represent all the values of its underlying type: int, unsigned int,
1793   //   long int, unsigned long int, long long int, or unsigned long long int.
1794   //   If none of the types in that list can represent all the values of its
1795   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1796   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1797   //   type.
1798   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1799       ToType->isIntegerType()) {
1800     // Determine whether the type we're converting from is signed or
1801     // unsigned.
1802     bool FromIsSigned = FromType->isSignedIntegerType();
1803     uint64_t FromSize = Context.getTypeSize(FromType);
1804
1805     // The types we'll try to promote to, in the appropriate
1806     // order. Try each of these types.
1807     QualType PromoteTypes[6] = {
1808       Context.IntTy, Context.UnsignedIntTy,
1809       Context.LongTy, Context.UnsignedLongTy ,
1810       Context.LongLongTy, Context.UnsignedLongLongTy
1811     };
1812     for (int Idx = 0; Idx < 6; ++Idx) {
1813       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1814       if (FromSize < ToSize ||
1815           (FromSize == ToSize &&
1816            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1817         // We found the type that we can promote to. If this is the
1818         // type we wanted, we have a promotion. Otherwise, no
1819         // promotion.
1820         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1821       }
1822     }
1823   }
1824
1825   // An rvalue for an integral bit-field (9.6) can be converted to an
1826   // rvalue of type int if int can represent all the values of the
1827   // bit-field; otherwise, it can be converted to unsigned int if
1828   // unsigned int can represent all the values of the bit-field. If
1829   // the bit-field is larger yet, no integral promotion applies to
1830   // it. If the bit-field has an enumerated type, it is treated as any
1831   // other value of that type for promotion purposes (C++ 4.5p3).
1832   // FIXME: We should delay checking of bit-fields until we actually perform the
1833   // conversion.
1834   using llvm::APSInt;
1835   if (From)
1836     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1837       APSInt BitWidth;
1838       if (FromType->isIntegralType(Context) &&
1839           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1840         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1841         ToSize = Context.getTypeSize(ToType);
1842
1843         // Are we promoting to an int from a bitfield that fits in an int?
1844         if (BitWidth < ToSize ||
1845             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1846           return To->getKind() == BuiltinType::Int;
1847         }
1848
1849         // Are we promoting to an unsigned int from an unsigned bitfield
1850         // that fits into an unsigned int?
1851         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1852           return To->getKind() == BuiltinType::UInt;
1853         }
1854
1855         return false;
1856       }
1857     }
1858
1859   // An rvalue of type bool can be converted to an rvalue of type int,
1860   // with false becoming zero and true becoming one (C++ 4.5p4).
1861   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1862     return true;
1863   }
1864
1865   return false;
1866 }
1867
1868 /// IsFloatingPointPromotion - Determines whether the conversion from
1869 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1870 /// returns true and sets PromotedType to the promoted type.
1871 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1872   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1873     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1874       /// An rvalue of type float can be converted to an rvalue of type
1875       /// double. (C++ 4.6p1).
1876       if (FromBuiltin->getKind() == BuiltinType::Float &&
1877           ToBuiltin->getKind() == BuiltinType::Double)
1878         return true;
1879
1880       // C99 6.3.1.5p1:
1881       //   When a float is promoted to double or long double, or a
1882       //   double is promoted to long double [...].
1883       if (!getLangOpts().CPlusPlus &&
1884           (FromBuiltin->getKind() == BuiltinType::Float ||
1885            FromBuiltin->getKind() == BuiltinType::Double) &&
1886           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1887         return true;
1888
1889       // Half can be promoted to float.
1890       if (!getLangOpts().NativeHalfType &&
1891            FromBuiltin->getKind() == BuiltinType::Half &&
1892           ToBuiltin->getKind() == BuiltinType::Float)
1893         return true;
1894     }
1895
1896   return false;
1897 }
1898
1899 /// \brief Determine if a conversion is a complex promotion.
1900 ///
1901 /// A complex promotion is defined as a complex -> complex conversion
1902 /// where the conversion between the underlying real types is a
1903 /// floating-point or integral promotion.
1904 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1905   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1906   if (!FromComplex)
1907     return false;
1908
1909   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1910   if (!ToComplex)
1911     return false;
1912
1913   return IsFloatingPointPromotion(FromComplex->getElementType(),
1914                                   ToComplex->getElementType()) ||
1915     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
1916                         ToComplex->getElementType());
1917 }
1918
1919 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1920 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1921 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1922 /// if non-empty, will be a pointer to ToType that may or may not have
1923 /// the right set of qualifiers on its pointee.
1924 ///
1925 static QualType
1926 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1927                                    QualType ToPointee, QualType ToType,
1928                                    ASTContext &Context,
1929                                    bool StripObjCLifetime = false) {
1930   assert((FromPtr->getTypeClass() == Type::Pointer ||
1931           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1932          "Invalid similarly-qualified pointer type");
1933
1934   /// Conversions to 'id' subsume cv-qualifier conversions.
1935   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 
1936     return ToType.getUnqualifiedType();
1937
1938   QualType CanonFromPointee
1939     = Context.getCanonicalType(FromPtr->getPointeeType());
1940   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1941   Qualifiers Quals = CanonFromPointee.getQualifiers();
1942
1943   if (StripObjCLifetime)
1944     Quals.removeObjCLifetime();
1945   
1946   // Exact qualifier match -> return the pointer type we're converting to.
1947   if (CanonToPointee.getLocalQualifiers() == Quals) {
1948     // ToType is exactly what we need. Return it.
1949     if (!ToType.isNull())
1950       return ToType.getUnqualifiedType();
1951
1952     // Build a pointer to ToPointee. It has the right qualifiers
1953     // already.
1954     if (isa<ObjCObjectPointerType>(ToType))
1955       return Context.getObjCObjectPointerType(ToPointee);
1956     return Context.getPointerType(ToPointee);
1957   }
1958
1959   // Just build a canonical type that has the right qualifiers.
1960   QualType QualifiedCanonToPointee
1961     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1962
1963   if (isa<ObjCObjectPointerType>(ToType))
1964     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1965   return Context.getPointerType(QualifiedCanonToPointee);
1966 }
1967
1968 static bool isNullPointerConstantForConversion(Expr *Expr,
1969                                                bool InOverloadResolution,
1970                                                ASTContext &Context) {
1971   // Handle value-dependent integral null pointer constants correctly.
1972   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1973   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1974       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1975     return !InOverloadResolution;
1976
1977   return Expr->isNullPointerConstant(Context,
1978                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1979                                         : Expr::NPC_ValueDependentIsNull);
1980 }
1981
1982 /// IsPointerConversion - Determines whether the conversion of the
1983 /// expression From, which has the (possibly adjusted) type FromType,
1984 /// can be converted to the type ToType via a pointer conversion (C++
1985 /// 4.10). If so, returns true and places the converted type (that
1986 /// might differ from ToType in its cv-qualifiers at some level) into
1987 /// ConvertedType.
1988 ///
1989 /// This routine also supports conversions to and from block pointers
1990 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1991 /// pointers to interfaces. FIXME: Once we've determined the
1992 /// appropriate overloading rules for Objective-C, we may want to
1993 /// split the Objective-C checks into a different routine; however,
1994 /// GCC seems to consider all of these conversions to be pointer
1995 /// conversions, so for now they live here. IncompatibleObjC will be
1996 /// set if the conversion is an allowed Objective-C conversion that
1997 /// should result in a warning.
1998 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1999                                bool InOverloadResolution,
2000                                QualType& ConvertedType,
2001                                bool &IncompatibleObjC) {
2002   IncompatibleObjC = false;
2003   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2004                               IncompatibleObjC))
2005     return true;
2006
2007   // Conversion from a null pointer constant to any Objective-C pointer type.
2008   if (ToType->isObjCObjectPointerType() &&
2009       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2010     ConvertedType = ToType;
2011     return true;
2012   }
2013
2014   // Blocks: Block pointers can be converted to void*.
2015   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2016       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2017     ConvertedType = ToType;
2018     return true;
2019   }
2020   // Blocks: A null pointer constant can be converted to a block
2021   // pointer type.
2022   if (ToType->isBlockPointerType() &&
2023       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2024     ConvertedType = ToType;
2025     return true;
2026   }
2027
2028   // If the left-hand-side is nullptr_t, the right side can be a null
2029   // pointer constant.
2030   if (ToType->isNullPtrType() &&
2031       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2032     ConvertedType = ToType;
2033     return true;
2034   }
2035
2036   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2037   if (!ToTypePtr)
2038     return false;
2039
2040   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2041   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2042     ConvertedType = ToType;
2043     return true;
2044   }
2045
2046   // Beyond this point, both types need to be pointers
2047   // , including objective-c pointers.
2048   QualType ToPointeeType = ToTypePtr->getPointeeType();
2049   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2050       !getLangOpts().ObjCAutoRefCount) {
2051     ConvertedType = BuildSimilarlyQualifiedPointerType(
2052                                       FromType->getAs<ObjCObjectPointerType>(),
2053                                                        ToPointeeType,
2054                                                        ToType, Context);
2055     return true;
2056   }
2057   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2058   if (!FromTypePtr)
2059     return false;
2060
2061   QualType FromPointeeType = FromTypePtr->getPointeeType();
2062
2063   // If the unqualified pointee types are the same, this can't be a
2064   // pointer conversion, so don't do all of the work below.
2065   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2066     return false;
2067
2068   // An rvalue of type "pointer to cv T," where T is an object type,
2069   // can be converted to an rvalue of type "pointer to cv void" (C++
2070   // 4.10p2).
2071   if (FromPointeeType->isIncompleteOrObjectType() &&
2072       ToPointeeType->isVoidType()) {
2073     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2074                                                        ToPointeeType,
2075                                                        ToType, Context,
2076                                                    /*StripObjCLifetime=*/true);
2077     return true;
2078   }
2079
2080   // MSVC allows implicit function to void* type conversion.
2081   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2082       ToPointeeType->isVoidType()) {
2083     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2084                                                        ToPointeeType,
2085                                                        ToType, Context);
2086     return true;
2087   }
2088
2089   // When we're overloading in C, we allow a special kind of pointer
2090   // conversion for compatible-but-not-identical pointee types.
2091   if (!getLangOpts().CPlusPlus &&
2092       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2093     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2094                                                        ToPointeeType,
2095                                                        ToType, Context);
2096     return true;
2097   }
2098
2099   // C++ [conv.ptr]p3:
2100   //
2101   //   An rvalue of type "pointer to cv D," where D is a class type,
2102   //   can be converted to an rvalue of type "pointer to cv B," where
2103   //   B is a base class (clause 10) of D. If B is an inaccessible
2104   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2105   //   necessitates this conversion is ill-formed. The result of the
2106   //   conversion is a pointer to the base class sub-object of the
2107   //   derived class object. The null pointer value is converted to
2108   //   the null pointer value of the destination type.
2109   //
2110   // Note that we do not check for ambiguity or inaccessibility
2111   // here. That is handled by CheckPointerConversion.
2112   if (getLangOpts().CPlusPlus &&
2113       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2114       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2115       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2116       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2117     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2118                                                        ToPointeeType,
2119                                                        ToType, Context);
2120     return true;
2121   }
2122
2123   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2124       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2125     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2126                                                        ToPointeeType,
2127                                                        ToType, Context);
2128     return true;
2129   }
2130   
2131   return false;
2132 }
2133  
2134 /// \brief Adopt the given qualifiers for the given type.
2135 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2136   Qualifiers TQs = T.getQualifiers();
2137   
2138   // Check whether qualifiers already match.
2139   if (TQs == Qs)
2140     return T;
2141   
2142   if (Qs.compatiblyIncludes(TQs))
2143     return Context.getQualifiedType(T, Qs);
2144   
2145   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2146 }
2147
2148 /// isObjCPointerConversion - Determines whether this is an
2149 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2150 /// with the same arguments and return values.
2151 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2152                                    QualType& ConvertedType,
2153                                    bool &IncompatibleObjC) {
2154   if (!getLangOpts().ObjC1)
2155     return false;
2156
2157   // The set of qualifiers on the type we're converting from.
2158   Qualifiers FromQualifiers = FromType.getQualifiers();
2159   
2160   // First, we handle all conversions on ObjC object pointer types.
2161   const ObjCObjectPointerType* ToObjCPtr =
2162     ToType->getAs<ObjCObjectPointerType>();
2163   const ObjCObjectPointerType *FromObjCPtr =
2164     FromType->getAs<ObjCObjectPointerType>();
2165
2166   if (ToObjCPtr && FromObjCPtr) {
2167     // If the pointee types are the same (ignoring qualifications),
2168     // then this is not a pointer conversion.
2169     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2170                                        FromObjCPtr->getPointeeType()))
2171       return false;
2172
2173     // Check for compatible 
2174     // Objective C++: We're able to convert between "id" or "Class" and a
2175     // pointer to any interface (in both directions).
2176     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2177       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2178       return true;
2179     }
2180     // Conversions with Objective-C's id<...>.
2181     if ((FromObjCPtr->isObjCQualifiedIdType() ||
2182          ToObjCPtr->isObjCQualifiedIdType()) &&
2183         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2184                                                   /*compare=*/false)) {
2185       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2186       return true;
2187     }
2188     // Objective C++: We're able to convert from a pointer to an
2189     // interface to a pointer to a different interface.
2190     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2191       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2192       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2193       if (getLangOpts().CPlusPlus && LHS && RHS &&
2194           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2195                                                 FromObjCPtr->getPointeeType()))
2196         return false;
2197       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2198                                                    ToObjCPtr->getPointeeType(),
2199                                                          ToType, Context);
2200       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2201       return true;
2202     }
2203
2204     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2205       // Okay: this is some kind of implicit downcast of Objective-C
2206       // interfaces, which is permitted. However, we're going to
2207       // complain about it.
2208       IncompatibleObjC = true;
2209       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2210                                                    ToObjCPtr->getPointeeType(),
2211                                                          ToType, Context);
2212       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2213       return true;
2214     }
2215   }
2216   // Beyond this point, both types need to be C pointers or block pointers.
2217   QualType ToPointeeType;
2218   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2219     ToPointeeType = ToCPtr->getPointeeType();
2220   else if (const BlockPointerType *ToBlockPtr =
2221             ToType->getAs<BlockPointerType>()) {
2222     // Objective C++: We're able to convert from a pointer to any object
2223     // to a block pointer type.
2224     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2225       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2226       return true;
2227     }
2228     ToPointeeType = ToBlockPtr->getPointeeType();
2229   }
2230   else if (FromType->getAs<BlockPointerType>() &&
2231            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2232     // Objective C++: We're able to convert from a block pointer type to a
2233     // pointer to any object.
2234     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2235     return true;
2236   }
2237   else
2238     return false;
2239
2240   QualType FromPointeeType;
2241   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2242     FromPointeeType = FromCPtr->getPointeeType();
2243   else if (const BlockPointerType *FromBlockPtr =
2244            FromType->getAs<BlockPointerType>())
2245     FromPointeeType = FromBlockPtr->getPointeeType();
2246   else
2247     return false;
2248
2249   // If we have pointers to pointers, recursively check whether this
2250   // is an Objective-C conversion.
2251   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2252       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2253                               IncompatibleObjC)) {
2254     // We always complain about this conversion.
2255     IncompatibleObjC = true;
2256     ConvertedType = Context.getPointerType(ConvertedType);
2257     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2258     return true;
2259   }
2260   // Allow conversion of pointee being objective-c pointer to another one;
2261   // as in I* to id.
2262   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2263       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2264       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2265                               IncompatibleObjC)) {
2266         
2267     ConvertedType = Context.getPointerType(ConvertedType);
2268     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2269     return true;
2270   }
2271
2272   // If we have pointers to functions or blocks, check whether the only
2273   // differences in the argument and result types are in Objective-C
2274   // pointer conversions. If so, we permit the conversion (but
2275   // complain about it).
2276   const FunctionProtoType *FromFunctionType
2277     = FromPointeeType->getAs<FunctionProtoType>();
2278   const FunctionProtoType *ToFunctionType
2279     = ToPointeeType->getAs<FunctionProtoType>();
2280   if (FromFunctionType && ToFunctionType) {
2281     // If the function types are exactly the same, this isn't an
2282     // Objective-C pointer conversion.
2283     if (Context.getCanonicalType(FromPointeeType)
2284           == Context.getCanonicalType(ToPointeeType))
2285       return false;
2286
2287     // Perform the quick checks that will tell us whether these
2288     // function types are obviously different.
2289     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2290         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2291         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2292       return false;
2293
2294     bool HasObjCConversion = false;
2295     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2296         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2297       // Okay, the types match exactly. Nothing to do.
2298     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2299                                        ToFunctionType->getReturnType(),
2300                                        ConvertedType, IncompatibleObjC)) {
2301       // Okay, we have an Objective-C pointer conversion.
2302       HasObjCConversion = true;
2303     } else {
2304       // Function types are too different. Abort.
2305       return false;
2306     }
2307
2308     // Check argument types.
2309     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2310          ArgIdx != NumArgs; ++ArgIdx) {
2311       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2312       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2313       if (Context.getCanonicalType(FromArgType)
2314             == Context.getCanonicalType(ToArgType)) {
2315         // Okay, the types match exactly. Nothing to do.
2316       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2317                                          ConvertedType, IncompatibleObjC)) {
2318         // Okay, we have an Objective-C pointer conversion.
2319         HasObjCConversion = true;
2320       } else {
2321         // Argument types are too different. Abort.
2322         return false;
2323       }
2324     }
2325
2326     if (HasObjCConversion) {
2327       // We had an Objective-C conversion. Allow this pointer
2328       // conversion, but complain about it.
2329       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2330       IncompatibleObjC = true;
2331       return true;
2332     }
2333   }
2334
2335   return false;
2336 }
2337
2338 /// \brief Determine whether this is an Objective-C writeback conversion,
2339 /// used for parameter passing when performing automatic reference counting.
2340 ///
2341 /// \param FromType The type we're converting form.
2342 ///
2343 /// \param ToType The type we're converting to.
2344 ///
2345 /// \param ConvertedType The type that will be produced after applying
2346 /// this conversion.
2347 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2348                                      QualType &ConvertedType) {
2349   if (!getLangOpts().ObjCAutoRefCount || 
2350       Context.hasSameUnqualifiedType(FromType, ToType))
2351     return false;
2352   
2353   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2354   QualType ToPointee;
2355   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2356     ToPointee = ToPointer->getPointeeType();
2357   else
2358     return false;
2359   
2360   Qualifiers ToQuals = ToPointee.getQualifiers();
2361   if (!ToPointee->isObjCLifetimeType() || 
2362       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2363       !ToQuals.withoutObjCLifetime().empty())
2364     return false;
2365   
2366   // Argument must be a pointer to __strong to __weak.
2367   QualType FromPointee;
2368   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2369     FromPointee = FromPointer->getPointeeType();
2370   else
2371     return false;
2372   
2373   Qualifiers FromQuals = FromPointee.getQualifiers();
2374   if (!FromPointee->isObjCLifetimeType() ||
2375       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2376        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2377     return false;
2378   
2379   // Make sure that we have compatible qualifiers.
2380   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2381   if (!ToQuals.compatiblyIncludes(FromQuals))
2382     return false;
2383   
2384   // Remove qualifiers from the pointee type we're converting from; they
2385   // aren't used in the compatibility check belong, and we'll be adding back
2386   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2387   FromPointee = FromPointee.getUnqualifiedType();
2388   
2389   // The unqualified form of the pointee types must be compatible.
2390   ToPointee = ToPointee.getUnqualifiedType();
2391   bool IncompatibleObjC;
2392   if (Context.typesAreCompatible(FromPointee, ToPointee))
2393     FromPointee = ToPointee;
2394   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2395                                     IncompatibleObjC))
2396     return false;
2397   
2398   /// \brief Construct the type we're converting to, which is a pointer to
2399   /// __autoreleasing pointee.
2400   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2401   ConvertedType = Context.getPointerType(FromPointee);
2402   return true;
2403 }
2404
2405 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2406                                     QualType& ConvertedType) {
2407   QualType ToPointeeType;
2408   if (const BlockPointerType *ToBlockPtr =
2409         ToType->getAs<BlockPointerType>())
2410     ToPointeeType = ToBlockPtr->getPointeeType();
2411   else
2412     return false;
2413   
2414   QualType FromPointeeType;
2415   if (const BlockPointerType *FromBlockPtr =
2416       FromType->getAs<BlockPointerType>())
2417     FromPointeeType = FromBlockPtr->getPointeeType();
2418   else
2419     return false;
2420   // We have pointer to blocks, check whether the only
2421   // differences in the argument and result types are in Objective-C
2422   // pointer conversions. If so, we permit the conversion.
2423   
2424   const FunctionProtoType *FromFunctionType
2425     = FromPointeeType->getAs<FunctionProtoType>();
2426   const FunctionProtoType *ToFunctionType
2427     = ToPointeeType->getAs<FunctionProtoType>();
2428   
2429   if (!FromFunctionType || !ToFunctionType)
2430     return false;
2431
2432   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2433     return true;
2434     
2435   // Perform the quick checks that will tell us whether these
2436   // function types are obviously different.
2437   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2438       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2439     return false;
2440     
2441   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2442   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2443   if (FromEInfo != ToEInfo)
2444     return false;
2445
2446   bool IncompatibleObjC = false;
2447   if (Context.hasSameType(FromFunctionType->getReturnType(),
2448                           ToFunctionType->getReturnType())) {
2449     // Okay, the types match exactly. Nothing to do.
2450   } else {
2451     QualType RHS = FromFunctionType->getReturnType();
2452     QualType LHS = ToFunctionType->getReturnType();
2453     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2454         !RHS.hasQualifiers() && LHS.hasQualifiers())
2455        LHS = LHS.getUnqualifiedType();
2456
2457      if (Context.hasSameType(RHS,LHS)) {
2458        // OK exact match.
2459      } else if (isObjCPointerConversion(RHS, LHS,
2460                                         ConvertedType, IncompatibleObjC)) {
2461      if (IncompatibleObjC)
2462        return false;
2463      // Okay, we have an Objective-C pointer conversion.
2464      }
2465      else
2466        return false;
2467    }
2468     
2469    // Check argument types.
2470    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2471         ArgIdx != NumArgs; ++ArgIdx) {
2472      IncompatibleObjC = false;
2473      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2474      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2475      if (Context.hasSameType(FromArgType, ToArgType)) {
2476        // Okay, the types match exactly. Nothing to do.
2477      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2478                                         ConvertedType, IncompatibleObjC)) {
2479        if (IncompatibleObjC)
2480          return false;
2481        // Okay, we have an Objective-C pointer conversion.
2482      } else
2483        // Argument types are too different. Abort.
2484        return false;
2485    }
2486    if (LangOpts.ObjCAutoRefCount && 
2487        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 
2488                                                     ToFunctionType))
2489      return false;
2490    
2491    ConvertedType = ToType;
2492    return true;
2493 }
2494
2495 enum {
2496   ft_default,
2497   ft_different_class,
2498   ft_parameter_arity,
2499   ft_parameter_mismatch,
2500   ft_return_type,
2501   ft_qualifer_mismatch
2502 };
2503
2504 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2505 /// function types.  Catches different number of parameter, mismatch in
2506 /// parameter types, and different return types.
2507 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2508                                       QualType FromType, QualType ToType) {
2509   // If either type is not valid, include no extra info.
2510   if (FromType.isNull() || ToType.isNull()) {
2511     PDiag << ft_default;
2512     return;
2513   }
2514
2515   // Get the function type from the pointers.
2516   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2517     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2518                             *ToMember = ToType->getAs<MemberPointerType>();
2519     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2520       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2521             << QualType(FromMember->getClass(), 0);
2522       return;
2523     }
2524     FromType = FromMember->getPointeeType();
2525     ToType = ToMember->getPointeeType();
2526   }
2527
2528   if (FromType->isPointerType())
2529     FromType = FromType->getPointeeType();
2530   if (ToType->isPointerType())
2531     ToType = ToType->getPointeeType();
2532
2533   // Remove references.
2534   FromType = FromType.getNonReferenceType();
2535   ToType = ToType.getNonReferenceType();
2536
2537   // Don't print extra info for non-specialized template functions.
2538   if (FromType->isInstantiationDependentType() &&
2539       !FromType->getAs<TemplateSpecializationType>()) {
2540     PDiag << ft_default;
2541     return;
2542   }
2543
2544   // No extra info for same types.
2545   if (Context.hasSameType(FromType, ToType)) {
2546     PDiag << ft_default;
2547     return;
2548   }
2549
2550   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2551                           *ToFunction = ToType->getAs<FunctionProtoType>();
2552
2553   // Both types need to be function types.
2554   if (!FromFunction || !ToFunction) {
2555     PDiag << ft_default;
2556     return;
2557   }
2558
2559   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2560     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2561           << FromFunction->getNumParams();
2562     return;
2563   }
2564
2565   // Handle different parameter types.
2566   unsigned ArgPos;
2567   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2568     PDiag << ft_parameter_mismatch << ArgPos + 1
2569           << ToFunction->getParamType(ArgPos)
2570           << FromFunction->getParamType(ArgPos);
2571     return;
2572   }
2573
2574   // Handle different return type.
2575   if (!Context.hasSameType(FromFunction->getReturnType(),
2576                            ToFunction->getReturnType())) {
2577     PDiag << ft_return_type << ToFunction->getReturnType()
2578           << FromFunction->getReturnType();
2579     return;
2580   }
2581
2582   unsigned FromQuals = FromFunction->getTypeQuals(),
2583            ToQuals = ToFunction->getTypeQuals();
2584   if (FromQuals != ToQuals) {
2585     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2586     return;
2587   }
2588
2589   // Unable to find a difference, so add no extra info.
2590   PDiag << ft_default;
2591 }
2592
2593 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2594 /// for equality of their argument types. Caller has already checked that
2595 /// they have same number of arguments.  If the parameters are different,
2596 /// ArgPos will have the parameter index of the first different parameter.
2597 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2598                                       const FunctionProtoType *NewType,
2599                                       unsigned *ArgPos) {
2600   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2601                                               N = NewType->param_type_begin(),
2602                                               E = OldType->param_type_end();
2603        O && (O != E); ++O, ++N) {
2604     if (!Context.hasSameType(O->getUnqualifiedType(),
2605                              N->getUnqualifiedType())) {
2606       if (ArgPos)
2607         *ArgPos = O - OldType->param_type_begin();
2608       return false;
2609     }
2610   }
2611   return true;
2612 }
2613
2614 /// CheckPointerConversion - Check the pointer conversion from the
2615 /// expression From to the type ToType. This routine checks for
2616 /// ambiguous or inaccessible derived-to-base pointer
2617 /// conversions for which IsPointerConversion has already returned
2618 /// true. It returns true and produces a diagnostic if there was an
2619 /// error, or returns false otherwise.
2620 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2621                                   CastKind &Kind,
2622                                   CXXCastPath& BasePath,
2623                                   bool IgnoreBaseAccess) {
2624   QualType FromType = From->getType();
2625   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2626
2627   Kind = CK_BitCast;
2628
2629   if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2630       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2631       Expr::NPCK_ZeroExpression) {
2632     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2633       DiagRuntimeBehavior(From->getExprLoc(), From,
2634                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2635                             << ToType << From->getSourceRange());
2636     else if (!isUnevaluatedContext())
2637       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2638         << ToType << From->getSourceRange();
2639   }
2640   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2641     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2642       QualType FromPointeeType = FromPtrType->getPointeeType(),
2643                ToPointeeType   = ToPtrType->getPointeeType();
2644
2645       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2646           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2647         // We must have a derived-to-base conversion. Check an
2648         // ambiguous or inaccessible conversion.
2649         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2650                                          From->getExprLoc(),
2651                                          From->getSourceRange(), &BasePath,
2652                                          IgnoreBaseAccess))
2653           return true;
2654
2655         // The conversion was successful.
2656         Kind = CK_DerivedToBase;
2657       }
2658     }
2659   } else if (const ObjCObjectPointerType *ToPtrType =
2660                ToType->getAs<ObjCObjectPointerType>()) {
2661     if (const ObjCObjectPointerType *FromPtrType =
2662           FromType->getAs<ObjCObjectPointerType>()) {
2663       // Objective-C++ conversions are always okay.
2664       // FIXME: We should have a different class of conversions for the
2665       // Objective-C++ implicit conversions.
2666       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2667         return false;
2668     } else if (FromType->isBlockPointerType()) {
2669       Kind = CK_BlockPointerToObjCPointerCast;
2670     } else {
2671       Kind = CK_CPointerToObjCPointerCast;
2672     }
2673   } else if (ToType->isBlockPointerType()) {
2674     if (!FromType->isBlockPointerType())
2675       Kind = CK_AnyPointerToBlockPointerCast;
2676   }
2677
2678   // We shouldn't fall into this case unless it's valid for other
2679   // reasons.
2680   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2681     Kind = CK_NullToPointer;
2682
2683   return false;
2684 }
2685
2686 /// IsMemberPointerConversion - Determines whether the conversion of the
2687 /// expression From, which has the (possibly adjusted) type FromType, can be
2688 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2689 /// If so, returns true and places the converted type (that might differ from
2690 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2691 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2692                                      QualType ToType,
2693                                      bool InOverloadResolution,
2694                                      QualType &ConvertedType) {
2695   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2696   if (!ToTypePtr)
2697     return false;
2698
2699   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2700   if (From->isNullPointerConstant(Context,
2701                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2702                                         : Expr::NPC_ValueDependentIsNull)) {
2703     ConvertedType = ToType;
2704     return true;
2705   }
2706
2707   // Otherwise, both types have to be member pointers.
2708   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2709   if (!FromTypePtr)
2710     return false;
2711
2712   // A pointer to member of B can be converted to a pointer to member of D,
2713   // where D is derived from B (C++ 4.11p2).
2714   QualType FromClass(FromTypePtr->getClass(), 0);
2715   QualType ToClass(ToTypePtr->getClass(), 0);
2716
2717   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2718       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2719       IsDerivedFrom(ToClass, FromClass)) {
2720     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2721                                                  ToClass.getTypePtr());
2722     return true;
2723   }
2724
2725   return false;
2726 }
2727
2728 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2729 /// expression From to the type ToType. This routine checks for ambiguous or
2730 /// virtual or inaccessible base-to-derived member pointer conversions
2731 /// for which IsMemberPointerConversion has already returned true. It returns
2732 /// true and produces a diagnostic if there was an error, or returns false
2733 /// otherwise.
2734 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2735                                         CastKind &Kind,
2736                                         CXXCastPath &BasePath,
2737                                         bool IgnoreBaseAccess) {
2738   QualType FromType = From->getType();
2739   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2740   if (!FromPtrType) {
2741     // This must be a null pointer to member pointer conversion
2742     assert(From->isNullPointerConstant(Context,
2743                                        Expr::NPC_ValueDependentIsNull) &&
2744            "Expr must be null pointer constant!");
2745     Kind = CK_NullToMemberPointer;
2746     return false;
2747   }
2748
2749   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2750   assert(ToPtrType && "No member pointer cast has a target type "
2751                       "that is not a member pointer.");
2752
2753   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2754   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2755
2756   // FIXME: What about dependent types?
2757   assert(FromClass->isRecordType() && "Pointer into non-class.");
2758   assert(ToClass->isRecordType() && "Pointer into non-class.");
2759
2760   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2761                      /*DetectVirtual=*/true);
2762   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2763   assert(DerivationOkay &&
2764          "Should not have been called if derivation isn't OK.");
2765   (void)DerivationOkay;
2766
2767   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2768                                   getUnqualifiedType())) {
2769     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2770     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2771       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2772     return true;
2773   }
2774
2775   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2776     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2777       << FromClass << ToClass << QualType(VBase, 0)
2778       << From->getSourceRange();
2779     return true;
2780   }
2781
2782   if (!IgnoreBaseAccess)
2783     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2784                          Paths.front(),
2785                          diag::err_downcast_from_inaccessible_base);
2786
2787   // Must be a base to derived member conversion.
2788   BuildBasePathArray(Paths, BasePath);
2789   Kind = CK_BaseToDerivedMemberPointer;
2790   return false;
2791 }
2792
2793 /// Determine whether the lifetime conversion between the two given
2794 /// qualifiers sets is nontrivial.
2795 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2796                                                Qualifiers ToQuals) {
2797   // Converting anything to const __unsafe_unretained is trivial.
2798   if (ToQuals.hasConst() && 
2799       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2800     return false;
2801
2802   return true;
2803 }
2804
2805 /// IsQualificationConversion - Determines whether the conversion from
2806 /// an rvalue of type FromType to ToType is a qualification conversion
2807 /// (C++ 4.4).
2808 ///
2809 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2810 /// when the qualification conversion involves a change in the Objective-C
2811 /// object lifetime.
2812 bool
2813 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2814                                 bool CStyle, bool &ObjCLifetimeConversion) {
2815   FromType = Context.getCanonicalType(FromType);
2816   ToType = Context.getCanonicalType(ToType);
2817   ObjCLifetimeConversion = false;
2818   
2819   // If FromType and ToType are the same type, this is not a
2820   // qualification conversion.
2821   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2822     return false;
2823
2824   // (C++ 4.4p4):
2825   //   A conversion can add cv-qualifiers at levels other than the first
2826   //   in multi-level pointers, subject to the following rules: [...]
2827   bool PreviousToQualsIncludeConst = true;
2828   bool UnwrappedAnyPointer = false;
2829   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2830     // Within each iteration of the loop, we check the qualifiers to
2831     // determine if this still looks like a qualification
2832     // conversion. Then, if all is well, we unwrap one more level of
2833     // pointers or pointers-to-members and do it all again
2834     // until there are no more pointers or pointers-to-members left to
2835     // unwrap.
2836     UnwrappedAnyPointer = true;
2837
2838     Qualifiers FromQuals = FromType.getQualifiers();
2839     Qualifiers ToQuals = ToType.getQualifiers();
2840     
2841     // Objective-C ARC:
2842     //   Check Objective-C lifetime conversions.
2843     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2844         UnwrappedAnyPointer) {
2845       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2846         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2847           ObjCLifetimeConversion = true;
2848         FromQuals.removeObjCLifetime();
2849         ToQuals.removeObjCLifetime();
2850       } else {
2851         // Qualification conversions cannot cast between different
2852         // Objective-C lifetime qualifiers.
2853         return false;
2854       }
2855     }
2856     
2857     // Allow addition/removal of GC attributes but not changing GC attributes.
2858     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2859         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2860       FromQuals.removeObjCGCAttr();
2861       ToQuals.removeObjCGCAttr();
2862     }
2863     
2864     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2865     //      2,j, and similarly for volatile.
2866     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2867       return false;
2868
2869     //   -- if the cv 1,j and cv 2,j are different, then const is in
2870     //      every cv for 0 < k < j.
2871     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2872         && !PreviousToQualsIncludeConst)
2873       return false;
2874
2875     // Keep track of whether all prior cv-qualifiers in the "to" type
2876     // include const.
2877     PreviousToQualsIncludeConst
2878       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2879   }
2880
2881   // We are left with FromType and ToType being the pointee types
2882   // after unwrapping the original FromType and ToType the same number
2883   // of types. If we unwrapped any pointers, and if FromType and
2884   // ToType have the same unqualified type (since we checked
2885   // qualifiers above), then this is a qualification conversion.
2886   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2887 }
2888
2889 /// \brief - Determine whether this is a conversion from a scalar type to an
2890 /// atomic type.
2891 ///
2892 /// If successful, updates \c SCS's second and third steps in the conversion
2893 /// sequence to finish the conversion.
2894 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2895                                 bool InOverloadResolution,
2896                                 StandardConversionSequence &SCS,
2897                                 bool CStyle) {
2898   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2899   if (!ToAtomic)
2900     return false;
2901   
2902   StandardConversionSequence InnerSCS;
2903   if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 
2904                             InOverloadResolution, InnerSCS,
2905                             CStyle, /*AllowObjCWritebackConversion=*/false))
2906     return false;
2907   
2908   SCS.Second = InnerSCS.Second;
2909   SCS.setToType(1, InnerSCS.getToType(1));
2910   SCS.Third = InnerSCS.Third;
2911   SCS.QualificationIncludesObjCLifetime
2912     = InnerSCS.QualificationIncludesObjCLifetime;
2913   SCS.setToType(2, InnerSCS.getToType(2));
2914   return true;
2915 }
2916
2917 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2918                                               CXXConstructorDecl *Constructor,
2919                                               QualType Type) {
2920   const FunctionProtoType *CtorType =
2921       Constructor->getType()->getAs<FunctionProtoType>();
2922   if (CtorType->getNumParams() > 0) {
2923     QualType FirstArg = CtorType->getParamType(0);
2924     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2925       return true;
2926   }
2927   return false;
2928 }
2929
2930 static OverloadingResult
2931 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2932                                        CXXRecordDecl *To,
2933                                        UserDefinedConversionSequence &User,
2934                                        OverloadCandidateSet &CandidateSet,
2935                                        bool AllowExplicit) {
2936   DeclContext::lookup_result R = S.LookupConstructors(To);
2937   for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2938        Con != ConEnd; ++Con) {
2939     NamedDecl *D = *Con;
2940     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2941
2942     // Find the constructor (which may be a template).
2943     CXXConstructorDecl *Constructor = nullptr;
2944     FunctionTemplateDecl *ConstructorTmpl
2945       = dyn_cast<FunctionTemplateDecl>(D);
2946     if (ConstructorTmpl)
2947       Constructor
2948         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2949     else
2950       Constructor = cast<CXXConstructorDecl>(D);
2951
2952     bool Usable = !Constructor->isInvalidDecl() &&
2953                   S.isInitListConstructor(Constructor) &&
2954                   (AllowExplicit || !Constructor->isExplicit());
2955     if (Usable) {
2956       // If the first argument is (a reference to) the target type,
2957       // suppress conversions.
2958       bool SuppressUserConversions =
2959           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2960       if (ConstructorTmpl)
2961         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2962                                        /*ExplicitArgs*/ nullptr,
2963                                        From, CandidateSet,
2964                                        SuppressUserConversions);
2965       else
2966         S.AddOverloadCandidate(Constructor, FoundDecl,
2967                                From, CandidateSet,
2968                                SuppressUserConversions);
2969     }
2970   }
2971
2972   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2973
2974   OverloadCandidateSet::iterator Best;
2975   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2976   case OR_Success: {
2977     // Record the standard conversion we used and the conversion function.
2978     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2979     QualType ThisType = Constructor->getThisType(S.Context);
2980     // Initializer lists don't have conversions as such.
2981     User.Before.setAsIdentityConversion();
2982     User.HadMultipleCandidates = HadMultipleCandidates;
2983     User.ConversionFunction = Constructor;
2984     User.FoundConversionFunction = Best->FoundDecl;
2985     User.After.setAsIdentityConversion();
2986     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2987     User.After.setAllToTypes(ToType);
2988     return OR_Success;
2989   }
2990
2991   case OR_No_Viable_Function:
2992     return OR_No_Viable_Function;
2993   case OR_Deleted:
2994     return OR_Deleted;
2995   case OR_Ambiguous:
2996     return OR_Ambiguous;
2997   }
2998
2999   llvm_unreachable("Invalid OverloadResult!");
3000 }
3001
3002 /// Determines whether there is a user-defined conversion sequence
3003 /// (C++ [over.ics.user]) that converts expression From to the type
3004 /// ToType. If such a conversion exists, User will contain the
3005 /// user-defined conversion sequence that performs such a conversion
3006 /// and this routine will return true. Otherwise, this routine returns
3007 /// false and User is unspecified.
3008 ///
3009 /// \param AllowExplicit  true if the conversion should consider C++0x
3010 /// "explicit" conversion functions as well as non-explicit conversion
3011 /// functions (C++0x [class.conv.fct]p2).
3012 ///
3013 /// \param AllowObjCConversionOnExplicit true if the conversion should
3014 /// allow an extra Objective-C pointer conversion on uses of explicit
3015 /// constructors. Requires \c AllowExplicit to also be set.
3016 static OverloadingResult
3017 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3018                         UserDefinedConversionSequence &User,
3019                         OverloadCandidateSet &CandidateSet,
3020                         bool AllowExplicit,
3021                         bool AllowObjCConversionOnExplicit) {
3022   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3023
3024   // Whether we will only visit constructors.
3025   bool ConstructorsOnly = false;
3026
3027   // If the type we are conversion to is a class type, enumerate its
3028   // constructors.
3029   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3030     // C++ [over.match.ctor]p1:
3031     //   When objects of class type are direct-initialized (8.5), or
3032     //   copy-initialized from an expression of the same or a
3033     //   derived class type (8.5), overload resolution selects the
3034     //   constructor. [...] For copy-initialization, the candidate
3035     //   functions are all the converting constructors (12.3.1) of
3036     //   that class. The argument list is the expression-list within
3037     //   the parentheses of the initializer.
3038     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3039         (From->getType()->getAs<RecordType>() &&
3040          S.IsDerivedFrom(From->getType(), ToType)))
3041       ConstructorsOnly = true;
3042
3043     S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3044     // RequireCompleteType may have returned true due to some invalid decl
3045     // during template instantiation, but ToType may be complete enough now
3046     // to try to recover.
3047     if (ToType->isIncompleteType()) {
3048       // We're not going to find any constructors.
3049     } else if (CXXRecordDecl *ToRecordDecl
3050                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3051
3052       Expr **Args = &From;
3053       unsigned NumArgs = 1;
3054       bool ListInitializing = false;
3055       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3056         // But first, see if there is an init-list-constructor that will work.
3057         OverloadingResult Result = IsInitializerListConstructorConversion(
3058             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3059         if (Result != OR_No_Viable_Function)
3060           return Result;
3061         // Never mind.
3062         CandidateSet.clear();
3063
3064         // If we're list-initializing, we pass the individual elements as
3065         // arguments, not the entire list.
3066         Args = InitList->getInits();
3067         NumArgs = InitList->getNumInits();
3068         ListInitializing = true;
3069       }
3070
3071       DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3072       for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3073            Con != ConEnd; ++Con) {
3074         NamedDecl *D = *Con;
3075         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3076
3077         // Find the constructor (which may be a template).
3078         CXXConstructorDecl *Constructor = nullptr;
3079         FunctionTemplateDecl *ConstructorTmpl
3080           = dyn_cast<FunctionTemplateDecl>(D);
3081         if (ConstructorTmpl)
3082           Constructor
3083             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3084         else
3085           Constructor = cast<CXXConstructorDecl>(D);
3086
3087         bool Usable = !Constructor->isInvalidDecl();
3088         if (ListInitializing)
3089           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3090         else
3091           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3092         if (Usable) {
3093           bool SuppressUserConversions = !ConstructorsOnly;
3094           if (SuppressUserConversions && ListInitializing) {
3095             SuppressUserConversions = false;
3096             if (NumArgs == 1) {
3097               // If the first argument is (a reference to) the target type,
3098               // suppress conversions.
3099               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3100                                                 S.Context, Constructor, ToType);
3101             }
3102           }
3103           if (ConstructorTmpl)
3104             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3105                                            /*ExplicitArgs*/ nullptr,
3106                                            llvm::makeArrayRef(Args, NumArgs),
3107                                            CandidateSet, SuppressUserConversions);
3108           else
3109             // Allow one user-defined conversion when user specifies a
3110             // From->ToType conversion via an static cast (c-style, etc).
3111             S.AddOverloadCandidate(Constructor, FoundDecl,
3112                                    llvm::makeArrayRef(Args, NumArgs),
3113                                    CandidateSet, SuppressUserConversions);
3114         }
3115       }
3116     }
3117   }
3118
3119   // Enumerate conversion functions, if we're allowed to.
3120   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3121   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3122     // No conversion functions from incomplete types.
3123   } else if (const RecordType *FromRecordType
3124                                    = From->getType()->getAs<RecordType>()) {
3125     if (CXXRecordDecl *FromRecordDecl
3126          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3127       // Add all of the conversion functions as candidates.
3128       std::pair<CXXRecordDecl::conversion_iterator,
3129                 CXXRecordDecl::conversion_iterator>
3130         Conversions = FromRecordDecl->getVisibleConversionFunctions();
3131       for (CXXRecordDecl::conversion_iterator
3132              I = Conversions.first, E = Conversions.second; I != E; ++I) {
3133         DeclAccessPair FoundDecl = I.getPair();
3134         NamedDecl *D = FoundDecl.getDecl();
3135         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3136         if (isa<UsingShadowDecl>(D))
3137           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3138
3139         CXXConversionDecl *Conv;
3140         FunctionTemplateDecl *ConvTemplate;
3141         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3142           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3143         else
3144           Conv = cast<CXXConversionDecl>(D);
3145
3146         if (AllowExplicit || !Conv->isExplicit()) {
3147           if (ConvTemplate)
3148             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3149                                              ActingContext, From, ToType,
3150                                              CandidateSet,
3151                                              AllowObjCConversionOnExplicit);
3152           else
3153             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3154                                      From, ToType, CandidateSet,
3155                                      AllowObjCConversionOnExplicit);
3156         }
3157       }
3158     }
3159   }
3160
3161   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3162
3163   OverloadCandidateSet::iterator Best;
3164   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3165   case OR_Success:
3166     // Record the standard conversion we used and the conversion function.
3167     if (CXXConstructorDecl *Constructor
3168           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3169       // C++ [over.ics.user]p1:
3170       //   If the user-defined conversion is specified by a
3171       //   constructor (12.3.1), the initial standard conversion
3172       //   sequence converts the source type to the type required by
3173       //   the argument of the constructor.
3174       //
3175       QualType ThisType = Constructor->getThisType(S.Context);
3176       if (isa<InitListExpr>(From)) {
3177         // Initializer lists don't have conversions as such.
3178         User.Before.setAsIdentityConversion();
3179       } else {
3180         if (Best->Conversions[0].isEllipsis())
3181           User.EllipsisConversion = true;
3182         else {
3183           User.Before = Best->Conversions[0].Standard;
3184           User.EllipsisConversion = false;
3185         }
3186       }
3187       User.HadMultipleCandidates = HadMultipleCandidates;
3188       User.ConversionFunction = Constructor;
3189       User.FoundConversionFunction = Best->FoundDecl;
3190       User.After.setAsIdentityConversion();
3191       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3192       User.After.setAllToTypes(ToType);
3193       return OR_Success;
3194     }
3195     if (CXXConversionDecl *Conversion
3196                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3197       // C++ [over.ics.user]p1:
3198       //
3199       //   [...] If the user-defined conversion is specified by a
3200       //   conversion function (12.3.2), the initial standard
3201       //   conversion sequence converts the source type to the
3202       //   implicit object parameter of the conversion function.
3203       User.Before = Best->Conversions[0].Standard;
3204       User.HadMultipleCandidates = HadMultipleCandidates;
3205       User.ConversionFunction = Conversion;
3206       User.FoundConversionFunction = Best->FoundDecl;
3207       User.EllipsisConversion = false;
3208
3209       // C++ [over.ics.user]p2:
3210       //   The second standard conversion sequence converts the
3211       //   result of the user-defined conversion to the target type
3212       //   for the sequence. Since an implicit conversion sequence
3213       //   is an initialization, the special rules for
3214       //   initialization by user-defined conversion apply when
3215       //   selecting the best user-defined conversion for a
3216       //   user-defined conversion sequence (see 13.3.3 and
3217       //   13.3.3.1).
3218       User.After = Best->FinalConversion;
3219       return OR_Success;
3220     }
3221     llvm_unreachable("Not a constructor or conversion function?");
3222
3223   case OR_No_Viable_Function:
3224     return OR_No_Viable_Function;
3225   case OR_Deleted:
3226     // No conversion here! We're done.
3227     return OR_Deleted;
3228
3229   case OR_Ambiguous:
3230     return OR_Ambiguous;
3231   }
3232
3233   llvm_unreachable("Invalid OverloadResult!");
3234 }
3235
3236 bool
3237 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3238   ImplicitConversionSequence ICS;
3239   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3240                                     OverloadCandidateSet::CSK_Normal);
3241   OverloadingResult OvResult =
3242     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3243                             CandidateSet, false, false);
3244   if (OvResult == OR_Ambiguous)
3245     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3246         << From->getType() << ToType << From->getSourceRange();
3247   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3248     if (!RequireCompleteType(From->getLocStart(), ToType,
3249                              diag::err_typecheck_nonviable_condition_incomplete,
3250                              From->getType(), From->getSourceRange()))
3251       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3252           << From->getType() << From->getSourceRange() << ToType;
3253   } else
3254     return false;
3255   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3256   return true;
3257 }
3258
3259 /// \brief Compare the user-defined conversion functions or constructors
3260 /// of two user-defined conversion sequences to determine whether any ordering
3261 /// is possible.
3262 static ImplicitConversionSequence::CompareKind
3263 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3264                            FunctionDecl *Function2) {
3265   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3266     return ImplicitConversionSequence::Indistinguishable;
3267
3268   // Objective-C++:
3269   //   If both conversion functions are implicitly-declared conversions from
3270   //   a lambda closure type to a function pointer and a block pointer,
3271   //   respectively, always prefer the conversion to a function pointer,
3272   //   because the function pointer is more lightweight and is more likely
3273   //   to keep code working.
3274   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3275   if (!Conv1)
3276     return ImplicitConversionSequence::Indistinguishable;
3277
3278   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3279   if (!Conv2)
3280     return ImplicitConversionSequence::Indistinguishable;
3281
3282   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3283     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3284     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3285     if (Block1 != Block2)
3286       return Block1 ? ImplicitConversionSequence::Worse
3287                     : ImplicitConversionSequence::Better;
3288   }
3289
3290   return ImplicitConversionSequence::Indistinguishable;
3291 }
3292
3293 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3294     const ImplicitConversionSequence &ICS) {
3295   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3296          (ICS.isUserDefined() &&
3297           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3298 }
3299
3300 /// CompareImplicitConversionSequences - Compare two implicit
3301 /// conversion sequences to determine whether one is better than the
3302 /// other or if they are indistinguishable (C++ 13.3.3.2).
3303 static ImplicitConversionSequence::CompareKind
3304 CompareImplicitConversionSequences(Sema &S,
3305                                    const ImplicitConversionSequence& ICS1,
3306                                    const ImplicitConversionSequence& ICS2)
3307 {
3308   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3309   // conversion sequences (as defined in 13.3.3.1)
3310   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3311   //      conversion sequence than a user-defined conversion sequence or
3312   //      an ellipsis conversion sequence, and
3313   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3314   //      conversion sequence than an ellipsis conversion sequence
3315   //      (13.3.3.1.3).
3316   //
3317   // C++0x [over.best.ics]p10:
3318   //   For the purpose of ranking implicit conversion sequences as
3319   //   described in 13.3.3.2, the ambiguous conversion sequence is
3320   //   treated as a user-defined sequence that is indistinguishable
3321   //   from any other user-defined conversion sequence.
3322
3323   // String literal to 'char *' conversion has been deprecated in C++03. It has
3324   // been removed from C++11. We still accept this conversion, if it happens at
3325   // the best viable function. Otherwise, this conversion is considered worse
3326   // than ellipsis conversion. Consider this as an extension; this is not in the
3327   // standard. For example:
3328   //
3329   // int &f(...);    // #1
3330   // void f(char*);  // #2
3331   // void g() { int &r = f("foo"); }
3332   //
3333   // In C++03, we pick #2 as the best viable function.
3334   // In C++11, we pick #1 as the best viable function, because ellipsis
3335   // conversion is better than string-literal to char* conversion (since there
3336   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3337   // convert arguments, #2 would be the best viable function in C++11.
3338   // If the best viable function has this conversion, a warning will be issued
3339   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3340
3341   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3342       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3343       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3344     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3345                ? ImplicitConversionSequence::Worse
3346                : ImplicitConversionSequence::Better;
3347
3348   if (ICS1.getKindRank() < ICS2.getKindRank())
3349     return ImplicitConversionSequence::Better;
3350   if (ICS2.getKindRank() < ICS1.getKindRank())
3351     return ImplicitConversionSequence::Worse;
3352
3353   // The following checks require both conversion sequences to be of
3354   // the same kind.
3355   if (ICS1.getKind() != ICS2.getKind())
3356     return ImplicitConversionSequence::Indistinguishable;
3357
3358   ImplicitConversionSequence::CompareKind Result =
3359       ImplicitConversionSequence::Indistinguishable;
3360
3361   // Two implicit conversion sequences of the same form are
3362   // indistinguishable conversion sequences unless one of the
3363   // following rules apply: (C++ 13.3.3.2p3):
3364   if (ICS1.isStandard())
3365     Result = CompareStandardConversionSequences(S,
3366                                                 ICS1.Standard, ICS2.Standard);
3367   else if (ICS1.isUserDefined()) {
3368     // User-defined conversion sequence U1 is a better conversion
3369     // sequence than another user-defined conversion sequence U2 if
3370     // they contain the same user-defined conversion function or
3371     // constructor and if the second standard conversion sequence of
3372     // U1 is better than the second standard conversion sequence of
3373     // U2 (C++ 13.3.3.2p3).
3374     if (ICS1.UserDefined.ConversionFunction ==
3375           ICS2.UserDefined.ConversionFunction)
3376       Result = CompareStandardConversionSequences(S,
3377                                                   ICS1.UserDefined.After,
3378                                                   ICS2.UserDefined.After);
3379     else
3380       Result = compareConversionFunctions(S, 
3381                                           ICS1.UserDefined.ConversionFunction,
3382                                           ICS2.UserDefined.ConversionFunction);
3383   }
3384
3385   // List-initialization sequence L1 is a better conversion sequence than
3386   // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3387   // for some X and L2 does not.
3388   if (Result == ImplicitConversionSequence::Indistinguishable &&
3389       !ICS1.isBad()) {
3390     if (ICS1.isStdInitializerListElement() &&
3391         !ICS2.isStdInitializerListElement())
3392       return ImplicitConversionSequence::Better;
3393     if (!ICS1.isStdInitializerListElement() &&
3394         ICS2.isStdInitializerListElement())
3395       return ImplicitConversionSequence::Worse;
3396   }
3397
3398   return Result;
3399 }
3400
3401 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3402   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3403     Qualifiers Quals;
3404     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3405     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3406   }
3407
3408   return Context.hasSameUnqualifiedType(T1, T2);
3409 }
3410
3411 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3412 // determine if one is a proper subset of the other.
3413 static ImplicitConversionSequence::CompareKind
3414 compareStandardConversionSubsets(ASTContext &Context,
3415                                  const StandardConversionSequence& SCS1,
3416                                  const StandardConversionSequence& SCS2) {
3417   ImplicitConversionSequence::CompareKind Result
3418     = ImplicitConversionSequence::Indistinguishable;
3419
3420   // the identity conversion sequence is considered to be a subsequence of
3421   // any non-identity conversion sequence
3422   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3423     return ImplicitConversionSequence::Better;
3424   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3425     return ImplicitConversionSequence::Worse;
3426
3427   if (SCS1.Second != SCS2.Second) {
3428     if (SCS1.Second == ICK_Identity)
3429       Result = ImplicitConversionSequence::Better;
3430     else if (SCS2.Second == ICK_Identity)
3431       Result = ImplicitConversionSequence::Worse;
3432     else
3433       return ImplicitConversionSequence::Indistinguishable;
3434   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3435     return ImplicitConversionSequence::Indistinguishable;
3436
3437   if (SCS1.Third == SCS2.Third) {
3438     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3439                              : ImplicitConversionSequence::Indistinguishable;
3440   }
3441
3442   if (SCS1.Third == ICK_Identity)
3443     return Result == ImplicitConversionSequence::Worse
3444              ? ImplicitConversionSequence::Indistinguishable
3445              : ImplicitConversionSequence::Better;
3446
3447   if (SCS2.Third == ICK_Identity)
3448     return Result == ImplicitConversionSequence::Better
3449              ? ImplicitConversionSequence::Indistinguishable
3450              : ImplicitConversionSequence::Worse;
3451
3452   return ImplicitConversionSequence::Indistinguishable;
3453 }
3454
3455 /// \brief Determine whether one of the given reference bindings is better
3456 /// than the other based on what kind of bindings they are.
3457 static bool
3458 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3459                              const StandardConversionSequence &SCS2) {
3460   // C++0x [over.ics.rank]p3b4:
3461   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3462   //      implicit object parameter of a non-static member function declared
3463   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3464   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3465   //      lvalue reference to a function lvalue and S2 binds an rvalue
3466   //      reference*.
3467   //
3468   // FIXME: Rvalue references. We're going rogue with the above edits,
3469   // because the semantics in the current C++0x working paper (N3225 at the
3470   // time of this writing) break the standard definition of std::forward
3471   // and std::reference_wrapper when dealing with references to functions.
3472   // Proposed wording changes submitted to CWG for consideration.
3473   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3474       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3475     return false;
3476
3477   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3478           SCS2.IsLvalueReference) ||
3479          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3480           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3481 }
3482
3483 /// CompareStandardConversionSequences - Compare two standard
3484 /// conversion sequences to determine whether one is better than the
3485 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3486 static ImplicitConversionSequence::CompareKind
3487 CompareStandardConversionSequences(Sema &S,
3488                                    const StandardConversionSequence& SCS1,
3489                                    const StandardConversionSequence& SCS2)
3490 {
3491   // Standard conversion sequence S1 is a better conversion sequence
3492   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3493
3494   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3495   //     sequences in the canonical form defined by 13.3.3.1.1,
3496   //     excluding any Lvalue Transformation; the identity conversion
3497   //     sequence is considered to be a subsequence of any
3498   //     non-identity conversion sequence) or, if not that,
3499   if (ImplicitConversionSequence::CompareKind CK
3500         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3501     return CK;
3502
3503   //  -- the rank of S1 is better than the rank of S2 (by the rules
3504   //     defined below), or, if not that,
3505   ImplicitConversionRank Rank1 = SCS1.getRank();
3506   ImplicitConversionRank Rank2 = SCS2.getRank();
3507   if (Rank1 < Rank2)
3508     return ImplicitConversionSequence::Better;
3509   else if (Rank2 < Rank1)
3510     return ImplicitConversionSequence::Worse;
3511
3512   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3513   // are indistinguishable unless one of the following rules
3514   // applies:
3515
3516   //   A conversion that is not a conversion of a pointer, or
3517   //   pointer to member, to bool is better than another conversion
3518   //   that is such a conversion.
3519   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3520     return SCS2.isPointerConversionToBool()
3521              ? ImplicitConversionSequence::Better
3522              : ImplicitConversionSequence::Worse;
3523
3524   // C++ [over.ics.rank]p4b2:
3525   //
3526   //   If class B is derived directly or indirectly from class A,
3527   //   conversion of B* to A* is better than conversion of B* to
3528   //   void*, and conversion of A* to void* is better than conversion
3529   //   of B* to void*.
3530   bool SCS1ConvertsToVoid
3531     = SCS1.isPointerConversionToVoidPointer(S.Context);
3532   bool SCS2ConvertsToVoid
3533     = SCS2.isPointerConversionToVoidPointer(S.Context);
3534   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3535     // Exactly one of the conversion sequences is a conversion to
3536     // a void pointer; it's the worse conversion.
3537     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3538                               : ImplicitConversionSequence::Worse;
3539   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3540     // Neither conversion sequence converts to a void pointer; compare
3541     // their derived-to-base conversions.
3542     if (ImplicitConversionSequence::CompareKind DerivedCK
3543           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3544       return DerivedCK;
3545   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3546              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3547     // Both conversion sequences are conversions to void
3548     // pointers. Compare the source types to determine if there's an
3549     // inheritance relationship in their sources.
3550     QualType FromType1 = SCS1.getFromType();
3551     QualType FromType2 = SCS2.getFromType();
3552
3553     // Adjust the types we're converting from via the array-to-pointer
3554     // conversion, if we need to.
3555     if (SCS1.First == ICK_Array_To_Pointer)
3556       FromType1 = S.Context.getArrayDecayedType(FromType1);
3557     if (SCS2.First == ICK_Array_To_Pointer)
3558       FromType2 = S.Context.getArrayDecayedType(FromType2);
3559
3560     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3561     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3562
3563     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3564       return ImplicitConversionSequence::Better;
3565     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3566       return ImplicitConversionSequence::Worse;
3567
3568     // Objective-C++: If one interface is more specific than the
3569     // other, it is the better one.
3570     const ObjCObjectPointerType* FromObjCPtr1
3571       = FromType1->getAs<ObjCObjectPointerType>();
3572     const ObjCObjectPointerType* FromObjCPtr2
3573       = FromType2->getAs<ObjCObjectPointerType>();
3574     if (FromObjCPtr1 && FromObjCPtr2) {
3575       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 
3576                                                           FromObjCPtr2);
3577       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 
3578                                                            FromObjCPtr1);
3579       if (AssignLeft != AssignRight) {
3580         return AssignLeft? ImplicitConversionSequence::Better
3581                          : ImplicitConversionSequence::Worse;
3582       }
3583     }
3584   }
3585
3586   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3587   // bullet 3).
3588   if (ImplicitConversionSequence::CompareKind QualCK
3589         = CompareQualificationConversions(S, SCS1, SCS2))
3590     return QualCK;
3591
3592   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3593     // Check for a better reference binding based on the kind of bindings.
3594     if (isBetterReferenceBindingKind(SCS1, SCS2))
3595       return ImplicitConversionSequence::Better;
3596     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3597       return ImplicitConversionSequence::Worse;
3598
3599     // C++ [over.ics.rank]p3b4:
3600     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3601     //      which the references refer are the same type except for
3602     //      top-level cv-qualifiers, and the type to which the reference
3603     //      initialized by S2 refers is more cv-qualified than the type
3604     //      to which the reference initialized by S1 refers.
3605     QualType T1 = SCS1.getToType(2);
3606     QualType T2 = SCS2.getToType(2);
3607     T1 = S.Context.getCanonicalType(T1);
3608     T2 = S.Context.getCanonicalType(T2);
3609     Qualifiers T1Quals, T2Quals;
3610     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3611     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3612     if (UnqualT1 == UnqualT2) {
3613       // Objective-C++ ARC: If the references refer to objects with different
3614       // lifetimes, prefer bindings that don't change lifetime.
3615       if (SCS1.ObjCLifetimeConversionBinding != 
3616                                           SCS2.ObjCLifetimeConversionBinding) {
3617         return SCS1.ObjCLifetimeConversionBinding
3618                                            ? ImplicitConversionSequence::Worse
3619                                            : ImplicitConversionSequence::Better;
3620       }
3621       
3622       // If the type is an array type, promote the element qualifiers to the
3623       // type for comparison.
3624       if (isa<ArrayType>(T1) && T1Quals)
3625         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3626       if (isa<ArrayType>(T2) && T2Quals)
3627         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3628       if (T2.isMoreQualifiedThan(T1))
3629         return ImplicitConversionSequence::Better;
3630       else if (T1.isMoreQualifiedThan(T2))
3631         return ImplicitConversionSequence::Worse;      
3632     }
3633   }
3634
3635   // In Microsoft mode, prefer an integral conversion to a
3636   // floating-to-integral conversion if the integral conversion
3637   // is between types of the same size.
3638   // For example:
3639   // void f(float);
3640   // void f(int);
3641   // int main {
3642   //    long a;
3643   //    f(a);
3644   // }
3645   // Here, MSVC will call f(int) instead of generating a compile error
3646   // as clang will do in standard mode.
3647   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3648       SCS2.Second == ICK_Floating_Integral &&
3649       S.Context.getTypeSize(SCS1.getFromType()) ==
3650           S.Context.getTypeSize(SCS1.getToType(2)))
3651     return ImplicitConversionSequence::Better;
3652
3653   return ImplicitConversionSequence::Indistinguishable;
3654 }
3655
3656 /// CompareQualificationConversions - Compares two standard conversion
3657 /// sequences to determine whether they can be ranked based on their
3658 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3659 ImplicitConversionSequence::CompareKind
3660 CompareQualificationConversions(Sema &S,
3661                                 const StandardConversionSequence& SCS1,
3662                                 const StandardConversionSequence& SCS2) {
3663   // C++ 13.3.3.2p3:
3664   //  -- S1 and S2 differ only in their qualification conversion and
3665   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3666   //     cv-qualification signature of type T1 is a proper subset of
3667   //     the cv-qualification signature of type T2, and S1 is not the
3668   //     deprecated string literal array-to-pointer conversion (4.2).
3669   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3670       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3671     return ImplicitConversionSequence::Indistinguishable;
3672
3673   // FIXME: the example in the standard doesn't use a qualification
3674   // conversion (!)
3675   QualType T1 = SCS1.getToType(2);
3676   QualType T2 = SCS2.getToType(2);
3677   T1 = S.Context.getCanonicalType(T1);
3678   T2 = S.Context.getCanonicalType(T2);
3679   Qualifiers T1Quals, T2Quals;
3680   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3681   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3682
3683   // If the types are the same, we won't learn anything by unwrapped
3684   // them.
3685   if (UnqualT1 == UnqualT2)
3686     return ImplicitConversionSequence::Indistinguishable;
3687
3688   // If the type is an array type, promote the element qualifiers to the type
3689   // for comparison.
3690   if (isa<ArrayType>(T1) && T1Quals)
3691     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3692   if (isa<ArrayType>(T2) && T2Quals)
3693     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3694
3695   ImplicitConversionSequence::CompareKind Result
3696     = ImplicitConversionSequence::Indistinguishable;
3697   
3698   // Objective-C++ ARC:
3699   //   Prefer qualification conversions not involving a change in lifetime
3700   //   to qualification conversions that do not change lifetime.
3701   if (SCS1.QualificationIncludesObjCLifetime != 
3702                                       SCS2.QualificationIncludesObjCLifetime) {
3703     Result = SCS1.QualificationIncludesObjCLifetime
3704                ? ImplicitConversionSequence::Worse
3705                : ImplicitConversionSequence::Better;
3706   }
3707   
3708   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3709     // Within each iteration of the loop, we check the qualifiers to
3710     // determine if this still looks like a qualification
3711     // conversion. Then, if all is well, we unwrap one more level of
3712     // pointers or pointers-to-members and do it all again
3713     // until there are no more pointers or pointers-to-members left
3714     // to unwrap. This essentially mimics what
3715     // IsQualificationConversion does, but here we're checking for a
3716     // strict subset of qualifiers.
3717     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3718       // The qualifiers are the same, so this doesn't tell us anything
3719       // about how the sequences rank.
3720       ;
3721     else if (T2.isMoreQualifiedThan(T1)) {
3722       // T1 has fewer qualifiers, so it could be the better sequence.
3723       if (Result == ImplicitConversionSequence::Worse)
3724         // Neither has qualifiers that are a subset of the other's
3725         // qualifiers.
3726         return ImplicitConversionSequence::Indistinguishable;
3727
3728       Result = ImplicitConversionSequence::Better;
3729     } else if (T1.isMoreQualifiedThan(T2)) {
3730       // T2 has fewer qualifiers, so it could be the better sequence.
3731       if (Result == ImplicitConversionSequence::Better)
3732         // Neither has qualifiers that are a subset of the other's
3733         // qualifiers.
3734         return ImplicitConversionSequence::Indistinguishable;
3735
3736       Result = ImplicitConversionSequence::Worse;
3737     } else {
3738       // Qualifiers are disjoint.
3739       return ImplicitConversionSequence::Indistinguishable;
3740     }
3741
3742     // If the types after this point are equivalent, we're done.
3743     if (S.Context.hasSameUnqualifiedType(T1, T2))
3744       break;
3745   }
3746
3747   // Check that the winning standard conversion sequence isn't using
3748   // the deprecated string literal array to pointer conversion.
3749   switch (Result) {
3750   case ImplicitConversionSequence::Better:
3751     if (SCS1.DeprecatedStringLiteralToCharPtr)
3752       Result = ImplicitConversionSequence::Indistinguishable;
3753     break;
3754
3755   case ImplicitConversionSequence::Indistinguishable:
3756     break;
3757
3758   case ImplicitConversionSequence::Worse:
3759     if (SCS2.DeprecatedStringLiteralToCharPtr)
3760       Result = ImplicitConversionSequence::Indistinguishable;
3761     break;
3762   }
3763
3764   return Result;
3765 }
3766
3767 /// CompareDerivedToBaseConversions - Compares two standard conversion
3768 /// sequences to determine whether they can be ranked based on their
3769 /// various kinds of derived-to-base conversions (C++
3770 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3771 /// conversions between Objective-C interface types.
3772 ImplicitConversionSequence::CompareKind
3773 CompareDerivedToBaseConversions(Sema &S,
3774                                 const StandardConversionSequence& SCS1,
3775                                 const StandardConversionSequence& SCS2) {
3776   QualType FromType1 = SCS1.getFromType();
3777   QualType ToType1 = SCS1.getToType(1);
3778   QualType FromType2 = SCS2.getFromType();
3779   QualType ToType2 = SCS2.getToType(1);
3780
3781   // Adjust the types we're converting from via the array-to-pointer
3782   // conversion, if we need to.
3783   if (SCS1.First == ICK_Array_To_Pointer)
3784     FromType1 = S.Context.getArrayDecayedType(FromType1);
3785   if (SCS2.First == ICK_Array_To_Pointer)
3786     FromType2 = S.Context.getArrayDecayedType(FromType2);
3787
3788   // Canonicalize all of the types.
3789   FromType1 = S.Context.getCanonicalType(FromType1);
3790   ToType1 = S.Context.getCanonicalType(ToType1);
3791   FromType2 = S.Context.getCanonicalType(FromType2);
3792   ToType2 = S.Context.getCanonicalType(ToType2);
3793
3794   // C++ [over.ics.rank]p4b3:
3795   //
3796   //   If class B is derived directly or indirectly from class A and
3797   //   class C is derived directly or indirectly from B,
3798   //
3799   // Compare based on pointer conversions.
3800   if (SCS1.Second == ICK_Pointer_Conversion &&
3801       SCS2.Second == ICK_Pointer_Conversion &&
3802       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3803       FromType1->isPointerType() && FromType2->isPointerType() &&
3804       ToType1->isPointerType() && ToType2->isPointerType()) {
3805     QualType FromPointee1
3806       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3807     QualType ToPointee1
3808       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3809     QualType FromPointee2
3810       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3811     QualType ToPointee2
3812       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3813
3814     //   -- conversion of C* to B* is better than conversion of C* to A*,
3815     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3816       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3817         return ImplicitConversionSequence::Better;
3818       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3819         return ImplicitConversionSequence::Worse;
3820     }
3821
3822     //   -- conversion of B* to A* is better than conversion of C* to A*,
3823     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3824       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3825         return ImplicitConversionSequence::Better;
3826       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3827         return ImplicitConversionSequence::Worse;
3828     }
3829   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3830              SCS2.Second == ICK_Pointer_Conversion) {
3831     const ObjCObjectPointerType *FromPtr1
3832       = FromType1->getAs<ObjCObjectPointerType>();
3833     const ObjCObjectPointerType *FromPtr2
3834       = FromType2->getAs<ObjCObjectPointerType>();
3835     const ObjCObjectPointerType *ToPtr1
3836       = ToType1->getAs<ObjCObjectPointerType>();
3837     const ObjCObjectPointerType *ToPtr2
3838       = ToType2->getAs<ObjCObjectPointerType>();
3839     
3840     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3841       // Apply the same conversion ranking rules for Objective-C pointer types
3842       // that we do for C++ pointers to class types. However, we employ the
3843       // Objective-C pseudo-subtyping relationship used for assignment of
3844       // Objective-C pointer types.
3845       bool FromAssignLeft
3846         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3847       bool FromAssignRight
3848         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3849       bool ToAssignLeft
3850         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3851       bool ToAssignRight
3852         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3853       
3854       // A conversion to an a non-id object pointer type or qualified 'id' 
3855       // type is better than a conversion to 'id'.
3856       if (ToPtr1->isObjCIdType() &&
3857           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3858         return ImplicitConversionSequence::Worse;
3859       if (ToPtr2->isObjCIdType() &&
3860           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3861         return ImplicitConversionSequence::Better;
3862       
3863       // A conversion to a non-id object pointer type is better than a 
3864       // conversion to a qualified 'id' type 
3865       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3866         return ImplicitConversionSequence::Worse;
3867       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3868         return ImplicitConversionSequence::Better;
3869   
3870       // A conversion to an a non-Class object pointer type or qualified 'Class' 
3871       // type is better than a conversion to 'Class'.
3872       if (ToPtr1->isObjCClassType() &&
3873           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3874         return ImplicitConversionSequence::Worse;
3875       if (ToPtr2->isObjCClassType() &&
3876           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3877         return ImplicitConversionSequence::Better;
3878       
3879       // A conversion to a non-Class object pointer type is better than a 
3880       // conversion to a qualified 'Class' type.
3881       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3882         return ImplicitConversionSequence::Worse;
3883       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3884         return ImplicitConversionSequence::Better;
3885
3886       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3887       if (S.Context.hasSameType(FromType1, FromType2) && 
3888           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3889           (ToAssignLeft != ToAssignRight))
3890         return ToAssignLeft? ImplicitConversionSequence::Worse
3891                            : ImplicitConversionSequence::Better;
3892
3893       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3894       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3895           (FromAssignLeft != FromAssignRight))
3896         return FromAssignLeft? ImplicitConversionSequence::Better
3897         : ImplicitConversionSequence::Worse;
3898     }
3899   }
3900   
3901   // Ranking of member-pointer types.
3902   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3903       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3904       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3905     const MemberPointerType * FromMemPointer1 =
3906                                         FromType1->getAs<MemberPointerType>();
3907     const MemberPointerType * ToMemPointer1 =
3908                                           ToType1->getAs<MemberPointerType>();
3909     const MemberPointerType * FromMemPointer2 =
3910                                           FromType2->getAs<MemberPointerType>();
3911     const MemberPointerType * ToMemPointer2 =
3912                                           ToType2->getAs<MemberPointerType>();
3913     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3914     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3915     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3916     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3917     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3918     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3919     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3920     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3921     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3922     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3923       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3924         return ImplicitConversionSequence::Worse;
3925       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3926         return ImplicitConversionSequence::Better;
3927     }
3928     // conversion of B::* to C::* is better than conversion of A::* to C::*
3929     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3930       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3931         return ImplicitConversionSequence::Better;
3932       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3933         return ImplicitConversionSequence::Worse;
3934     }
3935   }
3936
3937   if (SCS1.Second == ICK_Derived_To_Base) {
3938     //   -- conversion of C to B is better than conversion of C to A,
3939     //   -- binding of an expression of type C to a reference of type
3940     //      B& is better than binding an expression of type C to a
3941     //      reference of type A&,
3942     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3943         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3944       if (S.IsDerivedFrom(ToType1, ToType2))
3945         return ImplicitConversionSequence::Better;
3946       else if (S.IsDerivedFrom(ToType2, ToType1))
3947         return ImplicitConversionSequence::Worse;
3948     }
3949
3950     //   -- conversion of B to A is better than conversion of C to A.
3951     //   -- binding of an expression of type B to a reference of type
3952     //      A& is better than binding an expression of type C to a
3953     //      reference of type A&,
3954     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3955         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3956       if (S.IsDerivedFrom(FromType2, FromType1))
3957         return ImplicitConversionSequence::Better;
3958       else if (S.IsDerivedFrom(FromType1, FromType2))
3959         return ImplicitConversionSequence::Worse;
3960     }
3961   }
3962
3963   return ImplicitConversionSequence::Indistinguishable;
3964 }
3965
3966 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
3967 /// C++ class.
3968 static bool isTypeValid(QualType T) {
3969   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3970     return !Record->isInvalidDecl();
3971
3972   return true;
3973 }
3974
3975 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3976 /// determine whether they are reference-related,
3977 /// reference-compatible, reference-compatible with added
3978 /// qualification, or incompatible, for use in C++ initialization by
3979 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3980 /// type, and the first type (T1) is the pointee type of the reference
3981 /// type being initialized.
3982 Sema::ReferenceCompareResult
3983 Sema::CompareReferenceRelationship(SourceLocation Loc,
3984                                    QualType OrigT1, QualType OrigT2,
3985                                    bool &DerivedToBase,
3986                                    bool &ObjCConversion,
3987                                    bool &ObjCLifetimeConversion) {
3988   assert(!OrigT1->isReferenceType() &&
3989     "T1 must be the pointee type of the reference type");
3990   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3991
3992   QualType T1 = Context.getCanonicalType(OrigT1);
3993   QualType T2 = Context.getCanonicalType(OrigT2);
3994   Qualifiers T1Quals, T2Quals;
3995   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3996   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3997
3998   // C++ [dcl.init.ref]p4:
3999   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4000   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4001   //   T1 is a base class of T2.
4002   DerivedToBase = false;
4003   ObjCConversion = false;
4004   ObjCLifetimeConversion = false;
4005   if (UnqualT1 == UnqualT2) {
4006     // Nothing to do.
4007   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
4008              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4009              IsDerivedFrom(UnqualT2, UnqualT1))
4010     DerivedToBase = true;
4011   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4012            UnqualT2->isObjCObjectOrInterfaceType() &&
4013            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4014     ObjCConversion = true;
4015   else
4016     return Ref_Incompatible;
4017
4018   // At this point, we know that T1 and T2 are reference-related (at
4019   // least).
4020
4021   // If the type is an array type, promote the element qualifiers to the type
4022   // for comparison.
4023   if (isa<ArrayType>(T1) && T1Quals)
4024     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4025   if (isa<ArrayType>(T2) && T2Quals)
4026     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4027
4028   // C++ [dcl.init.ref]p4:
4029   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4030   //   reference-related to T2 and cv1 is the same cv-qualification
4031   //   as, or greater cv-qualification than, cv2. For purposes of
4032   //   overload resolution, cases for which cv1 is greater
4033   //   cv-qualification than cv2 are identified as
4034   //   reference-compatible with added qualification (see 13.3.3.2).
4035   //
4036   // Note that we also require equivalence of Objective-C GC and address-space
4037   // qualifiers when performing these computations, so that e.g., an int in
4038   // address space 1 is not reference-compatible with an int in address
4039   // space 2.
4040   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4041       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4042     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4043       ObjCLifetimeConversion = true;
4044
4045     T1Quals.removeObjCLifetime();
4046     T2Quals.removeObjCLifetime();    
4047   }
4048     
4049   if (T1Quals == T2Quals)
4050     return Ref_Compatible;
4051   else if (T1Quals.compatiblyIncludes(T2Quals))
4052     return Ref_Compatible_With_Added_Qualification;
4053   else
4054     return Ref_Related;
4055 }
4056
4057 /// \brief Look for a user-defined conversion to an value reference-compatible
4058 ///        with DeclType. Return true if something definite is found.
4059 static bool
4060 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4061                          QualType DeclType, SourceLocation DeclLoc,
4062                          Expr *Init, QualType T2, bool AllowRvalues,
4063                          bool AllowExplicit) {
4064   assert(T2->isRecordType() && "Can only find conversions of record types.");
4065   CXXRecordDecl *T2RecordDecl
4066     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4067
4068   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4069   std::pair<CXXRecordDecl::conversion_iterator,
4070             CXXRecordDecl::conversion_iterator>
4071     Conversions = T2RecordDecl->getVisibleConversionFunctions();
4072   for (CXXRecordDecl::conversion_iterator
4073          I = Conversions.first, E = Conversions.second; I != E; ++I) {
4074     NamedDecl *D = *I;
4075     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4076     if (isa<UsingShadowDecl>(D))
4077       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4078
4079     FunctionTemplateDecl *ConvTemplate
4080       = dyn_cast<FunctionTemplateDecl>(D);
4081     CXXConversionDecl *Conv;
4082     if (ConvTemplate)
4083       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4084     else
4085       Conv = cast<CXXConversionDecl>(D);
4086
4087     // If this is an explicit conversion, and we're not allowed to consider
4088     // explicit conversions, skip it.
4089     if (!AllowExplicit && Conv->isExplicit())
4090       continue;
4091
4092     if (AllowRvalues) {
4093       bool DerivedToBase = false;
4094       bool ObjCConversion = false;
4095       bool ObjCLifetimeConversion = false;
4096       
4097       // If we are initializing an rvalue reference, don't permit conversion
4098       // functions that return lvalues.
4099       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4100         const ReferenceType *RefType
4101           = Conv->getConversionType()->getAs<LValueReferenceType>();
4102         if (RefType && !RefType->getPointeeType()->isFunctionType())
4103           continue;
4104       }
4105       
4106       if (!ConvTemplate &&
4107           S.CompareReferenceRelationship(
4108             DeclLoc,
4109             Conv->getConversionType().getNonReferenceType()
4110               .getUnqualifiedType(),
4111             DeclType.getNonReferenceType().getUnqualifiedType(),
4112             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4113           Sema::Ref_Incompatible)
4114         continue;
4115     } else {
4116       // If the conversion function doesn't return a reference type,
4117       // it can't be considered for this conversion. An rvalue reference
4118       // is only acceptable if its referencee is a function type.
4119
4120       const ReferenceType *RefType =
4121         Conv->getConversionType()->getAs<ReferenceType>();
4122       if (!RefType ||
4123           (!RefType->isLValueReferenceType() &&
4124            !RefType->getPointeeType()->isFunctionType()))
4125         continue;
4126     }
4127
4128     if (ConvTemplate)
4129       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4130                                        Init, DeclType, CandidateSet,
4131                                        /*AllowObjCConversionOnExplicit=*/false);
4132     else
4133       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4134                                DeclType, CandidateSet,
4135                                /*AllowObjCConversionOnExplicit=*/false);
4136   }
4137
4138   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4139
4140   OverloadCandidateSet::iterator Best;
4141   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4142   case OR_Success:
4143     // C++ [over.ics.ref]p1:
4144     //
4145     //   [...] If the parameter binds directly to the result of
4146     //   applying a conversion function to the argument
4147     //   expression, the implicit conversion sequence is a
4148     //   user-defined conversion sequence (13.3.3.1.2), with the
4149     //   second standard conversion sequence either an identity
4150     //   conversion or, if the conversion function returns an
4151     //   entity of a type that is a derived class of the parameter
4152     //   type, a derived-to-base Conversion.
4153     if (!Best->FinalConversion.DirectBinding)
4154       return false;
4155
4156     ICS.setUserDefined();
4157     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4158     ICS.UserDefined.After = Best->FinalConversion;
4159     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4160     ICS.UserDefined.ConversionFunction = Best->Function;
4161     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4162     ICS.UserDefined.EllipsisConversion = false;
4163     assert(ICS.UserDefined.After.ReferenceBinding &&
4164            ICS.UserDefined.After.DirectBinding &&
4165            "Expected a direct reference binding!");
4166     return true;
4167
4168   case OR_Ambiguous:
4169     ICS.setAmbiguous();
4170     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4171          Cand != CandidateSet.end(); ++Cand)
4172       if (Cand->Viable)
4173         ICS.Ambiguous.addConversion(Cand->Function);
4174     return true;
4175
4176   case OR_No_Viable_Function:
4177   case OR_Deleted:
4178     // There was no suitable conversion, or we found a deleted
4179     // conversion; continue with other checks.
4180     return false;
4181   }
4182
4183   llvm_unreachable("Invalid OverloadResult!");
4184 }
4185
4186 /// \brief Compute an implicit conversion sequence for reference
4187 /// initialization.
4188 static ImplicitConversionSequence
4189 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4190                  SourceLocation DeclLoc,
4191                  bool SuppressUserConversions,
4192                  bool AllowExplicit) {
4193   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4194
4195   // Most paths end in a failed conversion.
4196   ImplicitConversionSequence ICS;
4197   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4198
4199   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4200   QualType T2 = Init->getType();
4201
4202   // If the initializer is the address of an overloaded function, try
4203   // to resolve the overloaded function. If all goes well, T2 is the
4204   // type of the resulting function.
4205   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4206     DeclAccessPair Found;
4207     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4208                                                                 false, Found))
4209       T2 = Fn->getType();
4210   }
4211
4212   // Compute some basic properties of the types and the initializer.
4213   bool isRValRef = DeclType->isRValueReferenceType();
4214   bool DerivedToBase = false;
4215   bool ObjCConversion = false;
4216   bool ObjCLifetimeConversion = false;
4217   Expr::Classification InitCategory = Init->Classify(S.Context);
4218   Sema::ReferenceCompareResult RefRelationship
4219     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4220                                      ObjCConversion, ObjCLifetimeConversion);
4221
4222
4223   // C++0x [dcl.init.ref]p5:
4224   //   A reference to type "cv1 T1" is initialized by an expression
4225   //   of type "cv2 T2" as follows:
4226
4227   //     -- If reference is an lvalue reference and the initializer expression
4228   if (!isRValRef) {
4229     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4230     //        reference-compatible with "cv2 T2," or
4231     //
4232     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4233     if (InitCategory.isLValue() &&
4234         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4235       // C++ [over.ics.ref]p1:
4236       //   When a parameter of reference type binds directly (8.5.3)
4237       //   to an argument expression, the implicit conversion sequence
4238       //   is the identity conversion, unless the argument expression
4239       //   has a type that is a derived class of the parameter type,
4240       //   in which case the implicit conversion sequence is a
4241       //   derived-to-base Conversion (13.3.3.1).
4242       ICS.setStandard();
4243       ICS.Standard.First = ICK_Identity;
4244       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4245                          : ObjCConversion? ICK_Compatible_Conversion
4246                          : ICK_Identity;
4247       ICS.Standard.Third = ICK_Identity;
4248       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4249       ICS.Standard.setToType(0, T2);
4250       ICS.Standard.setToType(1, T1);
4251       ICS.Standard.setToType(2, T1);
4252       ICS.Standard.ReferenceBinding = true;
4253       ICS.Standard.DirectBinding = true;
4254       ICS.Standard.IsLvalueReference = !isRValRef;
4255       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4256       ICS.Standard.BindsToRvalue = false;
4257       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4258       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4259       ICS.Standard.CopyConstructor = nullptr;
4260       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4261
4262       // Nothing more to do: the inaccessibility/ambiguity check for
4263       // derived-to-base conversions is suppressed when we're
4264       // computing the implicit conversion sequence (C++
4265       // [over.best.ics]p2).
4266       return ICS;
4267     }
4268
4269     //       -- has a class type (i.e., T2 is a class type), where T1 is
4270     //          not reference-related to T2, and can be implicitly
4271     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4272     //          is reference-compatible with "cv3 T3" 92) (this
4273     //          conversion is selected by enumerating the applicable
4274     //          conversion functions (13.3.1.6) and choosing the best
4275     //          one through overload resolution (13.3)),
4276     if (!SuppressUserConversions && T2->isRecordType() &&
4277         !S.RequireCompleteType(DeclLoc, T2, 0) &&
4278         RefRelationship == Sema::Ref_Incompatible) {
4279       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4280                                    Init, T2, /*AllowRvalues=*/false,
4281                                    AllowExplicit))
4282         return ICS;
4283     }
4284   }
4285
4286   //     -- Otherwise, the reference shall be an lvalue reference to a
4287   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4288   //        shall be an rvalue reference.
4289   //
4290   // We actually handle one oddity of C++ [over.ics.ref] at this
4291   // point, which is that, due to p2 (which short-circuits reference
4292   // binding by only attempting a simple conversion for non-direct
4293   // bindings) and p3's strange wording, we allow a const volatile
4294   // reference to bind to an rvalue. Hence the check for the presence
4295   // of "const" rather than checking for "const" being the only
4296   // qualifier.
4297   // This is also the point where rvalue references and lvalue inits no longer
4298   // go together.
4299   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4300     return ICS;
4301
4302   //       -- If the initializer expression
4303   //
4304   //            -- is an xvalue, class prvalue, array prvalue or function
4305   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4306   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4307       (InitCategory.isXValue() ||
4308       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4309       (InitCategory.isLValue() && T2->isFunctionType()))) {
4310     ICS.setStandard();
4311     ICS.Standard.First = ICK_Identity;
4312     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4313                       : ObjCConversion? ICK_Compatible_Conversion
4314                       : ICK_Identity;
4315     ICS.Standard.Third = ICK_Identity;
4316     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4317     ICS.Standard.setToType(0, T2);
4318     ICS.Standard.setToType(1, T1);
4319     ICS.Standard.setToType(2, T1);
4320     ICS.Standard.ReferenceBinding = true;
4321     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4322     // binding unless we're binding to a class prvalue.
4323     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4324     // allow the use of rvalue references in C++98/03 for the benefit of
4325     // standard library implementors; therefore, we need the xvalue check here.
4326     ICS.Standard.DirectBinding =
4327       S.getLangOpts().CPlusPlus11 ||
4328       !(InitCategory.isPRValue() || T2->isRecordType());
4329     ICS.Standard.IsLvalueReference = !isRValRef;
4330     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4331     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4332     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4333     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4334     ICS.Standard.CopyConstructor = nullptr;
4335     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4336     return ICS;
4337   }
4338
4339   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4340   //               reference-related to T2, and can be implicitly converted to
4341   //               an xvalue, class prvalue, or function lvalue of type
4342   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4343   //               "cv3 T3",
4344   //
4345   //          then the reference is bound to the value of the initializer
4346   //          expression in the first case and to the result of the conversion
4347   //          in the second case (or, in either case, to an appropriate base
4348   //          class subobject).
4349   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4350       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4351       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4352                                Init, T2, /*AllowRvalues=*/true,
4353                                AllowExplicit)) {
4354     // In the second case, if the reference is an rvalue reference
4355     // and the second standard conversion sequence of the
4356     // user-defined conversion sequence includes an lvalue-to-rvalue
4357     // conversion, the program is ill-formed.
4358     if (ICS.isUserDefined() && isRValRef &&
4359         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4360       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4361
4362     return ICS;
4363   }
4364
4365   // A temporary of function type cannot be created; don't even try.
4366   if (T1->isFunctionType())
4367     return ICS;
4368
4369   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4370   //          initialized from the initializer expression using the
4371   //          rules for a non-reference copy initialization (8.5). The
4372   //          reference is then bound to the temporary. If T1 is
4373   //          reference-related to T2, cv1 must be the same
4374   //          cv-qualification as, or greater cv-qualification than,
4375   //          cv2; otherwise, the program is ill-formed.
4376   if (RefRelationship == Sema::Ref_Related) {
4377     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4378     // we would be reference-compatible or reference-compatible with
4379     // added qualification. But that wasn't the case, so the reference
4380     // initialization fails.
4381     //
4382     // Note that we only want to check address spaces and cvr-qualifiers here.
4383     // ObjC GC and lifetime qualifiers aren't important.
4384     Qualifiers T1Quals = T1.getQualifiers();
4385     Qualifiers T2Quals = T2.getQualifiers();
4386     T1Quals.removeObjCGCAttr();
4387     T1Quals.removeObjCLifetime();
4388     T2Quals.removeObjCGCAttr();
4389     T2Quals.removeObjCLifetime();
4390     if (!T1Quals.compatiblyIncludes(T2Quals))
4391       return ICS;
4392   }
4393
4394   // If at least one of the types is a class type, the types are not
4395   // related, and we aren't allowed any user conversions, the
4396   // reference binding fails. This case is important for breaking
4397   // recursion, since TryImplicitConversion below will attempt to
4398   // create a temporary through the use of a copy constructor.
4399   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4400       (T1->isRecordType() || T2->isRecordType()))
4401     return ICS;
4402
4403   // If T1 is reference-related to T2 and the reference is an rvalue
4404   // reference, the initializer expression shall not be an lvalue.
4405   if (RefRelationship >= Sema::Ref_Related &&
4406       isRValRef && Init->Classify(S.Context).isLValue())
4407     return ICS;
4408
4409   // C++ [over.ics.ref]p2:
4410   //   When a parameter of reference type is not bound directly to
4411   //   an argument expression, the conversion sequence is the one
4412   //   required to convert the argument expression to the
4413   //   underlying type of the reference according to
4414   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4415   //   to copy-initializing a temporary of the underlying type with
4416   //   the argument expression. Any difference in top-level
4417   //   cv-qualification is subsumed by the initialization itself
4418   //   and does not constitute a conversion.
4419   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4420                               /*AllowExplicit=*/false,
4421                               /*InOverloadResolution=*/false,
4422                               /*CStyle=*/false,
4423                               /*AllowObjCWritebackConversion=*/false,
4424                               /*AllowObjCConversionOnExplicit=*/false);
4425
4426   // Of course, that's still a reference binding.
4427   if (ICS.isStandard()) {
4428     ICS.Standard.ReferenceBinding = true;
4429     ICS.Standard.IsLvalueReference = !isRValRef;
4430     ICS.Standard.BindsToFunctionLvalue = false;
4431     ICS.Standard.BindsToRvalue = true;
4432     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4433     ICS.Standard.ObjCLifetimeConversionBinding = false;
4434   } else if (ICS.isUserDefined()) {
4435     const ReferenceType *LValRefType =
4436         ICS.UserDefined.ConversionFunction->getReturnType()
4437             ->getAs<LValueReferenceType>();
4438
4439     // C++ [over.ics.ref]p3:
4440     //   Except for an implicit object parameter, for which see 13.3.1, a
4441     //   standard conversion sequence cannot be formed if it requires [...]
4442     //   binding an rvalue reference to an lvalue other than a function
4443     //   lvalue.
4444     // Note that the function case is not possible here.
4445     if (DeclType->isRValueReferenceType() && LValRefType) {
4446       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4447       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4448       // reference to an rvalue!
4449       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4450       return ICS;
4451     }
4452
4453     ICS.UserDefined.Before.setAsIdentityConversion();
4454     ICS.UserDefined.After.ReferenceBinding = true;
4455     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4456     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4457     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4458     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4459     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4460   }
4461
4462   return ICS;
4463 }
4464
4465 static ImplicitConversionSequence
4466 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4467                       bool SuppressUserConversions,
4468                       bool InOverloadResolution,
4469                       bool AllowObjCWritebackConversion,
4470                       bool AllowExplicit = false);
4471
4472 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4473 /// initializer list From.
4474 static ImplicitConversionSequence
4475 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4476                   bool SuppressUserConversions,
4477                   bool InOverloadResolution,
4478                   bool AllowObjCWritebackConversion) {
4479   // C++11 [over.ics.list]p1:
4480   //   When an argument is an initializer list, it is not an expression and
4481   //   special rules apply for converting it to a parameter type.
4482
4483   ImplicitConversionSequence Result;
4484   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4485
4486   // We need a complete type for what follows. Incomplete types can never be
4487   // initialized from init lists.
4488   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4489     return Result;
4490
4491   // C++11 [over.ics.list]p2:
4492   //   If the parameter type is std::initializer_list<X> or "array of X" and
4493   //   all the elements can be implicitly converted to X, the implicit
4494   //   conversion sequence is the worst conversion necessary to convert an
4495   //   element of the list to X.
4496   bool toStdInitializerList = false;
4497   QualType X;
4498   if (ToType->isArrayType())
4499     X = S.Context.getAsArrayType(ToType)->getElementType();
4500   else
4501     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4502   if (!X.isNull()) {
4503     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4504       Expr *Init = From->getInit(i);
4505       ImplicitConversionSequence ICS =
4506           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4507                                 InOverloadResolution,
4508                                 AllowObjCWritebackConversion);
4509       // If a single element isn't convertible, fail.
4510       if (ICS.isBad()) {
4511         Result = ICS;
4512         break;
4513       }
4514       // Otherwise, look for the worst conversion.
4515       if (Result.isBad() ||
4516           CompareImplicitConversionSequences(S, ICS, Result) ==
4517               ImplicitConversionSequence::Worse)
4518         Result = ICS;
4519     }
4520
4521     // For an empty list, we won't have computed any conversion sequence.
4522     // Introduce the identity conversion sequence.
4523     if (From->getNumInits() == 0) {
4524       Result.setStandard();
4525       Result.Standard.setAsIdentityConversion();
4526       Result.Standard.setFromType(ToType);
4527       Result.Standard.setAllToTypes(ToType);
4528     }
4529
4530     Result.setStdInitializerListElement(toStdInitializerList);
4531     return Result;
4532   }
4533
4534   // C++11 [over.ics.list]p3:
4535   //   Otherwise, if the parameter is a non-aggregate class X and overload
4536   //   resolution chooses a single best constructor [...] the implicit
4537   //   conversion sequence is a user-defined conversion sequence. If multiple
4538   //   constructors are viable but none is better than the others, the
4539   //   implicit conversion sequence is a user-defined conversion sequence.
4540   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4541     // This function can deal with initializer lists.
4542     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4543                                     /*AllowExplicit=*/false,
4544                                     InOverloadResolution, /*CStyle=*/false,
4545                                     AllowObjCWritebackConversion,
4546                                     /*AllowObjCConversionOnExplicit=*/false);
4547   }
4548
4549   // C++11 [over.ics.list]p4:
4550   //   Otherwise, if the parameter has an aggregate type which can be
4551   //   initialized from the initializer list [...] the implicit conversion
4552   //   sequence is a user-defined conversion sequence.
4553   if (ToType->isAggregateType()) {
4554     // Type is an aggregate, argument is an init list. At this point it comes
4555     // down to checking whether the initialization works.
4556     // FIXME: Find out whether this parameter is consumed or not.
4557     InitializedEntity Entity =
4558         InitializedEntity::InitializeParameter(S.Context, ToType,
4559                                                /*Consumed=*/false);
4560     if (S.CanPerformCopyInitialization(Entity, From)) {
4561       Result.setUserDefined();
4562       Result.UserDefined.Before.setAsIdentityConversion();
4563       // Initializer lists don't have a type.
4564       Result.UserDefined.Before.setFromType(QualType());
4565       Result.UserDefined.Before.setAllToTypes(QualType());
4566
4567       Result.UserDefined.After.setAsIdentityConversion();
4568       Result.UserDefined.After.setFromType(ToType);
4569       Result.UserDefined.After.setAllToTypes(ToType);
4570       Result.UserDefined.ConversionFunction = nullptr;
4571     }
4572     return Result;
4573   }
4574
4575   // C++11 [over.ics.list]p5:
4576   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4577   if (ToType->isReferenceType()) {
4578     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4579     // mention initializer lists in any way. So we go by what list-
4580     // initialization would do and try to extrapolate from that.
4581
4582     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4583
4584     // If the initializer list has a single element that is reference-related
4585     // to the parameter type, we initialize the reference from that.
4586     if (From->getNumInits() == 1) {
4587       Expr *Init = From->getInit(0);
4588
4589       QualType T2 = Init->getType();
4590
4591       // If the initializer is the address of an overloaded function, try
4592       // to resolve the overloaded function. If all goes well, T2 is the
4593       // type of the resulting function.
4594       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4595         DeclAccessPair Found;
4596         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4597                                    Init, ToType, false, Found))
4598           T2 = Fn->getType();
4599       }
4600
4601       // Compute some basic properties of the types and the initializer.
4602       bool dummy1 = false;
4603       bool dummy2 = false;
4604       bool dummy3 = false;
4605       Sema::ReferenceCompareResult RefRelationship
4606         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4607                                          dummy2, dummy3);
4608
4609       if (RefRelationship >= Sema::Ref_Related) {
4610         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4611                                 SuppressUserConversions,
4612                                 /*AllowExplicit=*/false);
4613       }
4614     }
4615
4616     // Otherwise, we bind the reference to a temporary created from the
4617     // initializer list.
4618     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4619                                InOverloadResolution,
4620                                AllowObjCWritebackConversion);
4621     if (Result.isFailure())
4622       return Result;
4623     assert(!Result.isEllipsis() &&
4624            "Sub-initialization cannot result in ellipsis conversion.");
4625
4626     // Can we even bind to a temporary?
4627     if (ToType->isRValueReferenceType() ||
4628         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4629       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4630                                             Result.UserDefined.After;
4631       SCS.ReferenceBinding = true;
4632       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4633       SCS.BindsToRvalue = true;
4634       SCS.BindsToFunctionLvalue = false;
4635       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4636       SCS.ObjCLifetimeConversionBinding = false;
4637     } else
4638       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4639                     From, ToType);
4640     return Result;
4641   }
4642
4643   // C++11 [over.ics.list]p6:
4644   //   Otherwise, if the parameter type is not a class:
4645   if (!ToType->isRecordType()) {
4646     //    - if the initializer list has one element, the implicit conversion
4647     //      sequence is the one required to convert the element to the
4648     //      parameter type.
4649     unsigned NumInits = From->getNumInits();
4650     if (NumInits == 1)
4651       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4652                                      SuppressUserConversions,
4653                                      InOverloadResolution,
4654                                      AllowObjCWritebackConversion);
4655     //    - if the initializer list has no elements, the implicit conversion
4656     //      sequence is the identity conversion.
4657     else if (NumInits == 0) {
4658       Result.setStandard();
4659       Result.Standard.setAsIdentityConversion();
4660       Result.Standard.setFromType(ToType);
4661       Result.Standard.setAllToTypes(ToType);
4662     }
4663     return Result;
4664   }
4665
4666   // C++11 [over.ics.list]p7:
4667   //   In all cases other than those enumerated above, no conversion is possible
4668   return Result;
4669 }
4670
4671 /// TryCopyInitialization - Try to copy-initialize a value of type
4672 /// ToType from the expression From. Return the implicit conversion
4673 /// sequence required to pass this argument, which may be a bad
4674 /// conversion sequence (meaning that the argument cannot be passed to
4675 /// a parameter of this type). If @p SuppressUserConversions, then we
4676 /// do not permit any user-defined conversion sequences.
4677 static ImplicitConversionSequence
4678 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4679                       bool SuppressUserConversions,
4680                       bool InOverloadResolution,
4681                       bool AllowObjCWritebackConversion,
4682                       bool AllowExplicit) {
4683   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4684     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4685                              InOverloadResolution,AllowObjCWritebackConversion);
4686
4687   if (ToType->isReferenceType())
4688     return TryReferenceInit(S, From, ToType,
4689                             /*FIXME:*/From->getLocStart(),
4690                             SuppressUserConversions,
4691                             AllowExplicit);
4692
4693   return TryImplicitConversion(S, From, ToType,
4694                                SuppressUserConversions,
4695                                /*AllowExplicit=*/false,
4696                                InOverloadResolution,
4697                                /*CStyle=*/false,
4698                                AllowObjCWritebackConversion,
4699                                /*AllowObjCConversionOnExplicit=*/false);
4700 }
4701
4702 static bool TryCopyInitialization(const CanQualType FromQTy,
4703                                   const CanQualType ToQTy,
4704                                   Sema &S,
4705                                   SourceLocation Loc,
4706                                   ExprValueKind FromVK) {
4707   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4708   ImplicitConversionSequence ICS =
4709     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4710
4711   return !ICS.isBad();
4712 }
4713
4714 /// TryObjectArgumentInitialization - Try to initialize the object
4715 /// parameter of the given member function (@c Method) from the
4716 /// expression @p From.
4717 static ImplicitConversionSequence
4718 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4719                                 Expr::Classification FromClassification,
4720                                 CXXMethodDecl *Method,
4721                                 CXXRecordDecl *ActingContext) {
4722   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4723   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4724   //                 const volatile object.
4725   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4726     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4727   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4728
4729   // Set up the conversion sequence as a "bad" conversion, to allow us
4730   // to exit early.
4731   ImplicitConversionSequence ICS;
4732
4733   // We need to have an object of class type.
4734   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4735     FromType = PT->getPointeeType();
4736
4737     // When we had a pointer, it's implicitly dereferenced, so we
4738     // better have an lvalue.
4739     assert(FromClassification.isLValue());
4740   }
4741
4742   assert(FromType->isRecordType());
4743
4744   // C++0x [over.match.funcs]p4:
4745   //   For non-static member functions, the type of the implicit object
4746   //   parameter is
4747   //
4748   //     - "lvalue reference to cv X" for functions declared without a
4749   //        ref-qualifier or with the & ref-qualifier
4750   //     - "rvalue reference to cv X" for functions declared with the &&
4751   //        ref-qualifier
4752   //
4753   // where X is the class of which the function is a member and cv is the
4754   // cv-qualification on the member function declaration.
4755   //
4756   // However, when finding an implicit conversion sequence for the argument, we
4757   // are not allowed to create temporaries or perform user-defined conversions
4758   // (C++ [over.match.funcs]p5). We perform a simplified version of
4759   // reference binding here, that allows class rvalues to bind to
4760   // non-constant references.
4761
4762   // First check the qualifiers.
4763   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4764   if (ImplicitParamType.getCVRQualifiers()
4765                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4766       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4767     ICS.setBad(BadConversionSequence::bad_qualifiers,
4768                FromType, ImplicitParamType);
4769     return ICS;
4770   }
4771
4772   // Check that we have either the same type or a derived type. It
4773   // affects the conversion rank.
4774   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4775   ImplicitConversionKind SecondKind;
4776   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4777     SecondKind = ICK_Identity;
4778   } else if (S.IsDerivedFrom(FromType, ClassType))
4779     SecondKind = ICK_Derived_To_Base;
4780   else {
4781     ICS.setBad(BadConversionSequence::unrelated_class,
4782                FromType, ImplicitParamType);
4783     return ICS;
4784   }
4785
4786   // Check the ref-qualifier.
4787   switch (Method->getRefQualifier()) {
4788   case RQ_None:
4789     // Do nothing; we don't care about lvalueness or rvalueness.
4790     break;
4791
4792   case RQ_LValue:
4793     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4794       // non-const lvalue reference cannot bind to an rvalue
4795       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4796                  ImplicitParamType);
4797       return ICS;
4798     }
4799     break;
4800
4801   case RQ_RValue:
4802     if (!FromClassification.isRValue()) {
4803       // rvalue reference cannot bind to an lvalue
4804       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4805                  ImplicitParamType);
4806       return ICS;
4807     }
4808     break;
4809   }
4810
4811   // Success. Mark this as a reference binding.
4812   ICS.setStandard();
4813   ICS.Standard.setAsIdentityConversion();
4814   ICS.Standard.Second = SecondKind;
4815   ICS.Standard.setFromType(FromType);
4816   ICS.Standard.setAllToTypes(ImplicitParamType);
4817   ICS.Standard.ReferenceBinding = true;
4818   ICS.Standard.DirectBinding = true;
4819   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4820   ICS.Standard.BindsToFunctionLvalue = false;
4821   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4822   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4823     = (Method->getRefQualifier() == RQ_None);
4824   return ICS;
4825 }
4826
4827 /// PerformObjectArgumentInitialization - Perform initialization of
4828 /// the implicit object parameter for the given Method with the given
4829 /// expression.
4830 ExprResult
4831 Sema::PerformObjectArgumentInitialization(Expr *From,
4832                                           NestedNameSpecifier *Qualifier,
4833                                           NamedDecl *FoundDecl,
4834                                           CXXMethodDecl *Method) {
4835   QualType FromRecordType, DestType;
4836   QualType ImplicitParamRecordType  =
4837     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4838
4839   Expr::Classification FromClassification;
4840   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4841     FromRecordType = PT->getPointeeType();
4842     DestType = Method->getThisType(Context);
4843     FromClassification = Expr::Classification::makeSimpleLValue();
4844   } else {
4845     FromRecordType = From->getType();
4846     DestType = ImplicitParamRecordType;
4847     FromClassification = From->Classify(Context);
4848   }
4849
4850   // Note that we always use the true parent context when performing
4851   // the actual argument initialization.
4852   ImplicitConversionSequence ICS
4853     = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4854                                       Method, Method->getParent());
4855   if (ICS.isBad()) {
4856     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4857       Qualifiers FromQs = FromRecordType.getQualifiers();
4858       Qualifiers ToQs = DestType.getQualifiers();
4859       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4860       if (CVR) {
4861         Diag(From->getLocStart(),
4862              diag::err_member_function_call_bad_cvr)
4863           << Method->getDeclName() << FromRecordType << (CVR - 1)
4864           << From->getSourceRange();
4865         Diag(Method->getLocation(), diag::note_previous_decl)
4866           << Method->getDeclName();
4867         return ExprError();
4868       }
4869     }
4870
4871     return Diag(From->getLocStart(),
4872                 diag::err_implicit_object_parameter_init)
4873        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4874   }
4875
4876   if (ICS.Standard.Second == ICK_Derived_To_Base) {
4877     ExprResult FromRes =
4878       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4879     if (FromRes.isInvalid())
4880       return ExprError();
4881     From = FromRes.get();
4882   }
4883
4884   if (!Context.hasSameType(From->getType(), DestType))
4885     From = ImpCastExprToType(From, DestType, CK_NoOp,
4886                              From->getValueKind()).get();
4887   return From;
4888 }
4889
4890 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4891 /// expression From to bool (C++0x [conv]p3).
4892 static ImplicitConversionSequence
4893 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4894   return TryImplicitConversion(S, From, S.Context.BoolTy,
4895                                /*SuppressUserConversions=*/false,
4896                                /*AllowExplicit=*/true,
4897                                /*InOverloadResolution=*/false,
4898                                /*CStyle=*/false,
4899                                /*AllowObjCWritebackConversion=*/false,
4900                                /*AllowObjCConversionOnExplicit=*/false);
4901 }
4902
4903 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4904 /// of the expression From to bool (C++0x [conv]p3).
4905 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4906   if (checkPlaceholderForOverload(*this, From))
4907     return ExprError();
4908
4909   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4910   if (!ICS.isBad())
4911     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4912
4913   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4914     return Diag(From->getLocStart(),
4915                 diag::err_typecheck_bool_condition)
4916                   << From->getType() << From->getSourceRange();
4917   return ExprError();
4918 }
4919
4920 /// Check that the specified conversion is permitted in a converted constant
4921 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4922 /// is acceptable.
4923 static bool CheckConvertedConstantConversions(Sema &S,
4924                                               StandardConversionSequence &SCS) {
4925   // Since we know that the target type is an integral or unscoped enumeration
4926   // type, most conversion kinds are impossible. All possible First and Third
4927   // conversions are fine.
4928   switch (SCS.Second) {
4929   case ICK_Identity:
4930   case ICK_Integral_Promotion:
4931   case ICK_Integral_Conversion:
4932   case ICK_Zero_Event_Conversion:
4933     return true;
4934
4935   case ICK_Boolean_Conversion:
4936     // Conversion from an integral or unscoped enumeration type to bool is
4937     // classified as ICK_Boolean_Conversion, but it's also an integral
4938     // conversion, so it's permitted in a converted constant expression.
4939     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4940            SCS.getToType(2)->isBooleanType();
4941
4942   case ICK_Floating_Integral:
4943   case ICK_Complex_Real:
4944     return false;
4945
4946   case ICK_Lvalue_To_Rvalue:
4947   case ICK_Array_To_Pointer:
4948   case ICK_Function_To_Pointer:
4949   case ICK_NoReturn_Adjustment:
4950   case ICK_Qualification:
4951   case ICK_Compatible_Conversion:
4952   case ICK_Vector_Conversion:
4953   case ICK_Vector_Splat:
4954   case ICK_Derived_To_Base:
4955   case ICK_Pointer_Conversion:
4956   case ICK_Pointer_Member:
4957   case ICK_Block_Pointer_Conversion:
4958   case ICK_Writeback_Conversion:
4959   case ICK_Floating_Promotion:
4960   case ICK_Complex_Promotion:
4961   case ICK_Complex_Conversion:
4962   case ICK_Floating_Conversion:
4963   case ICK_TransparentUnionConversion:
4964     llvm_unreachable("unexpected second conversion kind");
4965
4966   case ICK_Num_Conversion_Kinds:
4967     break;
4968   }
4969
4970   llvm_unreachable("unknown conversion kind");
4971 }
4972
4973 /// CheckConvertedConstantExpression - Check that the expression From is a
4974 /// converted constant expression of type T, perform the conversion and produce
4975 /// the converted expression, per C++11 [expr.const]p3.
4976 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4977                                                   llvm::APSInt &Value,
4978                                                   CCEKind CCE) {
4979   assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4980   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4981
4982   if (checkPlaceholderForOverload(*this, From))
4983     return ExprError();
4984
4985   // C++11 [expr.const]p3 with proposed wording fixes:
4986   //  A converted constant expression of type T is a core constant expression,
4987   //  implicitly converted to a prvalue of type T, where the converted
4988   //  expression is a literal constant expression and the implicit conversion
4989   //  sequence contains only user-defined conversions, lvalue-to-rvalue
4990   //  conversions, integral promotions, and integral conversions other than
4991   //  narrowing conversions.
4992   ImplicitConversionSequence ICS =
4993     TryImplicitConversion(From, T,
4994                           /*SuppressUserConversions=*/false,
4995                           /*AllowExplicit=*/false,
4996                           /*InOverloadResolution=*/false,
4997                           /*CStyle=*/false,
4998                           /*AllowObjcWritebackConversion=*/false);
4999   StandardConversionSequence *SCS = nullptr;
5000   switch (ICS.getKind()) {
5001   case ImplicitConversionSequence::StandardConversion:
5002     if (!CheckConvertedConstantConversions(*this, ICS.Standard))
5003       return Diag(From->getLocStart(),
5004                   diag::err_typecheck_converted_constant_expression_disallowed)
5005                << From->getType() << From->getSourceRange() << T;
5006     SCS = &ICS.Standard;
5007     break;
5008   case ImplicitConversionSequence::UserDefinedConversion:
5009     // We are converting from class type to an integral or enumeration type, so
5010     // the Before sequence must be trivial.
5011     if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
5012       return Diag(From->getLocStart(),
5013                   diag::err_typecheck_converted_constant_expression_disallowed)
5014                << From->getType() << From->getSourceRange() << T;
5015     SCS = &ICS.UserDefined.After;
5016     break;
5017   case ImplicitConversionSequence::AmbiguousConversion:
5018   case ImplicitConversionSequence::BadConversion:
5019     if (!DiagnoseMultipleUserDefinedConversion(From, T))
5020       return Diag(From->getLocStart(),
5021                   diag::err_typecheck_converted_constant_expression)
5022                     << From->getType() << From->getSourceRange() << T;
5023     return ExprError();
5024
5025   case ImplicitConversionSequence::EllipsisConversion:
5026     llvm_unreachable("ellipsis conversion in converted constant expression");
5027   }
5028
5029   ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
5030   if (Result.isInvalid())
5031     return Result;
5032
5033   // Check for a narrowing implicit conversion.
5034   APValue PreNarrowingValue;
5035   QualType PreNarrowingType;
5036   switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5037                                 PreNarrowingType)) {
5038   case NK_Variable_Narrowing:
5039     // Implicit conversion to a narrower type, and the value is not a constant
5040     // expression. We'll diagnose this in a moment.
5041   case NK_Not_Narrowing:
5042     break;
5043
5044   case NK_Constant_Narrowing:
5045     Diag(From->getLocStart(), diag::ext_cce_narrowing)
5046       << CCE << /*Constant*/1
5047       << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
5048     break;
5049
5050   case NK_Type_Narrowing:
5051     Diag(From->getLocStart(), diag::ext_cce_narrowing)
5052       << CCE << /*Constant*/0 << From->getType() << T;
5053     break;
5054   }
5055
5056   // Check the expression is a constant expression.
5057   SmallVector<PartialDiagnosticAt, 8> Notes;
5058   Expr::EvalResult Eval;
5059   Eval.Diag = &Notes;
5060
5061   if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
5062     // The expression can't be folded, so we can't keep it at this position in
5063     // the AST.
5064     Result = ExprError();
5065   } else {
5066     Value = Eval.Val.getInt();
5067
5068     if (Notes.empty()) {
5069       // It's a constant expression.
5070       return Result;
5071     }
5072   }
5073
5074   // It's not a constant expression. Produce an appropriate diagnostic.
5075   if (Notes.size() == 1 &&
5076       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5077     Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5078   else {
5079     Diag(From->getLocStart(), diag::err_expr_not_cce)
5080       << CCE << From->getSourceRange();
5081     for (unsigned I = 0; I < Notes.size(); ++I)
5082       Diag(Notes[I].first, Notes[I].second);
5083   }
5084   return Result;
5085 }
5086
5087 /// dropPointerConversions - If the given standard conversion sequence
5088 /// involves any pointer conversions, remove them.  This may change
5089 /// the result type of the conversion sequence.
5090 static void dropPointerConversion(StandardConversionSequence &SCS) {
5091   if (SCS.Second == ICK_Pointer_Conversion) {
5092     SCS.Second = ICK_Identity;
5093     SCS.Third = ICK_Identity;
5094     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5095   }
5096 }
5097
5098 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5099 /// convert the expression From to an Objective-C pointer type.
5100 static ImplicitConversionSequence
5101 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5102   // Do an implicit conversion to 'id'.
5103   QualType Ty = S.Context.getObjCIdType();
5104   ImplicitConversionSequence ICS
5105     = TryImplicitConversion(S, From, Ty,
5106                             // FIXME: Are these flags correct?
5107                             /*SuppressUserConversions=*/false,
5108                             /*AllowExplicit=*/true,
5109                             /*InOverloadResolution=*/false,
5110                             /*CStyle=*/false,
5111                             /*AllowObjCWritebackConversion=*/false,
5112                             /*AllowObjCConversionOnExplicit=*/true);
5113
5114   // Strip off any final conversions to 'id'.
5115   switch (ICS.getKind()) {
5116   case ImplicitConversionSequence::BadConversion:
5117   case ImplicitConversionSequence::AmbiguousConversion:
5118   case ImplicitConversionSequence::EllipsisConversion:
5119     break;
5120
5121   case ImplicitConversionSequence::UserDefinedConversion:
5122     dropPointerConversion(ICS.UserDefined.After);
5123     break;
5124
5125   case ImplicitConversionSequence::StandardConversion:
5126     dropPointerConversion(ICS.Standard);
5127     break;
5128   }
5129
5130   return ICS;
5131 }
5132
5133 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5134 /// conversion of the expression From to an Objective-C pointer type.
5135 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5136   if (checkPlaceholderForOverload(*this, From))
5137     return ExprError();
5138
5139   QualType Ty = Context.getObjCIdType();
5140   ImplicitConversionSequence ICS =
5141     TryContextuallyConvertToObjCPointer(*this, From);
5142   if (!ICS.isBad())
5143     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5144   return ExprError();
5145 }
5146
5147 /// Determine whether the provided type is an integral type, or an enumeration
5148 /// type of a permitted flavor.
5149 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5150   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5151                                  : T->isIntegralOrUnscopedEnumerationType();
5152 }
5153
5154 static ExprResult
5155 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5156                             Sema::ContextualImplicitConverter &Converter,
5157                             QualType T, UnresolvedSetImpl &ViableConversions) {
5158
5159   if (Converter.Suppress)
5160     return ExprError();
5161
5162   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5163   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5164     CXXConversionDecl *Conv =
5165         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5166     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5167     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5168   }
5169   return From;
5170 }
5171
5172 static bool
5173 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5174                            Sema::ContextualImplicitConverter &Converter,
5175                            QualType T, bool HadMultipleCandidates,
5176                            UnresolvedSetImpl &ExplicitConversions) {
5177   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5178     DeclAccessPair Found = ExplicitConversions[0];
5179     CXXConversionDecl *Conversion =
5180         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5181
5182     // The user probably meant to invoke the given explicit
5183     // conversion; use it.
5184     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5185     std::string TypeStr;
5186     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5187
5188     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5189         << FixItHint::CreateInsertion(From->getLocStart(),
5190                                       "static_cast<" + TypeStr + ">(")
5191         << FixItHint::CreateInsertion(
5192                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5193     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5194
5195     // If we aren't in a SFINAE context, build a call to the
5196     // explicit conversion function.
5197     if (SemaRef.isSFINAEContext())
5198       return true;
5199
5200     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5201     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5202                                                        HadMultipleCandidates);
5203     if (Result.isInvalid())
5204       return true;
5205     // Record usage of conversion in an implicit cast.
5206     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5207                                     CK_UserDefinedConversion, Result.get(),
5208                                     nullptr, Result.get()->getValueKind());
5209   }
5210   return false;
5211 }
5212
5213 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5214                              Sema::ContextualImplicitConverter &Converter,
5215                              QualType T, bool HadMultipleCandidates,
5216                              DeclAccessPair &Found) {
5217   CXXConversionDecl *Conversion =
5218       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5219   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5220
5221   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5222   if (!Converter.SuppressConversion) {
5223     if (SemaRef.isSFINAEContext())
5224       return true;
5225
5226     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5227         << From->getSourceRange();
5228   }
5229
5230   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5231                                                      HadMultipleCandidates);
5232   if (Result.isInvalid())
5233     return true;
5234   // Record usage of conversion in an implicit cast.
5235   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5236                                   CK_UserDefinedConversion, Result.get(),
5237                                   nullptr, Result.get()->getValueKind());
5238   return false;
5239 }
5240
5241 static ExprResult finishContextualImplicitConversion(
5242     Sema &SemaRef, SourceLocation Loc, Expr *From,
5243     Sema::ContextualImplicitConverter &Converter) {
5244   if (!Converter.match(From->getType()) && !Converter.Suppress)
5245     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5246         << From->getSourceRange();
5247
5248   return SemaRef.DefaultLvalueConversion(From);
5249 }
5250
5251 static void
5252 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5253                                   UnresolvedSetImpl &ViableConversions,
5254                                   OverloadCandidateSet &CandidateSet) {
5255   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5256     DeclAccessPair FoundDecl = ViableConversions[I];
5257     NamedDecl *D = FoundDecl.getDecl();
5258     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5259     if (isa<UsingShadowDecl>(D))
5260       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5261
5262     CXXConversionDecl *Conv;
5263     FunctionTemplateDecl *ConvTemplate;
5264     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5265       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5266     else
5267       Conv = cast<CXXConversionDecl>(D);
5268
5269     if (ConvTemplate)
5270       SemaRef.AddTemplateConversionCandidate(
5271         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5272         /*AllowObjCConversionOnExplicit=*/false);
5273     else
5274       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5275                                      ToType, CandidateSet,
5276                                      /*AllowObjCConversionOnExplicit=*/false);
5277   }
5278 }
5279
5280 /// \brief Attempt to convert the given expression to a type which is accepted
5281 /// by the given converter.
5282 ///
5283 /// This routine will attempt to convert an expression of class type to a
5284 /// type accepted by the specified converter. In C++11 and before, the class
5285 /// must have a single non-explicit conversion function converting to a matching
5286 /// type. In C++1y, there can be multiple such conversion functions, but only
5287 /// one target type.
5288 ///
5289 /// \param Loc The source location of the construct that requires the
5290 /// conversion.
5291 ///
5292 /// \param From The expression we're converting from.
5293 ///
5294 /// \param Converter Used to control and diagnose the conversion process.
5295 ///
5296 /// \returns The expression, converted to an integral or enumeration type if
5297 /// successful.
5298 ExprResult Sema::PerformContextualImplicitConversion(
5299     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5300   // We can't perform any more checking for type-dependent expressions.
5301   if (From->isTypeDependent())
5302     return From;
5303
5304   // Process placeholders immediately.
5305   if (From->hasPlaceholderType()) {
5306     ExprResult result = CheckPlaceholderExpr(From);
5307     if (result.isInvalid())
5308       return result;
5309     From = result.get();
5310   }
5311
5312   // If the expression already has a matching type, we're golden.
5313   QualType T = From->getType();
5314   if (Converter.match(T))
5315     return DefaultLvalueConversion(From);
5316
5317   // FIXME: Check for missing '()' if T is a function type?
5318
5319   // We can only perform contextual implicit conversions on objects of class
5320   // type.
5321   const RecordType *RecordTy = T->getAs<RecordType>();
5322   if (!RecordTy || !getLangOpts().CPlusPlus) {
5323     if (!Converter.Suppress)
5324       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5325     return From;
5326   }
5327
5328   // We must have a complete class type.
5329   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5330     ContextualImplicitConverter &Converter;
5331     Expr *From;
5332
5333     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5334         : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5335
5336     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5337       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5338     }
5339   } IncompleteDiagnoser(Converter, From);
5340
5341   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5342     return From;
5343
5344   // Look for a conversion to an integral or enumeration type.
5345   UnresolvedSet<4>
5346       ViableConversions; // These are *potentially* viable in C++1y.
5347   UnresolvedSet<4> ExplicitConversions;
5348   std::pair<CXXRecordDecl::conversion_iterator,
5349             CXXRecordDecl::conversion_iterator> Conversions =
5350       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5351
5352   bool HadMultipleCandidates =
5353       (std::distance(Conversions.first, Conversions.second) > 1);
5354
5355   // To check that there is only one target type, in C++1y:
5356   QualType ToType;
5357   bool HasUniqueTargetType = true;
5358
5359   // Collect explicit or viable (potentially in C++1y) conversions.
5360   for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5361                                           E = Conversions.second;
5362        I != E; ++I) {
5363     NamedDecl *D = (*I)->getUnderlyingDecl();
5364     CXXConversionDecl *Conversion;
5365     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5366     if (ConvTemplate) {
5367       if (getLangOpts().CPlusPlus1y)
5368         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5369       else
5370         continue; // C++11 does not consider conversion operator templates(?).
5371     } else
5372       Conversion = cast<CXXConversionDecl>(D);
5373
5374     assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5375            "Conversion operator templates are considered potentially "
5376            "viable in C++1y");
5377
5378     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5379     if (Converter.match(CurToType) || ConvTemplate) {
5380
5381       if (Conversion->isExplicit()) {
5382         // FIXME: For C++1y, do we need this restriction?
5383         // cf. diagnoseNoViableConversion()
5384         if (!ConvTemplate)
5385           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5386       } else {
5387         if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5388           if (ToType.isNull())
5389             ToType = CurToType.getUnqualifiedType();
5390           else if (HasUniqueTargetType &&
5391                    (CurToType.getUnqualifiedType() != ToType))
5392             HasUniqueTargetType = false;
5393         }
5394         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5395       }
5396     }
5397   }
5398
5399   if (getLangOpts().CPlusPlus1y) {
5400     // C++1y [conv]p6:
5401     // ... An expression e of class type E appearing in such a context
5402     // is said to be contextually implicitly converted to a specified
5403     // type T and is well-formed if and only if e can be implicitly
5404     // converted to a type T that is determined as follows: E is searched
5405     // for conversion functions whose return type is cv T or reference to
5406     // cv T such that T is allowed by the context. There shall be
5407     // exactly one such T.
5408
5409     // If no unique T is found:
5410     if (ToType.isNull()) {
5411       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5412                                      HadMultipleCandidates,
5413                                      ExplicitConversions))
5414         return ExprError();
5415       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5416     }
5417
5418     // If more than one unique Ts are found:
5419     if (!HasUniqueTargetType)
5420       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5421                                          ViableConversions);
5422
5423     // If one unique T is found:
5424     // First, build a candidate set from the previously recorded
5425     // potentially viable conversions.
5426     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5427     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5428                                       CandidateSet);
5429
5430     // Then, perform overload resolution over the candidate set.
5431     OverloadCandidateSet::iterator Best;
5432     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5433     case OR_Success: {
5434       // Apply this conversion.
5435       DeclAccessPair Found =
5436           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5437       if (recordConversion(*this, Loc, From, Converter, T,
5438                            HadMultipleCandidates, Found))
5439         return ExprError();
5440       break;
5441     }
5442     case OR_Ambiguous:
5443       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5444                                          ViableConversions);
5445     case OR_No_Viable_Function:
5446       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5447                                      HadMultipleCandidates,
5448                                      ExplicitConversions))
5449         return ExprError();
5450     // fall through 'OR_Deleted' case.
5451     case OR_Deleted:
5452       // We'll complain below about a non-integral condition type.
5453       break;
5454     }
5455   } else {
5456     switch (ViableConversions.size()) {
5457     case 0: {
5458       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5459                                      HadMultipleCandidates,
5460                                      ExplicitConversions))
5461         return ExprError();
5462
5463       // We'll complain below about a non-integral condition type.
5464       break;
5465     }
5466     case 1: {
5467       // Apply this conversion.
5468       DeclAccessPair Found = ViableConversions[0];
5469       if (recordConversion(*this, Loc, From, Converter, T,
5470                            HadMultipleCandidates, Found))
5471         return ExprError();
5472       break;
5473     }
5474     default:
5475       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5476                                          ViableConversions);
5477     }
5478   }
5479
5480   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5481 }
5482
5483 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5484 /// an acceptable non-member overloaded operator for a call whose
5485 /// arguments have types T1 (and, if non-empty, T2). This routine
5486 /// implements the check in C++ [over.match.oper]p3b2 concerning
5487 /// enumeration types.
5488 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5489                                                    FunctionDecl *Fn,
5490                                                    ArrayRef<Expr *> Args) {
5491   QualType T1 = Args[0]->getType();
5492   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5493
5494   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5495     return true;
5496
5497   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5498     return true;
5499
5500   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5501   if (Proto->getNumParams() < 1)
5502     return false;
5503
5504   if (T1->isEnumeralType()) {
5505     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5506     if (Context.hasSameUnqualifiedType(T1, ArgType))
5507       return true;
5508   }
5509
5510   if (Proto->getNumParams() < 2)
5511     return false;
5512
5513   if (!T2.isNull() && T2->isEnumeralType()) {
5514     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5515     if (Context.hasSameUnqualifiedType(T2, ArgType))
5516       return true;
5517   }
5518
5519   return false;
5520 }
5521
5522 /// AddOverloadCandidate - Adds the given function to the set of
5523 /// candidate functions, using the given function call arguments.  If
5524 /// @p SuppressUserConversions, then don't allow user-defined
5525 /// conversions via constructors or conversion operators.
5526 ///
5527 /// \param PartialOverloading true if we are performing "partial" overloading
5528 /// based on an incomplete set of function arguments. This feature is used by
5529 /// code completion.
5530 void
5531 Sema::AddOverloadCandidate(FunctionDecl *Function,
5532                            DeclAccessPair FoundDecl,
5533                            ArrayRef<Expr *> Args,
5534                            OverloadCandidateSet &CandidateSet,
5535                            bool SuppressUserConversions,
5536                            bool PartialOverloading,
5537                            bool AllowExplicit) {
5538   const FunctionProtoType *Proto
5539     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5540   assert(Proto && "Functions without a prototype cannot be overloaded");
5541   assert(!Function->getDescribedFunctionTemplate() &&
5542          "Use AddTemplateOverloadCandidate for function templates");
5543
5544   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5545     if (!isa<CXXConstructorDecl>(Method)) {
5546       // If we get here, it's because we're calling a member function
5547       // that is named without a member access expression (e.g.,
5548       // "this->f") that was either written explicitly or created
5549       // implicitly. This can happen with a qualified call to a member
5550       // function, e.g., X::f(). We use an empty type for the implied
5551       // object argument (C++ [over.call.func]p3), and the acting context
5552       // is irrelevant.
5553       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5554                          QualType(), Expr::Classification::makeSimpleLValue(),
5555                          Args, CandidateSet, SuppressUserConversions);
5556       return;
5557     }
5558     // We treat a constructor like a non-member function, since its object
5559     // argument doesn't participate in overload resolution.
5560   }
5561
5562   if (!CandidateSet.isNewCandidate(Function))
5563     return;
5564
5565   // C++ [over.match.oper]p3:
5566   //   if no operand has a class type, only those non-member functions in the
5567   //   lookup set that have a first parameter of type T1 or "reference to
5568   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5569   //   is a right operand) a second parameter of type T2 or "reference to
5570   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5571   //   candidate functions.
5572   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5573       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5574     return;
5575
5576   // C++11 [class.copy]p11: [DR1402]
5577   //   A defaulted move constructor that is defined as deleted is ignored by
5578   //   overload resolution.
5579   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5580   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5581       Constructor->isMoveConstructor())
5582     return;
5583
5584   // Overload resolution is always an unevaluated context.
5585   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5586
5587   if (Constructor) {
5588     // C++ [class.copy]p3:
5589     //   A member function template is never instantiated to perform the copy
5590     //   of a class object to an object of its class type.
5591     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5592     if (Args.size() == 1 &&
5593         Constructor->isSpecializationCopyingObject() &&
5594         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5595          IsDerivedFrom(Args[0]->getType(), ClassType)))
5596       return;
5597   }
5598
5599   // Add this candidate
5600   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5601   Candidate.FoundDecl = FoundDecl;
5602   Candidate.Function = Function;
5603   Candidate.Viable = true;
5604   Candidate.IsSurrogate = false;
5605   Candidate.IgnoreObjectArgument = false;
5606   Candidate.ExplicitCallArguments = Args.size();
5607
5608   unsigned NumParams = Proto->getNumParams();
5609
5610   // (C++ 13.3.2p2): A candidate function having fewer than m
5611   // parameters is viable only if it has an ellipsis in its parameter
5612   // list (8.3.5).
5613   if ((Args.size() + (PartialOverloading && Args.size())) > NumParams &&
5614       !Proto->isVariadic()) {
5615     Candidate.Viable = false;
5616     Candidate.FailureKind = ovl_fail_too_many_arguments;
5617     return;
5618   }
5619
5620   // (C++ 13.3.2p2): A candidate function having more than m parameters
5621   // is viable only if the (m+1)st parameter has a default argument
5622   // (8.3.6). For the purposes of overload resolution, the
5623   // parameter list is truncated on the right, so that there are
5624   // exactly m parameters.
5625   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5626   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5627     // Not enough arguments.
5628     Candidate.Viable = false;
5629     Candidate.FailureKind = ovl_fail_too_few_arguments;
5630     return;
5631   }
5632
5633   // (CUDA B.1): Check for invalid calls between targets.
5634   if (getLangOpts().CUDA)
5635     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5636       if (CheckCUDATarget(Caller, Function)) {
5637         Candidate.Viable = false;
5638         Candidate.FailureKind = ovl_fail_bad_target;
5639         return;
5640       }
5641
5642   // Determine the implicit conversion sequences for each of the
5643   // arguments.
5644   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5645     if (ArgIdx < NumParams) {
5646       // (C++ 13.3.2p3): for F to be a viable function, there shall
5647       // exist for each argument an implicit conversion sequence
5648       // (13.3.3.1) that converts that argument to the corresponding
5649       // parameter of F.
5650       QualType ParamType = Proto->getParamType(ArgIdx);
5651       Candidate.Conversions[ArgIdx]
5652         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5653                                 SuppressUserConversions,
5654                                 /*InOverloadResolution=*/true,
5655                                 /*AllowObjCWritebackConversion=*/
5656                                   getLangOpts().ObjCAutoRefCount,
5657                                 AllowExplicit);
5658       if (Candidate.Conversions[ArgIdx].isBad()) {
5659         Candidate.Viable = false;
5660         Candidate.FailureKind = ovl_fail_bad_conversion;
5661         return;
5662       }
5663     } else {
5664       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5665       // argument for which there is no corresponding parameter is
5666       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5667       Candidate.Conversions[ArgIdx].setEllipsis();
5668     }
5669   }
5670
5671   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5672     Candidate.Viable = false;
5673     Candidate.FailureKind = ovl_fail_enable_if;
5674     Candidate.DeductionFailure.Data = FailedAttr;
5675     return;
5676   }
5677 }
5678
5679 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5680
5681 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5682                                   bool MissingImplicitThis) {
5683   // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5684   // we need to find the first failing one.
5685   if (!Function->hasAttrs())
5686     return nullptr;
5687   AttrVec Attrs = Function->getAttrs();
5688   AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5689                                        IsNotEnableIfAttr);
5690   if (Attrs.begin() == E)
5691     return nullptr;
5692   std::reverse(Attrs.begin(), E);
5693
5694   SFINAETrap Trap(*this);
5695
5696   // Convert the arguments.
5697   SmallVector<Expr *, 16> ConvertedArgs;
5698   bool InitializationFailed = false;
5699   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5700     if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5701         !cast<CXXMethodDecl>(Function)->isStatic() &&
5702         !isa<CXXConstructorDecl>(Function)) {
5703       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5704       ExprResult R =
5705         PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5706                                             Method, Method);
5707       if (R.isInvalid()) {
5708         InitializationFailed = true;
5709         break;
5710       }
5711       ConvertedArgs.push_back(R.get());
5712     } else {
5713       ExprResult R =
5714         PerformCopyInitialization(InitializedEntity::InitializeParameter(
5715                                                 Context,
5716                                                 Function->getParamDecl(i)),
5717                                   SourceLocation(),
5718                                   Args[i]);
5719       if (R.isInvalid()) {
5720         InitializationFailed = true;
5721         break;
5722       }
5723       ConvertedArgs.push_back(R.get());
5724     }
5725   }
5726
5727   if (InitializationFailed || Trap.hasErrorOccurred())
5728     return cast<EnableIfAttr>(Attrs[0]);
5729
5730   for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5731     APValue Result;
5732     EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5733     if (!EIA->getCond()->EvaluateWithSubstitution(
5734             Result, Context, Function,
5735             ArrayRef<const Expr*>(ConvertedArgs.data(),
5736                                   ConvertedArgs.size())) ||
5737         !Result.isInt() || !Result.getInt().getBoolValue()) {
5738       return EIA;
5739     }
5740   }
5741   return nullptr;
5742 }
5743
5744 /// \brief Add all of the function declarations in the given function set to
5745 /// the overload candidate set.
5746 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5747                                  ArrayRef<Expr *> Args,
5748                                  OverloadCandidateSet& CandidateSet,
5749                                  bool SuppressUserConversions,
5750                                TemplateArgumentListInfo *ExplicitTemplateArgs) {
5751   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5752     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5753     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5754       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5755         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5756                            cast<CXXMethodDecl>(FD)->getParent(),
5757                            Args[0]->getType(), Args[0]->Classify(Context),
5758                            Args.slice(1), CandidateSet,
5759                            SuppressUserConversions);
5760       else
5761         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5762                              SuppressUserConversions);
5763     } else {
5764       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5765       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5766           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5767         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5768                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5769                                    ExplicitTemplateArgs,
5770                                    Args[0]->getType(),
5771                                    Args[0]->Classify(Context), Args.slice(1),
5772                                    CandidateSet, SuppressUserConversions);
5773       else
5774         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5775                                      ExplicitTemplateArgs, Args,
5776                                      CandidateSet, SuppressUserConversions);
5777     }
5778   }
5779 }
5780
5781 /// AddMethodCandidate - Adds a named decl (which is some kind of
5782 /// method) as a method candidate to the given overload set.
5783 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5784                               QualType ObjectType,
5785                               Expr::Classification ObjectClassification,
5786                               ArrayRef<Expr *> Args,
5787                               OverloadCandidateSet& CandidateSet,
5788                               bool SuppressUserConversions) {
5789   NamedDecl *Decl = FoundDecl.getDecl();
5790   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5791
5792   if (isa<UsingShadowDecl>(Decl))
5793     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5794
5795   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5796     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5797            "Expected a member function template");
5798     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5799                                /*ExplicitArgs*/ nullptr,
5800                                ObjectType, ObjectClassification,
5801                                Args, CandidateSet,
5802                                SuppressUserConversions);
5803   } else {
5804     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5805                        ObjectType, ObjectClassification,
5806                        Args,
5807                        CandidateSet, SuppressUserConversions);
5808   }
5809 }
5810
5811 /// AddMethodCandidate - Adds the given C++ member function to the set
5812 /// of candidate functions, using the given function call arguments
5813 /// and the object argument (@c Object). For example, in a call
5814 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5815 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5816 /// allow user-defined conversions via constructors or conversion
5817 /// operators.
5818 void
5819 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5820                          CXXRecordDecl *ActingContext, QualType ObjectType,
5821                          Expr::Classification ObjectClassification,
5822                          ArrayRef<Expr *> Args,
5823                          OverloadCandidateSet &CandidateSet,
5824                          bool SuppressUserConversions) {
5825   const FunctionProtoType *Proto
5826     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5827   assert(Proto && "Methods without a prototype cannot be overloaded");
5828   assert(!isa<CXXConstructorDecl>(Method) &&
5829          "Use AddOverloadCandidate for constructors");
5830
5831   if (!CandidateSet.isNewCandidate(Method))
5832     return;
5833
5834   // C++11 [class.copy]p23: [DR1402]
5835   //   A defaulted move assignment operator that is defined as deleted is
5836   //   ignored by overload resolution.
5837   if (Method->isDefaulted() && Method->isDeleted() &&
5838       Method->isMoveAssignmentOperator())
5839     return;
5840
5841   // Overload resolution is always an unevaluated context.
5842   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5843
5844   // Add this candidate
5845   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5846   Candidate.FoundDecl = FoundDecl;
5847   Candidate.Function = Method;
5848   Candidate.IsSurrogate = false;
5849   Candidate.IgnoreObjectArgument = false;
5850   Candidate.ExplicitCallArguments = Args.size();
5851
5852   unsigned NumParams = Proto->getNumParams();
5853
5854   // (C++ 13.3.2p2): A candidate function having fewer than m
5855   // parameters is viable only if it has an ellipsis in its parameter
5856   // list (8.3.5).
5857   if (Args.size() > NumParams && !Proto->isVariadic()) {
5858     Candidate.Viable = false;
5859     Candidate.FailureKind = ovl_fail_too_many_arguments;
5860     return;
5861   }
5862
5863   // (C++ 13.3.2p2): A candidate function having more than m parameters
5864   // is viable only if the (m+1)st parameter has a default argument
5865   // (8.3.6). For the purposes of overload resolution, the
5866   // parameter list is truncated on the right, so that there are
5867   // exactly m parameters.
5868   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5869   if (Args.size() < MinRequiredArgs) {
5870     // Not enough arguments.
5871     Candidate.Viable = false;
5872     Candidate.FailureKind = ovl_fail_too_few_arguments;
5873     return;
5874   }
5875
5876   Candidate.Viable = true;
5877
5878   if (Method->isStatic() || ObjectType.isNull())
5879     // The implicit object argument is ignored.
5880     Candidate.IgnoreObjectArgument = true;
5881   else {
5882     // Determine the implicit conversion sequence for the object
5883     // parameter.
5884     Candidate.Conversions[0]
5885       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5886                                         Method, ActingContext);
5887     if (Candidate.Conversions[0].isBad()) {
5888       Candidate.Viable = false;
5889       Candidate.FailureKind = ovl_fail_bad_conversion;
5890       return;
5891     }
5892   }
5893
5894   // Determine the implicit conversion sequences for each of the
5895   // arguments.
5896   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5897     if (ArgIdx < NumParams) {
5898       // (C++ 13.3.2p3): for F to be a viable function, there shall
5899       // exist for each argument an implicit conversion sequence
5900       // (13.3.3.1) that converts that argument to the corresponding
5901       // parameter of F.
5902       QualType ParamType = Proto->getParamType(ArgIdx);
5903       Candidate.Conversions[ArgIdx + 1]
5904         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5905                                 SuppressUserConversions,
5906                                 /*InOverloadResolution=*/true,
5907                                 /*AllowObjCWritebackConversion=*/
5908                                   getLangOpts().ObjCAutoRefCount);
5909       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5910         Candidate.Viable = false;
5911         Candidate.FailureKind = ovl_fail_bad_conversion;
5912         return;
5913       }
5914     } else {
5915       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5916       // argument for which there is no corresponding parameter is
5917       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
5918       Candidate.Conversions[ArgIdx + 1].setEllipsis();
5919     }
5920   }
5921
5922   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
5923     Candidate.Viable = false;
5924     Candidate.FailureKind = ovl_fail_enable_if;
5925     Candidate.DeductionFailure.Data = FailedAttr;
5926     return;
5927   }
5928 }
5929
5930 /// \brief Add a C++ member function template as a candidate to the candidate
5931 /// set, using template argument deduction to produce an appropriate member
5932 /// function template specialization.
5933 void
5934 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5935                                  DeclAccessPair FoundDecl,
5936                                  CXXRecordDecl *ActingContext,
5937                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5938                                  QualType ObjectType,
5939                                  Expr::Classification ObjectClassification,
5940                                  ArrayRef<Expr *> Args,
5941                                  OverloadCandidateSet& CandidateSet,
5942                                  bool SuppressUserConversions) {
5943   if (!CandidateSet.isNewCandidate(MethodTmpl))
5944     return;
5945
5946   // C++ [over.match.funcs]p7:
5947   //   In each case where a candidate is a function template, candidate
5948   //   function template specializations are generated using template argument
5949   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5950   //   candidate functions in the usual way.113) A given name can refer to one
5951   //   or more function templates and also to a set of overloaded non-template
5952   //   functions. In such a case, the candidate functions generated from each
5953   //   function template are combined with the set of non-template candidate
5954   //   functions.
5955   TemplateDeductionInfo Info(CandidateSet.getLocation());
5956   FunctionDecl *Specialization = nullptr;
5957   if (TemplateDeductionResult Result
5958       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5959                                 Specialization, Info)) {
5960     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5961     Candidate.FoundDecl = FoundDecl;
5962     Candidate.Function = MethodTmpl->getTemplatedDecl();
5963     Candidate.Viable = false;
5964     Candidate.FailureKind = ovl_fail_bad_deduction;
5965     Candidate.IsSurrogate = false;
5966     Candidate.IgnoreObjectArgument = false;
5967     Candidate.ExplicitCallArguments = Args.size();
5968     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5969                                                           Info);
5970     return;
5971   }
5972
5973   // Add the function template specialization produced by template argument
5974   // deduction as a candidate.
5975   assert(Specialization && "Missing member function template specialization?");
5976   assert(isa<CXXMethodDecl>(Specialization) &&
5977          "Specialization is not a member function?");
5978   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5979                      ActingContext, ObjectType, ObjectClassification, Args,
5980                      CandidateSet, SuppressUserConversions);
5981 }
5982
5983 /// \brief Add a C++ function template specialization as a candidate
5984 /// in the candidate set, using template argument deduction to produce
5985 /// an appropriate function template specialization.
5986 void
5987 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5988                                    DeclAccessPair FoundDecl,
5989                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5990                                    ArrayRef<Expr *> Args,
5991                                    OverloadCandidateSet& CandidateSet,
5992                                    bool SuppressUserConversions) {
5993   if (!CandidateSet.isNewCandidate(FunctionTemplate))
5994     return;
5995
5996   // C++ [over.match.funcs]p7:
5997   //   In each case where a candidate is a function template, candidate
5998   //   function template specializations are generated using template argument
5999   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6000   //   candidate functions in the usual way.113) A given name can refer to one
6001   //   or more function templates and also to a set of overloaded non-template
6002   //   functions. In such a case, the candidate functions generated from each
6003   //   function template are combined with the set of non-template candidate
6004   //   functions.
6005   TemplateDeductionInfo Info(CandidateSet.getLocation());
6006   FunctionDecl *Specialization = nullptr;
6007   if (TemplateDeductionResult Result
6008         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6009                                   Specialization, Info)) {
6010     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6011     Candidate.FoundDecl = FoundDecl;
6012     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6013     Candidate.Viable = false;
6014     Candidate.FailureKind = ovl_fail_bad_deduction;
6015     Candidate.IsSurrogate = false;
6016     Candidate.IgnoreObjectArgument = false;
6017     Candidate.ExplicitCallArguments = Args.size();
6018     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6019                                                           Info);
6020     return;
6021   }
6022
6023   // Add the function template specialization produced by template argument
6024   // deduction as a candidate.
6025   assert(Specialization && "Missing function template specialization?");
6026   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6027                        SuppressUserConversions);
6028 }
6029
6030 /// Determine whether this is an allowable conversion from the result
6031 /// of an explicit conversion operator to the expected type, per C++
6032 /// [over.match.conv]p1 and [over.match.ref]p1.
6033 ///
6034 /// \param ConvType The return type of the conversion function.
6035 ///
6036 /// \param ToType The type we are converting to.
6037 ///
6038 /// \param AllowObjCPointerConversion Allow a conversion from one
6039 /// Objective-C pointer to another.
6040 ///
6041 /// \returns true if the conversion is allowable, false otherwise.
6042 static bool isAllowableExplicitConversion(Sema &S,
6043                                           QualType ConvType, QualType ToType,
6044                                           bool AllowObjCPointerConversion) {
6045   QualType ToNonRefType = ToType.getNonReferenceType();
6046
6047   // Easy case: the types are the same.
6048   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6049     return true;
6050
6051   // Allow qualification conversions.
6052   bool ObjCLifetimeConversion;
6053   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6054                                   ObjCLifetimeConversion))
6055     return true;
6056
6057   // If we're not allowed to consider Objective-C pointer conversions,
6058   // we're done.
6059   if (!AllowObjCPointerConversion)
6060     return false;
6061
6062   // Is this an Objective-C pointer conversion?
6063   bool IncompatibleObjC = false;
6064   QualType ConvertedType;
6065   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6066                                    IncompatibleObjC);
6067 }
6068                                           
6069 /// AddConversionCandidate - Add a C++ conversion function as a
6070 /// candidate in the candidate set (C++ [over.match.conv],
6071 /// C++ [over.match.copy]). From is the expression we're converting from,
6072 /// and ToType is the type that we're eventually trying to convert to
6073 /// (which may or may not be the same type as the type that the
6074 /// conversion function produces).
6075 void
6076 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6077                              DeclAccessPair FoundDecl,
6078                              CXXRecordDecl *ActingContext,
6079                              Expr *From, QualType ToType,
6080                              OverloadCandidateSet& CandidateSet,
6081                              bool AllowObjCConversionOnExplicit) {
6082   assert(!Conversion->getDescribedFunctionTemplate() &&
6083          "Conversion function templates use AddTemplateConversionCandidate");
6084   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6085   if (!CandidateSet.isNewCandidate(Conversion))
6086     return;
6087
6088   // If the conversion function has an undeduced return type, trigger its
6089   // deduction now.
6090   if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
6091     if (DeduceReturnType(Conversion, From->getExprLoc()))
6092       return;
6093     ConvType = Conversion->getConversionType().getNonReferenceType();
6094   }
6095
6096   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6097   // operator is only a candidate if its return type is the target type or
6098   // can be converted to the target type with a qualification conversion.
6099   if (Conversion->isExplicit() && 
6100       !isAllowableExplicitConversion(*this, ConvType, ToType, 
6101                                      AllowObjCConversionOnExplicit))
6102     return;
6103
6104   // Overload resolution is always an unevaluated context.
6105   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6106
6107   // Add this candidate
6108   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6109   Candidate.FoundDecl = FoundDecl;
6110   Candidate.Function = Conversion;
6111   Candidate.IsSurrogate = false;
6112   Candidate.IgnoreObjectArgument = false;
6113   Candidate.FinalConversion.setAsIdentityConversion();
6114   Candidate.FinalConversion.setFromType(ConvType);
6115   Candidate.FinalConversion.setAllToTypes(ToType);
6116   Candidate.Viable = true;
6117   Candidate.ExplicitCallArguments = 1;
6118
6119   // C++ [over.match.funcs]p4:
6120   //   For conversion functions, the function is considered to be a member of
6121   //   the class of the implicit implied object argument for the purpose of
6122   //   defining the type of the implicit object parameter.
6123   //
6124   // Determine the implicit conversion sequence for the implicit
6125   // object parameter.
6126   QualType ImplicitParamType = From->getType();
6127   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6128     ImplicitParamType = FromPtrType->getPointeeType();
6129   CXXRecordDecl *ConversionContext
6130     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6131
6132   Candidate.Conversions[0]
6133     = TryObjectArgumentInitialization(*this, From->getType(),
6134                                       From->Classify(Context),
6135                                       Conversion, ConversionContext);
6136
6137   if (Candidate.Conversions[0].isBad()) {
6138     Candidate.Viable = false;
6139     Candidate.FailureKind = ovl_fail_bad_conversion;
6140     return;
6141   }
6142
6143   // We won't go through a user-defined type conversion function to convert a
6144   // derived to base as such conversions are given Conversion Rank. They only
6145   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6146   QualType FromCanon
6147     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6148   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6149   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6150     Candidate.Viable = false;
6151     Candidate.FailureKind = ovl_fail_trivial_conversion;
6152     return;
6153   }
6154
6155   // To determine what the conversion from the result of calling the
6156   // conversion function to the type we're eventually trying to
6157   // convert to (ToType), we need to synthesize a call to the
6158   // conversion function and attempt copy initialization from it. This
6159   // makes sure that we get the right semantics with respect to
6160   // lvalues/rvalues and the type. Fortunately, we can allocate this
6161   // call on the stack and we don't need its arguments to be
6162   // well-formed.
6163   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6164                             VK_LValue, From->getLocStart());
6165   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6166                                 Context.getPointerType(Conversion->getType()),
6167                                 CK_FunctionToPointerDecay,
6168                                 &ConversionRef, VK_RValue);
6169
6170   QualType ConversionType = Conversion->getConversionType();
6171   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
6172     Candidate.Viable = false;
6173     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6174     return;
6175   }
6176
6177   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6178
6179   // Note that it is safe to allocate CallExpr on the stack here because
6180   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6181   // allocator).
6182   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6183   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6184                 From->getLocStart());
6185   ImplicitConversionSequence ICS =
6186     TryCopyInitialization(*this, &Call, ToType,
6187                           /*SuppressUserConversions=*/true,
6188                           /*InOverloadResolution=*/false,
6189                           /*AllowObjCWritebackConversion=*/false);
6190
6191   switch (ICS.getKind()) {
6192   case ImplicitConversionSequence::StandardConversion:
6193     Candidate.FinalConversion = ICS.Standard;
6194
6195     // C++ [over.ics.user]p3:
6196     //   If the user-defined conversion is specified by a specialization of a
6197     //   conversion function template, the second standard conversion sequence
6198     //   shall have exact match rank.
6199     if (Conversion->getPrimaryTemplate() &&
6200         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6201       Candidate.Viable = false;
6202       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6203       return;
6204     }
6205
6206     // C++0x [dcl.init.ref]p5:
6207     //    In the second case, if the reference is an rvalue reference and
6208     //    the second standard conversion sequence of the user-defined
6209     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6210     //    program is ill-formed.
6211     if (ToType->isRValueReferenceType() &&
6212         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6213       Candidate.Viable = false;
6214       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6215       return;
6216     }
6217     break;
6218
6219   case ImplicitConversionSequence::BadConversion:
6220     Candidate.Viable = false;
6221     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6222     return;
6223
6224   default:
6225     llvm_unreachable(
6226            "Can only end up with a standard conversion sequence or failure");
6227   }
6228
6229   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6230     Candidate.Viable = false;
6231     Candidate.FailureKind = ovl_fail_enable_if;
6232     Candidate.DeductionFailure.Data = FailedAttr;
6233     return;
6234   }
6235 }
6236
6237 /// \brief Adds a conversion function template specialization
6238 /// candidate to the overload set, using template argument deduction
6239 /// to deduce the template arguments of the conversion function
6240 /// template from the type that we are converting to (C++
6241 /// [temp.deduct.conv]).
6242 void
6243 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6244                                      DeclAccessPair FoundDecl,
6245                                      CXXRecordDecl *ActingDC,
6246                                      Expr *From, QualType ToType,
6247                                      OverloadCandidateSet &CandidateSet,
6248                                      bool AllowObjCConversionOnExplicit) {
6249   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6250          "Only conversion function templates permitted here");
6251
6252   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6253     return;
6254
6255   TemplateDeductionInfo Info(CandidateSet.getLocation());
6256   CXXConversionDecl *Specialization = nullptr;
6257   if (TemplateDeductionResult Result
6258         = DeduceTemplateArguments(FunctionTemplate, ToType,
6259                                   Specialization, Info)) {
6260     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6261     Candidate.FoundDecl = FoundDecl;
6262     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6263     Candidate.Viable = false;
6264     Candidate.FailureKind = ovl_fail_bad_deduction;
6265     Candidate.IsSurrogate = false;
6266     Candidate.IgnoreObjectArgument = false;
6267     Candidate.ExplicitCallArguments = 1;
6268     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6269                                                           Info);
6270     return;
6271   }
6272
6273   // Add the conversion function template specialization produced by
6274   // template argument deduction as a candidate.
6275   assert(Specialization && "Missing function template specialization?");
6276   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6277                          CandidateSet, AllowObjCConversionOnExplicit);
6278 }
6279
6280 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6281 /// converts the given @c Object to a function pointer via the
6282 /// conversion function @c Conversion, and then attempts to call it
6283 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6284 /// the type of function that we'll eventually be calling.
6285 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6286                                  DeclAccessPair FoundDecl,
6287                                  CXXRecordDecl *ActingContext,
6288                                  const FunctionProtoType *Proto,
6289                                  Expr *Object,
6290                                  ArrayRef<Expr *> Args,
6291                                  OverloadCandidateSet& CandidateSet) {
6292   if (!CandidateSet.isNewCandidate(Conversion))
6293     return;
6294
6295   // Overload resolution is always an unevaluated context.
6296   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6297
6298   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6299   Candidate.FoundDecl = FoundDecl;
6300   Candidate.Function = nullptr;
6301   Candidate.Surrogate = Conversion;
6302   Candidate.Viable = true;
6303   Candidate.IsSurrogate = true;
6304   Candidate.IgnoreObjectArgument = false;
6305   Candidate.ExplicitCallArguments = Args.size();
6306
6307   // Determine the implicit conversion sequence for the implicit
6308   // object parameter.
6309   ImplicitConversionSequence ObjectInit
6310     = TryObjectArgumentInitialization(*this, Object->getType(),
6311                                       Object->Classify(Context),
6312                                       Conversion, ActingContext);
6313   if (ObjectInit.isBad()) {
6314     Candidate.Viable = false;
6315     Candidate.FailureKind = ovl_fail_bad_conversion;
6316     Candidate.Conversions[0] = ObjectInit;
6317     return;
6318   }
6319
6320   // The first conversion is actually a user-defined conversion whose
6321   // first conversion is ObjectInit's standard conversion (which is
6322   // effectively a reference binding). Record it as such.
6323   Candidate.Conversions[0].setUserDefined();
6324   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6325   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6326   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6327   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6328   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6329   Candidate.Conversions[0].UserDefined.After
6330     = Candidate.Conversions[0].UserDefined.Before;
6331   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6332
6333   // Find the
6334   unsigned NumParams = Proto->getNumParams();
6335
6336   // (C++ 13.3.2p2): A candidate function having fewer than m
6337   // parameters is viable only if it has an ellipsis in its parameter
6338   // list (8.3.5).
6339   if (Args.size() > NumParams && !Proto->isVariadic()) {
6340     Candidate.Viable = false;
6341     Candidate.FailureKind = ovl_fail_too_many_arguments;
6342     return;
6343   }
6344
6345   // Function types don't have any default arguments, so just check if
6346   // we have enough arguments.
6347   if (Args.size() < NumParams) {
6348     // Not enough arguments.
6349     Candidate.Viable = false;
6350     Candidate.FailureKind = ovl_fail_too_few_arguments;
6351     return;
6352   }
6353
6354   // Determine the implicit conversion sequences for each of the
6355   // arguments.
6356   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6357     if (ArgIdx < NumParams) {
6358       // (C++ 13.3.2p3): for F to be a viable function, there shall
6359       // exist for each argument an implicit conversion sequence
6360       // (13.3.3.1) that converts that argument to the corresponding
6361       // parameter of F.
6362       QualType ParamType = Proto->getParamType(ArgIdx);
6363       Candidate.Conversions[ArgIdx + 1]
6364         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6365                                 /*SuppressUserConversions=*/false,
6366                                 /*InOverloadResolution=*/false,
6367                                 /*AllowObjCWritebackConversion=*/
6368                                   getLangOpts().ObjCAutoRefCount);
6369       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6370         Candidate.Viable = false;
6371         Candidate.FailureKind = ovl_fail_bad_conversion;
6372         return;
6373       }
6374     } else {
6375       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6376       // argument for which there is no corresponding parameter is
6377       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6378       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6379     }
6380   }
6381
6382   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6383     Candidate.Viable = false;
6384     Candidate.FailureKind = ovl_fail_enable_if;
6385     Candidate.DeductionFailure.Data = FailedAttr;
6386     return;
6387   }
6388 }
6389
6390 /// \brief Add overload candidates for overloaded operators that are
6391 /// member functions.
6392 ///
6393 /// Add the overloaded operator candidates that are member functions
6394 /// for the operator Op that was used in an operator expression such
6395 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6396 /// CandidateSet will store the added overload candidates. (C++
6397 /// [over.match.oper]).
6398 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6399                                        SourceLocation OpLoc,
6400                                        ArrayRef<Expr *> Args,
6401                                        OverloadCandidateSet& CandidateSet,
6402                                        SourceRange OpRange) {
6403   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6404
6405   // C++ [over.match.oper]p3:
6406   //   For a unary operator @ with an operand of a type whose
6407   //   cv-unqualified version is T1, and for a binary operator @ with
6408   //   a left operand of a type whose cv-unqualified version is T1 and
6409   //   a right operand of a type whose cv-unqualified version is T2,
6410   //   three sets of candidate functions, designated member
6411   //   candidates, non-member candidates and built-in candidates, are
6412   //   constructed as follows:
6413   QualType T1 = Args[0]->getType();
6414
6415   //     -- If T1 is a complete class type or a class currently being
6416   //        defined, the set of member candidates is the result of the
6417   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6418   //        the set of member candidates is empty.
6419   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6420     // Complete the type if it can be completed.
6421     RequireCompleteType(OpLoc, T1, 0);
6422     // If the type is neither complete nor being defined, bail out now.
6423     if (!T1Rec->getDecl()->getDefinition())
6424       return;
6425
6426     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6427     LookupQualifiedName(Operators, T1Rec->getDecl());
6428     Operators.suppressDiagnostics();
6429
6430     for (LookupResult::iterator Oper = Operators.begin(),
6431                              OperEnd = Operators.end();
6432          Oper != OperEnd;
6433          ++Oper)
6434       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6435                          Args[0]->Classify(Context), 
6436                          Args.slice(1),
6437                          CandidateSet,
6438                          /* SuppressUserConversions = */ false);
6439   }
6440 }
6441
6442 /// AddBuiltinCandidate - Add a candidate for a built-in
6443 /// operator. ResultTy and ParamTys are the result and parameter types
6444 /// of the built-in candidate, respectively. Args and NumArgs are the
6445 /// arguments being passed to the candidate. IsAssignmentOperator
6446 /// should be true when this built-in candidate is an assignment
6447 /// operator. NumContextualBoolArguments is the number of arguments
6448 /// (at the beginning of the argument list) that will be contextually
6449 /// converted to bool.
6450 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6451                                ArrayRef<Expr *> Args,
6452                                OverloadCandidateSet& CandidateSet,
6453                                bool IsAssignmentOperator,
6454                                unsigned NumContextualBoolArguments) {
6455   // Overload resolution is always an unevaluated context.
6456   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6457
6458   // Add this candidate
6459   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6460   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6461   Candidate.Function = nullptr;
6462   Candidate.IsSurrogate = false;
6463   Candidate.IgnoreObjectArgument = false;
6464   Candidate.BuiltinTypes.ResultTy = ResultTy;
6465   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6466     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6467
6468   // Determine the implicit conversion sequences for each of the
6469   // arguments.
6470   Candidate.Viable = true;
6471   Candidate.ExplicitCallArguments = Args.size();
6472   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6473     // C++ [over.match.oper]p4:
6474     //   For the built-in assignment operators, conversions of the
6475     //   left operand are restricted as follows:
6476     //     -- no temporaries are introduced to hold the left operand, and
6477     //     -- no user-defined conversions are applied to the left
6478     //        operand to achieve a type match with the left-most
6479     //        parameter of a built-in candidate.
6480     //
6481     // We block these conversions by turning off user-defined
6482     // conversions, since that is the only way that initialization of
6483     // a reference to a non-class type can occur from something that
6484     // is not of the same type.
6485     if (ArgIdx < NumContextualBoolArguments) {
6486       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6487              "Contextual conversion to bool requires bool type");
6488       Candidate.Conversions[ArgIdx]
6489         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6490     } else {
6491       Candidate.Conversions[ArgIdx]
6492         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6493                                 ArgIdx == 0 && IsAssignmentOperator,
6494                                 /*InOverloadResolution=*/false,
6495                                 /*AllowObjCWritebackConversion=*/
6496                                   getLangOpts().ObjCAutoRefCount);
6497     }
6498     if (Candidate.Conversions[ArgIdx].isBad()) {
6499       Candidate.Viable = false;
6500       Candidate.FailureKind = ovl_fail_bad_conversion;
6501       break;
6502     }
6503   }
6504 }
6505
6506 namespace {
6507
6508 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6509 /// candidate operator functions for built-in operators (C++
6510 /// [over.built]). The types are separated into pointer types and
6511 /// enumeration types.
6512 class BuiltinCandidateTypeSet  {
6513   /// TypeSet - A set of types.
6514   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6515
6516   /// PointerTypes - The set of pointer types that will be used in the
6517   /// built-in candidates.
6518   TypeSet PointerTypes;
6519
6520   /// MemberPointerTypes - The set of member pointer types that will be
6521   /// used in the built-in candidates.
6522   TypeSet MemberPointerTypes;
6523
6524   /// EnumerationTypes - The set of enumeration types that will be
6525   /// used in the built-in candidates.
6526   TypeSet EnumerationTypes;
6527
6528   /// \brief The set of vector types that will be used in the built-in
6529   /// candidates.
6530   TypeSet VectorTypes;
6531
6532   /// \brief A flag indicating non-record types are viable candidates
6533   bool HasNonRecordTypes;
6534
6535   /// \brief A flag indicating whether either arithmetic or enumeration types
6536   /// were present in the candidate set.
6537   bool HasArithmeticOrEnumeralTypes;
6538
6539   /// \brief A flag indicating whether the nullptr type was present in the
6540   /// candidate set.
6541   bool HasNullPtrType;
6542   
6543   /// Sema - The semantic analysis instance where we are building the
6544   /// candidate type set.
6545   Sema &SemaRef;
6546
6547   /// Context - The AST context in which we will build the type sets.
6548   ASTContext &Context;
6549
6550   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6551                                                const Qualifiers &VisibleQuals);
6552   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6553
6554 public:
6555   /// iterator - Iterates through the types that are part of the set.
6556   typedef TypeSet::iterator iterator;
6557
6558   BuiltinCandidateTypeSet(Sema &SemaRef)
6559     : HasNonRecordTypes(false),
6560       HasArithmeticOrEnumeralTypes(false),
6561       HasNullPtrType(false),
6562       SemaRef(SemaRef),
6563       Context(SemaRef.Context) { }
6564
6565   void AddTypesConvertedFrom(QualType Ty,
6566                              SourceLocation Loc,
6567                              bool AllowUserConversions,
6568                              bool AllowExplicitConversions,
6569                              const Qualifiers &VisibleTypeConversionsQuals);
6570
6571   /// pointer_begin - First pointer type found;
6572   iterator pointer_begin() { return PointerTypes.begin(); }
6573
6574   /// pointer_end - Past the last pointer type found;
6575   iterator pointer_end() { return PointerTypes.end(); }
6576
6577   /// member_pointer_begin - First member pointer type found;
6578   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6579
6580   /// member_pointer_end - Past the last member pointer type found;
6581   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6582
6583   /// enumeration_begin - First enumeration type found;
6584   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6585
6586   /// enumeration_end - Past the last enumeration type found;
6587   iterator enumeration_end() { return EnumerationTypes.end(); }
6588
6589   iterator vector_begin() { return VectorTypes.begin(); }
6590   iterator vector_end() { return VectorTypes.end(); }
6591
6592   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6593   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6594   bool hasNullPtrType() const { return HasNullPtrType; }
6595 };
6596
6597 } // end anonymous namespace
6598
6599 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6600 /// the set of pointer types along with any more-qualified variants of
6601 /// that type. For example, if @p Ty is "int const *", this routine
6602 /// will add "int const *", "int const volatile *", "int const
6603 /// restrict *", and "int const volatile restrict *" to the set of
6604 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6605 /// false otherwise.
6606 ///
6607 /// FIXME: what to do about extended qualifiers?
6608 bool
6609 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6610                                              const Qualifiers &VisibleQuals) {
6611
6612   // Insert this type.
6613   if (!PointerTypes.insert(Ty))
6614     return false;
6615
6616   QualType PointeeTy;
6617   const PointerType *PointerTy = Ty->getAs<PointerType>();
6618   bool buildObjCPtr = false;
6619   if (!PointerTy) {
6620     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6621     PointeeTy = PTy->getPointeeType();
6622     buildObjCPtr = true;
6623   } else {
6624     PointeeTy = PointerTy->getPointeeType();
6625   }
6626   
6627   // Don't add qualified variants of arrays. For one, they're not allowed
6628   // (the qualifier would sink to the element type), and for another, the
6629   // only overload situation where it matters is subscript or pointer +- int,
6630   // and those shouldn't have qualifier variants anyway.
6631   if (PointeeTy->isArrayType())
6632     return true;
6633   
6634   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6635   bool hasVolatile = VisibleQuals.hasVolatile();
6636   bool hasRestrict = VisibleQuals.hasRestrict();
6637
6638   // Iterate through all strict supersets of BaseCVR.
6639   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6640     if ((CVR | BaseCVR) != CVR) continue;
6641     // Skip over volatile if no volatile found anywhere in the types.
6642     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6643     
6644     // Skip over restrict if no restrict found anywhere in the types, or if
6645     // the type cannot be restrict-qualified.
6646     if ((CVR & Qualifiers::Restrict) &&
6647         (!hasRestrict ||
6648          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6649       continue;
6650   
6651     // Build qualified pointee type.
6652     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6653     
6654     // Build qualified pointer type.
6655     QualType QPointerTy;
6656     if (!buildObjCPtr)
6657       QPointerTy = Context.getPointerType(QPointeeTy);
6658     else
6659       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6660     
6661     // Insert qualified pointer type.
6662     PointerTypes.insert(QPointerTy);
6663   }
6664
6665   return true;
6666 }
6667
6668 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6669 /// to the set of pointer types along with any more-qualified variants of
6670 /// that type. For example, if @p Ty is "int const *", this routine
6671 /// will add "int const *", "int const volatile *", "int const
6672 /// restrict *", and "int const volatile restrict *" to the set of
6673 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6674 /// false otherwise.
6675 ///
6676 /// FIXME: what to do about extended qualifiers?
6677 bool
6678 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6679     QualType Ty) {
6680   // Insert this type.
6681   if (!MemberPointerTypes.insert(Ty))
6682     return false;
6683
6684   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6685   assert(PointerTy && "type was not a member pointer type!");
6686
6687   QualType PointeeTy = PointerTy->getPointeeType();
6688   // Don't add qualified variants of arrays. For one, they're not allowed
6689   // (the qualifier would sink to the element type), and for another, the
6690   // only overload situation where it matters is subscript or pointer +- int,
6691   // and those shouldn't have qualifier variants anyway.
6692   if (PointeeTy->isArrayType())
6693     return true;
6694   const Type *ClassTy = PointerTy->getClass();
6695
6696   // Iterate through all strict supersets of the pointee type's CVR
6697   // qualifiers.
6698   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6699   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6700     if ((CVR | BaseCVR) != CVR) continue;
6701
6702     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6703     MemberPointerTypes.insert(
6704       Context.getMemberPointerType(QPointeeTy, ClassTy));
6705   }
6706
6707   return true;
6708 }
6709
6710 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6711 /// Ty can be implicit converted to the given set of @p Types. We're
6712 /// primarily interested in pointer types and enumeration types. We also
6713 /// take member pointer types, for the conditional operator.
6714 /// AllowUserConversions is true if we should look at the conversion
6715 /// functions of a class type, and AllowExplicitConversions if we
6716 /// should also include the explicit conversion functions of a class
6717 /// type.
6718 void
6719 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6720                                                SourceLocation Loc,
6721                                                bool AllowUserConversions,
6722                                                bool AllowExplicitConversions,
6723                                                const Qualifiers &VisibleQuals) {
6724   // Only deal with canonical types.
6725   Ty = Context.getCanonicalType(Ty);
6726
6727   // Look through reference types; they aren't part of the type of an
6728   // expression for the purposes of conversions.
6729   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6730     Ty = RefTy->getPointeeType();
6731
6732   // If we're dealing with an array type, decay to the pointer.
6733   if (Ty->isArrayType())
6734     Ty = SemaRef.Context.getArrayDecayedType(Ty);
6735
6736   // Otherwise, we don't care about qualifiers on the type.
6737   Ty = Ty.getLocalUnqualifiedType();
6738
6739   // Flag if we ever add a non-record type.
6740   const RecordType *TyRec = Ty->getAs<RecordType>();
6741   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6742
6743   // Flag if we encounter an arithmetic type.
6744   HasArithmeticOrEnumeralTypes =
6745     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6746
6747   if (Ty->isObjCIdType() || Ty->isObjCClassType())
6748     PointerTypes.insert(Ty);
6749   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6750     // Insert our type, and its more-qualified variants, into the set
6751     // of types.
6752     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6753       return;
6754   } else if (Ty->isMemberPointerType()) {
6755     // Member pointers are far easier, since the pointee can't be converted.
6756     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6757       return;
6758   } else if (Ty->isEnumeralType()) {
6759     HasArithmeticOrEnumeralTypes = true;
6760     EnumerationTypes.insert(Ty);
6761   } else if (Ty->isVectorType()) {
6762     // We treat vector types as arithmetic types in many contexts as an
6763     // extension.
6764     HasArithmeticOrEnumeralTypes = true;
6765     VectorTypes.insert(Ty);
6766   } else if (Ty->isNullPtrType()) {
6767     HasNullPtrType = true;
6768   } else if (AllowUserConversions && TyRec) {
6769     // No conversion functions in incomplete types.
6770     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6771       return;
6772
6773     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6774     std::pair<CXXRecordDecl::conversion_iterator,
6775               CXXRecordDecl::conversion_iterator>
6776       Conversions = ClassDecl->getVisibleConversionFunctions();
6777     for (CXXRecordDecl::conversion_iterator
6778            I = Conversions.first, E = Conversions.second; I != E; ++I) {
6779       NamedDecl *D = I.getDecl();
6780       if (isa<UsingShadowDecl>(D))
6781         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6782
6783       // Skip conversion function templates; they don't tell us anything
6784       // about which builtin types we can convert to.
6785       if (isa<FunctionTemplateDecl>(D))
6786         continue;
6787
6788       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6789       if (AllowExplicitConversions || !Conv->isExplicit()) {
6790         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6791                               VisibleQuals);
6792       }
6793     }
6794   }
6795 }
6796
6797 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6798 /// the volatile- and non-volatile-qualified assignment operators for the
6799 /// given type to the candidate set.
6800 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6801                                                    QualType T,
6802                                                    ArrayRef<Expr *> Args,
6803                                     OverloadCandidateSet &CandidateSet) {
6804   QualType ParamTypes[2];
6805
6806   // T& operator=(T&, T)
6807   ParamTypes[0] = S.Context.getLValueReferenceType(T);
6808   ParamTypes[1] = T;
6809   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6810                         /*IsAssignmentOperator=*/true);
6811
6812   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6813     // volatile T& operator=(volatile T&, T)
6814     ParamTypes[0]
6815       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6816     ParamTypes[1] = T;
6817     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6818                           /*IsAssignmentOperator=*/true);
6819   }
6820 }
6821
6822 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6823 /// if any, found in visible type conversion functions found in ArgExpr's type.
6824 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6825     Qualifiers VRQuals;
6826     const RecordType *TyRec;
6827     if (const MemberPointerType *RHSMPType =
6828         ArgExpr->getType()->getAs<MemberPointerType>())
6829       TyRec = RHSMPType->getClass()->getAs<RecordType>();
6830     else
6831       TyRec = ArgExpr->getType()->getAs<RecordType>();
6832     if (!TyRec) {
6833       // Just to be safe, assume the worst case.
6834       VRQuals.addVolatile();
6835       VRQuals.addRestrict();
6836       return VRQuals;
6837     }
6838
6839     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6840     if (!ClassDecl->hasDefinition())
6841       return VRQuals;
6842
6843     std::pair<CXXRecordDecl::conversion_iterator,
6844               CXXRecordDecl::conversion_iterator>
6845       Conversions = ClassDecl->getVisibleConversionFunctions();
6846
6847     for (CXXRecordDecl::conversion_iterator
6848            I = Conversions.first, E = Conversions.second; I != E; ++I) {
6849       NamedDecl *D = I.getDecl();
6850       if (isa<UsingShadowDecl>(D))
6851         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6852       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6853         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6854         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6855           CanTy = ResTypeRef->getPointeeType();
6856         // Need to go down the pointer/mempointer chain and add qualifiers
6857         // as see them.
6858         bool done = false;
6859         while (!done) {
6860           if (CanTy.isRestrictQualified())
6861             VRQuals.addRestrict();
6862           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6863             CanTy = ResTypePtr->getPointeeType();
6864           else if (const MemberPointerType *ResTypeMPtr =
6865                 CanTy->getAs<MemberPointerType>())
6866             CanTy = ResTypeMPtr->getPointeeType();
6867           else
6868             done = true;
6869           if (CanTy.isVolatileQualified())
6870             VRQuals.addVolatile();
6871           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6872             return VRQuals;
6873         }
6874       }
6875     }
6876     return VRQuals;
6877 }
6878
6879 namespace {
6880
6881 /// \brief Helper class to manage the addition of builtin operator overload
6882 /// candidates. It provides shared state and utility methods used throughout
6883 /// the process, as well as a helper method to add each group of builtin
6884 /// operator overloads from the standard to a candidate set.
6885 class BuiltinOperatorOverloadBuilder {
6886   // Common instance state available to all overload candidate addition methods.
6887   Sema &S;
6888   ArrayRef<Expr *> Args;
6889   Qualifiers VisibleTypeConversionsQuals;
6890   bool HasArithmeticOrEnumeralCandidateType;
6891   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6892   OverloadCandidateSet &CandidateSet;
6893
6894   // Define some constants used to index and iterate over the arithemetic types
6895   // provided via the getArithmeticType() method below.
6896   // The "promoted arithmetic types" are the arithmetic
6897   // types are that preserved by promotion (C++ [over.built]p2).
6898   static const unsigned FirstIntegralType = 3;
6899   static const unsigned LastIntegralType = 20;
6900   static const unsigned FirstPromotedIntegralType = 3,
6901                         LastPromotedIntegralType = 11;
6902   static const unsigned FirstPromotedArithmeticType = 0,
6903                         LastPromotedArithmeticType = 11;
6904   static const unsigned NumArithmeticTypes = 20;
6905
6906   /// \brief Get the canonical type for a given arithmetic type index.
6907   CanQualType getArithmeticType(unsigned index) {
6908     assert(index < NumArithmeticTypes);
6909     static CanQualType ASTContext::* const
6910       ArithmeticTypes[NumArithmeticTypes] = {
6911       // Start of promoted types.
6912       &ASTContext::FloatTy,
6913       &ASTContext::DoubleTy,
6914       &ASTContext::LongDoubleTy,
6915
6916       // Start of integral types.
6917       &ASTContext::IntTy,
6918       &ASTContext::LongTy,
6919       &ASTContext::LongLongTy,
6920       &ASTContext::Int128Ty,
6921       &ASTContext::UnsignedIntTy,
6922       &ASTContext::UnsignedLongTy,
6923       &ASTContext::UnsignedLongLongTy,
6924       &ASTContext::UnsignedInt128Ty,
6925       // End of promoted types.
6926
6927       &ASTContext::BoolTy,
6928       &ASTContext::CharTy,
6929       &ASTContext::WCharTy,
6930       &ASTContext::Char16Ty,
6931       &ASTContext::Char32Ty,
6932       &ASTContext::SignedCharTy,
6933       &ASTContext::ShortTy,
6934       &ASTContext::UnsignedCharTy,
6935       &ASTContext::UnsignedShortTy,
6936       // End of integral types.
6937       // FIXME: What about complex? What about half?
6938     };
6939     return S.Context.*ArithmeticTypes[index];
6940   }
6941
6942   /// \brief Gets the canonical type resulting from the usual arithemetic
6943   /// converions for the given arithmetic types.
6944   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6945     // Accelerator table for performing the usual arithmetic conversions.
6946     // The rules are basically:
6947     //   - if either is floating-point, use the wider floating-point
6948     //   - if same signedness, use the higher rank
6949     //   - if same size, use unsigned of the higher rank
6950     //   - use the larger type
6951     // These rules, together with the axiom that higher ranks are
6952     // never smaller, are sufficient to precompute all of these results
6953     // *except* when dealing with signed types of higher rank.
6954     // (we could precompute SLL x UI for all known platforms, but it's
6955     // better not to make any assumptions).
6956     // We assume that int128 has a higher rank than long long on all platforms.
6957     enum PromotedType {
6958             Dep=-1,
6959             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6960     };
6961     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6962                                         [LastPromotedArithmeticType] = {
6963 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6964 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6965 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6966 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6967 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6968 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6969 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6970 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6971 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6972 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6973 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6974     };
6975
6976     assert(L < LastPromotedArithmeticType);
6977     assert(R < LastPromotedArithmeticType);
6978     int Idx = ConversionsTable[L][R];
6979
6980     // Fast path: the table gives us a concrete answer.
6981     if (Idx != Dep) return getArithmeticType(Idx);
6982
6983     // Slow path: we need to compare widths.
6984     // An invariant is that the signed type has higher rank.
6985     CanQualType LT = getArithmeticType(L),
6986                 RT = getArithmeticType(R);
6987     unsigned LW = S.Context.getIntWidth(LT),
6988              RW = S.Context.getIntWidth(RT);
6989
6990     // If they're different widths, use the signed type.
6991     if (LW > RW) return LT;
6992     else if (LW < RW) return RT;
6993
6994     // Otherwise, use the unsigned type of the signed type's rank.
6995     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6996     assert(L == SLL || R == SLL);
6997     return S.Context.UnsignedLongLongTy;
6998   }
6999
7000   /// \brief Helper method to factor out the common pattern of adding overloads
7001   /// for '++' and '--' builtin operators.
7002   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7003                                            bool HasVolatile,
7004                                            bool HasRestrict) {
7005     QualType ParamTypes[2] = {
7006       S.Context.getLValueReferenceType(CandidateTy),
7007       S.Context.IntTy
7008     };
7009
7010     // Non-volatile version.
7011     if (Args.size() == 1)
7012       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7013     else
7014       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7015
7016     // Use a heuristic to reduce number of builtin candidates in the set:
7017     // add volatile version only if there are conversions to a volatile type.
7018     if (HasVolatile) {
7019       ParamTypes[0] =
7020         S.Context.getLValueReferenceType(
7021           S.Context.getVolatileType(CandidateTy));
7022       if (Args.size() == 1)
7023         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7024       else
7025         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7026     }
7027     
7028     // Add restrict version only if there are conversions to a restrict type
7029     // and our candidate type is a non-restrict-qualified pointer.
7030     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7031         !CandidateTy.isRestrictQualified()) {
7032       ParamTypes[0]
7033         = S.Context.getLValueReferenceType(
7034             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7035       if (Args.size() == 1)
7036         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7037       else
7038         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7039       
7040       if (HasVolatile) {
7041         ParamTypes[0]
7042           = S.Context.getLValueReferenceType(
7043               S.Context.getCVRQualifiedType(CandidateTy,
7044                                             (Qualifiers::Volatile |
7045                                              Qualifiers::Restrict)));
7046         if (Args.size() == 1)
7047           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7048         else
7049           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7050       }
7051     }
7052
7053   }
7054
7055 public:
7056   BuiltinOperatorOverloadBuilder(
7057     Sema &S, ArrayRef<Expr *> Args,
7058     Qualifiers VisibleTypeConversionsQuals,
7059     bool HasArithmeticOrEnumeralCandidateType,
7060     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7061     OverloadCandidateSet &CandidateSet)
7062     : S(S), Args(Args),
7063       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7064       HasArithmeticOrEnumeralCandidateType(
7065         HasArithmeticOrEnumeralCandidateType),
7066       CandidateTypes(CandidateTypes),
7067       CandidateSet(CandidateSet) {
7068     // Validate some of our static helper constants in debug builds.
7069     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7070            "Invalid first promoted integral type");
7071     assert(getArithmeticType(LastPromotedIntegralType - 1)
7072              == S.Context.UnsignedInt128Ty &&
7073            "Invalid last promoted integral type");
7074     assert(getArithmeticType(FirstPromotedArithmeticType)
7075              == S.Context.FloatTy &&
7076            "Invalid first promoted arithmetic type");
7077     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7078              == S.Context.UnsignedInt128Ty &&
7079            "Invalid last promoted arithmetic type");
7080   }
7081
7082   // C++ [over.built]p3:
7083   //
7084   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7085   //   is either volatile or empty, there exist candidate operator
7086   //   functions of the form
7087   //
7088   //       VQ T&      operator++(VQ T&);
7089   //       T          operator++(VQ T&, int);
7090   //
7091   // C++ [over.built]p4:
7092   //
7093   //   For every pair (T, VQ), where T is an arithmetic type other
7094   //   than bool, and VQ is either volatile or empty, there exist
7095   //   candidate operator functions of the form
7096   //
7097   //       VQ T&      operator--(VQ T&);
7098   //       T          operator--(VQ T&, int);
7099   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7100     if (!HasArithmeticOrEnumeralCandidateType)
7101       return;
7102
7103     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7104          Arith < NumArithmeticTypes; ++Arith) {
7105       addPlusPlusMinusMinusStyleOverloads(
7106         getArithmeticType(Arith),
7107         VisibleTypeConversionsQuals.hasVolatile(),
7108         VisibleTypeConversionsQuals.hasRestrict());
7109     }
7110   }
7111
7112   // C++ [over.built]p5:
7113   //
7114   //   For every pair (T, VQ), where T is a cv-qualified or
7115   //   cv-unqualified object type, and VQ is either volatile or
7116   //   empty, there exist candidate operator functions of the form
7117   //
7118   //       T*VQ&      operator++(T*VQ&);
7119   //       T*VQ&      operator--(T*VQ&);
7120   //       T*         operator++(T*VQ&, int);
7121   //       T*         operator--(T*VQ&, int);
7122   void addPlusPlusMinusMinusPointerOverloads() {
7123     for (BuiltinCandidateTypeSet::iterator
7124               Ptr = CandidateTypes[0].pointer_begin(),
7125            PtrEnd = CandidateTypes[0].pointer_end();
7126          Ptr != PtrEnd; ++Ptr) {
7127       // Skip pointer types that aren't pointers to object types.
7128       if (!(*Ptr)->getPointeeType()->isObjectType())
7129         continue;
7130
7131       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7132         (!(*Ptr).isVolatileQualified() &&
7133          VisibleTypeConversionsQuals.hasVolatile()),
7134         (!(*Ptr).isRestrictQualified() &&
7135          VisibleTypeConversionsQuals.hasRestrict()));
7136     }
7137   }
7138
7139   // C++ [over.built]p6:
7140   //   For every cv-qualified or cv-unqualified object type T, there
7141   //   exist candidate operator functions of the form
7142   //
7143   //       T&         operator*(T*);
7144   //
7145   // C++ [over.built]p7:
7146   //   For every function type T that does not have cv-qualifiers or a
7147   //   ref-qualifier, there exist candidate operator functions of the form
7148   //       T&         operator*(T*);
7149   void addUnaryStarPointerOverloads() {
7150     for (BuiltinCandidateTypeSet::iterator
7151               Ptr = CandidateTypes[0].pointer_begin(),
7152            PtrEnd = CandidateTypes[0].pointer_end();
7153          Ptr != PtrEnd; ++Ptr) {
7154       QualType ParamTy = *Ptr;
7155       QualType PointeeTy = ParamTy->getPointeeType();
7156       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7157         continue;
7158
7159       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7160         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7161           continue;
7162
7163       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7164                             &ParamTy, Args, CandidateSet);
7165     }
7166   }
7167
7168   // C++ [over.built]p9:
7169   //  For every promoted arithmetic type T, there exist candidate
7170   //  operator functions of the form
7171   //
7172   //       T         operator+(T);
7173   //       T         operator-(T);
7174   void addUnaryPlusOrMinusArithmeticOverloads() {
7175     if (!HasArithmeticOrEnumeralCandidateType)
7176       return;
7177
7178     for (unsigned Arith = FirstPromotedArithmeticType;
7179          Arith < LastPromotedArithmeticType; ++Arith) {
7180       QualType ArithTy = getArithmeticType(Arith);
7181       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7182     }
7183
7184     // Extension: We also add these operators for vector types.
7185     for (BuiltinCandidateTypeSet::iterator
7186               Vec = CandidateTypes[0].vector_begin(),
7187            VecEnd = CandidateTypes[0].vector_end();
7188          Vec != VecEnd; ++Vec) {
7189       QualType VecTy = *Vec;
7190       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7191     }
7192   }
7193
7194   // C++ [over.built]p8:
7195   //   For every type T, there exist candidate operator functions of
7196   //   the form
7197   //
7198   //       T*         operator+(T*);
7199   void addUnaryPlusPointerOverloads() {
7200     for (BuiltinCandidateTypeSet::iterator
7201               Ptr = CandidateTypes[0].pointer_begin(),
7202            PtrEnd = CandidateTypes[0].pointer_end();
7203          Ptr != PtrEnd; ++Ptr) {
7204       QualType ParamTy = *Ptr;
7205       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7206     }
7207   }
7208
7209   // C++ [over.built]p10:
7210   //   For every promoted integral type T, there exist candidate
7211   //   operator functions of the form
7212   //
7213   //        T         operator~(T);
7214   void addUnaryTildePromotedIntegralOverloads() {
7215     if (!HasArithmeticOrEnumeralCandidateType)
7216       return;
7217
7218     for (unsigned Int = FirstPromotedIntegralType;
7219          Int < LastPromotedIntegralType; ++Int) {
7220       QualType IntTy = getArithmeticType(Int);
7221       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7222     }
7223
7224     // Extension: We also add this operator for vector types.
7225     for (BuiltinCandidateTypeSet::iterator
7226               Vec = CandidateTypes[0].vector_begin(),
7227            VecEnd = CandidateTypes[0].vector_end();
7228          Vec != VecEnd; ++Vec) {
7229       QualType VecTy = *Vec;
7230       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7231     }
7232   }
7233
7234   // C++ [over.match.oper]p16:
7235   //   For every pointer to member type T, there exist candidate operator
7236   //   functions of the form
7237   //
7238   //        bool operator==(T,T);
7239   //        bool operator!=(T,T);
7240   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7241     /// Set of (canonical) types that we've already handled.
7242     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7243
7244     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7245       for (BuiltinCandidateTypeSet::iterator
7246                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7247              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7248            MemPtr != MemPtrEnd;
7249            ++MemPtr) {
7250         // Don't add the same builtin candidate twice.
7251         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7252           continue;
7253
7254         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7255         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7256       }
7257     }
7258   }
7259
7260   // C++ [over.built]p15:
7261   //
7262   //   For every T, where T is an enumeration type, a pointer type, or 
7263   //   std::nullptr_t, there exist candidate operator functions of the form
7264   //
7265   //        bool       operator<(T, T);
7266   //        bool       operator>(T, T);
7267   //        bool       operator<=(T, T);
7268   //        bool       operator>=(T, T);
7269   //        bool       operator==(T, T);
7270   //        bool       operator!=(T, T);
7271   void addRelationalPointerOrEnumeralOverloads() {
7272     // C++ [over.match.oper]p3:
7273     //   [...]the built-in candidates include all of the candidate operator
7274     //   functions defined in 13.6 that, compared to the given operator, [...]
7275     //   do not have the same parameter-type-list as any non-template non-member
7276     //   candidate.
7277     //
7278     // Note that in practice, this only affects enumeration types because there
7279     // aren't any built-in candidates of record type, and a user-defined operator
7280     // must have an operand of record or enumeration type. Also, the only other
7281     // overloaded operator with enumeration arguments, operator=,
7282     // cannot be overloaded for enumeration types, so this is the only place
7283     // where we must suppress candidates like this.
7284     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7285       UserDefinedBinaryOperators;
7286
7287     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7288       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7289           CandidateTypes[ArgIdx].enumeration_end()) {
7290         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7291                                          CEnd = CandidateSet.end();
7292              C != CEnd; ++C) {
7293           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7294             continue;
7295
7296           if (C->Function->isFunctionTemplateSpecialization())
7297             continue;
7298
7299           QualType FirstParamType =
7300             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7301           QualType SecondParamType =
7302             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7303
7304           // Skip if either parameter isn't of enumeral type.
7305           if (!FirstParamType->isEnumeralType() ||
7306               !SecondParamType->isEnumeralType())
7307             continue;
7308
7309           // Add this operator to the set of known user-defined operators.
7310           UserDefinedBinaryOperators.insert(
7311             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7312                            S.Context.getCanonicalType(SecondParamType)));
7313         }
7314       }
7315     }
7316
7317     /// Set of (canonical) types that we've already handled.
7318     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7319
7320     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7321       for (BuiltinCandidateTypeSet::iterator
7322                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7323              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7324            Ptr != PtrEnd; ++Ptr) {
7325         // Don't add the same builtin candidate twice.
7326         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7327           continue;
7328
7329         QualType ParamTypes[2] = { *Ptr, *Ptr };
7330         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7331       }
7332       for (BuiltinCandidateTypeSet::iterator
7333                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7334              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7335            Enum != EnumEnd; ++Enum) {
7336         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7337
7338         // Don't add the same builtin candidate twice, or if a user defined
7339         // candidate exists.
7340         if (!AddedTypes.insert(CanonType) ||
7341             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7342                                                             CanonType)))
7343           continue;
7344
7345         QualType ParamTypes[2] = { *Enum, *Enum };
7346         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7347       }
7348       
7349       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7350         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7351         if (AddedTypes.insert(NullPtrTy) &&
7352             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7353                                                              NullPtrTy))) {
7354           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7355           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7356                                 CandidateSet);
7357         }
7358       }
7359     }
7360   }
7361
7362   // C++ [over.built]p13:
7363   //
7364   //   For every cv-qualified or cv-unqualified object type T
7365   //   there exist candidate operator functions of the form
7366   //
7367   //      T*         operator+(T*, ptrdiff_t);
7368   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7369   //      T*         operator-(T*, ptrdiff_t);
7370   //      T*         operator+(ptrdiff_t, T*);
7371   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7372   //
7373   // C++ [over.built]p14:
7374   //
7375   //   For every T, where T is a pointer to object type, there
7376   //   exist candidate operator functions of the form
7377   //
7378   //      ptrdiff_t  operator-(T, T);
7379   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7380     /// Set of (canonical) types that we've already handled.
7381     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7382
7383     for (int Arg = 0; Arg < 2; ++Arg) {
7384       QualType AsymetricParamTypes[2] = {
7385         S.Context.getPointerDiffType(),
7386         S.Context.getPointerDiffType(),
7387       };
7388       for (BuiltinCandidateTypeSet::iterator
7389                 Ptr = CandidateTypes[Arg].pointer_begin(),
7390              PtrEnd = CandidateTypes[Arg].pointer_end();
7391            Ptr != PtrEnd; ++Ptr) {
7392         QualType PointeeTy = (*Ptr)->getPointeeType();
7393         if (!PointeeTy->isObjectType())
7394           continue;
7395
7396         AsymetricParamTypes[Arg] = *Ptr;
7397         if (Arg == 0 || Op == OO_Plus) {
7398           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7399           // T* operator+(ptrdiff_t, T*);
7400           S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7401         }
7402         if (Op == OO_Minus) {
7403           // ptrdiff_t operator-(T, T);
7404           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7405             continue;
7406
7407           QualType ParamTypes[2] = { *Ptr, *Ptr };
7408           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7409                                 Args, CandidateSet);
7410         }
7411       }
7412     }
7413   }
7414
7415   // C++ [over.built]p12:
7416   //
7417   //   For every pair of promoted arithmetic types L and R, there
7418   //   exist candidate operator functions of the form
7419   //
7420   //        LR         operator*(L, R);
7421   //        LR         operator/(L, R);
7422   //        LR         operator+(L, R);
7423   //        LR         operator-(L, R);
7424   //        bool       operator<(L, R);
7425   //        bool       operator>(L, R);
7426   //        bool       operator<=(L, R);
7427   //        bool       operator>=(L, R);
7428   //        bool       operator==(L, R);
7429   //        bool       operator!=(L, R);
7430   //
7431   //   where LR is the result of the usual arithmetic conversions
7432   //   between types L and R.
7433   //
7434   // C++ [over.built]p24:
7435   //
7436   //   For every pair of promoted arithmetic types L and R, there exist
7437   //   candidate operator functions of the form
7438   //
7439   //        LR       operator?(bool, L, R);
7440   //
7441   //   where LR is the result of the usual arithmetic conversions
7442   //   between types L and R.
7443   // Our candidates ignore the first parameter.
7444   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7445     if (!HasArithmeticOrEnumeralCandidateType)
7446       return;
7447
7448     for (unsigned Left = FirstPromotedArithmeticType;
7449          Left < LastPromotedArithmeticType; ++Left) {
7450       for (unsigned Right = FirstPromotedArithmeticType;
7451            Right < LastPromotedArithmeticType; ++Right) {
7452         QualType LandR[2] = { getArithmeticType(Left),
7453                               getArithmeticType(Right) };
7454         QualType Result =
7455           isComparison ? S.Context.BoolTy
7456                        : getUsualArithmeticConversions(Left, Right);
7457         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7458       }
7459     }
7460
7461     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7462     // conditional operator for vector types.
7463     for (BuiltinCandidateTypeSet::iterator
7464               Vec1 = CandidateTypes[0].vector_begin(),
7465            Vec1End = CandidateTypes[0].vector_end();
7466          Vec1 != Vec1End; ++Vec1) {
7467       for (BuiltinCandidateTypeSet::iterator
7468                 Vec2 = CandidateTypes[1].vector_begin(),
7469              Vec2End = CandidateTypes[1].vector_end();
7470            Vec2 != Vec2End; ++Vec2) {
7471         QualType LandR[2] = { *Vec1, *Vec2 };
7472         QualType Result = S.Context.BoolTy;
7473         if (!isComparison) {
7474           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7475             Result = *Vec1;
7476           else
7477             Result = *Vec2;
7478         }
7479
7480         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7481       }
7482     }
7483   }
7484
7485   // C++ [over.built]p17:
7486   //
7487   //   For every pair of promoted integral types L and R, there
7488   //   exist candidate operator functions of the form
7489   //
7490   //      LR         operator%(L, R);
7491   //      LR         operator&(L, R);
7492   //      LR         operator^(L, R);
7493   //      LR         operator|(L, R);
7494   //      L          operator<<(L, R);
7495   //      L          operator>>(L, R);
7496   //
7497   //   where LR is the result of the usual arithmetic conversions
7498   //   between types L and R.
7499   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7500     if (!HasArithmeticOrEnumeralCandidateType)
7501       return;
7502
7503     for (unsigned Left = FirstPromotedIntegralType;
7504          Left < LastPromotedIntegralType; ++Left) {
7505       for (unsigned Right = FirstPromotedIntegralType;
7506            Right < LastPromotedIntegralType; ++Right) {
7507         QualType LandR[2] = { getArithmeticType(Left),
7508                               getArithmeticType(Right) };
7509         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7510             ? LandR[0]
7511             : getUsualArithmeticConversions(Left, Right);
7512         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7513       }
7514     }
7515   }
7516
7517   // C++ [over.built]p20:
7518   //
7519   //   For every pair (T, VQ), where T is an enumeration or
7520   //   pointer to member type and VQ is either volatile or
7521   //   empty, there exist candidate operator functions of the form
7522   //
7523   //        VQ T&      operator=(VQ T&, T);
7524   void addAssignmentMemberPointerOrEnumeralOverloads() {
7525     /// Set of (canonical) types that we've already handled.
7526     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7527
7528     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7529       for (BuiltinCandidateTypeSet::iterator
7530                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7531              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7532            Enum != EnumEnd; ++Enum) {
7533         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7534           continue;
7535
7536         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7537       }
7538
7539       for (BuiltinCandidateTypeSet::iterator
7540                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7541              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7542            MemPtr != MemPtrEnd; ++MemPtr) {
7543         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7544           continue;
7545
7546         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7547       }
7548     }
7549   }
7550
7551   // C++ [over.built]p19:
7552   //
7553   //   For every pair (T, VQ), where T is any type and VQ is either
7554   //   volatile or empty, there exist candidate operator functions
7555   //   of the form
7556   //
7557   //        T*VQ&      operator=(T*VQ&, T*);
7558   //
7559   // C++ [over.built]p21:
7560   //
7561   //   For every pair (T, VQ), where T is a cv-qualified or
7562   //   cv-unqualified object type and VQ is either volatile or
7563   //   empty, there exist candidate operator functions of the form
7564   //
7565   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7566   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7567   void addAssignmentPointerOverloads(bool isEqualOp) {
7568     /// Set of (canonical) types that we've already handled.
7569     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7570
7571     for (BuiltinCandidateTypeSet::iterator
7572               Ptr = CandidateTypes[0].pointer_begin(),
7573            PtrEnd = CandidateTypes[0].pointer_end();
7574          Ptr != PtrEnd; ++Ptr) {
7575       // If this is operator=, keep track of the builtin candidates we added.
7576       if (isEqualOp)
7577         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7578       else if (!(*Ptr)->getPointeeType()->isObjectType())
7579         continue;
7580
7581       // non-volatile version
7582       QualType ParamTypes[2] = {
7583         S.Context.getLValueReferenceType(*Ptr),
7584         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7585       };
7586       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7587                             /*IsAssigmentOperator=*/ isEqualOp);
7588
7589       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7590                           VisibleTypeConversionsQuals.hasVolatile();
7591       if (NeedVolatile) {
7592         // volatile version
7593         ParamTypes[0] =
7594           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7595         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7596                               /*IsAssigmentOperator=*/isEqualOp);
7597       }
7598       
7599       if (!(*Ptr).isRestrictQualified() &&
7600           VisibleTypeConversionsQuals.hasRestrict()) {
7601         // restrict version
7602         ParamTypes[0]
7603           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7604         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7605                               /*IsAssigmentOperator=*/isEqualOp);
7606         
7607         if (NeedVolatile) {
7608           // volatile restrict version
7609           ParamTypes[0]
7610             = S.Context.getLValueReferenceType(
7611                 S.Context.getCVRQualifiedType(*Ptr,
7612                                               (Qualifiers::Volatile |
7613                                                Qualifiers::Restrict)));
7614           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7615                                 /*IsAssigmentOperator=*/isEqualOp);
7616         }
7617       }
7618     }
7619
7620     if (isEqualOp) {
7621       for (BuiltinCandidateTypeSet::iterator
7622                 Ptr = CandidateTypes[1].pointer_begin(),
7623              PtrEnd = CandidateTypes[1].pointer_end();
7624            Ptr != PtrEnd; ++Ptr) {
7625         // Make sure we don't add the same candidate twice.
7626         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7627           continue;
7628
7629         QualType ParamTypes[2] = {
7630           S.Context.getLValueReferenceType(*Ptr),
7631           *Ptr,
7632         };
7633
7634         // non-volatile version
7635         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7636                               /*IsAssigmentOperator=*/true);
7637
7638         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7639                            VisibleTypeConversionsQuals.hasVolatile();
7640         if (NeedVolatile) {
7641           // volatile version
7642           ParamTypes[0] =
7643             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7644           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7645                                 /*IsAssigmentOperator=*/true);
7646         }
7647       
7648         if (!(*Ptr).isRestrictQualified() &&
7649             VisibleTypeConversionsQuals.hasRestrict()) {
7650           // restrict version
7651           ParamTypes[0]
7652             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7653           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7654                                 /*IsAssigmentOperator=*/true);
7655           
7656           if (NeedVolatile) {
7657             // volatile restrict version
7658             ParamTypes[0]
7659               = S.Context.getLValueReferenceType(
7660                   S.Context.getCVRQualifiedType(*Ptr,
7661                                                 (Qualifiers::Volatile |
7662                                                  Qualifiers::Restrict)));
7663             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7664                                   /*IsAssigmentOperator=*/true);
7665           }
7666         }
7667       }
7668     }
7669   }
7670
7671   // C++ [over.built]p18:
7672   //
7673   //   For every triple (L, VQ, R), where L is an arithmetic type,
7674   //   VQ is either volatile or empty, and R is a promoted
7675   //   arithmetic type, there exist candidate operator functions of
7676   //   the form
7677   //
7678   //        VQ L&      operator=(VQ L&, R);
7679   //        VQ L&      operator*=(VQ L&, R);
7680   //        VQ L&      operator/=(VQ L&, R);
7681   //        VQ L&      operator+=(VQ L&, R);
7682   //        VQ L&      operator-=(VQ L&, R);
7683   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7684     if (!HasArithmeticOrEnumeralCandidateType)
7685       return;
7686
7687     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7688       for (unsigned Right = FirstPromotedArithmeticType;
7689            Right < LastPromotedArithmeticType; ++Right) {
7690         QualType ParamTypes[2];
7691         ParamTypes[1] = getArithmeticType(Right);
7692
7693         // Add this built-in operator as a candidate (VQ is empty).
7694         ParamTypes[0] =
7695           S.Context.getLValueReferenceType(getArithmeticType(Left));
7696         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7697                               /*IsAssigmentOperator=*/isEqualOp);
7698
7699         // Add this built-in operator as a candidate (VQ is 'volatile').
7700         if (VisibleTypeConversionsQuals.hasVolatile()) {
7701           ParamTypes[0] =
7702             S.Context.getVolatileType(getArithmeticType(Left));
7703           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7704           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7705                                 /*IsAssigmentOperator=*/isEqualOp);
7706         }
7707       }
7708     }
7709
7710     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7711     for (BuiltinCandidateTypeSet::iterator
7712               Vec1 = CandidateTypes[0].vector_begin(),
7713            Vec1End = CandidateTypes[0].vector_end();
7714          Vec1 != Vec1End; ++Vec1) {
7715       for (BuiltinCandidateTypeSet::iterator
7716                 Vec2 = CandidateTypes[1].vector_begin(),
7717              Vec2End = CandidateTypes[1].vector_end();
7718            Vec2 != Vec2End; ++Vec2) {
7719         QualType ParamTypes[2];
7720         ParamTypes[1] = *Vec2;
7721         // Add this built-in operator as a candidate (VQ is empty).
7722         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7723         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7724                               /*IsAssigmentOperator=*/isEqualOp);
7725
7726         // Add this built-in operator as a candidate (VQ is 'volatile').
7727         if (VisibleTypeConversionsQuals.hasVolatile()) {
7728           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7729           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7730           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7731                                 /*IsAssigmentOperator=*/isEqualOp);
7732         }
7733       }
7734     }
7735   }
7736
7737   // C++ [over.built]p22:
7738   //
7739   //   For every triple (L, VQ, R), where L is an integral type, VQ
7740   //   is either volatile or empty, and R is a promoted integral
7741   //   type, there exist candidate operator functions of the form
7742   //
7743   //        VQ L&       operator%=(VQ L&, R);
7744   //        VQ L&       operator<<=(VQ L&, R);
7745   //        VQ L&       operator>>=(VQ L&, R);
7746   //        VQ L&       operator&=(VQ L&, R);
7747   //        VQ L&       operator^=(VQ L&, R);
7748   //        VQ L&       operator|=(VQ L&, R);
7749   void addAssignmentIntegralOverloads() {
7750     if (!HasArithmeticOrEnumeralCandidateType)
7751       return;
7752
7753     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7754       for (unsigned Right = FirstPromotedIntegralType;
7755            Right < LastPromotedIntegralType; ++Right) {
7756         QualType ParamTypes[2];
7757         ParamTypes[1] = getArithmeticType(Right);
7758
7759         // Add this built-in operator as a candidate (VQ is empty).
7760         ParamTypes[0] =
7761           S.Context.getLValueReferenceType(getArithmeticType(Left));
7762         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7763         if (VisibleTypeConversionsQuals.hasVolatile()) {
7764           // Add this built-in operator as a candidate (VQ is 'volatile').
7765           ParamTypes[0] = getArithmeticType(Left);
7766           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7767           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7768           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7769         }
7770       }
7771     }
7772   }
7773
7774   // C++ [over.operator]p23:
7775   //
7776   //   There also exist candidate operator functions of the form
7777   //
7778   //        bool        operator!(bool);
7779   //        bool        operator&&(bool, bool);
7780   //        bool        operator||(bool, bool);
7781   void addExclaimOverload() {
7782     QualType ParamTy = S.Context.BoolTy;
7783     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7784                           /*IsAssignmentOperator=*/false,
7785                           /*NumContextualBoolArguments=*/1);
7786   }
7787   void addAmpAmpOrPipePipeOverload() {
7788     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7789     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7790                           /*IsAssignmentOperator=*/false,
7791                           /*NumContextualBoolArguments=*/2);
7792   }
7793
7794   // C++ [over.built]p13:
7795   //
7796   //   For every cv-qualified or cv-unqualified object type T there
7797   //   exist candidate operator functions of the form
7798   //
7799   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7800   //        T&         operator[](T*, ptrdiff_t);
7801   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7802   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7803   //        T&         operator[](ptrdiff_t, T*);
7804   void addSubscriptOverloads() {
7805     for (BuiltinCandidateTypeSet::iterator
7806               Ptr = CandidateTypes[0].pointer_begin(),
7807            PtrEnd = CandidateTypes[0].pointer_end();
7808          Ptr != PtrEnd; ++Ptr) {
7809       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7810       QualType PointeeType = (*Ptr)->getPointeeType();
7811       if (!PointeeType->isObjectType())
7812         continue;
7813
7814       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7815
7816       // T& operator[](T*, ptrdiff_t)
7817       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7818     }
7819
7820     for (BuiltinCandidateTypeSet::iterator
7821               Ptr = CandidateTypes[1].pointer_begin(),
7822            PtrEnd = CandidateTypes[1].pointer_end();
7823          Ptr != PtrEnd; ++Ptr) {
7824       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7825       QualType PointeeType = (*Ptr)->getPointeeType();
7826       if (!PointeeType->isObjectType())
7827         continue;
7828
7829       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7830
7831       // T& operator[](ptrdiff_t, T*)
7832       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7833     }
7834   }
7835
7836   // C++ [over.built]p11:
7837   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7838   //    C1 is the same type as C2 or is a derived class of C2, T is an object
7839   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7840   //    there exist candidate operator functions of the form
7841   //
7842   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7843   //
7844   //    where CV12 is the union of CV1 and CV2.
7845   void addArrowStarOverloads() {
7846     for (BuiltinCandidateTypeSet::iterator
7847              Ptr = CandidateTypes[0].pointer_begin(),
7848            PtrEnd = CandidateTypes[0].pointer_end();
7849          Ptr != PtrEnd; ++Ptr) {
7850       QualType C1Ty = (*Ptr);
7851       QualType C1;
7852       QualifierCollector Q1;
7853       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7854       if (!isa<RecordType>(C1))
7855         continue;
7856       // heuristic to reduce number of builtin candidates in the set.
7857       // Add volatile/restrict version only if there are conversions to a
7858       // volatile/restrict type.
7859       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7860         continue;
7861       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7862         continue;
7863       for (BuiltinCandidateTypeSet::iterator
7864                 MemPtr = CandidateTypes[1].member_pointer_begin(),
7865              MemPtrEnd = CandidateTypes[1].member_pointer_end();
7866            MemPtr != MemPtrEnd; ++MemPtr) {
7867         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7868         QualType C2 = QualType(mptr->getClass(), 0);
7869         C2 = C2.getUnqualifiedType();
7870         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7871           break;
7872         QualType ParamTypes[2] = { *Ptr, *MemPtr };
7873         // build CV12 T&
7874         QualType T = mptr->getPointeeType();
7875         if (!VisibleTypeConversionsQuals.hasVolatile() &&
7876             T.isVolatileQualified())
7877           continue;
7878         if (!VisibleTypeConversionsQuals.hasRestrict() &&
7879             T.isRestrictQualified())
7880           continue;
7881         T = Q1.apply(S.Context, T);
7882         QualType ResultTy = S.Context.getLValueReferenceType(T);
7883         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7884       }
7885     }
7886   }
7887
7888   // Note that we don't consider the first argument, since it has been
7889   // contextually converted to bool long ago. The candidates below are
7890   // therefore added as binary.
7891   //
7892   // C++ [over.built]p25:
7893   //   For every type T, where T is a pointer, pointer-to-member, or scoped
7894   //   enumeration type, there exist candidate operator functions of the form
7895   //
7896   //        T        operator?(bool, T, T);
7897   //
7898   void addConditionalOperatorOverloads() {
7899     /// Set of (canonical) types that we've already handled.
7900     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7901
7902     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7903       for (BuiltinCandidateTypeSet::iterator
7904                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7905              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7906            Ptr != PtrEnd; ++Ptr) {
7907         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7908           continue;
7909
7910         QualType ParamTypes[2] = { *Ptr, *Ptr };
7911         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
7912       }
7913
7914       for (BuiltinCandidateTypeSet::iterator
7915                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7916              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7917            MemPtr != MemPtrEnd; ++MemPtr) {
7918         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7919           continue;
7920
7921         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7922         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
7923       }
7924
7925       if (S.getLangOpts().CPlusPlus11) {
7926         for (BuiltinCandidateTypeSet::iterator
7927                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7928                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7929              Enum != EnumEnd; ++Enum) {
7930           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7931             continue;
7932
7933           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7934             continue;
7935
7936           QualType ParamTypes[2] = { *Enum, *Enum };
7937           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
7938         }
7939       }
7940     }
7941   }
7942 };
7943
7944 } // end anonymous namespace
7945
7946 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
7947 /// operator overloads to the candidate set (C++ [over.built]), based
7948 /// on the operator @p Op and the arguments given. For example, if the
7949 /// operator is a binary '+', this routine might add "int
7950 /// operator+(int, int)" to cover integer addition.
7951 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7952                                         SourceLocation OpLoc,
7953                                         ArrayRef<Expr *> Args,
7954                                         OverloadCandidateSet &CandidateSet) {
7955   // Find all of the types that the arguments can convert to, but only
7956   // if the operator we're looking at has built-in operator candidates
7957   // that make use of these types. Also record whether we encounter non-record
7958   // candidate types or either arithmetic or enumeral candidate types.
7959   Qualifiers VisibleTypeConversionsQuals;
7960   VisibleTypeConversionsQuals.addConst();
7961   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7962     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7963
7964   bool HasNonRecordCandidateType = false;
7965   bool HasArithmeticOrEnumeralCandidateType = false;
7966   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7967   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7968     CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7969     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7970                                                  OpLoc,
7971                                                  true,
7972                                                  (Op == OO_Exclaim ||
7973                                                   Op == OO_AmpAmp ||
7974                                                   Op == OO_PipePipe),
7975                                                  VisibleTypeConversionsQuals);
7976     HasNonRecordCandidateType = HasNonRecordCandidateType ||
7977         CandidateTypes[ArgIdx].hasNonRecordTypes();
7978     HasArithmeticOrEnumeralCandidateType =
7979         HasArithmeticOrEnumeralCandidateType ||
7980         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7981   }
7982
7983   // Exit early when no non-record types have been added to the candidate set
7984   // for any of the arguments to the operator.
7985   //
7986   // We can't exit early for !, ||, or &&, since there we have always have
7987   // 'bool' overloads.
7988   if (!HasNonRecordCandidateType &&
7989       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7990     return;
7991
7992   // Setup an object to manage the common state for building overloads.
7993   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
7994                                            VisibleTypeConversionsQuals,
7995                                            HasArithmeticOrEnumeralCandidateType,
7996                                            CandidateTypes, CandidateSet);
7997
7998   // Dispatch over the operation to add in only those overloads which apply.
7999   switch (Op) {
8000   case OO_None:
8001   case NUM_OVERLOADED_OPERATORS:
8002     llvm_unreachable("Expected an overloaded operator");
8003
8004   case OO_New:
8005   case OO_Delete:
8006   case OO_Array_New:
8007   case OO_Array_Delete:
8008   case OO_Call:
8009     llvm_unreachable(
8010                     "Special operators don't use AddBuiltinOperatorCandidates");
8011
8012   case OO_Comma:
8013   case OO_Arrow:
8014     // C++ [over.match.oper]p3:
8015     //   -- For the operator ',', the unary operator '&', or the
8016     //      operator '->', the built-in candidates set is empty.
8017     break;
8018
8019   case OO_Plus: // '+' is either unary or binary
8020     if (Args.size() == 1)
8021       OpBuilder.addUnaryPlusPointerOverloads();
8022     // Fall through.
8023
8024   case OO_Minus: // '-' is either unary or binary
8025     if (Args.size() == 1) {
8026       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8027     } else {
8028       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8029       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8030     }
8031     break;
8032
8033   case OO_Star: // '*' is either unary or binary
8034     if (Args.size() == 1)
8035       OpBuilder.addUnaryStarPointerOverloads();
8036     else
8037       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8038     break;
8039
8040   case OO_Slash:
8041     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8042     break;
8043
8044   case OO_PlusPlus:
8045   case OO_MinusMinus:
8046     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8047     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8048     break;
8049
8050   case OO_EqualEqual:
8051   case OO_ExclaimEqual:
8052     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8053     // Fall through.
8054
8055   case OO_Less:
8056   case OO_Greater:
8057   case OO_LessEqual:
8058   case OO_GreaterEqual:
8059     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8060     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8061     break;
8062
8063   case OO_Percent:
8064   case OO_Caret:
8065   case OO_Pipe:
8066   case OO_LessLess:
8067   case OO_GreaterGreater:
8068     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8069     break;
8070
8071   case OO_Amp: // '&' is either unary or binary
8072     if (Args.size() == 1)
8073       // C++ [over.match.oper]p3:
8074       //   -- For the operator ',', the unary operator '&', or the
8075       //      operator '->', the built-in candidates set is empty.
8076       break;
8077
8078     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8079     break;
8080
8081   case OO_Tilde:
8082     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8083     break;
8084
8085   case OO_Equal:
8086     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8087     // Fall through.
8088
8089   case OO_PlusEqual:
8090   case OO_MinusEqual:
8091     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8092     // Fall through.
8093
8094   case OO_StarEqual:
8095   case OO_SlashEqual:
8096     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8097     break;
8098
8099   case OO_PercentEqual:
8100   case OO_LessLessEqual:
8101   case OO_GreaterGreaterEqual:
8102   case OO_AmpEqual:
8103   case OO_CaretEqual:
8104   case OO_PipeEqual:
8105     OpBuilder.addAssignmentIntegralOverloads();
8106     break;
8107
8108   case OO_Exclaim:
8109     OpBuilder.addExclaimOverload();
8110     break;
8111
8112   case OO_AmpAmp:
8113   case OO_PipePipe:
8114     OpBuilder.addAmpAmpOrPipePipeOverload();
8115     break;
8116
8117   case OO_Subscript:
8118     OpBuilder.addSubscriptOverloads();
8119     break;
8120
8121   case OO_ArrowStar:
8122     OpBuilder.addArrowStarOverloads();
8123     break;
8124
8125   case OO_Conditional:
8126     OpBuilder.addConditionalOperatorOverloads();
8127     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8128     break;
8129   }
8130 }
8131
8132 /// \brief Add function candidates found via argument-dependent lookup
8133 /// to the set of overloading candidates.
8134 ///
8135 /// This routine performs argument-dependent name lookup based on the
8136 /// given function name (which may also be an operator name) and adds
8137 /// all of the overload candidates found by ADL to the overload
8138 /// candidate set (C++ [basic.lookup.argdep]).
8139 void
8140 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8141                                            SourceLocation Loc,
8142                                            ArrayRef<Expr *> Args,
8143                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8144                                            OverloadCandidateSet& CandidateSet,
8145                                            bool PartialOverloading) {
8146   ADLResult Fns;
8147
8148   // FIXME: This approach for uniquing ADL results (and removing
8149   // redundant candidates from the set) relies on pointer-equality,
8150   // which means we need to key off the canonical decl.  However,
8151   // always going back to the canonical decl might not get us the
8152   // right set of default arguments.  What default arguments are
8153   // we supposed to consider on ADL candidates, anyway?
8154
8155   // FIXME: Pass in the explicit template arguments?
8156   ArgumentDependentLookup(Name, Loc, Args, Fns);
8157
8158   // Erase all of the candidates we already knew about.
8159   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8160                                    CandEnd = CandidateSet.end();
8161        Cand != CandEnd; ++Cand)
8162     if (Cand->Function) {
8163       Fns.erase(Cand->Function);
8164       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8165         Fns.erase(FunTmpl);
8166     }
8167
8168   // For each of the ADL candidates we found, add it to the overload
8169   // set.
8170   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8171     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8172     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8173       if (ExplicitTemplateArgs)
8174         continue;
8175
8176       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8177                            PartialOverloading);
8178     } else
8179       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8180                                    FoundDecl, ExplicitTemplateArgs,
8181                                    Args, CandidateSet);
8182   }
8183 }
8184
8185 /// isBetterOverloadCandidate - Determines whether the first overload
8186 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8187 bool
8188 isBetterOverloadCandidate(Sema &S,
8189                           const OverloadCandidate &Cand1,
8190                           const OverloadCandidate &Cand2,
8191                           SourceLocation Loc,
8192                           bool UserDefinedConversion) {
8193   // Define viable functions to be better candidates than non-viable
8194   // functions.
8195   if (!Cand2.Viable)
8196     return Cand1.Viable;
8197   else if (!Cand1.Viable)
8198     return false;
8199
8200   // C++ [over.match.best]p1:
8201   //
8202   //   -- if F is a static member function, ICS1(F) is defined such
8203   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8204   //      any function G, and, symmetrically, ICS1(G) is neither
8205   //      better nor worse than ICS1(F).
8206   unsigned StartArg = 0;
8207   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8208     StartArg = 1;
8209
8210   // C++ [over.match.best]p1:
8211   //   A viable function F1 is defined to be a better function than another
8212   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8213   //   conversion sequence than ICSi(F2), and then...
8214   unsigned NumArgs = Cand1.NumConversions;
8215   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8216   bool HasBetterConversion = false;
8217   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8218     switch (CompareImplicitConversionSequences(S,
8219                                                Cand1.Conversions[ArgIdx],
8220                                                Cand2.Conversions[ArgIdx])) {
8221     case ImplicitConversionSequence::Better:
8222       // Cand1 has a better conversion sequence.
8223       HasBetterConversion = true;
8224       break;
8225
8226     case ImplicitConversionSequence::Worse:
8227       // Cand1 can't be better than Cand2.
8228       return false;
8229
8230     case ImplicitConversionSequence::Indistinguishable:
8231       // Do nothing.
8232       break;
8233     }
8234   }
8235
8236   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8237   //       ICSj(F2), or, if not that,
8238   if (HasBetterConversion)
8239     return true;
8240
8241   //   -- the context is an initialization by user-defined conversion
8242   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8243   //      from the return type of F1 to the destination type (i.e.,
8244   //      the type of the entity being initialized) is a better
8245   //      conversion sequence than the standard conversion sequence
8246   //      from the return type of F2 to the destination type.
8247   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8248       isa<CXXConversionDecl>(Cand1.Function) &&
8249       isa<CXXConversionDecl>(Cand2.Function)) {
8250     // First check whether we prefer one of the conversion functions over the
8251     // other. This only distinguishes the results in non-standard, extension
8252     // cases such as the conversion from a lambda closure type to a function
8253     // pointer or block.
8254     ImplicitConversionSequence::CompareKind Result =
8255         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8256     if (Result == ImplicitConversionSequence::Indistinguishable)
8257       Result = CompareStandardConversionSequences(S,
8258                                                   Cand1.FinalConversion,
8259                                                   Cand2.FinalConversion);
8260
8261     if (Result != ImplicitConversionSequence::Indistinguishable)
8262       return Result == ImplicitConversionSequence::Better;
8263
8264     // FIXME: Compare kind of reference binding if conversion functions
8265     // convert to a reference type used in direct reference binding, per
8266     // C++14 [over.match.best]p1 section 2 bullet 3.
8267   }
8268
8269   //    -- F1 is a non-template function and F2 is a function template
8270   //       specialization, or, if not that,
8271   bool Cand1IsSpecialization = Cand1.Function &&
8272                                Cand1.Function->getPrimaryTemplate();
8273   bool Cand2IsSpecialization = Cand2.Function &&
8274                                Cand2.Function->getPrimaryTemplate();
8275   if (Cand1IsSpecialization != Cand2IsSpecialization)
8276     return Cand2IsSpecialization;
8277
8278   //   -- F1 and F2 are function template specializations, and the function
8279   //      template for F1 is more specialized than the template for F2
8280   //      according to the partial ordering rules described in 14.5.5.2, or,
8281   //      if not that,
8282   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8283     if (FunctionTemplateDecl *BetterTemplate
8284           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8285                                          Cand2.Function->getPrimaryTemplate(),
8286                                          Loc,
8287                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8288                                                              : TPOC_Call,
8289                                          Cand1.ExplicitCallArguments,
8290                                          Cand2.ExplicitCallArguments))
8291       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8292   }
8293
8294   // Check for enable_if value-based overload resolution.
8295   if (Cand1.Function && Cand2.Function &&
8296       (Cand1.Function->hasAttr<EnableIfAttr>() ||
8297        Cand2.Function->hasAttr<EnableIfAttr>())) {
8298     // FIXME: The next several lines are just
8299     // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8300     // instead of reverse order which is how they're stored in the AST.
8301     AttrVec Cand1Attrs;
8302     if (Cand1.Function->hasAttrs()) {
8303       Cand1Attrs = Cand1.Function->getAttrs();
8304       Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8305                                       IsNotEnableIfAttr),
8306                        Cand1Attrs.end());
8307       std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
8308     }
8309
8310     AttrVec Cand2Attrs;
8311     if (Cand2.Function->hasAttrs()) {
8312       Cand2Attrs = Cand2.Function->getAttrs();
8313       Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8314                                       IsNotEnableIfAttr),
8315                        Cand2Attrs.end());
8316       std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
8317     }
8318
8319     // Candidate 1 is better if it has strictly more attributes and
8320     // the common sequence is identical.
8321     if (Cand1Attrs.size() <= Cand2Attrs.size())
8322       return false;
8323
8324     auto Cand1I = Cand1Attrs.begin();
8325     for (auto &Cand2A : Cand2Attrs) {
8326       auto &Cand1A = *Cand1I++;
8327       llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8328       cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8329                                                      S.getASTContext(), true);
8330       cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8331                                                      S.getASTContext(), true);
8332       if (Cand1ID != Cand2ID)
8333         return false;
8334     }
8335
8336     return true;
8337   }
8338
8339   return false;
8340 }
8341
8342 /// \brief Computes the best viable function (C++ 13.3.3)
8343 /// within an overload candidate set.
8344 ///
8345 /// \param Loc The location of the function name (or operator symbol) for
8346 /// which overload resolution occurs.
8347 ///
8348 /// \param Best If overload resolution was successful or found a deleted
8349 /// function, \p Best points to the candidate function found.
8350 ///
8351 /// \returns The result of overload resolution.
8352 OverloadingResult
8353 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8354                                          iterator &Best,
8355                                          bool UserDefinedConversion) {
8356   // Find the best viable function.
8357   Best = end();
8358   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8359     if (Cand->Viable)
8360       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8361                                                      UserDefinedConversion))
8362         Best = Cand;
8363   }
8364
8365   // If we didn't find any viable functions, abort.
8366   if (Best == end())
8367     return OR_No_Viable_Function;
8368
8369   // Make sure that this function is better than every other viable
8370   // function. If not, we have an ambiguity.
8371   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8372     if (Cand->Viable &&
8373         Cand != Best &&
8374         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8375                                    UserDefinedConversion)) {
8376       Best = end();
8377       return OR_Ambiguous;
8378     }
8379   }
8380
8381   // Best is the best viable function.
8382   if (Best->Function &&
8383       (Best->Function->isDeleted() ||
8384        S.isFunctionConsideredUnavailable(Best->Function)))
8385     return OR_Deleted;
8386
8387   return OR_Success;
8388 }
8389
8390 namespace {
8391
8392 enum OverloadCandidateKind {
8393   oc_function,
8394   oc_method,
8395   oc_constructor,
8396   oc_function_template,
8397   oc_method_template,
8398   oc_constructor_template,
8399   oc_implicit_default_constructor,
8400   oc_implicit_copy_constructor,
8401   oc_implicit_move_constructor,
8402   oc_implicit_copy_assignment,
8403   oc_implicit_move_assignment,
8404   oc_implicit_inherited_constructor
8405 };
8406
8407 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8408                                                 FunctionDecl *Fn,
8409                                                 std::string &Description) {
8410   bool isTemplate = false;
8411
8412   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8413     isTemplate = true;
8414     Description = S.getTemplateArgumentBindingsText(
8415       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8416   }
8417
8418   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8419     if (!Ctor->isImplicit())
8420       return isTemplate ? oc_constructor_template : oc_constructor;
8421
8422     if (Ctor->getInheritedConstructor())
8423       return oc_implicit_inherited_constructor;
8424
8425     if (Ctor->isDefaultConstructor())
8426       return oc_implicit_default_constructor;
8427
8428     if (Ctor->isMoveConstructor())
8429       return oc_implicit_move_constructor;
8430
8431     assert(Ctor->isCopyConstructor() &&
8432            "unexpected sort of implicit constructor");
8433     return oc_implicit_copy_constructor;
8434   }
8435
8436   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8437     // This actually gets spelled 'candidate function' for now, but
8438     // it doesn't hurt to split it out.
8439     if (!Meth->isImplicit())
8440       return isTemplate ? oc_method_template : oc_method;
8441
8442     if (Meth->isMoveAssignmentOperator())
8443       return oc_implicit_move_assignment;
8444
8445     if (Meth->isCopyAssignmentOperator())
8446       return oc_implicit_copy_assignment;
8447
8448     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8449     return oc_method;
8450   }
8451
8452   return isTemplate ? oc_function_template : oc_function;
8453 }
8454
8455 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8456   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8457   if (!Ctor) return;
8458
8459   Ctor = Ctor->getInheritedConstructor();
8460   if (!Ctor) return;
8461
8462   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8463 }
8464
8465 } // end anonymous namespace
8466
8467 // Notes the location of an overload candidate.
8468 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8469   std::string FnDesc;
8470   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8471   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8472                              << (unsigned) K << FnDesc;
8473   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8474   Diag(Fn->getLocation(), PD);
8475   MaybeEmitInheritedConstructorNote(*this, Fn);
8476 }
8477
8478 // Notes the location of all overload candidates designated through
8479 // OverloadedExpr
8480 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8481   assert(OverloadedExpr->getType() == Context.OverloadTy);
8482
8483   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8484   OverloadExpr *OvlExpr = Ovl.Expression;
8485
8486   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8487                             IEnd = OvlExpr->decls_end(); 
8488        I != IEnd; ++I) {
8489     if (FunctionTemplateDecl *FunTmpl = 
8490                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8491       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8492     } else if (FunctionDecl *Fun 
8493                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8494       NoteOverloadCandidate(Fun, DestType);
8495     }
8496   }
8497 }
8498
8499 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8500 /// "lead" diagnostic; it will be given two arguments, the source and
8501 /// target types of the conversion.
8502 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8503                                  Sema &S,
8504                                  SourceLocation CaretLoc,
8505                                  const PartialDiagnostic &PDiag) const {
8506   S.Diag(CaretLoc, PDiag)
8507     << Ambiguous.getFromType() << Ambiguous.getToType();
8508   // FIXME: The note limiting machinery is borrowed from
8509   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8510   // refactoring here.
8511   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8512   unsigned CandsShown = 0;
8513   AmbiguousConversionSequence::const_iterator I, E;
8514   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8515     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8516       break;
8517     ++CandsShown;
8518     S.NoteOverloadCandidate(*I);
8519   }
8520   if (I != E)
8521     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8522 }
8523
8524 namespace {
8525
8526 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8527   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8528   assert(Conv.isBad());
8529   assert(Cand->Function && "for now, candidate must be a function");
8530   FunctionDecl *Fn = Cand->Function;
8531
8532   // There's a conversion slot for the object argument if this is a
8533   // non-constructor method.  Note that 'I' corresponds the
8534   // conversion-slot index.
8535   bool isObjectArgument = false;
8536   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8537     if (I == 0)
8538       isObjectArgument = true;
8539     else
8540       I--;
8541   }
8542
8543   std::string FnDesc;
8544   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8545
8546   Expr *FromExpr = Conv.Bad.FromExpr;
8547   QualType FromTy = Conv.Bad.getFromType();
8548   QualType ToTy = Conv.Bad.getToType();
8549
8550   if (FromTy == S.Context.OverloadTy) {
8551     assert(FromExpr && "overload set argument came from implicit argument?");
8552     Expr *E = FromExpr->IgnoreParens();
8553     if (isa<UnaryOperator>(E))
8554       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8555     DeclarationName Name = cast<OverloadExpr>(E)->getName();
8556
8557     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8558       << (unsigned) FnKind << FnDesc
8559       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8560       << ToTy << Name << I+1;
8561     MaybeEmitInheritedConstructorNote(S, Fn);
8562     return;
8563   }
8564
8565   // Do some hand-waving analysis to see if the non-viability is due
8566   // to a qualifier mismatch.
8567   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8568   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8569   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8570     CToTy = RT->getPointeeType();
8571   else {
8572     // TODO: detect and diagnose the full richness of const mismatches.
8573     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8574       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8575         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8576   }
8577
8578   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8579       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8580     Qualifiers FromQs = CFromTy.getQualifiers();
8581     Qualifiers ToQs = CToTy.getQualifiers();
8582
8583     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8584       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8585         << (unsigned) FnKind << FnDesc
8586         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8587         << FromTy
8588         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8589         << (unsigned) isObjectArgument << I+1;
8590       MaybeEmitInheritedConstructorNote(S, Fn);
8591       return;
8592     }
8593
8594     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8595       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8596         << (unsigned) FnKind << FnDesc
8597         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8598         << FromTy
8599         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8600         << (unsigned) isObjectArgument << I+1;
8601       MaybeEmitInheritedConstructorNote(S, Fn);
8602       return;
8603     }
8604
8605     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8606       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8607       << (unsigned) FnKind << FnDesc
8608       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8609       << FromTy
8610       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8611       << (unsigned) isObjectArgument << I+1;
8612       MaybeEmitInheritedConstructorNote(S, Fn);
8613       return;
8614     }
8615
8616     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8617     assert(CVR && "unexpected qualifiers mismatch");
8618
8619     if (isObjectArgument) {
8620       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8621         << (unsigned) FnKind << FnDesc
8622         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8623         << FromTy << (CVR - 1);
8624     } else {
8625       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8626         << (unsigned) FnKind << FnDesc
8627         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8628         << FromTy << (CVR - 1) << I+1;
8629     }
8630     MaybeEmitInheritedConstructorNote(S, Fn);
8631     return;
8632   }
8633
8634   // Special diagnostic for failure to convert an initializer list, since
8635   // telling the user that it has type void is not useful.
8636   if (FromExpr && isa<InitListExpr>(FromExpr)) {
8637     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8638       << (unsigned) FnKind << FnDesc
8639       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8640       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8641     MaybeEmitInheritedConstructorNote(S, Fn);
8642     return;
8643   }
8644
8645   // Diagnose references or pointers to incomplete types differently,
8646   // since it's far from impossible that the incompleteness triggered
8647   // the failure.
8648   QualType TempFromTy = FromTy.getNonReferenceType();
8649   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8650     TempFromTy = PTy->getPointeeType();
8651   if (TempFromTy->isIncompleteType()) {
8652     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8653       << (unsigned) FnKind << FnDesc
8654       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8655       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8656     MaybeEmitInheritedConstructorNote(S, Fn);
8657     return;
8658   }
8659
8660   // Diagnose base -> derived pointer conversions.
8661   unsigned BaseToDerivedConversion = 0;
8662   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8663     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8664       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8665                                                FromPtrTy->getPointeeType()) &&
8666           !FromPtrTy->getPointeeType()->isIncompleteType() &&
8667           !ToPtrTy->getPointeeType()->isIncompleteType() &&
8668           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8669                           FromPtrTy->getPointeeType()))
8670         BaseToDerivedConversion = 1;
8671     }
8672   } else if (const ObjCObjectPointerType *FromPtrTy
8673                                     = FromTy->getAs<ObjCObjectPointerType>()) {
8674     if (const ObjCObjectPointerType *ToPtrTy
8675                                         = ToTy->getAs<ObjCObjectPointerType>())
8676       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8677         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8678           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8679                                                 FromPtrTy->getPointeeType()) &&
8680               FromIface->isSuperClassOf(ToIface))
8681             BaseToDerivedConversion = 2;
8682   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8683     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8684         !FromTy->isIncompleteType() &&
8685         !ToRefTy->getPointeeType()->isIncompleteType() &&
8686         S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8687       BaseToDerivedConversion = 3;
8688     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8689                ToTy.getNonReferenceType().getCanonicalType() ==
8690                FromTy.getNonReferenceType().getCanonicalType()) {
8691       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8692         << (unsigned) FnKind << FnDesc
8693         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8694         << (unsigned) isObjectArgument << I + 1;
8695       MaybeEmitInheritedConstructorNote(S, Fn);
8696       return;
8697     }
8698   }
8699
8700   if (BaseToDerivedConversion) {
8701     S.Diag(Fn->getLocation(),
8702            diag::note_ovl_candidate_bad_base_to_derived_conv)
8703       << (unsigned) FnKind << FnDesc
8704       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8705       << (BaseToDerivedConversion - 1)
8706       << FromTy << ToTy << I+1;
8707     MaybeEmitInheritedConstructorNote(S, Fn);
8708     return;
8709   }
8710
8711   if (isa<ObjCObjectPointerType>(CFromTy) &&
8712       isa<PointerType>(CToTy)) {
8713       Qualifiers FromQs = CFromTy.getQualifiers();
8714       Qualifiers ToQs = CToTy.getQualifiers();
8715       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8716         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8717         << (unsigned) FnKind << FnDesc
8718         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8719         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8720         MaybeEmitInheritedConstructorNote(S, Fn);
8721         return;
8722       }
8723   }
8724   
8725   // Emit the generic diagnostic and, optionally, add the hints to it.
8726   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8727   FDiag << (unsigned) FnKind << FnDesc
8728     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8729     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8730     << (unsigned) (Cand->Fix.Kind);
8731
8732   // If we can fix the conversion, suggest the FixIts.
8733   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8734        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8735     FDiag << *HI;
8736   S.Diag(Fn->getLocation(), FDiag);
8737
8738   MaybeEmitInheritedConstructorNote(S, Fn);
8739 }
8740
8741 /// Additional arity mismatch diagnosis specific to a function overload
8742 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
8743 /// over a candidate in any candidate set.
8744 bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8745                         unsigned NumArgs) {
8746   FunctionDecl *Fn = Cand->Function;
8747   unsigned MinParams = Fn->getMinRequiredArguments();
8748
8749   // With invalid overloaded operators, it's possible that we think we
8750   // have an arity mismatch when in fact it looks like we have the
8751   // right number of arguments, because only overloaded operators have
8752   // the weird behavior of overloading member and non-member functions.
8753   // Just don't report anything.
8754   if (Fn->isInvalidDecl() && 
8755       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8756     return true;
8757
8758   if (NumArgs < MinParams) {
8759     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8760            (Cand->FailureKind == ovl_fail_bad_deduction &&
8761             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8762   } else {
8763     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8764            (Cand->FailureKind == ovl_fail_bad_deduction &&
8765             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8766   }
8767
8768   return false;
8769 }
8770
8771 /// General arity mismatch diagnosis over a candidate in a candidate set.
8772 void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8773   assert(isa<FunctionDecl>(D) &&
8774       "The templated declaration should at least be a function"
8775       " when diagnosing bad template argument deduction due to too many"
8776       " or too few arguments");
8777   
8778   FunctionDecl *Fn = cast<FunctionDecl>(D);
8779   
8780   // TODO: treat calls to a missing default constructor as a special case
8781   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8782   unsigned MinParams = Fn->getMinRequiredArguments();
8783
8784   // at least / at most / exactly
8785   unsigned mode, modeCount;
8786   if (NumFormalArgs < MinParams) {
8787     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8788         FnTy->isTemplateVariadic())
8789       mode = 0; // "at least"
8790     else
8791       mode = 2; // "exactly"
8792     modeCount = MinParams;
8793   } else {
8794     if (MinParams != FnTy->getNumParams())
8795       mode = 1; // "at most"
8796     else
8797       mode = 2; // "exactly"
8798     modeCount = FnTy->getNumParams();
8799   }
8800
8801   std::string Description;
8802   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8803
8804   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8805     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8806       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8807       << mode << Fn->getParamDecl(0) << NumFormalArgs;
8808   else
8809     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8810       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8811       << mode << modeCount << NumFormalArgs;
8812   MaybeEmitInheritedConstructorNote(S, Fn);
8813 }
8814
8815 /// Arity mismatch diagnosis specific to a function overload candidate.
8816 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8817                            unsigned NumFormalArgs) {
8818   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8819     DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8820 }
8821
8822 TemplateDecl *getDescribedTemplate(Decl *Templated) {
8823   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8824     return FD->getDescribedFunctionTemplate();
8825   else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8826     return RD->getDescribedClassTemplate();
8827
8828   llvm_unreachable("Unsupported: Getting the described template declaration"
8829                    " for bad deduction diagnosis");
8830 }
8831
8832 /// Diagnose a failed template-argument deduction.
8833 void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8834                           DeductionFailureInfo &DeductionFailure,
8835                           unsigned NumArgs) {
8836   TemplateParameter Param = DeductionFailure.getTemplateParameter();
8837   NamedDecl *ParamD;
8838   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8839   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8840   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8841   switch (DeductionFailure.Result) {
8842   case Sema::TDK_Success:
8843     llvm_unreachable("TDK_success while diagnosing bad deduction");
8844
8845   case Sema::TDK_Incomplete: {
8846     assert(ParamD && "no parameter found for incomplete deduction result");
8847     S.Diag(Templated->getLocation(),
8848            diag::note_ovl_candidate_incomplete_deduction)
8849         << ParamD->getDeclName();
8850     MaybeEmitInheritedConstructorNote(S, Templated);
8851     return;
8852   }
8853
8854   case Sema::TDK_Underqualified: {
8855     assert(ParamD && "no parameter found for bad qualifiers deduction result");
8856     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8857
8858     QualType Param = DeductionFailure.getFirstArg()->getAsType();
8859
8860     // Param will have been canonicalized, but it should just be a
8861     // qualified version of ParamD, so move the qualifiers to that.
8862     QualifierCollector Qs;
8863     Qs.strip(Param);
8864     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8865     assert(S.Context.hasSameType(Param, NonCanonParam));
8866
8867     // Arg has also been canonicalized, but there's nothing we can do
8868     // about that.  It also doesn't matter as much, because it won't
8869     // have any template parameters in it (because deduction isn't
8870     // done on dependent types).
8871     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
8872
8873     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8874         << ParamD->getDeclName() << Arg << NonCanonParam;
8875     MaybeEmitInheritedConstructorNote(S, Templated);
8876     return;
8877   }
8878
8879   case Sema::TDK_Inconsistent: {
8880     assert(ParamD && "no parameter found for inconsistent deduction result");
8881     int which = 0;
8882     if (isa<TemplateTypeParmDecl>(ParamD))
8883       which = 0;
8884     else if (isa<NonTypeTemplateParmDecl>(ParamD))
8885       which = 1;
8886     else {
8887       which = 2;
8888     }
8889
8890     S.Diag(Templated->getLocation(),
8891            diag::note_ovl_candidate_inconsistent_deduction)
8892         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8893         << *DeductionFailure.getSecondArg();
8894     MaybeEmitInheritedConstructorNote(S, Templated);
8895     return;
8896   }
8897
8898   case Sema::TDK_InvalidExplicitArguments:
8899     assert(ParamD && "no parameter found for invalid explicit arguments");
8900     if (ParamD->getDeclName())
8901       S.Diag(Templated->getLocation(),
8902              diag::note_ovl_candidate_explicit_arg_mismatch_named)
8903           << ParamD->getDeclName();
8904     else {
8905       int index = 0;
8906       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8907         index = TTP->getIndex();
8908       else if (NonTypeTemplateParmDecl *NTTP
8909                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8910         index = NTTP->getIndex();
8911       else
8912         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8913       S.Diag(Templated->getLocation(),
8914              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8915           << (index + 1);
8916     }
8917     MaybeEmitInheritedConstructorNote(S, Templated);
8918     return;
8919
8920   case Sema::TDK_TooManyArguments:
8921   case Sema::TDK_TooFewArguments:
8922     DiagnoseArityMismatch(S, Templated, NumArgs);
8923     return;
8924
8925   case Sema::TDK_InstantiationDepth:
8926     S.Diag(Templated->getLocation(),
8927            diag::note_ovl_candidate_instantiation_depth);
8928     MaybeEmitInheritedConstructorNote(S, Templated);
8929     return;
8930
8931   case Sema::TDK_SubstitutionFailure: {
8932     // Format the template argument list into the argument string.
8933     SmallString<128> TemplateArgString;
8934     if (TemplateArgumentList *Args =
8935             DeductionFailure.getTemplateArgumentList()) {
8936       TemplateArgString = " ";
8937       TemplateArgString += S.getTemplateArgumentBindingsText(
8938           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
8939     }
8940
8941     // If this candidate was disabled by enable_if, say so.
8942     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
8943     if (PDiag && PDiag->second.getDiagID() ==
8944           diag::err_typename_nested_not_found_enable_if) {
8945       // FIXME: Use the source range of the condition, and the fully-qualified
8946       //        name of the enable_if template. These are both present in PDiag.
8947       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8948         << "'enable_if'" << TemplateArgString;
8949       return;
8950     }
8951
8952     // Format the SFINAE diagnostic into the argument string.
8953     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8954     //        formatted message in another diagnostic.
8955     SmallString<128> SFINAEArgString;
8956     SourceRange R;
8957     if (PDiag) {
8958       SFINAEArgString = ": ";
8959       R = SourceRange(PDiag->first, PDiag->first);
8960       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8961     }
8962
8963     S.Diag(Templated->getLocation(),
8964            diag::note_ovl_candidate_substitution_failure)
8965         << TemplateArgString << SFINAEArgString << R;
8966     MaybeEmitInheritedConstructorNote(S, Templated);
8967     return;
8968   }
8969
8970   case Sema::TDK_FailedOverloadResolution: {
8971     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8972     S.Diag(Templated->getLocation(),
8973            diag::note_ovl_candidate_failed_overload_resolution)
8974         << R.Expression->getName();
8975     return;
8976   }
8977
8978   case Sema::TDK_NonDeducedMismatch: {
8979     // FIXME: Provide a source location to indicate what we couldn't match.
8980     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8981     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
8982     if (FirstTA.getKind() == TemplateArgument::Template &&
8983         SecondTA.getKind() == TemplateArgument::Template) {
8984       TemplateName FirstTN = FirstTA.getAsTemplate();
8985       TemplateName SecondTN = SecondTA.getAsTemplate();
8986       if (FirstTN.getKind() == TemplateName::Template &&
8987           SecondTN.getKind() == TemplateName::Template) {
8988         if (FirstTN.getAsTemplateDecl()->getName() ==
8989             SecondTN.getAsTemplateDecl()->getName()) {
8990           // FIXME: This fixes a bad diagnostic where both templates are named
8991           // the same.  This particular case is a bit difficult since:
8992           // 1) It is passed as a string to the diagnostic printer.
8993           // 2) The diagnostic printer only attempts to find a better
8994           //    name for types, not decls.
8995           // Ideally, this should folded into the diagnostic printer.
8996           S.Diag(Templated->getLocation(),
8997                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8998               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8999           return;
9000         }
9001       }
9002     }
9003     // FIXME: For generic lambda parameters, check if the function is a lambda
9004     // call operator, and if so, emit a prettier and more informative 
9005     // diagnostic that mentions 'auto' and lambda in addition to 
9006     // (or instead of?) the canonical template type parameters.
9007     S.Diag(Templated->getLocation(),
9008            diag::note_ovl_candidate_non_deduced_mismatch)
9009         << FirstTA << SecondTA;
9010     return;
9011   }
9012   // TODO: diagnose these individually, then kill off
9013   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9014   case Sema::TDK_MiscellaneousDeductionFailure:
9015     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9016     MaybeEmitInheritedConstructorNote(S, Templated);
9017     return;
9018   }
9019 }
9020
9021 /// Diagnose a failed template-argument deduction, for function calls.
9022 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
9023   unsigned TDK = Cand->DeductionFailure.Result;
9024   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9025     if (CheckArityMismatch(S, Cand, NumArgs))
9026       return;
9027   }
9028   DiagnoseBadDeduction(S, Cand->Function, // pattern
9029                        Cand->DeductionFailure, NumArgs);
9030 }
9031
9032 /// CUDA: diagnose an invalid call across targets.
9033 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9034   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9035   FunctionDecl *Callee = Cand->Function;
9036
9037   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9038                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9039
9040   std::string FnDesc;
9041   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9042
9043   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9044       << (unsigned) FnKind << CalleeTarget << CallerTarget;
9045 }
9046
9047 void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9048   FunctionDecl *Callee = Cand->Function;
9049   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9050
9051   S.Diag(Callee->getLocation(),
9052          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9053       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9054 }
9055
9056 /// Generates a 'note' diagnostic for an overload candidate.  We've
9057 /// already generated a primary error at the call site.
9058 ///
9059 /// It really does need to be a single diagnostic with its caret
9060 /// pointed at the candidate declaration.  Yes, this creates some
9061 /// major challenges of technical writing.  Yes, this makes pointing
9062 /// out problems with specific arguments quite awkward.  It's still
9063 /// better than generating twenty screens of text for every failed
9064 /// overload.
9065 ///
9066 /// It would be great to be able to express per-candidate problems
9067 /// more richly for those diagnostic clients that cared, but we'd
9068 /// still have to be just as careful with the default diagnostics.
9069 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9070                            unsigned NumArgs) {
9071   FunctionDecl *Fn = Cand->Function;
9072
9073   // Note deleted candidates, but only if they're viable.
9074   if (Cand->Viable && (Fn->isDeleted() ||
9075       S.isFunctionConsideredUnavailable(Fn))) {
9076     std::string FnDesc;
9077     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9078
9079     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9080       << FnKind << FnDesc
9081       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9082     MaybeEmitInheritedConstructorNote(S, Fn);
9083     return;
9084   }
9085
9086   // We don't really have anything else to say about viable candidates.
9087   if (Cand->Viable) {
9088     S.NoteOverloadCandidate(Fn);
9089     return;
9090   }
9091
9092   switch (Cand->FailureKind) {
9093   case ovl_fail_too_many_arguments:
9094   case ovl_fail_too_few_arguments:
9095     return DiagnoseArityMismatch(S, Cand, NumArgs);
9096
9097   case ovl_fail_bad_deduction:
9098     return DiagnoseBadDeduction(S, Cand, NumArgs);
9099
9100   case ovl_fail_trivial_conversion:
9101   case ovl_fail_bad_final_conversion:
9102   case ovl_fail_final_conversion_not_exact:
9103     return S.NoteOverloadCandidate(Fn);
9104
9105   case ovl_fail_bad_conversion: {
9106     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9107     for (unsigned N = Cand->NumConversions; I != N; ++I)
9108       if (Cand->Conversions[I].isBad())
9109         return DiagnoseBadConversion(S, Cand, I);
9110
9111     // FIXME: this currently happens when we're called from SemaInit
9112     // when user-conversion overload fails.  Figure out how to handle
9113     // those conditions and diagnose them well.
9114     return S.NoteOverloadCandidate(Fn);
9115   }
9116
9117   case ovl_fail_bad_target:
9118     return DiagnoseBadTarget(S, Cand);
9119
9120   case ovl_fail_enable_if:
9121     return DiagnoseFailedEnableIfAttr(S, Cand);
9122   }
9123 }
9124
9125 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9126   // Desugar the type of the surrogate down to a function type,
9127   // retaining as many typedefs as possible while still showing
9128   // the function type (and, therefore, its parameter types).
9129   QualType FnType = Cand->Surrogate->getConversionType();
9130   bool isLValueReference = false;
9131   bool isRValueReference = false;
9132   bool isPointer = false;
9133   if (const LValueReferenceType *FnTypeRef =
9134         FnType->getAs<LValueReferenceType>()) {
9135     FnType = FnTypeRef->getPointeeType();
9136     isLValueReference = true;
9137   } else if (const RValueReferenceType *FnTypeRef =
9138                FnType->getAs<RValueReferenceType>()) {
9139     FnType = FnTypeRef->getPointeeType();
9140     isRValueReference = true;
9141   }
9142   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9143     FnType = FnTypePtr->getPointeeType();
9144     isPointer = true;
9145   }
9146   // Desugar down to a function type.
9147   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9148   // Reconstruct the pointer/reference as appropriate.
9149   if (isPointer) FnType = S.Context.getPointerType(FnType);
9150   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9151   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9152
9153   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9154     << FnType;
9155   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9156 }
9157
9158 void NoteBuiltinOperatorCandidate(Sema &S,
9159                                   StringRef Opc,
9160                                   SourceLocation OpLoc,
9161                                   OverloadCandidate *Cand) {
9162   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9163   std::string TypeStr("operator");
9164   TypeStr += Opc;
9165   TypeStr += "(";
9166   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9167   if (Cand->NumConversions == 1) {
9168     TypeStr += ")";
9169     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9170   } else {
9171     TypeStr += ", ";
9172     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9173     TypeStr += ")";
9174     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9175   }
9176 }
9177
9178 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9179                                   OverloadCandidate *Cand) {
9180   unsigned NoOperands = Cand->NumConversions;
9181   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9182     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9183     if (ICS.isBad()) break; // all meaningless after first invalid
9184     if (!ICS.isAmbiguous()) continue;
9185
9186     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9187                               S.PDiag(diag::note_ambiguous_type_conversion));
9188   }
9189 }
9190
9191 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9192   if (Cand->Function)
9193     return Cand->Function->getLocation();
9194   if (Cand->IsSurrogate)
9195     return Cand->Surrogate->getLocation();
9196   return SourceLocation();
9197 }
9198
9199 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9200   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9201   case Sema::TDK_Success:
9202     llvm_unreachable("TDK_success while diagnosing bad deduction");
9203
9204   case Sema::TDK_Invalid:
9205   case Sema::TDK_Incomplete:
9206     return 1;
9207
9208   case Sema::TDK_Underqualified:
9209   case Sema::TDK_Inconsistent:
9210     return 2;
9211
9212   case Sema::TDK_SubstitutionFailure:
9213   case Sema::TDK_NonDeducedMismatch:
9214   case Sema::TDK_MiscellaneousDeductionFailure:
9215     return 3;
9216
9217   case Sema::TDK_InstantiationDepth:
9218   case Sema::TDK_FailedOverloadResolution:
9219     return 4;
9220
9221   case Sema::TDK_InvalidExplicitArguments:
9222     return 5;
9223
9224   case Sema::TDK_TooManyArguments:
9225   case Sema::TDK_TooFewArguments:
9226     return 6;
9227   }
9228   llvm_unreachable("Unhandled deduction result");
9229 }
9230
9231 struct CompareOverloadCandidatesForDisplay {
9232   Sema &S;
9233   size_t NumArgs;
9234
9235   CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9236       : S(S), NumArgs(nArgs) {}
9237
9238   bool operator()(const OverloadCandidate *L,
9239                   const OverloadCandidate *R) {
9240     // Fast-path this check.
9241     if (L == R) return false;
9242
9243     // Order first by viability.
9244     if (L->Viable) {
9245       if (!R->Viable) return true;
9246
9247       // TODO: introduce a tri-valued comparison for overload
9248       // candidates.  Would be more worthwhile if we had a sort
9249       // that could exploit it.
9250       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9251       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9252     } else if (R->Viable)
9253       return false;
9254
9255     assert(L->Viable == R->Viable);
9256
9257     // Criteria by which we can sort non-viable candidates:
9258     if (!L->Viable) {
9259       // 1. Arity mismatches come after other candidates.
9260       if (L->FailureKind == ovl_fail_too_many_arguments ||
9261           L->FailureKind == ovl_fail_too_few_arguments) {
9262         if (R->FailureKind == ovl_fail_too_many_arguments ||
9263             R->FailureKind == ovl_fail_too_few_arguments) {
9264           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9265           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9266           if (LDist == RDist) {
9267             if (L->FailureKind == R->FailureKind)
9268               // Sort non-surrogates before surrogates.
9269               return !L->IsSurrogate && R->IsSurrogate;
9270             // Sort candidates requiring fewer parameters than there were
9271             // arguments given after candidates requiring more parameters
9272             // than there were arguments given.
9273             return L->FailureKind == ovl_fail_too_many_arguments;
9274           }
9275           return LDist < RDist;
9276         }
9277         return false;
9278       }
9279       if (R->FailureKind == ovl_fail_too_many_arguments ||
9280           R->FailureKind == ovl_fail_too_few_arguments)
9281         return true;
9282
9283       // 2. Bad conversions come first and are ordered by the number
9284       // of bad conversions and quality of good conversions.
9285       if (L->FailureKind == ovl_fail_bad_conversion) {
9286         if (R->FailureKind != ovl_fail_bad_conversion)
9287           return true;
9288
9289         // The conversion that can be fixed with a smaller number of changes,
9290         // comes first.
9291         unsigned numLFixes = L->Fix.NumConversionsFixed;
9292         unsigned numRFixes = R->Fix.NumConversionsFixed;
9293         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9294         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9295         if (numLFixes != numRFixes) {
9296           if (numLFixes < numRFixes)
9297             return true;
9298           else
9299             return false;
9300         }
9301
9302         // If there's any ordering between the defined conversions...
9303         // FIXME: this might not be transitive.
9304         assert(L->NumConversions == R->NumConversions);
9305
9306         int leftBetter = 0;
9307         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9308         for (unsigned E = L->NumConversions; I != E; ++I) {
9309           switch (CompareImplicitConversionSequences(S,
9310                                                      L->Conversions[I],
9311                                                      R->Conversions[I])) {
9312           case ImplicitConversionSequence::Better:
9313             leftBetter++;
9314             break;
9315
9316           case ImplicitConversionSequence::Worse:
9317             leftBetter--;
9318             break;
9319
9320           case ImplicitConversionSequence::Indistinguishable:
9321             break;
9322           }
9323         }
9324         if (leftBetter > 0) return true;
9325         if (leftBetter < 0) return false;
9326
9327       } else if (R->FailureKind == ovl_fail_bad_conversion)
9328         return false;
9329
9330       if (L->FailureKind == ovl_fail_bad_deduction) {
9331         if (R->FailureKind != ovl_fail_bad_deduction)
9332           return true;
9333
9334         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9335           return RankDeductionFailure(L->DeductionFailure)
9336                < RankDeductionFailure(R->DeductionFailure);
9337       } else if (R->FailureKind == ovl_fail_bad_deduction)
9338         return false;
9339
9340       // TODO: others?
9341     }
9342
9343     // Sort everything else by location.
9344     SourceLocation LLoc = GetLocationForCandidate(L);
9345     SourceLocation RLoc = GetLocationForCandidate(R);
9346
9347     // Put candidates without locations (e.g. builtins) at the end.
9348     if (LLoc.isInvalid()) return false;
9349     if (RLoc.isInvalid()) return true;
9350
9351     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9352   }
9353 };
9354
9355 /// CompleteNonViableCandidate - Normally, overload resolution only
9356 /// computes up to the first. Produces the FixIt set if possible.
9357 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9358                                 ArrayRef<Expr *> Args) {
9359   assert(!Cand->Viable);
9360
9361   // Don't do anything on failures other than bad conversion.
9362   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9363
9364   // We only want the FixIts if all the arguments can be corrected.
9365   bool Unfixable = false;
9366   // Use a implicit copy initialization to check conversion fixes.
9367   Cand->Fix.setConversionChecker(TryCopyInitialization);
9368
9369   // Skip forward to the first bad conversion.
9370   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9371   unsigned ConvCount = Cand->NumConversions;
9372   while (true) {
9373     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9374     ConvIdx++;
9375     if (Cand->Conversions[ConvIdx - 1].isBad()) {
9376       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9377       break;
9378     }
9379   }
9380
9381   if (ConvIdx == ConvCount)
9382     return;
9383
9384   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9385          "remaining conversion is initialized?");
9386
9387   // FIXME: this should probably be preserved from the overload
9388   // operation somehow.
9389   bool SuppressUserConversions = false;
9390
9391   const FunctionProtoType* Proto;
9392   unsigned ArgIdx = ConvIdx;
9393
9394   if (Cand->IsSurrogate) {
9395     QualType ConvType
9396       = Cand->Surrogate->getConversionType().getNonReferenceType();
9397     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9398       ConvType = ConvPtrType->getPointeeType();
9399     Proto = ConvType->getAs<FunctionProtoType>();
9400     ArgIdx--;
9401   } else if (Cand->Function) {
9402     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9403     if (isa<CXXMethodDecl>(Cand->Function) &&
9404         !isa<CXXConstructorDecl>(Cand->Function))
9405       ArgIdx--;
9406   } else {
9407     // Builtin binary operator with a bad first conversion.
9408     assert(ConvCount <= 3);
9409     for (; ConvIdx != ConvCount; ++ConvIdx)
9410       Cand->Conversions[ConvIdx]
9411         = TryCopyInitialization(S, Args[ConvIdx],
9412                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9413                                 SuppressUserConversions,
9414                                 /*InOverloadResolution*/ true,
9415                                 /*AllowObjCWritebackConversion=*/
9416                                   S.getLangOpts().ObjCAutoRefCount);
9417     return;
9418   }
9419
9420   // Fill in the rest of the conversions.
9421   unsigned NumParams = Proto->getNumParams();
9422   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9423     if (ArgIdx < NumParams) {
9424       Cand->Conversions[ConvIdx] = TryCopyInitialization(
9425           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9426           /*InOverloadResolution=*/true,
9427           /*AllowObjCWritebackConversion=*/
9428           S.getLangOpts().ObjCAutoRefCount);
9429       // Store the FixIt in the candidate if it exists.
9430       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9431         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9432     }
9433     else
9434       Cand->Conversions[ConvIdx].setEllipsis();
9435   }
9436 }
9437
9438 } // end anonymous namespace
9439
9440 /// PrintOverloadCandidates - When overload resolution fails, prints
9441 /// diagnostic messages containing the candidates in the candidate
9442 /// set.
9443 void OverloadCandidateSet::NoteCandidates(Sema &S,
9444                                           OverloadCandidateDisplayKind OCD,
9445                                           ArrayRef<Expr *> Args,
9446                                           StringRef Opc,
9447                                           SourceLocation OpLoc) {
9448   // Sort the candidates by viability and position.  Sorting directly would
9449   // be prohibitive, so we make a set of pointers and sort those.
9450   SmallVector<OverloadCandidate*, 32> Cands;
9451   if (OCD == OCD_AllCandidates) Cands.reserve(size());
9452   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9453     if (Cand->Viable)
9454       Cands.push_back(Cand);
9455     else if (OCD == OCD_AllCandidates) {
9456       CompleteNonViableCandidate(S, Cand, Args);
9457       if (Cand->Function || Cand->IsSurrogate)
9458         Cands.push_back(Cand);
9459       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
9460       // want to list every possible builtin candidate.
9461     }
9462   }
9463
9464   std::sort(Cands.begin(), Cands.end(),
9465             CompareOverloadCandidatesForDisplay(S, Args.size()));
9466
9467   bool ReportedAmbiguousConversions = false;
9468
9469   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9470   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9471   unsigned CandsShown = 0;
9472   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9473     OverloadCandidate *Cand = *I;
9474
9475     // Set an arbitrary limit on the number of candidate functions we'll spam
9476     // the user with.  FIXME: This limit should depend on details of the
9477     // candidate list.
9478     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9479       break;
9480     }
9481     ++CandsShown;
9482
9483     if (Cand->Function)
9484       NoteFunctionCandidate(S, Cand, Args.size());
9485     else if (Cand->IsSurrogate)
9486       NoteSurrogateCandidate(S, Cand);
9487     else {
9488       assert(Cand->Viable &&
9489              "Non-viable built-in candidates are not added to Cands.");
9490       // Generally we only see ambiguities including viable builtin
9491       // operators if overload resolution got screwed up by an
9492       // ambiguous user-defined conversion.
9493       //
9494       // FIXME: It's quite possible for different conversions to see
9495       // different ambiguities, though.
9496       if (!ReportedAmbiguousConversions) {
9497         NoteAmbiguousUserConversions(S, OpLoc, Cand);
9498         ReportedAmbiguousConversions = true;
9499       }
9500
9501       // If this is a viable builtin, print it.
9502       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9503     }
9504   }
9505
9506   if (I != E)
9507     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9508 }
9509
9510 static SourceLocation
9511 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9512   return Cand->Specialization ? Cand->Specialization->getLocation()
9513                               : SourceLocation();
9514 }
9515
9516 struct CompareTemplateSpecCandidatesForDisplay {
9517   Sema &S;
9518   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9519
9520   bool operator()(const TemplateSpecCandidate *L,
9521                   const TemplateSpecCandidate *R) {
9522     // Fast-path this check.
9523     if (L == R)
9524       return false;
9525
9526     // Assuming that both candidates are not matches...
9527
9528     // Sort by the ranking of deduction failures.
9529     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9530       return RankDeductionFailure(L->DeductionFailure) <
9531              RankDeductionFailure(R->DeductionFailure);
9532
9533     // Sort everything else by location.
9534     SourceLocation LLoc = GetLocationForCandidate(L);
9535     SourceLocation RLoc = GetLocationForCandidate(R);
9536
9537     // Put candidates without locations (e.g. builtins) at the end.
9538     if (LLoc.isInvalid())
9539       return false;
9540     if (RLoc.isInvalid())
9541       return true;
9542
9543     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9544   }
9545 };
9546
9547 /// Diagnose a template argument deduction failure.
9548 /// We are treating these failures as overload failures due to bad
9549 /// deductions.
9550 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9551   DiagnoseBadDeduction(S, Specialization, // pattern
9552                        DeductionFailure, /*NumArgs=*/0);
9553 }
9554
9555 void TemplateSpecCandidateSet::destroyCandidates() {
9556   for (iterator i = begin(), e = end(); i != e; ++i) {
9557     i->DeductionFailure.Destroy();
9558   }
9559 }
9560
9561 void TemplateSpecCandidateSet::clear() {
9562   destroyCandidates();
9563   Candidates.clear();
9564 }
9565
9566 /// NoteCandidates - When no template specialization match is found, prints
9567 /// diagnostic messages containing the non-matching specializations that form
9568 /// the candidate set.
9569 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9570 /// OCD == OCD_AllCandidates and Cand->Viable == false.
9571 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9572   // Sort the candidates by position (assuming no candidate is a match).
9573   // Sorting directly would be prohibitive, so we make a set of pointers
9574   // and sort those.
9575   SmallVector<TemplateSpecCandidate *, 32> Cands;
9576   Cands.reserve(size());
9577   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9578     if (Cand->Specialization)
9579       Cands.push_back(Cand);
9580     // Otherwise, this is a non-matching builtin candidate.  We do not,
9581     // in general, want to list every possible builtin candidate.
9582   }
9583
9584   std::sort(Cands.begin(), Cands.end(),
9585             CompareTemplateSpecCandidatesForDisplay(S));
9586
9587   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9588   // for generalization purposes (?).
9589   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9590
9591   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9592   unsigned CandsShown = 0;
9593   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9594     TemplateSpecCandidate *Cand = *I;
9595
9596     // Set an arbitrary limit on the number of candidates we'll spam
9597     // the user with.  FIXME: This limit should depend on details of the
9598     // candidate list.
9599     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9600       break;
9601     ++CandsShown;
9602
9603     assert(Cand->Specialization &&
9604            "Non-matching built-in candidates are not added to Cands.");
9605     Cand->NoteDeductionFailure(S);
9606   }
9607
9608   if (I != E)
9609     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9610 }
9611
9612 // [PossiblyAFunctionType]  -->   [Return]
9613 // NonFunctionType --> NonFunctionType
9614 // R (A) --> R(A)
9615 // R (*)(A) --> R (A)
9616 // R (&)(A) --> R (A)
9617 // R (S::*)(A) --> R (A)
9618 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9619   QualType Ret = PossiblyAFunctionType;
9620   if (const PointerType *ToTypePtr = 
9621     PossiblyAFunctionType->getAs<PointerType>())
9622     Ret = ToTypePtr->getPointeeType();
9623   else if (const ReferenceType *ToTypeRef = 
9624     PossiblyAFunctionType->getAs<ReferenceType>())
9625     Ret = ToTypeRef->getPointeeType();
9626   else if (const MemberPointerType *MemTypePtr =
9627     PossiblyAFunctionType->getAs<MemberPointerType>()) 
9628     Ret = MemTypePtr->getPointeeType();   
9629   Ret = 
9630     Context.getCanonicalType(Ret).getUnqualifiedType();
9631   return Ret;
9632 }
9633
9634 // A helper class to help with address of function resolution
9635 // - allows us to avoid passing around all those ugly parameters
9636 class AddressOfFunctionResolver 
9637 {
9638   Sema& S;
9639   Expr* SourceExpr;
9640   const QualType& TargetType; 
9641   QualType TargetFunctionType; // Extracted function type from target type 
9642    
9643   bool Complain;
9644   //DeclAccessPair& ResultFunctionAccessPair;
9645   ASTContext& Context;
9646
9647   bool TargetTypeIsNonStaticMemberFunction;
9648   bool FoundNonTemplateFunction;
9649   bool StaticMemberFunctionFromBoundPointer;
9650
9651   OverloadExpr::FindResult OvlExprInfo; 
9652   OverloadExpr *OvlExpr;
9653   TemplateArgumentListInfo OvlExplicitTemplateArgs;
9654   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9655   TemplateSpecCandidateSet FailedCandidates;
9656
9657 public:
9658   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9659                             const QualType &TargetType, bool Complain)
9660       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9661         Complain(Complain), Context(S.getASTContext()),
9662         TargetTypeIsNonStaticMemberFunction(
9663             !!TargetType->getAs<MemberPointerType>()),
9664         FoundNonTemplateFunction(false),
9665         StaticMemberFunctionFromBoundPointer(false),
9666         OvlExprInfo(OverloadExpr::find(SourceExpr)),
9667         OvlExpr(OvlExprInfo.Expression),
9668         FailedCandidates(OvlExpr->getNameLoc()) {
9669     ExtractUnqualifiedFunctionTypeFromTargetType();
9670
9671     if (TargetFunctionType->isFunctionType()) {
9672       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9673         if (!UME->isImplicitAccess() &&
9674             !S.ResolveSingleFunctionTemplateSpecialization(UME))
9675           StaticMemberFunctionFromBoundPointer = true;
9676     } else if (OvlExpr->hasExplicitTemplateArgs()) {
9677       DeclAccessPair dap;
9678       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9679               OvlExpr, false, &dap)) {
9680         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9681           if (!Method->isStatic()) {
9682             // If the target type is a non-function type and the function found
9683             // is a non-static member function, pretend as if that was the
9684             // target, it's the only possible type to end up with.
9685             TargetTypeIsNonStaticMemberFunction = true;
9686
9687             // And skip adding the function if its not in the proper form.
9688             // We'll diagnose this due to an empty set of functions.
9689             if (!OvlExprInfo.HasFormOfMemberPointer)
9690               return;
9691           }
9692
9693         Matches.push_back(std::make_pair(dap, Fn));
9694       }
9695       return;
9696     }
9697     
9698     if (OvlExpr->hasExplicitTemplateArgs())
9699       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9700
9701     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9702       // C++ [over.over]p4:
9703       //   If more than one function is selected, [...]
9704       if (Matches.size() > 1) {
9705         if (FoundNonTemplateFunction)
9706           EliminateAllTemplateMatches();
9707         else
9708           EliminateAllExceptMostSpecializedTemplate();
9709       }
9710     }
9711   }
9712   
9713 private:
9714   bool isTargetTypeAFunction() const {
9715     return TargetFunctionType->isFunctionType();
9716   }
9717
9718   // [ToType]     [Return]
9719
9720   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9721   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9722   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9723   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9724     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9725   }
9726
9727   // return true if any matching specializations were found
9728   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 
9729                                    const DeclAccessPair& CurAccessFunPair) {
9730     if (CXXMethodDecl *Method
9731               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9732       // Skip non-static function templates when converting to pointer, and
9733       // static when converting to member pointer.
9734       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9735         return false;
9736     } 
9737     else if (TargetTypeIsNonStaticMemberFunction)
9738       return false;
9739
9740     // C++ [over.over]p2:
9741     //   If the name is a function template, template argument deduction is
9742     //   done (14.8.2.2), and if the argument deduction succeeds, the
9743     //   resulting template argument list is used to generate a single
9744     //   function template specialization, which is added to the set of
9745     //   overloaded functions considered.
9746     FunctionDecl *Specialization = nullptr;
9747     TemplateDeductionInfo Info(FailedCandidates.getLocation());
9748     if (Sema::TemplateDeductionResult Result
9749           = S.DeduceTemplateArguments(FunctionTemplate, 
9750                                       &OvlExplicitTemplateArgs,
9751                                       TargetFunctionType, Specialization, 
9752                                       Info, /*InOverloadResolution=*/true)) {
9753       // Make a note of the failed deduction for diagnostics.
9754       FailedCandidates.addCandidate()
9755           .set(FunctionTemplate->getTemplatedDecl(),
9756                MakeDeductionFailureInfo(Context, Result, Info));
9757       return false;
9758     } 
9759     
9760     // Template argument deduction ensures that we have an exact match or
9761     // compatible pointer-to-function arguments that would be adjusted by ICS.
9762     // This function template specicalization works.
9763     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9764     assert(S.isSameOrCompatibleFunctionType(
9765               Context.getCanonicalType(Specialization->getType()),
9766               Context.getCanonicalType(TargetFunctionType)));
9767     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9768     return true;
9769   }
9770   
9771   bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 
9772                                       const DeclAccessPair& CurAccessFunPair) {
9773     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9774       // Skip non-static functions when converting to pointer, and static
9775       // when converting to member pointer.
9776       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9777         return false;
9778     } 
9779     else if (TargetTypeIsNonStaticMemberFunction)
9780       return false;
9781
9782     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9783       if (S.getLangOpts().CUDA)
9784         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9785           if (S.CheckCUDATarget(Caller, FunDecl))
9786             return false;
9787
9788       // If any candidate has a placeholder return type, trigger its deduction
9789       // now.
9790       if (S.getLangOpts().CPlusPlus1y &&
9791           FunDecl->getReturnType()->isUndeducedType() &&
9792           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9793         return false;
9794
9795       QualType ResultTy;
9796       if (Context.hasSameUnqualifiedType(TargetFunctionType, 
9797                                          FunDecl->getType()) ||
9798           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9799                                  ResultTy)) {
9800         Matches.push_back(std::make_pair(CurAccessFunPair,
9801           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9802         FoundNonTemplateFunction = true;
9803         return true;
9804       }
9805     }
9806     
9807     return false;
9808   }
9809   
9810   bool FindAllFunctionsThatMatchTargetTypeExactly() {
9811     bool Ret = false;
9812     
9813     // If the overload expression doesn't have the form of a pointer to
9814     // member, don't try to convert it to a pointer-to-member type.
9815     if (IsInvalidFormOfPointerToMemberFunction())
9816       return false;
9817
9818     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9819                                E = OvlExpr->decls_end(); 
9820          I != E; ++I) {
9821       // Look through any using declarations to find the underlying function.
9822       NamedDecl *Fn = (*I)->getUnderlyingDecl();
9823
9824       // C++ [over.over]p3:
9825       //   Non-member functions and static member functions match
9826       //   targets of type "pointer-to-function" or "reference-to-function."
9827       //   Nonstatic member functions match targets of
9828       //   type "pointer-to-member-function."
9829       // Note that according to DR 247, the containing class does not matter.
9830       if (FunctionTemplateDecl *FunctionTemplate
9831                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
9832         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9833           Ret = true;
9834       }
9835       // If we have explicit template arguments supplied, skip non-templates.
9836       else if (!OvlExpr->hasExplicitTemplateArgs() &&
9837                AddMatchingNonTemplateFunction(Fn, I.getPair()))
9838         Ret = true;
9839     }
9840     assert(Ret || Matches.empty());
9841     return Ret;
9842   }
9843
9844   void EliminateAllExceptMostSpecializedTemplate() {
9845     //   [...] and any given function template specialization F1 is
9846     //   eliminated if the set contains a second function template
9847     //   specialization whose function template is more specialized
9848     //   than the function template of F1 according to the partial
9849     //   ordering rules of 14.5.5.2.
9850
9851     // The algorithm specified above is quadratic. We instead use a
9852     // two-pass algorithm (similar to the one used to identify the
9853     // best viable function in an overload set) that identifies the
9854     // best function template (if it exists).
9855
9856     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9857     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9858       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9859
9860     // TODO: It looks like FailedCandidates does not serve much purpose
9861     // here, since the no_viable diagnostic has index 0.
9862     UnresolvedSetIterator Result = S.getMostSpecialized(
9863         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
9864         SourceExpr->getLocStart(), S.PDiag(),
9865         S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9866                                                      .second->getDeclName(),
9867         S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9868         Complain, TargetFunctionType);
9869
9870     if (Result != MatchesCopy.end()) {
9871       // Make it the first and only element
9872       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9873       Matches[0].second = cast<FunctionDecl>(*Result);
9874       Matches.resize(1);
9875     }
9876   }
9877
9878   void EliminateAllTemplateMatches() {
9879     //   [...] any function template specializations in the set are
9880     //   eliminated if the set also contains a non-template function, [...]
9881     for (unsigned I = 0, N = Matches.size(); I != N; ) {
9882       if (Matches[I].second->getPrimaryTemplate() == nullptr)
9883         ++I;
9884       else {
9885         Matches[I] = Matches[--N];
9886         Matches.set_size(N);
9887       }
9888     }
9889   }
9890
9891 public:
9892   void ComplainNoMatchesFound() const {
9893     assert(Matches.empty());
9894     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9895         << OvlExpr->getName() << TargetFunctionType
9896         << OvlExpr->getSourceRange();
9897     if (FailedCandidates.empty())
9898       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9899     else {
9900       // We have some deduction failure messages. Use them to diagnose
9901       // the function templates, and diagnose the non-template candidates
9902       // normally.
9903       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9904                                  IEnd = OvlExpr->decls_end();
9905            I != IEnd; ++I)
9906         if (FunctionDecl *Fun =
9907                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9908           S.NoteOverloadCandidate(Fun, TargetFunctionType);
9909       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9910     }
9911   }
9912
9913   bool IsInvalidFormOfPointerToMemberFunction() const {
9914     return TargetTypeIsNonStaticMemberFunction &&
9915       !OvlExprInfo.HasFormOfMemberPointer;
9916   }
9917
9918   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9919       // TODO: Should we condition this on whether any functions might
9920       // have matched, or is it more appropriate to do that in callers?
9921       // TODO: a fixit wouldn't hurt.
9922       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9923         << TargetType << OvlExpr->getSourceRange();
9924   }
9925
9926   bool IsStaticMemberFunctionFromBoundPointer() const {
9927     return StaticMemberFunctionFromBoundPointer;
9928   }
9929
9930   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9931     S.Diag(OvlExpr->getLocStart(),
9932            diag::err_invalid_form_pointer_member_function)
9933       << OvlExpr->getSourceRange();
9934   }
9935
9936   void ComplainOfInvalidConversion() const {
9937     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9938       << OvlExpr->getName() << TargetType;
9939   }
9940
9941   void ComplainMultipleMatchesFound() const {
9942     assert(Matches.size() > 1);
9943     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9944       << OvlExpr->getName()
9945       << OvlExpr->getSourceRange();
9946     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9947   }
9948
9949   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9950
9951   int getNumMatches() const { return Matches.size(); }
9952   
9953   FunctionDecl* getMatchingFunctionDecl() const {
9954     if (Matches.size() != 1) return nullptr;
9955     return Matches[0].second;
9956   }
9957   
9958   const DeclAccessPair* getMatchingFunctionAccessPair() const {
9959     if (Matches.size() != 1) return nullptr;
9960     return &Matches[0].first;
9961   }
9962 };
9963   
9964 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9965 /// an overloaded function (C++ [over.over]), where @p From is an
9966 /// expression with overloaded function type and @p ToType is the type
9967 /// we're trying to resolve to. For example:
9968 ///
9969 /// @code
9970 /// int f(double);
9971 /// int f(int);
9972 ///
9973 /// int (*pfd)(double) = f; // selects f(double)
9974 /// @endcode
9975 ///
9976 /// This routine returns the resulting FunctionDecl if it could be
9977 /// resolved, and NULL otherwise. When @p Complain is true, this
9978 /// routine will emit diagnostics if there is an error.
9979 FunctionDecl *
9980 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9981                                          QualType TargetType,
9982                                          bool Complain,
9983                                          DeclAccessPair &FoundResult,
9984                                          bool *pHadMultipleCandidates) {
9985   assert(AddressOfExpr->getType() == Context.OverloadTy);
9986
9987   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9988                                      Complain);
9989   int NumMatches = Resolver.getNumMatches();
9990   FunctionDecl *Fn = nullptr;
9991   if (NumMatches == 0 && Complain) {
9992     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9993       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9994     else
9995       Resolver.ComplainNoMatchesFound();
9996   }
9997   else if (NumMatches > 1 && Complain)
9998     Resolver.ComplainMultipleMatchesFound();
9999   else if (NumMatches == 1) {
10000     Fn = Resolver.getMatchingFunctionDecl();
10001     assert(Fn);
10002     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10003     if (Complain) {
10004       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10005         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10006       else
10007         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10008     }
10009   }
10010
10011   if (pHadMultipleCandidates)
10012     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10013   return Fn;
10014 }
10015
10016 /// \brief Given an expression that refers to an overloaded function, try to
10017 /// resolve that overloaded function expression down to a single function.
10018 ///
10019 /// This routine can only resolve template-ids that refer to a single function
10020 /// template, where that template-id refers to a single template whose template
10021 /// arguments are either provided by the template-id or have defaults,
10022 /// as described in C++0x [temp.arg.explicit]p3.
10023 ///
10024 /// If no template-ids are found, no diagnostics are emitted and NULL is
10025 /// returned.
10026 FunctionDecl *
10027 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 
10028                                                   bool Complain,
10029                                                   DeclAccessPair *FoundResult) {
10030   // C++ [over.over]p1:
10031   //   [...] [Note: any redundant set of parentheses surrounding the
10032   //   overloaded function name is ignored (5.1). ]
10033   // C++ [over.over]p1:
10034   //   [...] The overloaded function name can be preceded by the &
10035   //   operator.
10036
10037   // If we didn't actually find any template-ids, we're done.
10038   if (!ovl->hasExplicitTemplateArgs())
10039     return nullptr;
10040
10041   TemplateArgumentListInfo ExplicitTemplateArgs;
10042   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
10043   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10044
10045   // Look through all of the overloaded functions, searching for one
10046   // whose type matches exactly.
10047   FunctionDecl *Matched = nullptr;
10048   for (UnresolvedSetIterator I = ovl->decls_begin(),
10049          E = ovl->decls_end(); I != E; ++I) {
10050     // C++0x [temp.arg.explicit]p3:
10051     //   [...] In contexts where deduction is done and fails, or in contexts
10052     //   where deduction is not done, if a template argument list is
10053     //   specified and it, along with any default template arguments,
10054     //   identifies a single function template specialization, then the
10055     //   template-id is an lvalue for the function template specialization.
10056     FunctionTemplateDecl *FunctionTemplate
10057       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10058
10059     // C++ [over.over]p2:
10060     //   If the name is a function template, template argument deduction is
10061     //   done (14.8.2.2), and if the argument deduction succeeds, the
10062     //   resulting template argument list is used to generate a single
10063     //   function template specialization, which is added to the set of
10064     //   overloaded functions considered.
10065     FunctionDecl *Specialization = nullptr;
10066     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10067     if (TemplateDeductionResult Result
10068           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10069                                     Specialization, Info,
10070                                     /*InOverloadResolution=*/true)) {
10071       // Make a note of the failed deduction for diagnostics.
10072       // TODO: Actually use the failed-deduction info?
10073       FailedCandidates.addCandidate()
10074           .set(FunctionTemplate->getTemplatedDecl(),
10075                MakeDeductionFailureInfo(Context, Result, Info));
10076       continue;
10077     }
10078
10079     assert(Specialization && "no specialization and no error?");
10080
10081     // Multiple matches; we can't resolve to a single declaration.
10082     if (Matched) {
10083       if (Complain) {
10084         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10085           << ovl->getName();
10086         NoteAllOverloadCandidates(ovl);
10087       }
10088       return nullptr;
10089     }
10090     
10091     Matched = Specialization;
10092     if (FoundResult) *FoundResult = I.getPair();    
10093   }
10094
10095   if (Matched && getLangOpts().CPlusPlus1y &&
10096       Matched->getReturnType()->isUndeducedType() &&
10097       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10098     return nullptr;
10099
10100   return Matched;
10101 }
10102
10103
10104
10105
10106 // Resolve and fix an overloaded expression that can be resolved
10107 // because it identifies a single function template specialization.
10108 //
10109 // Last three arguments should only be supplied if Complain = true
10110 //
10111 // Return true if it was logically possible to so resolve the
10112 // expression, regardless of whether or not it succeeded.  Always
10113 // returns true if 'complain' is set.
10114 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10115                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10116                    bool complain, const SourceRange& OpRangeForComplaining, 
10117                                            QualType DestTypeForComplaining, 
10118                                             unsigned DiagIDForComplaining) {
10119   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10120
10121   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10122
10123   DeclAccessPair found;
10124   ExprResult SingleFunctionExpression;
10125   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10126                            ovl.Expression, /*complain*/ false, &found)) {
10127     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10128       SrcExpr = ExprError();
10129       return true;
10130     }
10131
10132     // It is only correct to resolve to an instance method if we're
10133     // resolving a form that's permitted to be a pointer to member.
10134     // Otherwise we'll end up making a bound member expression, which
10135     // is illegal in all the contexts we resolve like this.
10136     if (!ovl.HasFormOfMemberPointer &&
10137         isa<CXXMethodDecl>(fn) &&
10138         cast<CXXMethodDecl>(fn)->isInstance()) {
10139       if (!complain) return false;
10140
10141       Diag(ovl.Expression->getExprLoc(),
10142            diag::err_bound_member_function)
10143         << 0 << ovl.Expression->getSourceRange();
10144
10145       // TODO: I believe we only end up here if there's a mix of
10146       // static and non-static candidates (otherwise the expression
10147       // would have 'bound member' type, not 'overload' type).
10148       // Ideally we would note which candidate was chosen and why
10149       // the static candidates were rejected.
10150       SrcExpr = ExprError();
10151       return true;
10152     }
10153
10154     // Fix the expression to refer to 'fn'.
10155     SingleFunctionExpression =
10156         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10157
10158     // If desired, do function-to-pointer decay.
10159     if (doFunctionPointerConverion) {
10160       SingleFunctionExpression =
10161         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10162       if (SingleFunctionExpression.isInvalid()) {
10163         SrcExpr = ExprError();
10164         return true;
10165       }
10166     }
10167   }
10168
10169   if (!SingleFunctionExpression.isUsable()) {
10170     if (complain) {
10171       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10172         << ovl.Expression->getName()
10173         << DestTypeForComplaining
10174         << OpRangeForComplaining 
10175         << ovl.Expression->getQualifierLoc().getSourceRange();
10176       NoteAllOverloadCandidates(SrcExpr.get());
10177
10178       SrcExpr = ExprError();
10179       return true;
10180     }
10181
10182     return false;
10183   }
10184
10185   SrcExpr = SingleFunctionExpression;
10186   return true;
10187 }
10188
10189 /// \brief Add a single candidate to the overload set.
10190 static void AddOverloadedCallCandidate(Sema &S,
10191                                        DeclAccessPair FoundDecl,
10192                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
10193                                        ArrayRef<Expr *> Args,
10194                                        OverloadCandidateSet &CandidateSet,
10195                                        bool PartialOverloading,
10196                                        bool KnownValid) {
10197   NamedDecl *Callee = FoundDecl.getDecl();
10198   if (isa<UsingShadowDecl>(Callee))
10199     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10200
10201   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10202     if (ExplicitTemplateArgs) {
10203       assert(!KnownValid && "Explicit template arguments?");
10204       return;
10205     }
10206     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10207                            PartialOverloading);
10208     return;
10209   }
10210
10211   if (FunctionTemplateDecl *FuncTemplate
10212       = dyn_cast<FunctionTemplateDecl>(Callee)) {
10213     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10214                                    ExplicitTemplateArgs, Args, CandidateSet);
10215     return;
10216   }
10217
10218   assert(!KnownValid && "unhandled case in overloaded call candidate");
10219 }
10220
10221 /// \brief Add the overload candidates named by callee and/or found by argument
10222 /// dependent lookup to the given overload set.
10223 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10224                                        ArrayRef<Expr *> Args,
10225                                        OverloadCandidateSet &CandidateSet,
10226                                        bool PartialOverloading) {
10227
10228 #ifndef NDEBUG
10229   // Verify that ArgumentDependentLookup is consistent with the rules
10230   // in C++0x [basic.lookup.argdep]p3:
10231   //
10232   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10233   //   and let Y be the lookup set produced by argument dependent
10234   //   lookup (defined as follows). If X contains
10235   //
10236   //     -- a declaration of a class member, or
10237   //
10238   //     -- a block-scope function declaration that is not a
10239   //        using-declaration, or
10240   //
10241   //     -- a declaration that is neither a function or a function
10242   //        template
10243   //
10244   //   then Y is empty.
10245
10246   if (ULE->requiresADL()) {
10247     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10248            E = ULE->decls_end(); I != E; ++I) {
10249       assert(!(*I)->getDeclContext()->isRecord());
10250       assert(isa<UsingShadowDecl>(*I) ||
10251              !(*I)->getDeclContext()->isFunctionOrMethod());
10252       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
10253     }
10254   }
10255 #endif
10256
10257   // It would be nice to avoid this copy.
10258   TemplateArgumentListInfo TABuffer;
10259   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10260   if (ULE->hasExplicitTemplateArgs()) {
10261     ULE->copyTemplateArgumentsInto(TABuffer);
10262     ExplicitTemplateArgs = &TABuffer;
10263   }
10264
10265   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10266          E = ULE->decls_end(); I != E; ++I)
10267     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10268                                CandidateSet, PartialOverloading,
10269                                /*KnownValid*/ true);
10270
10271   if (ULE->requiresADL())
10272     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10273                                          Args, ExplicitTemplateArgs,
10274                                          CandidateSet, PartialOverloading);
10275 }
10276
10277 /// Determine whether a declaration with the specified name could be moved into
10278 /// a different namespace.
10279 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10280   switch (Name.getCXXOverloadedOperator()) {
10281   case OO_New: case OO_Array_New:
10282   case OO_Delete: case OO_Array_Delete:
10283     return false;
10284
10285   default:
10286     return true;
10287   }
10288 }
10289
10290 /// Attempt to recover from an ill-formed use of a non-dependent name in a
10291 /// template, where the non-dependent name was declared after the template
10292 /// was defined. This is common in code written for a compilers which do not
10293 /// correctly implement two-stage name lookup.
10294 ///
10295 /// Returns true if a viable candidate was found and a diagnostic was issued.
10296 static bool
10297 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10298                        const CXXScopeSpec &SS, LookupResult &R,
10299                        OverloadCandidateSet::CandidateSetKind CSK,
10300                        TemplateArgumentListInfo *ExplicitTemplateArgs,
10301                        ArrayRef<Expr *> Args) {
10302   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10303     return false;
10304
10305   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10306     if (DC->isTransparentContext())
10307       continue;
10308
10309     SemaRef.LookupQualifiedName(R, DC);
10310
10311     if (!R.empty()) {
10312       R.suppressDiagnostics();
10313
10314       if (isa<CXXRecordDecl>(DC)) {
10315         // Don't diagnose names we find in classes; we get much better
10316         // diagnostics for these from DiagnoseEmptyLookup.
10317         R.clear();
10318         return false;
10319       }
10320
10321       OverloadCandidateSet Candidates(FnLoc, CSK);
10322       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10323         AddOverloadedCallCandidate(SemaRef, I.getPair(),
10324                                    ExplicitTemplateArgs, Args,
10325                                    Candidates, false, /*KnownValid*/ false);
10326
10327       OverloadCandidateSet::iterator Best;
10328       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10329         // No viable functions. Don't bother the user with notes for functions
10330         // which don't work and shouldn't be found anyway.
10331         R.clear();
10332         return false;
10333       }
10334
10335       // Find the namespaces where ADL would have looked, and suggest
10336       // declaring the function there instead.
10337       Sema::AssociatedNamespaceSet AssociatedNamespaces;
10338       Sema::AssociatedClassSet AssociatedClasses;
10339       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10340                                                  AssociatedNamespaces,
10341                                                  AssociatedClasses);
10342       Sema::AssociatedNamespaceSet SuggestedNamespaces;
10343       if (canBeDeclaredInNamespace(R.getLookupName())) {
10344         DeclContext *Std = SemaRef.getStdNamespace();
10345         for (Sema::AssociatedNamespaceSet::iterator
10346                it = AssociatedNamespaces.begin(),
10347                end = AssociatedNamespaces.end(); it != end; ++it) {
10348           // Never suggest declaring a function within namespace 'std'.
10349           if (Std && Std->Encloses(*it))
10350             continue;
10351
10352           // Never suggest declaring a function within a namespace with a
10353           // reserved name, like __gnu_cxx.
10354           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10355           if (NS &&
10356               NS->getQualifiedNameAsString().find("__") != std::string::npos)
10357             continue;
10358
10359           SuggestedNamespaces.insert(*it);
10360         }
10361       }
10362
10363       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10364         << R.getLookupName();
10365       if (SuggestedNamespaces.empty()) {
10366         SemaRef.Diag(Best->Function->getLocation(),
10367                      diag::note_not_found_by_two_phase_lookup)
10368           << R.getLookupName() << 0;
10369       } else if (SuggestedNamespaces.size() == 1) {
10370         SemaRef.Diag(Best->Function->getLocation(),
10371                      diag::note_not_found_by_two_phase_lookup)
10372           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10373       } else {
10374         // FIXME: It would be useful to list the associated namespaces here,
10375         // but the diagnostics infrastructure doesn't provide a way to produce
10376         // a localized representation of a list of items.
10377         SemaRef.Diag(Best->Function->getLocation(),
10378                      diag::note_not_found_by_two_phase_lookup)
10379           << R.getLookupName() << 2;
10380       }
10381
10382       // Try to recover by calling this function.
10383       return true;
10384     }
10385
10386     R.clear();
10387   }
10388
10389   return false;
10390 }
10391
10392 /// Attempt to recover from ill-formed use of a non-dependent operator in a
10393 /// template, where the non-dependent operator was declared after the template
10394 /// was defined.
10395 ///
10396 /// Returns true if a viable candidate was found and a diagnostic was issued.
10397 static bool
10398 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10399                                SourceLocation OpLoc,
10400                                ArrayRef<Expr *> Args) {
10401   DeclarationName OpName =
10402     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10403   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10404   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10405                                 OverloadCandidateSet::CSK_Operator,
10406                                 /*ExplicitTemplateArgs=*/nullptr, Args);
10407 }
10408
10409 namespace {
10410 class BuildRecoveryCallExprRAII {
10411   Sema &SemaRef;
10412 public:
10413   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10414     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10415     SemaRef.IsBuildingRecoveryCallExpr = true;
10416   }
10417
10418   ~BuildRecoveryCallExprRAII() {
10419     SemaRef.IsBuildingRecoveryCallExpr = false;
10420   }
10421 };
10422
10423 }
10424
10425 /// Attempts to recover from a call where no functions were found.
10426 ///
10427 /// Returns true if new candidates were found.
10428 static ExprResult
10429 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10430                       UnresolvedLookupExpr *ULE,
10431                       SourceLocation LParenLoc,
10432                       MutableArrayRef<Expr *> Args,
10433                       SourceLocation RParenLoc,
10434                       bool EmptyLookup, bool AllowTypoCorrection) {
10435   // Do not try to recover if it is already building a recovery call.
10436   // This stops infinite loops for template instantiations like
10437   //
10438   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10439   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10440   //
10441   if (SemaRef.IsBuildingRecoveryCallExpr)
10442     return ExprError();
10443   BuildRecoveryCallExprRAII RCE(SemaRef);
10444
10445   CXXScopeSpec SS;
10446   SS.Adopt(ULE->getQualifierLoc());
10447   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10448
10449   TemplateArgumentListInfo TABuffer;
10450   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10451   if (ULE->hasExplicitTemplateArgs()) {
10452     ULE->copyTemplateArgumentsInto(TABuffer);
10453     ExplicitTemplateArgs = &TABuffer;
10454   }
10455
10456   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10457                  Sema::LookupOrdinaryName);
10458   FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10459                                   ExplicitTemplateArgs != nullptr,
10460                                   dyn_cast<MemberExpr>(Fn));
10461   NoTypoCorrectionCCC RejectAll;
10462   CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10463       (CorrectionCandidateCallback*)&Validator :
10464       (CorrectionCandidateCallback*)&RejectAll;
10465   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10466                               OverloadCandidateSet::CSK_Normal,
10467                               ExplicitTemplateArgs, Args) &&
10468       (!EmptyLookup ||
10469        SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
10470                                    ExplicitTemplateArgs, Args)))
10471     return ExprError();
10472
10473   assert(!R.empty() && "lookup results empty despite recovery");
10474
10475   // Build an implicit member call if appropriate.  Just drop the
10476   // casts and such from the call, we don't really care.
10477   ExprResult NewFn = ExprError();
10478   if ((*R.begin())->isCXXClassMember())
10479     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10480                                                     R, ExplicitTemplateArgs);
10481   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10482     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10483                                         ExplicitTemplateArgs);
10484   else
10485     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10486
10487   if (NewFn.isInvalid())
10488     return ExprError();
10489
10490   // This shouldn't cause an infinite loop because we're giving it
10491   // an expression with viable lookup results, which should never
10492   // end up here.
10493   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
10494                                MultiExprArg(Args.data(), Args.size()),
10495                                RParenLoc);
10496 }
10497
10498 /// \brief Constructs and populates an OverloadedCandidateSet from
10499 /// the given function.
10500 /// \returns true when an the ExprResult output parameter has been set.
10501 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10502                                   UnresolvedLookupExpr *ULE,
10503                                   MultiExprArg Args,
10504                                   SourceLocation RParenLoc,
10505                                   OverloadCandidateSet *CandidateSet,
10506                                   ExprResult *Result) {
10507 #ifndef NDEBUG
10508   if (ULE->requiresADL()) {
10509     // To do ADL, we must have found an unqualified name.
10510     assert(!ULE->getQualifier() && "qualified name with ADL");
10511
10512     // We don't perform ADL for implicit declarations of builtins.
10513     // Verify that this was correctly set up.
10514     FunctionDecl *F;
10515     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10516         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10517         F->getBuiltinID() && F->isImplicit())
10518       llvm_unreachable("performing ADL for builtin");
10519
10520     // We don't perform ADL in C.
10521     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10522   }
10523 #endif
10524
10525   UnbridgedCastsSet UnbridgedCasts;
10526   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10527     *Result = ExprError();
10528     return true;
10529   }
10530
10531   // Add the functions denoted by the callee to the set of candidate
10532   // functions, including those from argument-dependent lookup.
10533   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10534
10535   // If we found nothing, try to recover.
10536   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10537   // out if it fails.
10538   if (CandidateSet->empty()) {
10539     // In Microsoft mode, if we are inside a template class member function then
10540     // create a type dependent CallExpr. The goal is to postpone name lookup
10541     // to instantiation time to be able to search into type dependent base
10542     // classes.
10543     if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
10544         (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10545       CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10546                                             Context.DependentTy, VK_RValue,
10547                                             RParenLoc);
10548       CE->setTypeDependent(true);
10549       *Result = CE;
10550       return true;
10551     }
10552     return false;
10553   }
10554
10555   UnbridgedCasts.restore();
10556   return false;
10557 }
10558
10559 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10560 /// the completed call expression. If overload resolution fails, emits
10561 /// diagnostics and returns ExprError()
10562 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10563                                            UnresolvedLookupExpr *ULE,
10564                                            SourceLocation LParenLoc,
10565                                            MultiExprArg Args,
10566                                            SourceLocation RParenLoc,
10567                                            Expr *ExecConfig,
10568                                            OverloadCandidateSet *CandidateSet,
10569                                            OverloadCandidateSet::iterator *Best,
10570                                            OverloadingResult OverloadResult,
10571                                            bool AllowTypoCorrection) {
10572   if (CandidateSet->empty())
10573     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10574                                  RParenLoc, /*EmptyLookup=*/true,
10575                                  AllowTypoCorrection);
10576
10577   switch (OverloadResult) {
10578   case OR_Success: {
10579     FunctionDecl *FDecl = (*Best)->Function;
10580     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10581     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10582       return ExprError();
10583     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10584     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10585                                          ExecConfig);
10586   }
10587
10588   case OR_No_Viable_Function: {
10589     // Try to recover by looking for viable functions which the user might
10590     // have meant to call.
10591     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10592                                                 Args, RParenLoc,
10593                                                 /*EmptyLookup=*/false,
10594                                                 AllowTypoCorrection);
10595     if (!Recovery.isInvalid())
10596       return Recovery;
10597
10598     SemaRef.Diag(Fn->getLocStart(),
10599          diag::err_ovl_no_viable_function_in_call)
10600       << ULE->getName() << Fn->getSourceRange();
10601     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10602     break;
10603   }
10604
10605   case OR_Ambiguous:
10606     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10607       << ULE->getName() << Fn->getSourceRange();
10608     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10609     break;
10610
10611   case OR_Deleted: {
10612     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10613       << (*Best)->Function->isDeleted()
10614       << ULE->getName()
10615       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10616       << Fn->getSourceRange();
10617     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10618
10619     // We emitted an error for the unvailable/deleted function call but keep
10620     // the call in the AST.
10621     FunctionDecl *FDecl = (*Best)->Function;
10622     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10623     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10624                                          ExecConfig);
10625   }
10626   }
10627
10628   // Overload resolution failed.
10629   return ExprError();
10630 }
10631
10632 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10633 /// (which eventually refers to the declaration Func) and the call
10634 /// arguments Args/NumArgs, attempt to resolve the function call down
10635 /// to a specific function. If overload resolution succeeds, returns
10636 /// the call expression produced by overload resolution.
10637 /// Otherwise, emits diagnostics and returns ExprError.
10638 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10639                                          UnresolvedLookupExpr *ULE,
10640                                          SourceLocation LParenLoc,
10641                                          MultiExprArg Args,
10642                                          SourceLocation RParenLoc,
10643                                          Expr *ExecConfig,
10644                                          bool AllowTypoCorrection) {
10645   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10646                                     OverloadCandidateSet::CSK_Normal);
10647   ExprResult result;
10648
10649   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10650                              &result))
10651     return result;
10652
10653   OverloadCandidateSet::iterator Best;
10654   OverloadingResult OverloadResult =
10655       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10656
10657   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10658                                   RParenLoc, ExecConfig, &CandidateSet,
10659                                   &Best, OverloadResult,
10660                                   AllowTypoCorrection);
10661 }
10662
10663 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10664   return Functions.size() > 1 ||
10665     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10666 }
10667
10668 /// \brief Create a unary operation that may resolve to an overloaded
10669 /// operator.
10670 ///
10671 /// \param OpLoc The location of the operator itself (e.g., '*').
10672 ///
10673 /// \param OpcIn The UnaryOperator::Opcode that describes this
10674 /// operator.
10675 ///
10676 /// \param Fns The set of non-member functions that will be
10677 /// considered by overload resolution. The caller needs to build this
10678 /// set based on the context using, e.g.,
10679 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10680 /// set should not contain any member functions; those will be added
10681 /// by CreateOverloadedUnaryOp().
10682 ///
10683 /// \param Input The input argument.
10684 ExprResult
10685 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10686                               const UnresolvedSetImpl &Fns,
10687                               Expr *Input) {
10688   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10689
10690   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10691   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10692   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10693   // TODO: provide better source location info.
10694   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10695
10696   if (checkPlaceholderForOverload(*this, Input))
10697     return ExprError();
10698
10699   Expr *Args[2] = { Input, nullptr };
10700   unsigned NumArgs = 1;
10701
10702   // For post-increment and post-decrement, add the implicit '0' as
10703   // the second argument, so that we know this is a post-increment or
10704   // post-decrement.
10705   if (Opc == UO_PostInc || Opc == UO_PostDec) {
10706     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10707     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10708                                      SourceLocation());
10709     NumArgs = 2;
10710   }
10711
10712   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10713
10714   if (Input->isTypeDependent()) {
10715     if (Fns.empty())
10716       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10717                                          VK_RValue, OK_Ordinary, OpLoc);
10718
10719     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10720     UnresolvedLookupExpr *Fn
10721       = UnresolvedLookupExpr::Create(Context, NamingClass,
10722                                      NestedNameSpecifierLoc(), OpNameInfo,
10723                                      /*ADL*/ true, IsOverloaded(Fns),
10724                                      Fns.begin(), Fns.end());
10725     return new (Context)
10726         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10727                             VK_RValue, OpLoc, false);
10728   }
10729
10730   // Build an empty overload set.
10731   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
10732
10733   // Add the candidates from the given function set.
10734   AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
10735
10736   // Add operator candidates that are member functions.
10737   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10738
10739   // Add candidates from ADL.
10740   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
10741                                        /*ExplicitTemplateArgs*/nullptr,
10742                                        CandidateSet);
10743
10744   // Add builtin operator candidates.
10745   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10746
10747   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10748
10749   // Perform overload resolution.
10750   OverloadCandidateSet::iterator Best;
10751   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10752   case OR_Success: {
10753     // We found a built-in operator or an overloaded operator.
10754     FunctionDecl *FnDecl = Best->Function;
10755
10756     if (FnDecl) {
10757       // We matched an overloaded operator. Build a call to that
10758       // operator.
10759
10760       // Convert the arguments.
10761       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10762         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
10763
10764         ExprResult InputRes =
10765           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
10766                                               Best->FoundDecl, Method);
10767         if (InputRes.isInvalid())
10768           return ExprError();
10769         Input = InputRes.get();
10770       } else {
10771         // Convert the arguments.
10772         ExprResult InputInit
10773           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10774                                                       Context,
10775                                                       FnDecl->getParamDecl(0)),
10776                                       SourceLocation(),
10777                                       Input);
10778         if (InputInit.isInvalid())
10779           return ExprError();
10780         Input = InputInit.get();
10781       }
10782
10783       // Build the actual expression node.
10784       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10785                                                 HadMultipleCandidates, OpLoc);
10786       if (FnExpr.isInvalid())
10787         return ExprError();
10788
10789       // Determine the result type.
10790       QualType ResultTy = FnDecl->getReturnType();
10791       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10792       ResultTy = ResultTy.getNonLValueExprType(Context);
10793
10794       Args[0] = Input;
10795       CallExpr *TheCall =
10796         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
10797                                           ResultTy, VK, OpLoc, false);
10798
10799       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
10800         return ExprError();
10801
10802       return MaybeBindToTemporary(TheCall);
10803     } else {
10804       // We matched a built-in operator. Convert the arguments, then
10805       // break out so that we will build the appropriate built-in
10806       // operator node.
10807       ExprResult InputRes =
10808         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10809                                   Best->Conversions[0], AA_Passing);
10810       if (InputRes.isInvalid())
10811         return ExprError();
10812       Input = InputRes.get();
10813       break;
10814     }
10815   }
10816
10817   case OR_No_Viable_Function:
10818     // This is an erroneous use of an operator which can be overloaded by
10819     // a non-member function. Check for non-member operators which were
10820     // defined too late to be candidates.
10821     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
10822       // FIXME: Recover by calling the found function.
10823       return ExprError();
10824
10825     // No viable function; fall through to handling this as a
10826     // built-in operator, which will produce an error message for us.
10827     break;
10828
10829   case OR_Ambiguous:
10830     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10831         << UnaryOperator::getOpcodeStr(Opc)
10832         << Input->getType()
10833         << Input->getSourceRange();
10834     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
10835                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10836     return ExprError();
10837
10838   case OR_Deleted:
10839     Diag(OpLoc, diag::err_ovl_deleted_oper)
10840       << Best->Function->isDeleted()
10841       << UnaryOperator::getOpcodeStr(Opc)
10842       << getDeletedOrUnavailableSuffix(Best->Function)
10843       << Input->getSourceRange();
10844     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
10845                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10846     return ExprError();
10847   }
10848
10849   // Either we found no viable overloaded operator or we matched a
10850   // built-in operator. In either case, fall through to trying to
10851   // build a built-in operation.
10852   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10853 }
10854
10855 /// \brief Create a binary operation that may resolve to an overloaded
10856 /// operator.
10857 ///
10858 /// \param OpLoc The location of the operator itself (e.g., '+').
10859 ///
10860 /// \param OpcIn The BinaryOperator::Opcode that describes this
10861 /// operator.
10862 ///
10863 /// \param Fns The set of non-member functions that will be
10864 /// considered by overload resolution. The caller needs to build this
10865 /// set based on the context using, e.g.,
10866 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10867 /// set should not contain any member functions; those will be added
10868 /// by CreateOverloadedBinOp().
10869 ///
10870 /// \param LHS Left-hand argument.
10871 /// \param RHS Right-hand argument.
10872 ExprResult
10873 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10874                             unsigned OpcIn,
10875                             const UnresolvedSetImpl &Fns,
10876                             Expr *LHS, Expr *RHS) {
10877   Expr *Args[2] = { LHS, RHS };
10878   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
10879
10880   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10881   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10882   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10883
10884   // If either side is type-dependent, create an appropriate dependent
10885   // expression.
10886   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10887     if (Fns.empty()) {
10888       // If there are no functions to store, just build a dependent
10889       // BinaryOperator or CompoundAssignment.
10890       if (Opc <= BO_Assign || Opc > BO_OrAssign)
10891         return new (Context) BinaryOperator(
10892             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
10893             OpLoc, FPFeatures.fp_contract);
10894
10895       return new (Context) CompoundAssignOperator(
10896           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
10897           Context.DependentTy, Context.DependentTy, OpLoc,
10898           FPFeatures.fp_contract);
10899     }
10900
10901     // FIXME: save results of ADL from here?
10902     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10903     // TODO: provide better source location info in DNLoc component.
10904     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10905     UnresolvedLookupExpr *Fn
10906       = UnresolvedLookupExpr::Create(Context, NamingClass, 
10907                                      NestedNameSpecifierLoc(), OpNameInfo, 
10908                                      /*ADL*/ true, IsOverloaded(Fns),
10909                                      Fns.begin(), Fns.end());
10910     return new (Context)
10911         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
10912                             VK_RValue, OpLoc, FPFeatures.fp_contract);
10913   }
10914
10915   // Always do placeholder-like conversions on the RHS.
10916   if (checkPlaceholderForOverload(*this, Args[1]))
10917     return ExprError();
10918
10919   // Do placeholder-like conversion on the LHS; note that we should
10920   // not get here with a PseudoObject LHS.
10921   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10922   if (checkPlaceholderForOverload(*this, Args[0]))
10923     return ExprError();
10924
10925   // If this is the assignment operator, we only perform overload resolution
10926   // if the left-hand side is a class or enumeration type. This is actually
10927   // a hack. The standard requires that we do overload resolution between the
10928   // various built-in candidates, but as DR507 points out, this can lead to
10929   // problems. So we do it this way, which pretty much follows what GCC does.
10930   // Note that we go the traditional code path for compound assignment forms.
10931   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10932     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10933
10934   // If this is the .* operator, which is not overloadable, just
10935   // create a built-in binary operator.
10936   if (Opc == BO_PtrMemD)
10937     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10938
10939   // Build an empty overload set.
10940   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
10941
10942   // Add the candidates from the given function set.
10943   AddFunctionCandidates(Fns, Args, CandidateSet, false);
10944
10945   // Add operator candidates that are member functions.
10946   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10947
10948   // Add candidates from ADL.
10949   AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
10950                                        /*ExplicitTemplateArgs*/ nullptr,
10951                                        CandidateSet);
10952
10953   // Add builtin operator candidates.
10954   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10955
10956   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10957
10958   // Perform overload resolution.
10959   OverloadCandidateSet::iterator Best;
10960   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10961     case OR_Success: {
10962       // We found a built-in operator or an overloaded operator.
10963       FunctionDecl *FnDecl = Best->Function;
10964
10965       if (FnDecl) {
10966         // We matched an overloaded operator. Build a call to that
10967         // operator.
10968
10969         // Convert the arguments.
10970         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10971           // Best->Access is only meaningful for class members.
10972           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10973
10974           ExprResult Arg1 =
10975             PerformCopyInitialization(
10976               InitializedEntity::InitializeParameter(Context,
10977                                                      FnDecl->getParamDecl(0)),
10978               SourceLocation(), Args[1]);
10979           if (Arg1.isInvalid())
10980             return ExprError();
10981
10982           ExprResult Arg0 =
10983             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
10984                                                 Best->FoundDecl, Method);
10985           if (Arg0.isInvalid())
10986             return ExprError();
10987           Args[0] = Arg0.getAs<Expr>();
10988           Args[1] = RHS = Arg1.getAs<Expr>();
10989         } else {
10990           // Convert the arguments.
10991           ExprResult Arg0 = PerformCopyInitialization(
10992             InitializedEntity::InitializeParameter(Context,
10993                                                    FnDecl->getParamDecl(0)),
10994             SourceLocation(), Args[0]);
10995           if (Arg0.isInvalid())
10996             return ExprError();
10997
10998           ExprResult Arg1 =
10999             PerformCopyInitialization(
11000               InitializedEntity::InitializeParameter(Context,
11001                                                      FnDecl->getParamDecl(1)),
11002               SourceLocation(), Args[1]);
11003           if (Arg1.isInvalid())
11004             return ExprError();
11005           Args[0] = LHS = Arg0.getAs<Expr>();
11006           Args[1] = RHS = Arg1.getAs<Expr>();
11007         }
11008
11009         // Build the actual expression node.
11010         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11011                                                   Best->FoundDecl,
11012                                                   HadMultipleCandidates, OpLoc);
11013         if (FnExpr.isInvalid())
11014           return ExprError();
11015
11016         // Determine the result type.
11017         QualType ResultTy = FnDecl->getReturnType();
11018         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11019         ResultTy = ResultTy.getNonLValueExprType(Context);
11020
11021         CXXOperatorCallExpr *TheCall =
11022           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11023                                             Args, ResultTy, VK, OpLoc,
11024                                             FPFeatures.fp_contract);
11025
11026         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11027                                 FnDecl))
11028           return ExprError();
11029
11030         ArrayRef<const Expr *> ArgsArray(Args, 2);
11031         // Cut off the implicit 'this'.
11032         if (isa<CXXMethodDecl>(FnDecl))
11033           ArgsArray = ArgsArray.slice(1);
11034         checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 
11035                   TheCall->getSourceRange(), VariadicDoesNotApply);
11036
11037         return MaybeBindToTemporary(TheCall);
11038       } else {
11039         // We matched a built-in operator. Convert the arguments, then
11040         // break out so that we will build the appropriate built-in
11041         // operator node.
11042         ExprResult ArgsRes0 =
11043           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11044                                     Best->Conversions[0], AA_Passing);
11045         if (ArgsRes0.isInvalid())
11046           return ExprError();
11047         Args[0] = ArgsRes0.get();
11048
11049         ExprResult ArgsRes1 =
11050           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11051                                     Best->Conversions[1], AA_Passing);
11052         if (ArgsRes1.isInvalid())
11053           return ExprError();
11054         Args[1] = ArgsRes1.get();
11055         break;
11056       }
11057     }
11058
11059     case OR_No_Viable_Function: {
11060       // C++ [over.match.oper]p9:
11061       //   If the operator is the operator , [...] and there are no
11062       //   viable functions, then the operator is assumed to be the
11063       //   built-in operator and interpreted according to clause 5.
11064       if (Opc == BO_Comma)
11065         break;
11066
11067       // For class as left operand for assignment or compound assigment
11068       // operator do not fall through to handling in built-in, but report that
11069       // no overloaded assignment operator found
11070       ExprResult Result = ExprError();
11071       if (Args[0]->getType()->isRecordType() &&
11072           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11073         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11074              << BinaryOperator::getOpcodeStr(Opc)
11075              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11076         if (Args[0]->getType()->isIncompleteType()) {
11077           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11078             << Args[0]->getType()
11079             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11080         }
11081       } else {
11082         // This is an erroneous use of an operator which can be overloaded by
11083         // a non-member function. Check for non-member operators which were
11084         // defined too late to be candidates.
11085         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11086           // FIXME: Recover by calling the found function.
11087           return ExprError();
11088
11089         // No viable function; try to create a built-in operation, which will
11090         // produce an error. Then, show the non-viable candidates.
11091         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11092       }
11093       assert(Result.isInvalid() &&
11094              "C++ binary operator overloading is missing candidates!");
11095       if (Result.isInvalid())
11096         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11097                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11098       return Result;
11099     }
11100
11101     case OR_Ambiguous:
11102       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11103           << BinaryOperator::getOpcodeStr(Opc)
11104           << Args[0]->getType() << Args[1]->getType()
11105           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11106       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11107                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11108       return ExprError();
11109
11110     case OR_Deleted:
11111       if (isImplicitlyDeleted(Best->Function)) {
11112         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11113         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11114           << Context.getRecordType(Method->getParent())
11115           << getSpecialMember(Method);
11116
11117         // The user probably meant to call this special member. Just
11118         // explain why it's deleted.
11119         NoteDeletedFunction(Method);
11120         return ExprError();
11121       } else {
11122         Diag(OpLoc, diag::err_ovl_deleted_oper)
11123           << Best->Function->isDeleted()
11124           << BinaryOperator::getOpcodeStr(Opc)
11125           << getDeletedOrUnavailableSuffix(Best->Function)
11126           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11127       }
11128       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11129                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11130       return ExprError();
11131   }
11132
11133   // We matched a built-in operator; build it.
11134   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11135 }
11136
11137 ExprResult
11138 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11139                                          SourceLocation RLoc,
11140                                          Expr *Base, Expr *Idx) {
11141   Expr *Args[2] = { Base, Idx };
11142   DeclarationName OpName =
11143       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11144
11145   // If either side is type-dependent, create an appropriate dependent
11146   // expression.
11147   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11148
11149     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11150     // CHECKME: no 'operator' keyword?
11151     DeclarationNameInfo OpNameInfo(OpName, LLoc);
11152     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11153     UnresolvedLookupExpr *Fn
11154       = UnresolvedLookupExpr::Create(Context, NamingClass,
11155                                      NestedNameSpecifierLoc(), OpNameInfo,
11156                                      /*ADL*/ true, /*Overloaded*/ false,
11157                                      UnresolvedSetIterator(),
11158                                      UnresolvedSetIterator());
11159     // Can't add any actual overloads yet
11160
11161     return new (Context)
11162         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11163                             Context.DependentTy, VK_RValue, RLoc, false);
11164   }
11165
11166   // Handle placeholders on both operands.
11167   if (checkPlaceholderForOverload(*this, Args[0]))
11168     return ExprError();
11169   if (checkPlaceholderForOverload(*this, Args[1]))
11170     return ExprError();
11171
11172   // Build an empty overload set.
11173   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11174
11175   // Subscript can only be overloaded as a member function.
11176
11177   // Add operator candidates that are member functions.
11178   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11179
11180   // Add builtin operator candidates.
11181   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11182
11183   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11184
11185   // Perform overload resolution.
11186   OverloadCandidateSet::iterator Best;
11187   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11188     case OR_Success: {
11189       // We found a built-in operator or an overloaded operator.
11190       FunctionDecl *FnDecl = Best->Function;
11191
11192       if (FnDecl) {
11193         // We matched an overloaded operator. Build a call to that
11194         // operator.
11195
11196         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11197
11198         // Convert the arguments.
11199         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11200         ExprResult Arg0 =
11201           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11202                                               Best->FoundDecl, Method);
11203         if (Arg0.isInvalid())
11204           return ExprError();
11205         Args[0] = Arg0.get();
11206
11207         // Convert the arguments.
11208         ExprResult InputInit
11209           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11210                                                       Context,
11211                                                       FnDecl->getParamDecl(0)),
11212                                       SourceLocation(),
11213                                       Args[1]);
11214         if (InputInit.isInvalid())
11215           return ExprError();
11216
11217         Args[1] = InputInit.getAs<Expr>();
11218
11219         // Build the actual expression node.
11220         DeclarationNameInfo OpLocInfo(OpName, LLoc);
11221         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11222         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11223                                                   Best->FoundDecl,
11224                                                   HadMultipleCandidates,
11225                                                   OpLocInfo.getLoc(),
11226                                                   OpLocInfo.getInfo());
11227         if (FnExpr.isInvalid())
11228           return ExprError();
11229
11230         // Determine the result type
11231         QualType ResultTy = FnDecl->getReturnType();
11232         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11233         ResultTy = ResultTy.getNonLValueExprType(Context);
11234
11235         CXXOperatorCallExpr *TheCall =
11236           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11237                                             FnExpr.get(), Args,
11238                                             ResultTy, VK, RLoc,
11239                                             false);
11240
11241         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11242           return ExprError();
11243
11244         return MaybeBindToTemporary(TheCall);
11245       } else {
11246         // We matched a built-in operator. Convert the arguments, then
11247         // break out so that we will build the appropriate built-in
11248         // operator node.
11249         ExprResult ArgsRes0 =
11250           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11251                                     Best->Conversions[0], AA_Passing);
11252         if (ArgsRes0.isInvalid())
11253           return ExprError();
11254         Args[0] = ArgsRes0.get();
11255
11256         ExprResult ArgsRes1 =
11257           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11258                                     Best->Conversions[1], AA_Passing);
11259         if (ArgsRes1.isInvalid())
11260           return ExprError();
11261         Args[1] = ArgsRes1.get();
11262
11263         break;
11264       }
11265     }
11266
11267     case OR_No_Viable_Function: {
11268       if (CandidateSet.empty())
11269         Diag(LLoc, diag::err_ovl_no_oper)
11270           << Args[0]->getType() << /*subscript*/ 0
11271           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11272       else
11273         Diag(LLoc, diag::err_ovl_no_viable_subscript)
11274           << Args[0]->getType()
11275           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11276       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11277                                   "[]", LLoc);
11278       return ExprError();
11279     }
11280
11281     case OR_Ambiguous:
11282       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
11283           << "[]"
11284           << Args[0]->getType() << Args[1]->getType()
11285           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11286       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11287                                   "[]", LLoc);
11288       return ExprError();
11289
11290     case OR_Deleted:
11291       Diag(LLoc, diag::err_ovl_deleted_oper)
11292         << Best->Function->isDeleted() << "[]"
11293         << getDeletedOrUnavailableSuffix(Best->Function)
11294         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11295       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11296                                   "[]", LLoc);
11297       return ExprError();
11298     }
11299
11300   // We matched a built-in operator; build it.
11301   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11302 }
11303
11304 /// BuildCallToMemberFunction - Build a call to a member
11305 /// function. MemExpr is the expression that refers to the member
11306 /// function (and includes the object parameter), Args/NumArgs are the
11307 /// arguments to the function call (not including the object
11308 /// parameter). The caller needs to validate that the member
11309 /// expression refers to a non-static member function or an overloaded
11310 /// member function.
11311 ExprResult
11312 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11313                                 SourceLocation LParenLoc,
11314                                 MultiExprArg Args,
11315                                 SourceLocation RParenLoc) {
11316   assert(MemExprE->getType() == Context.BoundMemberTy ||
11317          MemExprE->getType() == Context.OverloadTy);
11318
11319   // Dig out the member expression. This holds both the object
11320   // argument and the member function we're referring to.
11321   Expr *NakedMemExpr = MemExprE->IgnoreParens();
11322
11323   // Determine whether this is a call to a pointer-to-member function.
11324   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11325     assert(op->getType() == Context.BoundMemberTy);
11326     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11327
11328     QualType fnType =
11329       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11330
11331     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11332     QualType resultType = proto->getCallResultType(Context);
11333     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
11334
11335     // Check that the object type isn't more qualified than the
11336     // member function we're calling.
11337     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11338
11339     QualType objectType = op->getLHS()->getType();
11340     if (op->getOpcode() == BO_PtrMemI)
11341       objectType = objectType->castAs<PointerType>()->getPointeeType();
11342     Qualifiers objectQuals = objectType.getQualifiers();
11343
11344     Qualifiers difference = objectQuals - funcQuals;
11345     difference.removeObjCGCAttr();
11346     difference.removeAddressSpace();
11347     if (difference) {
11348       std::string qualsString = difference.getAsString();
11349       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11350         << fnType.getUnqualifiedType()
11351         << qualsString
11352         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11353     }
11354
11355     CXXMemberCallExpr *call
11356       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11357                                         resultType, valueKind, RParenLoc);
11358
11359     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
11360                             call, nullptr))
11361       return ExprError();
11362
11363     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
11364       return ExprError();
11365
11366     if (CheckOtherCall(call, proto))
11367       return ExprError();
11368
11369     return MaybeBindToTemporary(call);
11370   }
11371
11372   UnbridgedCastsSet UnbridgedCasts;
11373   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11374     return ExprError();
11375
11376   MemberExpr *MemExpr;
11377   CXXMethodDecl *Method = nullptr;
11378   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11379   NestedNameSpecifier *Qualifier = nullptr;
11380   if (isa<MemberExpr>(NakedMemExpr)) {
11381     MemExpr = cast<MemberExpr>(NakedMemExpr);
11382     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11383     FoundDecl = MemExpr->getFoundDecl();
11384     Qualifier = MemExpr->getQualifier();
11385     UnbridgedCasts.restore();
11386   } else {
11387     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11388     Qualifier = UnresExpr->getQualifier();
11389
11390     QualType ObjectType = UnresExpr->getBaseType();
11391     Expr::Classification ObjectClassification
11392       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11393                             : UnresExpr->getBase()->Classify(Context);
11394
11395     // Add overload candidates
11396     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11397                                       OverloadCandidateSet::CSK_Normal);
11398
11399     // FIXME: avoid copy.
11400     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
11401     if (UnresExpr->hasExplicitTemplateArgs()) {
11402       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11403       TemplateArgs = &TemplateArgsBuffer;
11404     }
11405
11406     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11407            E = UnresExpr->decls_end(); I != E; ++I) {
11408
11409       NamedDecl *Func = *I;
11410       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11411       if (isa<UsingShadowDecl>(Func))
11412         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11413
11414
11415       // Microsoft supports direct constructor calls.
11416       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11417         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11418                              Args, CandidateSet);
11419       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11420         // If explicit template arguments were provided, we can't call a
11421         // non-template member function.
11422         if (TemplateArgs)
11423           continue;
11424
11425         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11426                            ObjectClassification, Args, CandidateSet,
11427                            /*SuppressUserConversions=*/false);
11428       } else {
11429         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11430                                    I.getPair(), ActingDC, TemplateArgs,
11431                                    ObjectType,  ObjectClassification,
11432                                    Args, CandidateSet,
11433                                    /*SuppressUsedConversions=*/false);
11434       }
11435     }
11436
11437     DeclarationName DeclName = UnresExpr->getMemberName();
11438
11439     UnbridgedCasts.restore();
11440
11441     OverloadCandidateSet::iterator Best;
11442     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11443                                             Best)) {
11444     case OR_Success:
11445       Method = cast<CXXMethodDecl>(Best->Function);
11446       FoundDecl = Best->FoundDecl;
11447       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11448       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11449         return ExprError();
11450       // If FoundDecl is different from Method (such as if one is a template
11451       // and the other a specialization), make sure DiagnoseUseOfDecl is 
11452       // called on both.
11453       // FIXME: This would be more comprehensively addressed by modifying
11454       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11455       // being used.
11456       if (Method != FoundDecl.getDecl() && 
11457                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11458         return ExprError();
11459       break;
11460
11461     case OR_No_Viable_Function:
11462       Diag(UnresExpr->getMemberLoc(),
11463            diag::err_ovl_no_viable_member_function_in_call)
11464         << DeclName << MemExprE->getSourceRange();
11465       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11466       // FIXME: Leaking incoming expressions!
11467       return ExprError();
11468
11469     case OR_Ambiguous:
11470       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11471         << DeclName << MemExprE->getSourceRange();
11472       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11473       // FIXME: Leaking incoming expressions!
11474       return ExprError();
11475
11476     case OR_Deleted:
11477       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11478         << Best->Function->isDeleted()
11479         << DeclName 
11480         << getDeletedOrUnavailableSuffix(Best->Function)
11481         << MemExprE->getSourceRange();
11482       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11483       // FIXME: Leaking incoming expressions!
11484       return ExprError();
11485     }
11486
11487     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11488
11489     // If overload resolution picked a static member, build a
11490     // non-member call based on that function.
11491     if (Method->isStatic()) {
11492       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11493                                    RParenLoc);
11494     }
11495
11496     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11497   }
11498
11499   QualType ResultType = Method->getReturnType();
11500   ExprValueKind VK = Expr::getValueKindForType(ResultType);
11501   ResultType = ResultType.getNonLValueExprType(Context);
11502
11503   assert(Method && "Member call to something that isn't a method?");
11504   CXXMemberCallExpr *TheCall =
11505     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11506                                     ResultType, VK, RParenLoc);
11507
11508   // Check for a valid return type.
11509   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
11510                           TheCall, Method))
11511     return ExprError();
11512
11513   // Convert the object argument (for a non-static member function call).
11514   // We only need to do this if there was actually an overload; otherwise
11515   // it was done at lookup.
11516   if (!Method->isStatic()) {
11517     ExprResult ObjectArg =
11518       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11519                                           FoundDecl, Method);
11520     if (ObjectArg.isInvalid())
11521       return ExprError();
11522     MemExpr->setBase(ObjectArg.get());
11523   }
11524
11525   // Convert the rest of the arguments
11526   const FunctionProtoType *Proto =
11527     Method->getType()->getAs<FunctionProtoType>();
11528   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11529                               RParenLoc))
11530     return ExprError();
11531
11532   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11533
11534   if (CheckFunctionCall(Method, TheCall, Proto))
11535     return ExprError();
11536
11537   if ((isa<CXXConstructorDecl>(CurContext) || 
11538        isa<CXXDestructorDecl>(CurContext)) && 
11539       TheCall->getMethodDecl()->isPure()) {
11540     const CXXMethodDecl *MD = TheCall->getMethodDecl();
11541
11542     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11543       Diag(MemExpr->getLocStart(), 
11544            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11545         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11546         << MD->getParent()->getDeclName();
11547
11548       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11549     }
11550   }
11551   return MaybeBindToTemporary(TheCall);
11552 }
11553
11554 /// BuildCallToObjectOfClassType - Build a call to an object of class
11555 /// type (C++ [over.call.object]), which can end up invoking an
11556 /// overloaded function call operator (@c operator()) or performing a
11557 /// user-defined conversion on the object argument.
11558 ExprResult
11559 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11560                                    SourceLocation LParenLoc,
11561                                    MultiExprArg Args,
11562                                    SourceLocation RParenLoc) {
11563   if (checkPlaceholderForOverload(*this, Obj))
11564     return ExprError();
11565   ExprResult Object = Obj;
11566
11567   UnbridgedCastsSet UnbridgedCasts;
11568   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11569     return ExprError();
11570
11571   assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11572   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11573
11574   // C++ [over.call.object]p1:
11575   //  If the primary-expression E in the function call syntax
11576   //  evaluates to a class object of type "cv T", then the set of
11577   //  candidate functions includes at least the function call
11578   //  operators of T. The function call operators of T are obtained by
11579   //  ordinary lookup of the name operator() in the context of
11580   //  (E).operator().
11581   OverloadCandidateSet CandidateSet(LParenLoc,
11582                                     OverloadCandidateSet::CSK_Operator);
11583   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11584
11585   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11586                           diag::err_incomplete_object_call, Object.get()))
11587     return true;
11588
11589   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11590   LookupQualifiedName(R, Record->getDecl());
11591   R.suppressDiagnostics();
11592
11593   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11594        Oper != OperEnd; ++Oper) {
11595     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11596                        Object.get()->Classify(Context),
11597                        Args, CandidateSet,
11598                        /*SuppressUserConversions=*/ false);
11599   }
11600
11601   // C++ [over.call.object]p2:
11602   //   In addition, for each (non-explicit in C++0x) conversion function 
11603   //   declared in T of the form
11604   //
11605   //        operator conversion-type-id () cv-qualifier;
11606   //
11607   //   where cv-qualifier is the same cv-qualification as, or a
11608   //   greater cv-qualification than, cv, and where conversion-type-id
11609   //   denotes the type "pointer to function of (P1,...,Pn) returning
11610   //   R", or the type "reference to pointer to function of
11611   //   (P1,...,Pn) returning R", or the type "reference to function
11612   //   of (P1,...,Pn) returning R", a surrogate call function [...]
11613   //   is also considered as a candidate function. Similarly,
11614   //   surrogate call functions are added to the set of candidate
11615   //   functions for each conversion function declared in an
11616   //   accessible base class provided the function is not hidden
11617   //   within T by another intervening declaration.
11618   std::pair<CXXRecordDecl::conversion_iterator,
11619             CXXRecordDecl::conversion_iterator> Conversions
11620     = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11621   for (CXXRecordDecl::conversion_iterator
11622          I = Conversions.first, E = Conversions.second; I != E; ++I) {
11623     NamedDecl *D = *I;
11624     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11625     if (isa<UsingShadowDecl>(D))
11626       D = cast<UsingShadowDecl>(D)->getTargetDecl();
11627
11628     // Skip over templated conversion functions; they aren't
11629     // surrogates.
11630     if (isa<FunctionTemplateDecl>(D))
11631       continue;
11632
11633     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11634     if (!Conv->isExplicit()) {
11635       // Strip the reference type (if any) and then the pointer type (if
11636       // any) to get down to what might be a function type.
11637       QualType ConvType = Conv->getConversionType().getNonReferenceType();
11638       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11639         ConvType = ConvPtrType->getPointeeType();
11640
11641       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11642       {
11643         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11644                               Object.get(), Args, CandidateSet);
11645       }
11646     }
11647   }
11648
11649   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11650
11651   // Perform overload resolution.
11652   OverloadCandidateSet::iterator Best;
11653   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11654                              Best)) {
11655   case OR_Success:
11656     // Overload resolution succeeded; we'll build the appropriate call
11657     // below.
11658     break;
11659
11660   case OR_No_Viable_Function:
11661     if (CandidateSet.empty())
11662       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11663         << Object.get()->getType() << /*call*/ 1
11664         << Object.get()->getSourceRange();
11665     else
11666       Diag(Object.get()->getLocStart(),
11667            diag::err_ovl_no_viable_object_call)
11668         << Object.get()->getType() << Object.get()->getSourceRange();
11669     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11670     break;
11671
11672   case OR_Ambiguous:
11673     Diag(Object.get()->getLocStart(),
11674          diag::err_ovl_ambiguous_object_call)
11675       << Object.get()->getType() << Object.get()->getSourceRange();
11676     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11677     break;
11678
11679   case OR_Deleted:
11680     Diag(Object.get()->getLocStart(),
11681          diag::err_ovl_deleted_object_call)
11682       << Best->Function->isDeleted()
11683       << Object.get()->getType() 
11684       << getDeletedOrUnavailableSuffix(Best->Function)
11685       << Object.get()->getSourceRange();
11686     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11687     break;
11688   }
11689
11690   if (Best == CandidateSet.end())
11691     return true;
11692
11693   UnbridgedCasts.restore();
11694
11695   if (Best->Function == nullptr) {
11696     // Since there is no function declaration, this is one of the
11697     // surrogate candidates. Dig out the conversion function.
11698     CXXConversionDecl *Conv
11699       = cast<CXXConversionDecl>(
11700                          Best->Conversions[0].UserDefined.ConversionFunction);
11701
11702     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11703                               Best->FoundDecl);
11704     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11705       return ExprError();
11706     assert(Conv == Best->FoundDecl.getDecl() && 
11707              "Found Decl & conversion-to-functionptr should be same, right?!");
11708     // We selected one of the surrogate functions that converts the
11709     // object parameter to a function pointer. Perform the conversion
11710     // on the object argument, then let ActOnCallExpr finish the job.
11711
11712     // Create an implicit member expr to refer to the conversion operator.
11713     // and then call it.
11714     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11715                                              Conv, HadMultipleCandidates);
11716     if (Call.isInvalid())
11717       return ExprError();
11718     // Record usage of conversion in an implicit cast.
11719     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11720                                     CK_UserDefinedConversion, Call.get(),
11721                                     nullptr, VK_RValue);
11722
11723     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11724   }
11725
11726   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
11727
11728   // We found an overloaded operator(). Build a CXXOperatorCallExpr
11729   // that calls this method, using Object for the implicit object
11730   // parameter and passing along the remaining arguments.
11731   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11732
11733   // An error diagnostic has already been printed when parsing the declaration.
11734   if (Method->isInvalidDecl())
11735     return ExprError();
11736
11737   const FunctionProtoType *Proto =
11738     Method->getType()->getAs<FunctionProtoType>();
11739
11740   unsigned NumParams = Proto->getNumParams();
11741
11742   DeclarationNameInfo OpLocInfo(
11743                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11744   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11745   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11746                                            HadMultipleCandidates,
11747                                            OpLocInfo.getLoc(),
11748                                            OpLocInfo.getInfo());
11749   if (NewFn.isInvalid())
11750     return true;
11751
11752   // Build the full argument list for the method call (the implicit object
11753   // parameter is placed at the beginning of the list).
11754   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
11755   MethodArgs[0] = Object.get();
11756   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11757
11758   // Once we've built TheCall, all of the expressions are properly
11759   // owned.
11760   QualType ResultTy = Method->getReturnType();
11761   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11762   ResultTy = ResultTy.getNonLValueExprType(Context);
11763
11764   CXXOperatorCallExpr *TheCall = new (Context)
11765       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
11766                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11767                           ResultTy, VK, RParenLoc, false);
11768   MethodArgs.reset();
11769
11770   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
11771     return true;
11772
11773   // We may have default arguments. If so, we need to allocate more
11774   // slots in the call for them.
11775   if (Args.size() < NumParams)
11776     TheCall->setNumArgs(Context, NumParams + 1);
11777
11778   bool IsError = false;
11779
11780   // Initialize the implicit object parameter.
11781   ExprResult ObjRes =
11782     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
11783                                         Best->FoundDecl, Method);
11784   if (ObjRes.isInvalid())
11785     IsError = true;
11786   else
11787     Object = ObjRes;
11788   TheCall->setArg(0, Object.get());
11789
11790   // Check the argument types.
11791   for (unsigned i = 0; i != NumParams; i++) {
11792     Expr *Arg;
11793     if (i < Args.size()) {
11794       Arg = Args[i];
11795
11796       // Pass the argument.
11797
11798       ExprResult InputInit
11799         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11800                                                     Context,
11801                                                     Method->getParamDecl(i)),
11802                                     SourceLocation(), Arg);
11803
11804       IsError |= InputInit.isInvalid();
11805       Arg = InputInit.getAs<Expr>();
11806     } else {
11807       ExprResult DefArg
11808         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11809       if (DefArg.isInvalid()) {
11810         IsError = true;
11811         break;
11812       }
11813
11814       Arg = DefArg.getAs<Expr>();
11815     }
11816
11817     TheCall->setArg(i + 1, Arg);
11818   }
11819
11820   // If this is a variadic call, handle args passed through "...".
11821   if (Proto->isVariadic()) {
11822     // Promote the arguments (C99 6.5.2.2p7).
11823     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
11824       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
11825                                                         nullptr);
11826       IsError |= Arg.isInvalid();
11827       TheCall->setArg(i + 1, Arg.get());
11828     }
11829   }
11830
11831   if (IsError) return true;
11832
11833   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11834
11835   if (CheckFunctionCall(Method, TheCall, Proto))
11836     return true;
11837
11838   return MaybeBindToTemporary(TheCall);
11839 }
11840
11841 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11842 ///  (if one exists), where @c Base is an expression of class type and
11843 /// @c Member is the name of the member we're trying to find.
11844 ExprResult
11845 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11846                                bool *NoArrowOperatorFound) {
11847   assert(Base->getType()->isRecordType() &&
11848          "left-hand side must have class type");
11849
11850   if (checkPlaceholderForOverload(*this, Base))
11851     return ExprError();
11852
11853   SourceLocation Loc = Base->getExprLoc();
11854
11855   // C++ [over.ref]p1:
11856   //
11857   //   [...] An expression x->m is interpreted as (x.operator->())->m
11858   //   for a class object x of type T if T::operator->() exists and if
11859   //   the operator is selected as the best match function by the
11860   //   overload resolution mechanism (13.3).
11861   DeclarationName OpName =
11862     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11863   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
11864   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11865
11866   if (RequireCompleteType(Loc, Base->getType(),
11867                           diag::err_typecheck_incomplete_tag, Base))
11868     return ExprError();
11869
11870   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11871   LookupQualifiedName(R, BaseRecord->getDecl());
11872   R.suppressDiagnostics();
11873
11874   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11875        Oper != OperEnd; ++Oper) {
11876     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11877                        None, CandidateSet, /*SuppressUserConversions=*/false);
11878   }
11879
11880   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11881
11882   // Perform overload resolution.
11883   OverloadCandidateSet::iterator Best;
11884   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11885   case OR_Success:
11886     // Overload resolution succeeded; we'll build the call below.
11887     break;
11888
11889   case OR_No_Viable_Function:
11890     if (CandidateSet.empty()) {
11891       QualType BaseType = Base->getType();
11892       if (NoArrowOperatorFound) {
11893         // Report this specific error to the caller instead of emitting a
11894         // diagnostic, as requested.
11895         *NoArrowOperatorFound = true;
11896         return ExprError();
11897       }
11898       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11899         << BaseType << Base->getSourceRange();
11900       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
11901         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
11902           << FixItHint::CreateReplacement(OpLoc, ".");
11903       }
11904     } else
11905       Diag(OpLoc, diag::err_ovl_no_viable_oper)
11906         << "operator->" << Base->getSourceRange();
11907     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11908     return ExprError();
11909
11910   case OR_Ambiguous:
11911     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11912       << "->" << Base->getType() << Base->getSourceRange();
11913     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11914     return ExprError();
11915
11916   case OR_Deleted:
11917     Diag(OpLoc,  diag::err_ovl_deleted_oper)
11918       << Best->Function->isDeleted()
11919       << "->" 
11920       << getDeletedOrUnavailableSuffix(Best->Function)
11921       << Base->getSourceRange();
11922     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11923     return ExprError();
11924   }
11925
11926   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
11927
11928   // Convert the object parameter.
11929   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11930   ExprResult BaseResult =
11931     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
11932                                         Best->FoundDecl, Method);
11933   if (BaseResult.isInvalid())
11934     return ExprError();
11935   Base = BaseResult.get();
11936
11937   // Build the operator call.
11938   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11939                                             HadMultipleCandidates, OpLoc);
11940   if (FnExpr.isInvalid())
11941     return ExprError();
11942
11943   QualType ResultTy = Method->getReturnType();
11944   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11945   ResultTy = ResultTy.getNonLValueExprType(Context);
11946   CXXOperatorCallExpr *TheCall =
11947     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
11948                                       Base, ResultTy, VK, OpLoc, false);
11949
11950   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
11951           return ExprError();
11952
11953   return MaybeBindToTemporary(TheCall);
11954 }
11955
11956 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11957 /// a literal operator described by the provided lookup results.
11958 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11959                                           DeclarationNameInfo &SuffixInfo,
11960                                           ArrayRef<Expr*> Args,
11961                                           SourceLocation LitEndLoc,
11962                                        TemplateArgumentListInfo *TemplateArgs) {
11963   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11964
11965   OverloadCandidateSet CandidateSet(UDSuffixLoc,
11966                                     OverloadCandidateSet::CSK_Normal);
11967   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11968                         TemplateArgs);
11969
11970   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11971
11972   // Perform overload resolution. This will usually be trivial, but might need
11973   // to perform substitutions for a literal operator template.
11974   OverloadCandidateSet::iterator Best;
11975   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11976   case OR_Success:
11977   case OR_Deleted:
11978     break;
11979
11980   case OR_No_Viable_Function:
11981     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11982       << R.getLookupName();
11983     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11984     return ExprError();
11985
11986   case OR_Ambiguous:
11987     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11988     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11989     return ExprError();
11990   }
11991
11992   FunctionDecl *FD = Best->Function;
11993   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11994                                         HadMultipleCandidates,
11995                                         SuffixInfo.getLoc(),
11996                                         SuffixInfo.getInfo());
11997   if (Fn.isInvalid())
11998     return true;
11999
12000   // Check the argument types. This should almost always be a no-op, except
12001   // that array-to-pointer decay is applied to string literals.
12002   Expr *ConvArgs[2];
12003   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12004     ExprResult InputInit = PerformCopyInitialization(
12005       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12006       SourceLocation(), Args[ArgIdx]);
12007     if (InputInit.isInvalid())
12008       return true;
12009     ConvArgs[ArgIdx] = InputInit.get();
12010   }
12011
12012   QualType ResultTy = FD->getReturnType();
12013   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12014   ResultTy = ResultTy.getNonLValueExprType(Context);
12015
12016   UserDefinedLiteral *UDL =
12017     new (Context) UserDefinedLiteral(Context, Fn.get(),
12018                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12019                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12020
12021   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12022     return ExprError();
12023
12024   if (CheckFunctionCall(FD, UDL, nullptr))
12025     return ExprError();
12026
12027   return MaybeBindToTemporary(UDL);
12028 }
12029
12030 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12031 /// given LookupResult is non-empty, it is assumed to describe a member which
12032 /// will be invoked. Otherwise, the function will be found via argument
12033 /// dependent lookup.
12034 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12035 /// otherwise CallExpr is set to ExprError() and some non-success value
12036 /// is returned.
12037 Sema::ForRangeStatus
12038 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12039                                 SourceLocation RangeLoc, VarDecl *Decl,
12040                                 BeginEndFunction BEF,
12041                                 const DeclarationNameInfo &NameInfo,
12042                                 LookupResult &MemberLookup,
12043                                 OverloadCandidateSet *CandidateSet,
12044                                 Expr *Range, ExprResult *CallExpr) {
12045   CandidateSet->clear();
12046   if (!MemberLookup.empty()) {
12047     ExprResult MemberRef =
12048         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12049                                  /*IsPtr=*/false, CXXScopeSpec(),
12050                                  /*TemplateKWLoc=*/SourceLocation(),
12051                                  /*FirstQualifierInScope=*/nullptr,
12052                                  MemberLookup,
12053                                  /*TemplateArgs=*/nullptr);
12054     if (MemberRef.isInvalid()) {
12055       *CallExpr = ExprError();
12056       Diag(Range->getLocStart(), diag::note_in_for_range)
12057           << RangeLoc << BEF << Range->getType();
12058       return FRS_DiagnosticIssued;
12059     }
12060     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12061     if (CallExpr->isInvalid()) {
12062       *CallExpr = ExprError();
12063       Diag(Range->getLocStart(), diag::note_in_for_range)
12064           << RangeLoc << BEF << Range->getType();
12065       return FRS_DiagnosticIssued;
12066     }
12067   } else {
12068     UnresolvedSet<0> FoundNames;
12069     UnresolvedLookupExpr *Fn =
12070       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12071                                    NestedNameSpecifierLoc(), NameInfo,
12072                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12073                                    FoundNames.begin(), FoundNames.end());
12074
12075     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12076                                                     CandidateSet, CallExpr);
12077     if (CandidateSet->empty() || CandidateSetError) {
12078       *CallExpr = ExprError();
12079       return FRS_NoViableFunction;
12080     }
12081     OverloadCandidateSet::iterator Best;
12082     OverloadingResult OverloadResult =
12083         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12084
12085     if (OverloadResult == OR_No_Viable_Function) {
12086       *CallExpr = ExprError();
12087       return FRS_NoViableFunction;
12088     }
12089     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12090                                          Loc, nullptr, CandidateSet, &Best,
12091                                          OverloadResult,
12092                                          /*AllowTypoCorrection=*/false);
12093     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12094       *CallExpr = ExprError();
12095       Diag(Range->getLocStart(), diag::note_in_for_range)
12096           << RangeLoc << BEF << Range->getType();
12097       return FRS_DiagnosticIssued;
12098     }
12099   }
12100   return FRS_Success;
12101 }
12102
12103
12104 /// FixOverloadedFunctionReference - E is an expression that refers to
12105 /// a C++ overloaded function (possibly with some parentheses and
12106 /// perhaps a '&' around it). We have resolved the overloaded function
12107 /// to the function declaration Fn, so patch up the expression E to
12108 /// refer (possibly indirectly) to Fn. Returns the new expr.
12109 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12110                                            FunctionDecl *Fn) {
12111   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12112     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12113                                                    Found, Fn);
12114     if (SubExpr == PE->getSubExpr())
12115       return PE;
12116
12117     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12118   }
12119
12120   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12121     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12122                                                    Found, Fn);
12123     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12124                                SubExpr->getType()) &&
12125            "Implicit cast type cannot be determined from overload");
12126     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12127     if (SubExpr == ICE->getSubExpr())
12128       return ICE;
12129
12130     return ImplicitCastExpr::Create(Context, ICE->getType(),
12131                                     ICE->getCastKind(),
12132                                     SubExpr, nullptr,
12133                                     ICE->getValueKind());
12134   }
12135
12136   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12137     assert(UnOp->getOpcode() == UO_AddrOf &&
12138            "Can only take the address of an overloaded function");
12139     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12140       if (Method->isStatic()) {
12141         // Do nothing: static member functions aren't any different
12142         // from non-member functions.
12143       } else {
12144         // Fix the subexpression, which really has to be an
12145         // UnresolvedLookupExpr holding an overloaded member function
12146         // or template.
12147         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12148                                                        Found, Fn);
12149         if (SubExpr == UnOp->getSubExpr())
12150           return UnOp;
12151
12152         assert(isa<DeclRefExpr>(SubExpr)
12153                && "fixed to something other than a decl ref");
12154         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12155                && "fixed to a member ref with no nested name qualifier");
12156
12157         // We have taken the address of a pointer to member
12158         // function. Perform the computation here so that we get the
12159         // appropriate pointer to member type.
12160         QualType ClassType
12161           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12162         QualType MemPtrType
12163           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12164
12165         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12166                                            VK_RValue, OK_Ordinary,
12167                                            UnOp->getOperatorLoc());
12168       }
12169     }
12170     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12171                                                    Found, Fn);
12172     if (SubExpr == UnOp->getSubExpr())
12173       return UnOp;
12174
12175     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12176                                      Context.getPointerType(SubExpr->getType()),
12177                                        VK_RValue, OK_Ordinary,
12178                                        UnOp->getOperatorLoc());
12179   }
12180
12181   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12182     // FIXME: avoid copy.
12183     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12184     if (ULE->hasExplicitTemplateArgs()) {
12185       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12186       TemplateArgs = &TemplateArgsBuffer;
12187     }
12188
12189     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12190                                            ULE->getQualifierLoc(),
12191                                            ULE->getTemplateKeywordLoc(),
12192                                            Fn,
12193                                            /*enclosing*/ false, // FIXME?
12194                                            ULE->getNameLoc(),
12195                                            Fn->getType(),
12196                                            VK_LValue,
12197                                            Found.getDecl(),
12198                                            TemplateArgs);
12199     MarkDeclRefReferenced(DRE);
12200     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12201     return DRE;
12202   }
12203
12204   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12205     // FIXME: avoid copy.
12206     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12207     if (MemExpr->hasExplicitTemplateArgs()) {
12208       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12209       TemplateArgs = &TemplateArgsBuffer;
12210     }
12211
12212     Expr *Base;
12213
12214     // If we're filling in a static method where we used to have an
12215     // implicit member access, rewrite to a simple decl ref.
12216     if (MemExpr->isImplicitAccess()) {
12217       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12218         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12219                                                MemExpr->getQualifierLoc(),
12220                                                MemExpr->getTemplateKeywordLoc(),
12221                                                Fn,
12222                                                /*enclosing*/ false,
12223                                                MemExpr->getMemberLoc(),
12224                                                Fn->getType(),
12225                                                VK_LValue,
12226                                                Found.getDecl(),
12227                                                TemplateArgs);
12228         MarkDeclRefReferenced(DRE);
12229         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12230         return DRE;
12231       } else {
12232         SourceLocation Loc = MemExpr->getMemberLoc();
12233         if (MemExpr->getQualifier())
12234           Loc = MemExpr->getQualifierLoc().getBeginLoc();
12235         CheckCXXThisCapture(Loc);
12236         Base = new (Context) CXXThisExpr(Loc,
12237                                          MemExpr->getBaseType(),
12238                                          /*isImplicit=*/true);
12239       }
12240     } else
12241       Base = MemExpr->getBase();
12242
12243     ExprValueKind valueKind;
12244     QualType type;
12245     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12246       valueKind = VK_LValue;
12247       type = Fn->getType();
12248     } else {
12249       valueKind = VK_RValue;
12250       type = Context.BoundMemberTy;
12251     }
12252
12253     MemberExpr *ME = MemberExpr::Create(Context, Base,
12254                                         MemExpr->isArrow(),
12255                                         MemExpr->getQualifierLoc(),
12256                                         MemExpr->getTemplateKeywordLoc(),
12257                                         Fn,
12258                                         Found,
12259                                         MemExpr->getMemberNameInfo(),
12260                                         TemplateArgs,
12261                                         type, valueKind, OK_Ordinary);
12262     ME->setHadMultipleCandidates(true);
12263     MarkMemberReferenced(ME);
12264     return ME;
12265   }
12266
12267   llvm_unreachable("Invalid reference to overloaded function");
12268 }
12269
12270 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12271                                                 DeclAccessPair Found,
12272                                                 FunctionDecl *Fn) {
12273   return FixOverloadedFunctionReference(E.get(), Found, Fn);
12274 }
12275
12276 } // end namespace clang