]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaOverload.cpp
Merge bmake-20150418
[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 using 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 /// GetConversionRank - Retrieve the implicit conversion rank
106 /// corresponding to the given implicit conversion kind.
107 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
108   static const ImplicitConversionRank
109     Rank[(int)ICK_Num_Conversion_Kinds] = {
110     ICR_Exact_Match,
111     ICR_Exact_Match,
112     ICR_Exact_Match,
113     ICR_Exact_Match,
114     ICR_Exact_Match,
115     ICR_Exact_Match,
116     ICR_Promotion,
117     ICR_Promotion,
118     ICR_Promotion,
119     ICR_Conversion,
120     ICR_Conversion,
121     ICR_Conversion,
122     ICR_Conversion,
123     ICR_Conversion,
124     ICR_Conversion,
125     ICR_Conversion,
126     ICR_Conversion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Complex_Real_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Writeback_Conversion
134   };
135   return Rank[(int)Kind];
136 }
137
138 /// GetImplicitConversionName - Return the name of this kind of
139 /// implicit conversion.
140 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
141   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
142     "No conversion",
143     "Lvalue-to-rvalue",
144     "Array-to-pointer",
145     "Function-to-pointer",
146     "Noreturn adjustment",
147     "Qualification",
148     "Integral promotion",
149     "Floating point promotion",
150     "Complex promotion",
151     "Integral conversion",
152     "Floating conversion",
153     "Complex conversion",
154     "Floating-integral conversion",
155     "Pointer conversion",
156     "Pointer-to-member conversion",
157     "Boolean conversion",
158     "Compatible-types conversion",
159     "Derived-to-base conversion",
160     "Vector conversion",
161     "Vector splat",
162     "Complex-real conversion",
163     "Block Pointer conversion",
164     "Transparent Union Conversion",
165     "Writeback conversion"
166   };
167   return Name[Kind];
168 }
169
170 /// StandardConversionSequence - Set the standard conversion
171 /// sequence to the identity conversion.
172 void StandardConversionSequence::setAsIdentityConversion() {
173   First = ICK_Identity;
174   Second = ICK_Identity;
175   Third = ICK_Identity;
176   DeprecatedStringLiteralToCharPtr = false;
177   QualificationIncludesObjCLifetime = false;
178   ReferenceBinding = false;
179   DirectBinding = false;
180   IsLvalueReference = true;
181   BindsToFunctionLvalue = false;
182   BindsToRvalue = false;
183   BindsImplicitObjectArgumentWithoutRefQualifier = false;
184   ObjCLifetimeConversionBinding = false;
185   CopyConstructor = nullptr;
186 }
187
188 /// getRank - Retrieve the rank of this standard conversion sequence
189 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
190 /// implicit conversions.
191 ImplicitConversionRank StandardConversionSequence::getRank() const {
192   ImplicitConversionRank Rank = ICR_Exact_Match;
193   if  (GetConversionRank(First) > Rank)
194     Rank = GetConversionRank(First);
195   if  (GetConversionRank(Second) > Rank)
196     Rank = GetConversionRank(Second);
197   if  (GetConversionRank(Third) > Rank)
198     Rank = GetConversionRank(Third);
199   return Rank;
200 }
201
202 /// isPointerConversionToBool - Determines whether this conversion is
203 /// a conversion of a pointer or pointer-to-member to bool. This is
204 /// used as part of the ranking of standard conversion sequences
205 /// (C++ 13.3.3.2p4).
206 bool StandardConversionSequence::isPointerConversionToBool() const {
207   // Note that FromType has not necessarily been transformed by the
208   // array-to-pointer or function-to-pointer implicit conversions, so
209   // check for their presence as well as checking whether FromType is
210   // a pointer.
211   if (getToType(1)->isBooleanType() &&
212       (getFromType()->isPointerType() ||
213        getFromType()->isObjCObjectPointerType() ||
214        getFromType()->isBlockPointerType() ||
215        getFromType()->isNullPtrType() ||
216        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
217     return true;
218
219   return false;
220 }
221
222 /// isPointerConversionToVoidPointer - Determines whether this
223 /// conversion is a conversion of a pointer to a void pointer. This is
224 /// used as part of the ranking of standard conversion sequences (C++
225 /// 13.3.3.2p4).
226 bool
227 StandardConversionSequence::
228 isPointerConversionToVoidPointer(ASTContext& Context) const {
229   QualType FromType = getFromType();
230   QualType ToType = getToType(1);
231
232   // Note that FromType has not necessarily been transformed by the
233   // array-to-pointer implicit conversion, so check for its presence
234   // and redo the conversion to get a pointer.
235   if (First == ICK_Array_To_Pointer)
236     FromType = Context.getArrayDecayedType(FromType);
237
238   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
239     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
240       return ToPtrType->getPointeeType()->isVoidType();
241
242   return false;
243 }
244
245 /// Skip any implicit casts which could be either part of a narrowing conversion
246 /// or after one in an implicit conversion.
247 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
248   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
249     switch (ICE->getCastKind()) {
250     case CK_NoOp:
251     case CK_IntegralCast:
252     case CK_IntegralToBoolean:
253     case CK_IntegralToFloating:
254     case CK_FloatingToIntegral:
255     case CK_FloatingToBoolean:
256     case CK_FloatingCast:
257       Converted = ICE->getSubExpr();
258       continue;
259
260     default:
261       return Converted;
262     }
263   }
264
265   return Converted;
266 }
267
268 /// Check if this standard conversion sequence represents a narrowing
269 /// conversion, according to C++11 [dcl.init.list]p7.
270 ///
271 /// \param Ctx  The AST context.
272 /// \param Converted  The result of applying this standard conversion sequence.
273 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
274 ///        value of the expression prior to the narrowing conversion.
275 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
276 ///        type of the expression prior to the narrowing conversion.
277 NarrowingKind
278 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
279                                              const Expr *Converted,
280                                              APValue &ConstantValue,
281                                              QualType &ConstantType) const {
282   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
283
284   // C++11 [dcl.init.list]p7:
285   //   A narrowing conversion is an implicit conversion ...
286   QualType FromType = getToType(0);
287   QualType ToType = getToType(1);
288   switch (Second) {
289   // -- from a floating-point type to an integer type, or
290   //
291   // -- from an integer type or unscoped enumeration type to a floating-point
292   //    type, except where the source is a constant expression and the actual
293   //    value after conversion will fit into the target type and will produce
294   //    the original value when converted back to the original type, or
295   case ICK_Floating_Integral:
296     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
297       return NK_Type_Narrowing;
298     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
299       llvm::APSInt IntConstantValue;
300       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
301       if (Initializer &&
302           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
303         // Convert the integer to the floating type.
304         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
305         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
306                                 llvm::APFloat::rmNearestTiesToEven);
307         // And back.
308         llvm::APSInt ConvertedValue = IntConstantValue;
309         bool ignored;
310         Result.convertToInteger(ConvertedValue,
311                                 llvm::APFloat::rmTowardZero, &ignored);
312         // If the resulting value is different, this was a narrowing conversion.
313         if (IntConstantValue != ConvertedValue) {
314           ConstantValue = APValue(IntConstantValue);
315           ConstantType = Initializer->getType();
316           return NK_Constant_Narrowing;
317         }
318       } else {
319         // Variables are always narrowings.
320         return NK_Variable_Narrowing;
321       }
322     }
323     return NK_Not_Narrowing;
324
325   // -- from long double to double or float, or from double to float, except
326   //    where the source is a constant expression and the actual value after
327   //    conversion is within the range of values that can be represented (even
328   //    if it cannot be represented exactly), or
329   case ICK_Floating_Conversion:
330     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
331         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
332       // FromType is larger than ToType.
333       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
335         // Constant!
336         assert(ConstantValue.isFloat());
337         llvm::APFloat FloatVal = ConstantValue.getFloat();
338         // Convert the source value into the target type.
339         bool ignored;
340         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
341           Ctx.getFloatTypeSemantics(ToType),
342           llvm::APFloat::rmNearestTiesToEven, &ignored);
343         // If there was no overflow, the source value is within the range of
344         // values that can be represented.
345         if (ConvertStatus & llvm::APFloat::opOverflow) {
346           ConstantType = Initializer->getType();
347           return NK_Constant_Narrowing;
348         }
349       } else {
350         return NK_Variable_Narrowing;
351       }
352     }
353     return NK_Not_Narrowing;
354
355   // -- from an integer type or unscoped enumeration type to an integer type
356   //    that cannot represent all the values of the original type, except where
357   //    the source is a constant expression and the actual value after
358   //    conversion will fit into the target type and will produce the original
359   //    value when converted back to the original type.
360   case ICK_Boolean_Conversion:  // Bools are integers too.
361     if (!FromType->isIntegralOrUnscopedEnumerationType()) {
362       // Boolean conversions can be from pointers and pointers to members
363       // [conv.bool], and those aren't considered narrowing conversions.
364       return NK_Not_Narrowing;
365     }  // Otherwise, fall through to the integral case.
366   case ICK_Integral_Conversion: {
367     assert(FromType->isIntegralOrUnscopedEnumerationType());
368     assert(ToType->isIntegralOrUnscopedEnumerationType());
369     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
370     const unsigned FromWidth = Ctx.getIntWidth(FromType);
371     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
372     const unsigned ToWidth = Ctx.getIntWidth(ToType);
373
374     if (FromWidth > ToWidth ||
375         (FromWidth == ToWidth && FromSigned != ToSigned) ||
376         (FromSigned && !ToSigned)) {
377       // Not all values of FromType can be represented in ToType.
378       llvm::APSInt InitializerValue;
379       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
380       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
381         // Such conversions on variables are always narrowing.
382         return NK_Variable_Narrowing;
383       }
384       bool Narrowing = false;
385       if (FromWidth < ToWidth) {
386         // Negative -> unsigned is narrowing. Otherwise, more bits is never
387         // narrowing.
388         if (InitializerValue.isSigned() && InitializerValue.isNegative())
389           Narrowing = true;
390       } else {
391         // Add a bit to the InitializerValue so we don't have to worry about
392         // signed vs. unsigned comparisons.
393         InitializerValue = InitializerValue.extend(
394           InitializerValue.getBitWidth() + 1);
395         // Convert the initializer to and from the target width and signed-ness.
396         llvm::APSInt ConvertedValue = InitializerValue;
397         ConvertedValue = ConvertedValue.trunc(ToWidth);
398         ConvertedValue.setIsSigned(ToSigned);
399         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
400         ConvertedValue.setIsSigned(InitializerValue.isSigned());
401         // If the result is different, this was a narrowing conversion.
402         if (ConvertedValue != InitializerValue)
403           Narrowing = true;
404       }
405       if (Narrowing) {
406         ConstantType = Initializer->getType();
407         ConstantValue = APValue(InitializerValue);
408         return NK_Constant_Narrowing;
409       }
410     }
411     return NK_Not_Narrowing;
412   }
413
414   default:
415     // Other kinds of conversions are not narrowings.
416     return NK_Not_Narrowing;
417   }
418 }
419
420 /// dump - Print this standard conversion sequence to standard
421 /// error. Useful for debugging overloading issues.
422 void StandardConversionSequence::dump() const {
423   raw_ostream &OS = llvm::errs();
424   bool PrintedSomething = false;
425   if (First != ICK_Identity) {
426     OS << GetImplicitConversionName(First);
427     PrintedSomething = true;
428   }
429
430   if (Second != ICK_Identity) {
431     if (PrintedSomething) {
432       OS << " -> ";
433     }
434     OS << GetImplicitConversionName(Second);
435
436     if (CopyConstructor) {
437       OS << " (by copy constructor)";
438     } else if (DirectBinding) {
439       OS << " (direct reference binding)";
440     } else if (ReferenceBinding) {
441       OS << " (reference binding)";
442     }
443     PrintedSomething = true;
444   }
445
446   if (Third != ICK_Identity) {
447     if (PrintedSomething) {
448       OS << " -> ";
449     }
450     OS << GetImplicitConversionName(Third);
451     PrintedSomething = true;
452   }
453
454   if (!PrintedSomething) {
455     OS << "No conversions required";
456   }
457 }
458
459 /// dump - Print this user-defined conversion sequence to standard
460 /// error. Useful for debugging overloading issues.
461 void UserDefinedConversionSequence::dump() const {
462   raw_ostream &OS = llvm::errs();
463   if (Before.First || Before.Second || Before.Third) {
464     Before.dump();
465     OS << " -> ";
466   }
467   if (ConversionFunction)
468     OS << '\'' << *ConversionFunction << '\'';
469   else
470     OS << "aggregate initialization";
471   if (After.First || After.Second || After.Third) {
472     OS << " -> ";
473     After.dump();
474   }
475 }
476
477 /// dump - Print this implicit conversion sequence to standard
478 /// error. Useful for debugging overloading issues.
479 void ImplicitConversionSequence::dump() const {
480   raw_ostream &OS = llvm::errs();
481   if (isStdInitializerListElement())
482     OS << "Worst std::initializer_list element conversion: ";
483   switch (ConversionKind) {
484   case StandardConversion:
485     OS << "Standard conversion: ";
486     Standard.dump();
487     break;
488   case UserDefinedConversion:
489     OS << "User-defined conversion: ";
490     UserDefined.dump();
491     break;
492   case EllipsisConversion:
493     OS << "Ellipsis conversion";
494     break;
495   case AmbiguousConversion:
496     OS << "Ambiguous conversion";
497     break;
498   case BadConversion:
499     OS << "Bad conversion";
500     break;
501   }
502
503   OS << "\n";
504 }
505
506 void AmbiguousConversionSequence::construct() {
507   new (&conversions()) ConversionSet();
508 }
509
510 void AmbiguousConversionSequence::destruct() {
511   conversions().~ConversionSet();
512 }
513
514 void
515 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
516   FromTypePtr = O.FromTypePtr;
517   ToTypePtr = O.ToTypePtr;
518   new (&conversions()) ConversionSet(O.conversions());
519 }
520
521 namespace {
522   // Structure used by DeductionFailureInfo to store
523   // template argument information.
524   struct DFIArguments {
525     TemplateArgument FirstArg;
526     TemplateArgument SecondArg;
527   };
528   // Structure used by DeductionFailureInfo to store
529   // template parameter and template argument information.
530   struct DFIParamWithArguments : DFIArguments {
531     TemplateParameter Param;
532   };
533 }
534
535 /// \brief Convert from Sema's representation of template deduction information
536 /// to the form used in overload-candidate information.
537 DeductionFailureInfo
538 clang::MakeDeductionFailureInfo(ASTContext &Context,
539                                 Sema::TemplateDeductionResult TDK,
540                                 TemplateDeductionInfo &Info) {
541   DeductionFailureInfo Result;
542   Result.Result = static_cast<unsigned>(TDK);
543   Result.HasDiagnostic = false;
544   Result.Data = nullptr;
545   switch (TDK) {
546   case Sema::TDK_Success:
547   case Sema::TDK_Invalid:
548   case Sema::TDK_InstantiationDepth:
549   case Sema::TDK_TooManyArguments:
550   case Sema::TDK_TooFewArguments:
551     break;
552
553   case Sema::TDK_Incomplete:
554   case Sema::TDK_InvalidExplicitArguments:
555     Result.Data = Info.Param.getOpaqueValue();
556     break;
557
558   case Sema::TDK_NonDeducedMismatch: {
559     // FIXME: Should allocate from normal heap so that we can free this later.
560     DFIArguments *Saved = new (Context) DFIArguments;
561     Saved->FirstArg = Info.FirstArg;
562     Saved->SecondArg = Info.SecondArg;
563     Result.Data = Saved;
564     break;
565   }
566
567   case Sema::TDK_Inconsistent:
568   case Sema::TDK_Underqualified: {
569     // FIXME: Should allocate from normal heap so that we can free this later.
570     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
571     Saved->Param = Info.Param;
572     Saved->FirstArg = Info.FirstArg;
573     Saved->SecondArg = Info.SecondArg;
574     Result.Data = Saved;
575     break;
576   }
577
578   case Sema::TDK_SubstitutionFailure:
579     Result.Data = Info.take();
580     if (Info.hasSFINAEDiagnostic()) {
581       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
582           SourceLocation(), PartialDiagnostic::NullDiagnostic());
583       Info.takeSFINAEDiagnostic(*Diag);
584       Result.HasDiagnostic = true;
585     }
586     break;
587
588   case Sema::TDK_FailedOverloadResolution:
589     Result.Data = Info.Expression;
590     break;
591
592   case Sema::TDK_MiscellaneousDeductionFailure:
593     break;
594   }
595
596   return Result;
597 }
598
599 void DeductionFailureInfo::Destroy() {
600   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
601   case Sema::TDK_Success:
602   case Sema::TDK_Invalid:
603   case Sema::TDK_InstantiationDepth:
604   case Sema::TDK_Incomplete:
605   case Sema::TDK_TooManyArguments:
606   case Sema::TDK_TooFewArguments:
607   case Sema::TDK_InvalidExplicitArguments:
608   case Sema::TDK_FailedOverloadResolution:
609     break;
610
611   case Sema::TDK_Inconsistent:
612   case Sema::TDK_Underqualified:
613   case Sema::TDK_NonDeducedMismatch:
614     // FIXME: Destroy the data?
615     Data = nullptr;
616     break;
617
618   case Sema::TDK_SubstitutionFailure:
619     // FIXME: Destroy the template argument list?
620     Data = nullptr;
621     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
622       Diag->~PartialDiagnosticAt();
623       HasDiagnostic = false;
624     }
625     break;
626
627   // Unhandled
628   case Sema::TDK_MiscellaneousDeductionFailure:
629     break;
630   }
631 }
632
633 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
634   if (HasDiagnostic)
635     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
636   return nullptr;
637 }
638
639 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
640   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
641   case Sema::TDK_Success:
642   case Sema::TDK_Invalid:
643   case Sema::TDK_InstantiationDepth:
644   case Sema::TDK_TooManyArguments:
645   case Sema::TDK_TooFewArguments:
646   case Sema::TDK_SubstitutionFailure:
647   case Sema::TDK_NonDeducedMismatch:
648   case Sema::TDK_FailedOverloadResolution:
649     return TemplateParameter();
650
651   case Sema::TDK_Incomplete:
652   case Sema::TDK_InvalidExplicitArguments:
653     return TemplateParameter::getFromOpaqueValue(Data);
654
655   case Sema::TDK_Inconsistent:
656   case Sema::TDK_Underqualified:
657     return static_cast<DFIParamWithArguments*>(Data)->Param;
658
659   // Unhandled
660   case Sema::TDK_MiscellaneousDeductionFailure:
661     break;
662   }
663
664   return TemplateParameter();
665 }
666
667 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
668   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
669   case Sema::TDK_Success:
670   case Sema::TDK_Invalid:
671   case Sema::TDK_InstantiationDepth:
672   case Sema::TDK_TooManyArguments:
673   case Sema::TDK_TooFewArguments:
674   case Sema::TDK_Incomplete:
675   case Sema::TDK_InvalidExplicitArguments:
676   case Sema::TDK_Inconsistent:
677   case Sema::TDK_Underqualified:
678   case Sema::TDK_NonDeducedMismatch:
679   case Sema::TDK_FailedOverloadResolution:
680     return nullptr;
681
682   case Sema::TDK_SubstitutionFailure:
683     return static_cast<TemplateArgumentList*>(Data);
684
685   // Unhandled
686   case Sema::TDK_MiscellaneousDeductionFailure:
687     break;
688   }
689
690   return nullptr;
691 }
692
693 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
694   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695   case Sema::TDK_Success:
696   case Sema::TDK_Invalid:
697   case Sema::TDK_InstantiationDepth:
698   case Sema::TDK_Incomplete:
699   case Sema::TDK_TooManyArguments:
700   case Sema::TDK_TooFewArguments:
701   case Sema::TDK_InvalidExplicitArguments:
702   case Sema::TDK_SubstitutionFailure:
703   case Sema::TDK_FailedOverloadResolution:
704     return nullptr;
705
706   case Sema::TDK_Inconsistent:
707   case Sema::TDK_Underqualified:
708   case Sema::TDK_NonDeducedMismatch:
709     return &static_cast<DFIArguments*>(Data)->FirstArg;
710
711   // Unhandled
712   case Sema::TDK_MiscellaneousDeductionFailure:
713     break;
714   }
715
716   return nullptr;
717 }
718
719 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
720   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
721   case Sema::TDK_Success:
722   case Sema::TDK_Invalid:
723   case Sema::TDK_InstantiationDepth:
724   case Sema::TDK_Incomplete:
725   case Sema::TDK_TooManyArguments:
726   case Sema::TDK_TooFewArguments:
727   case Sema::TDK_InvalidExplicitArguments:
728   case Sema::TDK_SubstitutionFailure:
729   case Sema::TDK_FailedOverloadResolution:
730     return nullptr;
731
732   case Sema::TDK_Inconsistent:
733   case Sema::TDK_Underqualified:
734   case Sema::TDK_NonDeducedMismatch:
735     return &static_cast<DFIArguments*>(Data)->SecondArg;
736
737   // Unhandled
738   case Sema::TDK_MiscellaneousDeductionFailure:
739     break;
740   }
741
742   return nullptr;
743 }
744
745 Expr *DeductionFailureInfo::getExpr() {
746   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
747         Sema::TDK_FailedOverloadResolution)
748     return static_cast<Expr*>(Data);
749
750   return nullptr;
751 }
752
753 void OverloadCandidateSet::destroyCandidates() {
754   for (iterator i = begin(), e = end(); i != e; ++i) {
755     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
756       i->Conversions[ii].~ImplicitConversionSequence();
757     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
758       i->DeductionFailure.Destroy();
759   }
760 }
761
762 void OverloadCandidateSet::clear() {
763   destroyCandidates();
764   NumInlineSequences = 0;
765   Candidates.clear();
766   Functions.clear();
767 }
768
769 namespace {
770   class UnbridgedCastsSet {
771     struct Entry {
772       Expr **Addr;
773       Expr *Saved;
774     };
775     SmallVector<Entry, 2> Entries;
776     
777   public:
778     void save(Sema &S, Expr *&E) {
779       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
780       Entry entry = { &E, E };
781       Entries.push_back(entry);
782       E = S.stripARCUnbridgedCast(E);
783     }
784
785     void restore() {
786       for (SmallVectorImpl<Entry>::iterator
787              i = Entries.begin(), e = Entries.end(); i != e; ++i) 
788         *i->Addr = i->Saved;
789     }
790   };
791 }
792
793 /// checkPlaceholderForOverload - Do any interesting placeholder-like
794 /// preprocessing on the given expression.
795 ///
796 /// \param unbridgedCasts a collection to which to add unbridged casts;
797 ///   without this, they will be immediately diagnosed as errors
798 ///
799 /// Return true on unrecoverable error.
800 static bool
801 checkPlaceholderForOverload(Sema &S, Expr *&E,
802                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
803   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
804     // We can't handle overloaded expressions here because overload
805     // resolution might reasonably tweak them.
806     if (placeholder->getKind() == BuiltinType::Overload) return false;
807
808     // If the context potentially accepts unbridged ARC casts, strip
809     // the unbridged cast and add it to the collection for later restoration.
810     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
811         unbridgedCasts) {
812       unbridgedCasts->save(S, E);
813       return false;
814     }
815
816     // Go ahead and check everything else.
817     ExprResult result = S.CheckPlaceholderExpr(E);
818     if (result.isInvalid())
819       return true;
820
821     E = result.get();
822     return false;
823   }
824
825   // Nothing to do.
826   return false;
827 }
828
829 /// checkArgPlaceholdersForOverload - Check a set of call operands for
830 /// placeholders.
831 static bool checkArgPlaceholdersForOverload(Sema &S,
832                                             MultiExprArg Args,
833                                             UnbridgedCastsSet &unbridged) {
834   for (unsigned i = 0, e = Args.size(); i != e; ++i)
835     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
836       return true;
837
838   return false;
839 }
840
841 // IsOverload - Determine whether the given New declaration is an
842 // overload of the declarations in Old. This routine returns false if
843 // New and Old cannot be overloaded, e.g., if New has the same
844 // signature as some function in Old (C++ 1.3.10) or if the Old
845 // declarations aren't functions (or function templates) at all. When
846 // it does return false, MatchedDecl will point to the decl that New
847 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
848 // top of the underlying declaration.
849 //
850 // Example: Given the following input:
851 //
852 //   void f(int, float); // #1
853 //   void f(int, int); // #2
854 //   int f(int, int); // #3
855 //
856 // When we process #1, there is no previous declaration of "f",
857 // so IsOverload will not be used.
858 //
859 // When we process #2, Old contains only the FunctionDecl for #1.  By
860 // comparing the parameter types, we see that #1 and #2 are overloaded
861 // (since they have different signatures), so this routine returns
862 // false; MatchedDecl is unchanged.
863 //
864 // When we process #3, Old is an overload set containing #1 and #2. We
865 // compare the signatures of #3 to #1 (they're overloaded, so we do
866 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
867 // identical (return types of functions are not part of the
868 // signature), IsOverload returns false and MatchedDecl will be set to
869 // point to the FunctionDecl for #2.
870 //
871 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
872 // into a class by a using declaration.  The rules for whether to hide
873 // shadow declarations ignore some properties which otherwise figure
874 // into a function template's signature.
875 Sema::OverloadKind
876 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
877                     NamedDecl *&Match, bool NewIsUsingDecl) {
878   for (LookupResult::iterator I = Old.begin(), E = Old.end();
879          I != E; ++I) {
880     NamedDecl *OldD = *I;
881
882     bool OldIsUsingDecl = false;
883     if (isa<UsingShadowDecl>(OldD)) {
884       OldIsUsingDecl = true;
885
886       // We can always introduce two using declarations into the same
887       // context, even if they have identical signatures.
888       if (NewIsUsingDecl) continue;
889
890       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
891     }
892
893     // If either declaration was introduced by a using declaration,
894     // we'll need to use slightly different rules for matching.
895     // Essentially, these rules are the normal rules, except that
896     // function templates hide function templates with different
897     // return types or template parameter lists.
898     bool UseMemberUsingDeclRules =
899       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
900       !New->getFriendObjectKind();
901
902     if (FunctionDecl *OldF = OldD->getAsFunction()) {
903       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
904         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
905           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
906           continue;
907         }
908
909         if (!isa<FunctionTemplateDecl>(OldD) &&
910             !shouldLinkPossiblyHiddenDecl(*I, New))
911           continue;
912
913         Match = *I;
914         return Ovl_Match;
915       }
916     } else if (isa<UsingDecl>(OldD)) {
917       // We can overload with these, which can show up when doing
918       // redeclaration checks for UsingDecls.
919       assert(Old.getLookupKind() == LookupUsingDeclName);
920     } else if (isa<TagDecl>(OldD)) {
921       // We can always overload with tags by hiding them.
922     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
923       // Optimistically assume that an unresolved using decl will
924       // overload; if it doesn't, we'll have to diagnose during
925       // template instantiation.
926     } else {
927       // (C++ 13p1):
928       //   Only function declarations can be overloaded; object and type
929       //   declarations cannot be overloaded.
930       Match = *I;
931       return Ovl_NonFunction;
932     }
933   }
934
935   return Ovl_Overload;
936 }
937
938 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
939                       bool UseUsingDeclRules) {
940   // C++ [basic.start.main]p2: This function shall not be overloaded.
941   if (New->isMain())
942     return false;
943
944   // MSVCRT user defined entry points cannot be overloaded.
945   if (New->isMSVCRTEntryPoint())
946     return false;
947
948   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
949   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
950
951   // C++ [temp.fct]p2:
952   //   A function template can be overloaded with other function templates
953   //   and with normal (non-template) functions.
954   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
955     return true;
956
957   // Is the function New an overload of the function Old?
958   QualType OldQType = Context.getCanonicalType(Old->getType());
959   QualType NewQType = Context.getCanonicalType(New->getType());
960
961   // Compare the signatures (C++ 1.3.10) of the two functions to
962   // determine whether they are overloads. If we find any mismatch
963   // in the signature, they are overloads.
964
965   // If either of these functions is a K&R-style function (no
966   // prototype), then we consider them to have matching signatures.
967   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
968       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
969     return false;
970
971   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
972   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
973
974   // The signature of a function includes the types of its
975   // parameters (C++ 1.3.10), which includes the presence or absence
976   // of the ellipsis; see C++ DR 357).
977   if (OldQType != NewQType &&
978       (OldType->getNumParams() != NewType->getNumParams() ||
979        OldType->isVariadic() != NewType->isVariadic() ||
980        !FunctionParamTypesAreEqual(OldType, NewType)))
981     return true;
982
983   // C++ [temp.over.link]p4:
984   //   The signature of a function template consists of its function
985   //   signature, its return type and its template parameter list. The names
986   //   of the template parameters are significant only for establishing the
987   //   relationship between the template parameters and the rest of the
988   //   signature.
989   //
990   // We check the return type and template parameter lists for function
991   // templates first; the remaining checks follow.
992   //
993   // However, we don't consider either of these when deciding whether
994   // a member introduced by a shadow declaration is hidden.
995   if (!UseUsingDeclRules && NewTemplate &&
996       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
997                                        OldTemplate->getTemplateParameters(),
998                                        false, TPL_TemplateMatch) ||
999        OldType->getReturnType() != NewType->getReturnType()))
1000     return true;
1001
1002   // If the function is a class member, its signature includes the
1003   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1004   //
1005   // As part of this, also check whether one of the member functions
1006   // is static, in which case they are not overloads (C++
1007   // 13.1p2). While not part of the definition of the signature,
1008   // this check is important to determine whether these functions
1009   // can be overloaded.
1010   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1011   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1012   if (OldMethod && NewMethod &&
1013       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1014     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1015       if (!UseUsingDeclRules &&
1016           (OldMethod->getRefQualifier() == RQ_None ||
1017            NewMethod->getRefQualifier() == RQ_None)) {
1018         // C++0x [over.load]p2:
1019         //   - Member function declarations with the same name and the same
1020         //     parameter-type-list as well as member function template
1021         //     declarations with the same name, the same parameter-type-list, and
1022         //     the same template parameter lists cannot be overloaded if any of
1023         //     them, but not all, have a ref-qualifier (8.3.5).
1024         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1025           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1026         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1027       }
1028       return true;
1029     }
1030
1031     // We may not have applied the implicit const for a constexpr member
1032     // function yet (because we haven't yet resolved whether this is a static
1033     // or non-static member function). Add it now, on the assumption that this
1034     // is a redeclaration of OldMethod.
1035     unsigned OldQuals = OldMethod->getTypeQualifiers();
1036     unsigned NewQuals = NewMethod->getTypeQualifiers();
1037     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1038         !isa<CXXConstructorDecl>(NewMethod))
1039       NewQuals |= Qualifiers::Const;
1040
1041     // We do not allow overloading based off of '__restrict'.
1042     OldQuals &= ~Qualifiers::Restrict;
1043     NewQuals &= ~Qualifiers::Restrict;
1044     if (OldQuals != NewQuals)
1045       return true;
1046   }
1047
1048   // enable_if attributes are an order-sensitive part of the signature.
1049   for (specific_attr_iterator<EnableIfAttr>
1050          NewI = New->specific_attr_begin<EnableIfAttr>(),
1051          NewE = New->specific_attr_end<EnableIfAttr>(),
1052          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1053          OldE = Old->specific_attr_end<EnableIfAttr>();
1054        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1055     if (NewI == NewE || OldI == OldE)
1056       return true;
1057     llvm::FoldingSetNodeID NewID, OldID;
1058     NewI->getCond()->Profile(NewID, Context, true);
1059     OldI->getCond()->Profile(OldID, Context, true);
1060     if (NewID != OldID)
1061       return true;
1062   }
1063
1064   // The signatures match; this is not an overload.
1065   return false;
1066 }
1067
1068 /// \brief Checks availability of the function depending on the current
1069 /// function context. Inside an unavailable function, unavailability is ignored.
1070 ///
1071 /// \returns true if \arg FD is unavailable and current context is inside
1072 /// an available function, false otherwise.
1073 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1074   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1075 }
1076
1077 /// \brief Tries a user-defined conversion from From to ToType.
1078 ///
1079 /// Produces an implicit conversion sequence for when a standard conversion
1080 /// is not an option. See TryImplicitConversion for more information.
1081 static ImplicitConversionSequence
1082 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1083                          bool SuppressUserConversions,
1084                          bool AllowExplicit,
1085                          bool InOverloadResolution,
1086                          bool CStyle,
1087                          bool AllowObjCWritebackConversion,
1088                          bool AllowObjCConversionOnExplicit) {
1089   ImplicitConversionSequence ICS;
1090
1091   if (SuppressUserConversions) {
1092     // We're not in the case above, so there is no conversion that
1093     // we can perform.
1094     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1095     return ICS;
1096   }
1097
1098   // Attempt user-defined conversion.
1099   OverloadCandidateSet Conversions(From->getExprLoc(),
1100                                    OverloadCandidateSet::CSK_Normal);
1101   OverloadingResult UserDefResult
1102     = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1103                               AllowExplicit, AllowObjCConversionOnExplicit);
1104
1105   if (UserDefResult == OR_Success) {
1106     ICS.setUserDefined();
1107     ICS.UserDefined.Before.setAsIdentityConversion();
1108     // C++ [over.ics.user]p4:
1109     //   A conversion of an expression of class type to the same class
1110     //   type is given Exact Match rank, and a conversion of an
1111     //   expression of class type to a base class of that type is
1112     //   given Conversion rank, in spite of the fact that a copy
1113     //   constructor (i.e., a user-defined conversion function) is
1114     //   called for those cases.
1115     if (CXXConstructorDecl *Constructor
1116           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1117       QualType FromCanon
1118         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1119       QualType ToCanon
1120         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1121       if (Constructor->isCopyConstructor() &&
1122           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1123         // Turn this into a "standard" conversion sequence, so that it
1124         // gets ranked with standard conversion sequences.
1125         ICS.setStandard();
1126         ICS.Standard.setAsIdentityConversion();
1127         ICS.Standard.setFromType(From->getType());
1128         ICS.Standard.setAllToTypes(ToType);
1129         ICS.Standard.CopyConstructor = Constructor;
1130         if (ToCanon != FromCanon)
1131           ICS.Standard.Second = ICK_Derived_To_Base;
1132       }
1133     }
1134   } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1135     ICS.setAmbiguous();
1136     ICS.Ambiguous.setFromType(From->getType());
1137     ICS.Ambiguous.setToType(ToType);
1138     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1139          Cand != Conversions.end(); ++Cand)
1140       if (Cand->Viable)
1141         ICS.Ambiguous.addConversion(Cand->Function);
1142   } else {
1143     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1144   }
1145
1146   return ICS;
1147 }
1148
1149 /// TryImplicitConversion - Attempt to perform an implicit conversion
1150 /// from the given expression (Expr) to the given type (ToType). This
1151 /// function returns an implicit conversion sequence that can be used
1152 /// to perform the initialization. Given
1153 ///
1154 ///   void f(float f);
1155 ///   void g(int i) { f(i); }
1156 ///
1157 /// this routine would produce an implicit conversion sequence to
1158 /// describe the initialization of f from i, which will be a standard
1159 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1160 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1161 //
1162 /// Note that this routine only determines how the conversion can be
1163 /// performed; it does not actually perform the conversion. As such,
1164 /// it will not produce any diagnostics if no conversion is available,
1165 /// but will instead return an implicit conversion sequence of kind
1166 /// "BadConversion".
1167 ///
1168 /// If @p SuppressUserConversions, then user-defined conversions are
1169 /// not permitted.
1170 /// If @p AllowExplicit, then explicit user-defined conversions are
1171 /// permitted.
1172 ///
1173 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1174 /// writeback conversion, which allows __autoreleasing id* parameters to
1175 /// be initialized with __strong id* or __weak id* arguments.
1176 static ImplicitConversionSequence
1177 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1178                       bool SuppressUserConversions,
1179                       bool AllowExplicit,
1180                       bool InOverloadResolution,
1181                       bool CStyle,
1182                       bool AllowObjCWritebackConversion,
1183                       bool AllowObjCConversionOnExplicit) {
1184   ImplicitConversionSequence ICS;
1185   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1186                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1187     ICS.setStandard();
1188     return ICS;
1189   }
1190
1191   if (!S.getLangOpts().CPlusPlus) {
1192     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1193     return ICS;
1194   }
1195
1196   // C++ [over.ics.user]p4:
1197   //   A conversion of an expression of class type to the same class
1198   //   type is given Exact Match rank, and a conversion of an
1199   //   expression of class type to a base class of that type is
1200   //   given Conversion rank, in spite of the fact that a copy/move
1201   //   constructor (i.e., a user-defined conversion function) is
1202   //   called for those cases.
1203   QualType FromType = From->getType();
1204   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1205       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1206        S.IsDerivedFrom(FromType, ToType))) {
1207     ICS.setStandard();
1208     ICS.Standard.setAsIdentityConversion();
1209     ICS.Standard.setFromType(FromType);
1210     ICS.Standard.setAllToTypes(ToType);
1211
1212     // We don't actually check at this point whether there is a valid
1213     // copy/move constructor, since overloading just assumes that it
1214     // exists. When we actually perform initialization, we'll find the
1215     // appropriate constructor to copy the returned object, if needed.
1216     ICS.Standard.CopyConstructor = nullptr;
1217
1218     // Determine whether this is considered a derived-to-base conversion.
1219     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1220       ICS.Standard.Second = ICK_Derived_To_Base;
1221
1222     return ICS;
1223   }
1224
1225   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1226                                   AllowExplicit, InOverloadResolution, CStyle,
1227                                   AllowObjCWritebackConversion,
1228                                   AllowObjCConversionOnExplicit);
1229 }
1230
1231 ImplicitConversionSequence
1232 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1233                             bool SuppressUserConversions,
1234                             bool AllowExplicit,
1235                             bool InOverloadResolution,
1236                             bool CStyle,
1237                             bool AllowObjCWritebackConversion) {
1238   return ::TryImplicitConversion(*this, From, ToType, 
1239                                  SuppressUserConversions, AllowExplicit,
1240                                  InOverloadResolution, CStyle, 
1241                                  AllowObjCWritebackConversion,
1242                                  /*AllowObjCConversionOnExplicit=*/false);
1243 }
1244
1245 /// PerformImplicitConversion - Perform an implicit conversion of the
1246 /// expression From to the type ToType. Returns the
1247 /// converted expression. Flavor is the kind of conversion we're
1248 /// performing, used in the error message. If @p AllowExplicit,
1249 /// explicit user-defined conversions are permitted.
1250 ExprResult
1251 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1252                                 AssignmentAction Action, bool AllowExplicit) {
1253   ImplicitConversionSequence ICS;
1254   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1255 }
1256
1257 ExprResult
1258 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1259                                 AssignmentAction Action, bool AllowExplicit,
1260                                 ImplicitConversionSequence& ICS) {
1261   if (checkPlaceholderForOverload(*this, From))
1262     return ExprError();
1263
1264   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1265   bool AllowObjCWritebackConversion
1266     = getLangOpts().ObjCAutoRefCount && 
1267       (Action == AA_Passing || Action == AA_Sending);
1268   if (getLangOpts().ObjC1)
1269     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1270                                       ToType, From->getType(), From);
1271   ICS = ::TryImplicitConversion(*this, From, ToType,
1272                                 /*SuppressUserConversions=*/false,
1273                                 AllowExplicit,
1274                                 /*InOverloadResolution=*/false,
1275                                 /*CStyle=*/false,
1276                                 AllowObjCWritebackConversion,
1277                                 /*AllowObjCConversionOnExplicit=*/false);
1278   return PerformImplicitConversion(From, ToType, ICS, Action);
1279 }
1280
1281 /// \brief Determine whether the conversion from FromType to ToType is a valid
1282 /// conversion that strips "noreturn" off the nested function type.
1283 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1284                                 QualType &ResultTy) {
1285   if (Context.hasSameUnqualifiedType(FromType, ToType))
1286     return false;
1287
1288   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1289   // where F adds one of the following at most once:
1290   //   - a pointer
1291   //   - a member pointer
1292   //   - a block pointer
1293   CanQualType CanTo = Context.getCanonicalType(ToType);
1294   CanQualType CanFrom = Context.getCanonicalType(FromType);
1295   Type::TypeClass TyClass = CanTo->getTypeClass();
1296   if (TyClass != CanFrom->getTypeClass()) return false;
1297   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1298     if (TyClass == Type::Pointer) {
1299       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1300       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1301     } else if (TyClass == Type::BlockPointer) {
1302       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1303       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1304     } else if (TyClass == Type::MemberPointer) {
1305       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1306       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1307     } else {
1308       return false;
1309     }
1310
1311     TyClass = CanTo->getTypeClass();
1312     if (TyClass != CanFrom->getTypeClass()) return false;
1313     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1314       return false;
1315   }
1316
1317   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1318   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1319   if (!EInfo.getNoReturn()) return false;
1320
1321   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1322   assert(QualType(FromFn, 0).isCanonical());
1323   if (QualType(FromFn, 0) != CanTo) return false;
1324
1325   ResultTy = ToType;
1326   return true;
1327 }
1328
1329 /// \brief Determine whether the conversion from FromType to ToType is a valid
1330 /// vector conversion.
1331 ///
1332 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1333 /// conversion.
1334 static bool IsVectorConversion(Sema &S, QualType FromType,
1335                                QualType ToType, ImplicitConversionKind &ICK) {
1336   // We need at least one of these types to be a vector type to have a vector
1337   // conversion.
1338   if (!ToType->isVectorType() && !FromType->isVectorType())
1339     return false;
1340
1341   // Identical types require no conversions.
1342   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1343     return false;
1344
1345   // There are no conversions between extended vector types, only identity.
1346   if (ToType->isExtVectorType()) {
1347     // There are no conversions between extended vector types other than the
1348     // identity conversion.
1349     if (FromType->isExtVectorType())
1350       return false;
1351
1352     // Vector splat from any arithmetic type to a vector.
1353     if (FromType->isArithmeticType()) {
1354       ICK = ICK_Vector_Splat;
1355       return true;
1356     }
1357   }
1358
1359   // We can perform the conversion between vector types in the following cases:
1360   // 1)vector types are equivalent AltiVec and GCC vector types
1361   // 2)lax vector conversions are permitted and the vector types are of the
1362   //   same size
1363   if (ToType->isVectorType() && FromType->isVectorType()) {
1364     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1365         S.isLaxVectorConversion(FromType, ToType)) {
1366       ICK = ICK_Vector_Conversion;
1367       return true;
1368     }
1369   }
1370
1371   return false;
1372 }
1373
1374 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1375                                 bool InOverloadResolution,
1376                                 StandardConversionSequence &SCS,
1377                                 bool CStyle);
1378   
1379 /// IsStandardConversion - Determines whether there is a standard
1380 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1381 /// expression From to the type ToType. Standard conversion sequences
1382 /// only consider non-class types; for conversions that involve class
1383 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1384 /// contain the standard conversion sequence required to perform this
1385 /// conversion and this routine will return true. Otherwise, this
1386 /// routine will return false and the value of SCS is unspecified.
1387 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1388                                  bool InOverloadResolution,
1389                                  StandardConversionSequence &SCS,
1390                                  bool CStyle,
1391                                  bool AllowObjCWritebackConversion) {
1392   QualType FromType = From->getType();
1393
1394   // Standard conversions (C++ [conv])
1395   SCS.setAsIdentityConversion();
1396   SCS.IncompatibleObjC = false;
1397   SCS.setFromType(FromType);
1398   SCS.CopyConstructor = nullptr;
1399
1400   // There are no standard conversions for class types in C++, so
1401   // abort early. When overloading in C, however, we do permit
1402   if (FromType->isRecordType() || ToType->isRecordType()) {
1403     if (S.getLangOpts().CPlusPlus)
1404       return false;
1405
1406     // When we're overloading in C, we allow, as standard conversions,
1407   }
1408
1409   // The first conversion can be an lvalue-to-rvalue conversion,
1410   // array-to-pointer conversion, or function-to-pointer conversion
1411   // (C++ 4p1).
1412
1413   if (FromType == S.Context.OverloadTy) {
1414     DeclAccessPair AccessPair;
1415     if (FunctionDecl *Fn
1416           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1417                                                  AccessPair)) {
1418       // We were able to resolve the address of the overloaded function,
1419       // so we can convert to the type of that function.
1420       FromType = Fn->getType();
1421       SCS.setFromType(FromType);
1422
1423       // we can sometimes resolve &foo<int> regardless of ToType, so check
1424       // if the type matches (identity) or we are converting to bool
1425       if (!S.Context.hasSameUnqualifiedType(
1426                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1427         QualType resultTy;
1428         // if the function type matches except for [[noreturn]], it's ok
1429         if (!S.IsNoReturnConversion(FromType,
1430               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1431           // otherwise, only a boolean conversion is standard   
1432           if (!ToType->isBooleanType()) 
1433             return false; 
1434       }
1435
1436       // Check if the "from" expression is taking the address of an overloaded
1437       // function and recompute the FromType accordingly. Take advantage of the
1438       // fact that non-static member functions *must* have such an address-of
1439       // expression. 
1440       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1441       if (Method && !Method->isStatic()) {
1442         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1443                "Non-unary operator on non-static member address");
1444         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1445                == UO_AddrOf &&
1446                "Non-address-of operator on non-static member address");
1447         const Type *ClassType
1448           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1449         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1450       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1451         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1452                UO_AddrOf &&
1453                "Non-address-of operator for overloaded function expression");
1454         FromType = S.Context.getPointerType(FromType);
1455       }
1456
1457       // Check that we've computed the proper type after overload resolution.
1458       assert(S.Context.hasSameType(
1459         FromType,
1460         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1461     } else {
1462       return false;
1463     }
1464   }
1465   // Lvalue-to-rvalue conversion (C++11 4.1):
1466   //   A glvalue (3.10) of a non-function, non-array type T can
1467   //   be converted to a prvalue.
1468   bool argIsLValue = From->isGLValue();
1469   if (argIsLValue &&
1470       !FromType->isFunctionType() && !FromType->isArrayType() &&
1471       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1472     SCS.First = ICK_Lvalue_To_Rvalue;
1473
1474     // C11 6.3.2.1p2:
1475     //   ... if the lvalue has atomic type, the value has the non-atomic version 
1476     //   of the type of the lvalue ...
1477     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1478       FromType = Atomic->getValueType();
1479
1480     // If T is a non-class type, the type of the rvalue is the
1481     // cv-unqualified version of T. Otherwise, the type of the rvalue
1482     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1483     // just strip the qualifiers because they don't matter.
1484     FromType = FromType.getUnqualifiedType();
1485   } else if (FromType->isArrayType()) {
1486     // Array-to-pointer conversion (C++ 4.2)
1487     SCS.First = ICK_Array_To_Pointer;
1488
1489     // An lvalue or rvalue of type "array of N T" or "array of unknown
1490     // bound of T" can be converted to an rvalue of type "pointer to
1491     // T" (C++ 4.2p1).
1492     FromType = S.Context.getArrayDecayedType(FromType);
1493
1494     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1495       // This conversion is deprecated in C++03 (D.4)
1496       SCS.DeprecatedStringLiteralToCharPtr = true;
1497
1498       // For the purpose of ranking in overload resolution
1499       // (13.3.3.1.1), this conversion is considered an
1500       // array-to-pointer conversion followed by a qualification
1501       // conversion (4.4). (C++ 4.2p2)
1502       SCS.Second = ICK_Identity;
1503       SCS.Third = ICK_Qualification;
1504       SCS.QualificationIncludesObjCLifetime = false;
1505       SCS.setAllToTypes(FromType);
1506       return true;
1507     }
1508   } else if (FromType->isFunctionType() && argIsLValue) {
1509     // Function-to-pointer conversion (C++ 4.3).
1510     SCS.First = ICK_Function_To_Pointer;
1511
1512     // An lvalue of function type T can be converted to an rvalue of
1513     // type "pointer to T." The result is a pointer to the
1514     // function. (C++ 4.3p1).
1515     FromType = S.Context.getPointerType(FromType);
1516   } else {
1517     // We don't require any conversions for the first step.
1518     SCS.First = ICK_Identity;
1519   }
1520   SCS.setToType(0, FromType);
1521
1522   // The second conversion can be an integral promotion, floating
1523   // point promotion, integral conversion, floating point conversion,
1524   // floating-integral conversion, pointer conversion,
1525   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1526   // For overloading in C, this can also be a "compatible-type"
1527   // conversion.
1528   bool IncompatibleObjC = false;
1529   ImplicitConversionKind SecondICK = ICK_Identity;
1530   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1531     // The unqualified versions of the types are the same: there's no
1532     // conversion to do.
1533     SCS.Second = ICK_Identity;
1534   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1535     // Integral promotion (C++ 4.5).
1536     SCS.Second = ICK_Integral_Promotion;
1537     FromType = ToType.getUnqualifiedType();
1538   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1539     // Floating point promotion (C++ 4.6).
1540     SCS.Second = ICK_Floating_Promotion;
1541     FromType = ToType.getUnqualifiedType();
1542   } else if (S.IsComplexPromotion(FromType, ToType)) {
1543     // Complex promotion (Clang extension)
1544     SCS.Second = ICK_Complex_Promotion;
1545     FromType = ToType.getUnqualifiedType();
1546   } else if (ToType->isBooleanType() &&
1547              (FromType->isArithmeticType() ||
1548               FromType->isAnyPointerType() ||
1549               FromType->isBlockPointerType() ||
1550               FromType->isMemberPointerType() ||
1551               FromType->isNullPtrType())) {
1552     // Boolean conversions (C++ 4.12).
1553     SCS.Second = ICK_Boolean_Conversion;
1554     FromType = S.Context.BoolTy;
1555   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1556              ToType->isIntegralType(S.Context)) {
1557     // Integral conversions (C++ 4.7).
1558     SCS.Second = ICK_Integral_Conversion;
1559     FromType = ToType.getUnqualifiedType();
1560   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1561     // Complex conversions (C99 6.3.1.6)
1562     SCS.Second = ICK_Complex_Conversion;
1563     FromType = ToType.getUnqualifiedType();
1564   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1565              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1566     // Complex-real conversions (C99 6.3.1.7)
1567     SCS.Second = ICK_Complex_Real;
1568     FromType = ToType.getUnqualifiedType();
1569   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1570     // Floating point conversions (C++ 4.8).
1571     SCS.Second = ICK_Floating_Conversion;
1572     FromType = ToType.getUnqualifiedType();
1573   } else if ((FromType->isRealFloatingType() &&
1574               ToType->isIntegralType(S.Context)) ||
1575              (FromType->isIntegralOrUnscopedEnumerationType() &&
1576               ToType->isRealFloatingType())) {
1577     // Floating-integral conversions (C++ 4.9).
1578     SCS.Second = ICK_Floating_Integral;
1579     FromType = ToType.getUnqualifiedType();
1580   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1581     SCS.Second = ICK_Block_Pointer_Conversion;
1582   } else if (AllowObjCWritebackConversion &&
1583              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1584     SCS.Second = ICK_Writeback_Conversion;
1585   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1586                                    FromType, IncompatibleObjC)) {
1587     // Pointer conversions (C++ 4.10).
1588     SCS.Second = ICK_Pointer_Conversion;
1589     SCS.IncompatibleObjC = IncompatibleObjC;
1590     FromType = FromType.getUnqualifiedType();
1591   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1592                                          InOverloadResolution, FromType)) {
1593     // Pointer to member conversions (4.11).
1594     SCS.Second = ICK_Pointer_Member;
1595   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1596     SCS.Second = SecondICK;
1597     FromType = ToType.getUnqualifiedType();
1598   } else if (!S.getLangOpts().CPlusPlus &&
1599              S.Context.typesAreCompatible(ToType, FromType)) {
1600     // Compatible conversions (Clang extension for C function overloading)
1601     SCS.Second = ICK_Compatible_Conversion;
1602     FromType = ToType.getUnqualifiedType();
1603   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1604     // Treat a conversion that strips "noreturn" as an identity conversion.
1605     SCS.Second = ICK_NoReturn_Adjustment;
1606   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1607                                              InOverloadResolution,
1608                                              SCS, CStyle)) {
1609     SCS.Second = ICK_TransparentUnionConversion;
1610     FromType = ToType;
1611   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1612                                  CStyle)) {
1613     // tryAtomicConversion has updated the standard conversion sequence
1614     // appropriately.
1615     return true;
1616   } else if (ToType->isEventT() && 
1617              From->isIntegerConstantExpr(S.getASTContext()) &&
1618              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1619     SCS.Second = ICK_Zero_Event_Conversion;
1620     FromType = ToType;
1621   } else {
1622     // No second conversion required.
1623     SCS.Second = ICK_Identity;
1624   }
1625   SCS.setToType(1, FromType);
1626
1627   QualType CanonFrom;
1628   QualType CanonTo;
1629   // The third conversion can be a qualification conversion (C++ 4p1).
1630   bool ObjCLifetimeConversion;
1631   if (S.IsQualificationConversion(FromType, ToType, CStyle, 
1632                                   ObjCLifetimeConversion)) {
1633     SCS.Third = ICK_Qualification;
1634     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1635     FromType = ToType;
1636     CanonFrom = S.Context.getCanonicalType(FromType);
1637     CanonTo = S.Context.getCanonicalType(ToType);
1638   } else {
1639     // No conversion required
1640     SCS.Third = ICK_Identity;
1641
1642     // C++ [over.best.ics]p6:
1643     //   [...] Any difference in top-level cv-qualification is
1644     //   subsumed by the initialization itself and does not constitute
1645     //   a conversion. [...]
1646     CanonFrom = S.Context.getCanonicalType(FromType);
1647     CanonTo = S.Context.getCanonicalType(ToType);
1648     if (CanonFrom.getLocalUnqualifiedType()
1649                                        == CanonTo.getLocalUnqualifiedType() &&
1650         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1651       FromType = ToType;
1652       CanonFrom = CanonTo;
1653     }
1654   }
1655   SCS.setToType(2, FromType);
1656
1657   // If we have not converted the argument type to the parameter type,
1658   // this is a bad conversion sequence.
1659   if (CanonFrom != CanonTo)
1660     return false;
1661
1662   return true;
1663 }
1664   
1665 static bool
1666 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 
1667                                      QualType &ToType,
1668                                      bool InOverloadResolution,
1669                                      StandardConversionSequence &SCS,
1670                                      bool CStyle) {
1671     
1672   const RecordType *UT = ToType->getAsUnionType();
1673   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1674     return false;
1675   // The field to initialize within the transparent union.
1676   RecordDecl *UD = UT->getDecl();
1677   // It's compatible if the expression matches any of the fields.
1678   for (const auto *it : UD->fields()) {
1679     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1680                              CStyle, /*ObjCWritebackConversion=*/false)) {
1681       ToType = it->getType();
1682       return true;
1683     }
1684   }
1685   return false;
1686 }
1687
1688 /// IsIntegralPromotion - Determines whether the conversion from the
1689 /// expression From (whose potentially-adjusted type is FromType) to
1690 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1691 /// sets PromotedType to the promoted type.
1692 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1693   const BuiltinType *To = ToType->getAs<BuiltinType>();
1694   // All integers are built-in.
1695   if (!To) {
1696     return false;
1697   }
1698
1699   // An rvalue of type char, signed char, unsigned char, short int, or
1700   // unsigned short int can be converted to an rvalue of type int if
1701   // int can represent all the values of the source type; otherwise,
1702   // the source rvalue can be converted to an rvalue of type unsigned
1703   // int (C++ 4.5p1).
1704   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1705       !FromType->isEnumeralType()) {
1706     if (// We can promote any signed, promotable integer type to an int
1707         (FromType->isSignedIntegerType() ||
1708          // We can promote any unsigned integer type whose size is
1709          // less than int to an int.
1710          (!FromType->isSignedIntegerType() &&
1711           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1712       return To->getKind() == BuiltinType::Int;
1713     }
1714
1715     return To->getKind() == BuiltinType::UInt;
1716   }
1717
1718   // C++11 [conv.prom]p3:
1719   //   A prvalue of an unscoped enumeration type whose underlying type is not
1720   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1721   //   following types that can represent all the values of the enumeration
1722   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1723   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1724   //   long long int. If none of the types in that list can represent all the
1725   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1726   //   type can be converted to an rvalue a prvalue of the extended integer type
1727   //   with lowest integer conversion rank (4.13) greater than the rank of long
1728   //   long in which all the values of the enumeration can be represented. If
1729   //   there are two such extended types, the signed one is chosen.
1730   // C++11 [conv.prom]p4:
1731   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1732   //   can be converted to a prvalue of its underlying type. Moreover, if
1733   //   integral promotion can be applied to its underlying type, a prvalue of an
1734   //   unscoped enumeration type whose underlying type is fixed can also be
1735   //   converted to a prvalue of the promoted underlying type.
1736   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1737     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1738     // provided for a scoped enumeration.
1739     if (FromEnumType->getDecl()->isScoped())
1740       return false;
1741
1742     // We can perform an integral promotion to the underlying type of the enum,
1743     // even if that's not the promoted type.
1744     if (FromEnumType->getDecl()->isFixed()) {
1745       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1746       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1747              IsIntegralPromotion(From, Underlying, ToType);
1748     }
1749
1750     // We have already pre-calculated the promotion type, so this is trivial.
1751     if (ToType->isIntegerType() &&
1752         !RequireCompleteType(From->getLocStart(), FromType, 0))
1753       return Context.hasSameUnqualifiedType(ToType,
1754                                 FromEnumType->getDecl()->getPromotionType());
1755   }
1756
1757   // C++0x [conv.prom]p2:
1758   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1759   //   to an rvalue a prvalue of the first of the following types that can
1760   //   represent all the values of its underlying type: int, unsigned int,
1761   //   long int, unsigned long int, long long int, or unsigned long long int.
1762   //   If none of the types in that list can represent all the values of its
1763   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1764   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1765   //   type.
1766   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1767       ToType->isIntegerType()) {
1768     // Determine whether the type we're converting from is signed or
1769     // unsigned.
1770     bool FromIsSigned = FromType->isSignedIntegerType();
1771     uint64_t FromSize = Context.getTypeSize(FromType);
1772
1773     // The types we'll try to promote to, in the appropriate
1774     // order. Try each of these types.
1775     QualType PromoteTypes[6] = {
1776       Context.IntTy, Context.UnsignedIntTy,
1777       Context.LongTy, Context.UnsignedLongTy ,
1778       Context.LongLongTy, Context.UnsignedLongLongTy
1779     };
1780     for (int Idx = 0; Idx < 6; ++Idx) {
1781       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1782       if (FromSize < ToSize ||
1783           (FromSize == ToSize &&
1784            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1785         // We found the type that we can promote to. If this is the
1786         // type we wanted, we have a promotion. Otherwise, no
1787         // promotion.
1788         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1789       }
1790     }
1791   }
1792
1793   // An rvalue for an integral bit-field (9.6) can be converted to an
1794   // rvalue of type int if int can represent all the values of the
1795   // bit-field; otherwise, it can be converted to unsigned int if
1796   // unsigned int can represent all the values of the bit-field. If
1797   // the bit-field is larger yet, no integral promotion applies to
1798   // it. If the bit-field has an enumerated type, it is treated as any
1799   // other value of that type for promotion purposes (C++ 4.5p3).
1800   // FIXME: We should delay checking of bit-fields until we actually perform the
1801   // conversion.
1802   using llvm::APSInt;
1803   if (From)
1804     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1805       APSInt BitWidth;
1806       if (FromType->isIntegralType(Context) &&
1807           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1808         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1809         ToSize = Context.getTypeSize(ToType);
1810
1811         // Are we promoting to an int from a bitfield that fits in an int?
1812         if (BitWidth < ToSize ||
1813             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1814           return To->getKind() == BuiltinType::Int;
1815         }
1816
1817         // Are we promoting to an unsigned int from an unsigned bitfield
1818         // that fits into an unsigned int?
1819         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1820           return To->getKind() == BuiltinType::UInt;
1821         }
1822
1823         return false;
1824       }
1825     }
1826
1827   // An rvalue of type bool can be converted to an rvalue of type int,
1828   // with false becoming zero and true becoming one (C++ 4.5p4).
1829   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1830     return true;
1831   }
1832
1833   return false;
1834 }
1835
1836 /// IsFloatingPointPromotion - Determines whether the conversion from
1837 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1838 /// returns true and sets PromotedType to the promoted type.
1839 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1840   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1841     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1842       /// An rvalue of type float can be converted to an rvalue of type
1843       /// double. (C++ 4.6p1).
1844       if (FromBuiltin->getKind() == BuiltinType::Float &&
1845           ToBuiltin->getKind() == BuiltinType::Double)
1846         return true;
1847
1848       // C99 6.3.1.5p1:
1849       //   When a float is promoted to double or long double, or a
1850       //   double is promoted to long double [...].
1851       if (!getLangOpts().CPlusPlus &&
1852           (FromBuiltin->getKind() == BuiltinType::Float ||
1853            FromBuiltin->getKind() == BuiltinType::Double) &&
1854           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1855         return true;
1856
1857       // Half can be promoted to float.
1858       if (!getLangOpts().NativeHalfType &&
1859            FromBuiltin->getKind() == BuiltinType::Half &&
1860           ToBuiltin->getKind() == BuiltinType::Float)
1861         return true;
1862     }
1863
1864   return false;
1865 }
1866
1867 /// \brief Determine if a conversion is a complex promotion.
1868 ///
1869 /// A complex promotion is defined as a complex -> complex conversion
1870 /// where the conversion between the underlying real types is a
1871 /// floating-point or integral promotion.
1872 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1873   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1874   if (!FromComplex)
1875     return false;
1876
1877   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1878   if (!ToComplex)
1879     return false;
1880
1881   return IsFloatingPointPromotion(FromComplex->getElementType(),
1882                                   ToComplex->getElementType()) ||
1883     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
1884                         ToComplex->getElementType());
1885 }
1886
1887 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1888 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1889 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1890 /// if non-empty, will be a pointer to ToType that may or may not have
1891 /// the right set of qualifiers on its pointee.
1892 ///
1893 static QualType
1894 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1895                                    QualType ToPointee, QualType ToType,
1896                                    ASTContext &Context,
1897                                    bool StripObjCLifetime = false) {
1898   assert((FromPtr->getTypeClass() == Type::Pointer ||
1899           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1900          "Invalid similarly-qualified pointer type");
1901
1902   /// Conversions to 'id' subsume cv-qualifier conversions.
1903   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 
1904     return ToType.getUnqualifiedType();
1905
1906   QualType CanonFromPointee
1907     = Context.getCanonicalType(FromPtr->getPointeeType());
1908   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1909   Qualifiers Quals = CanonFromPointee.getQualifiers();
1910
1911   if (StripObjCLifetime)
1912     Quals.removeObjCLifetime();
1913   
1914   // Exact qualifier match -> return the pointer type we're converting to.
1915   if (CanonToPointee.getLocalQualifiers() == Quals) {
1916     // ToType is exactly what we need. Return it.
1917     if (!ToType.isNull())
1918       return ToType.getUnqualifiedType();
1919
1920     // Build a pointer to ToPointee. It has the right qualifiers
1921     // already.
1922     if (isa<ObjCObjectPointerType>(ToType))
1923       return Context.getObjCObjectPointerType(ToPointee);
1924     return Context.getPointerType(ToPointee);
1925   }
1926
1927   // Just build a canonical type that has the right qualifiers.
1928   QualType QualifiedCanonToPointee
1929     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1930
1931   if (isa<ObjCObjectPointerType>(ToType))
1932     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1933   return Context.getPointerType(QualifiedCanonToPointee);
1934 }
1935
1936 static bool isNullPointerConstantForConversion(Expr *Expr,
1937                                                bool InOverloadResolution,
1938                                                ASTContext &Context) {
1939   // Handle value-dependent integral null pointer constants correctly.
1940   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1941   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1942       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1943     return !InOverloadResolution;
1944
1945   return Expr->isNullPointerConstant(Context,
1946                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1947                                         : Expr::NPC_ValueDependentIsNull);
1948 }
1949
1950 /// IsPointerConversion - Determines whether the conversion of the
1951 /// expression From, which has the (possibly adjusted) type FromType,
1952 /// can be converted to the type ToType via a pointer conversion (C++
1953 /// 4.10). If so, returns true and places the converted type (that
1954 /// might differ from ToType in its cv-qualifiers at some level) into
1955 /// ConvertedType.
1956 ///
1957 /// This routine also supports conversions to and from block pointers
1958 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1959 /// pointers to interfaces. FIXME: Once we've determined the
1960 /// appropriate overloading rules for Objective-C, we may want to
1961 /// split the Objective-C checks into a different routine; however,
1962 /// GCC seems to consider all of these conversions to be pointer
1963 /// conversions, so for now they live here. IncompatibleObjC will be
1964 /// set if the conversion is an allowed Objective-C conversion that
1965 /// should result in a warning.
1966 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1967                                bool InOverloadResolution,
1968                                QualType& ConvertedType,
1969                                bool &IncompatibleObjC) {
1970   IncompatibleObjC = false;
1971   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1972                               IncompatibleObjC))
1973     return true;
1974
1975   // Conversion from a null pointer constant to any Objective-C pointer type.
1976   if (ToType->isObjCObjectPointerType() &&
1977       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1978     ConvertedType = ToType;
1979     return true;
1980   }
1981
1982   // Blocks: Block pointers can be converted to void*.
1983   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1984       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1985     ConvertedType = ToType;
1986     return true;
1987   }
1988   // Blocks: A null pointer constant can be converted to a block
1989   // pointer type.
1990   if (ToType->isBlockPointerType() &&
1991       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1992     ConvertedType = ToType;
1993     return true;
1994   }
1995
1996   // If the left-hand-side is nullptr_t, the right side can be a null
1997   // pointer constant.
1998   if (ToType->isNullPtrType() &&
1999       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2000     ConvertedType = ToType;
2001     return true;
2002   }
2003
2004   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2005   if (!ToTypePtr)
2006     return false;
2007
2008   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2009   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2010     ConvertedType = ToType;
2011     return true;
2012   }
2013
2014   // Beyond this point, both types need to be pointers
2015   // , including objective-c pointers.
2016   QualType ToPointeeType = ToTypePtr->getPointeeType();
2017   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2018       !getLangOpts().ObjCAutoRefCount) {
2019     ConvertedType = BuildSimilarlyQualifiedPointerType(
2020                                       FromType->getAs<ObjCObjectPointerType>(),
2021                                                        ToPointeeType,
2022                                                        ToType, Context);
2023     return true;
2024   }
2025   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2026   if (!FromTypePtr)
2027     return false;
2028
2029   QualType FromPointeeType = FromTypePtr->getPointeeType();
2030
2031   // If the unqualified pointee types are the same, this can't be a
2032   // pointer conversion, so don't do all of the work below.
2033   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2034     return false;
2035
2036   // An rvalue of type "pointer to cv T," where T is an object type,
2037   // can be converted to an rvalue of type "pointer to cv void" (C++
2038   // 4.10p2).
2039   if (FromPointeeType->isIncompleteOrObjectType() &&
2040       ToPointeeType->isVoidType()) {
2041     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2042                                                        ToPointeeType,
2043                                                        ToType, Context,
2044                                                    /*StripObjCLifetime=*/true);
2045     return true;
2046   }
2047
2048   // MSVC allows implicit function to void* type conversion.
2049   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2050       ToPointeeType->isVoidType()) {
2051     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2052                                                        ToPointeeType,
2053                                                        ToType, Context);
2054     return true;
2055   }
2056
2057   // When we're overloading in C, we allow a special kind of pointer
2058   // conversion for compatible-but-not-identical pointee types.
2059   if (!getLangOpts().CPlusPlus &&
2060       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2061     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2062                                                        ToPointeeType,
2063                                                        ToType, Context);
2064     return true;
2065   }
2066
2067   // C++ [conv.ptr]p3:
2068   //
2069   //   An rvalue of type "pointer to cv D," where D is a class type,
2070   //   can be converted to an rvalue of type "pointer to cv B," where
2071   //   B is a base class (clause 10) of D. If B is an inaccessible
2072   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2073   //   necessitates this conversion is ill-formed. The result of the
2074   //   conversion is a pointer to the base class sub-object of the
2075   //   derived class object. The null pointer value is converted to
2076   //   the null pointer value of the destination type.
2077   //
2078   // Note that we do not check for ambiguity or inaccessibility
2079   // here. That is handled by CheckPointerConversion.
2080   if (getLangOpts().CPlusPlus &&
2081       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2082       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2083       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2084       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2085     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2086                                                        ToPointeeType,
2087                                                        ToType, Context);
2088     return true;
2089   }
2090
2091   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2092       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2093     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2094                                                        ToPointeeType,
2095                                                        ToType, Context);
2096     return true;
2097   }
2098   
2099   return false;
2100 }
2101  
2102 /// \brief Adopt the given qualifiers for the given type.
2103 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2104   Qualifiers TQs = T.getQualifiers();
2105   
2106   // Check whether qualifiers already match.
2107   if (TQs == Qs)
2108     return T;
2109   
2110   if (Qs.compatiblyIncludes(TQs))
2111     return Context.getQualifiedType(T, Qs);
2112   
2113   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2114 }
2115
2116 /// isObjCPointerConversion - Determines whether this is an
2117 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2118 /// with the same arguments and return values.
2119 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2120                                    QualType& ConvertedType,
2121                                    bool &IncompatibleObjC) {
2122   if (!getLangOpts().ObjC1)
2123     return false;
2124
2125   // The set of qualifiers on the type we're converting from.
2126   Qualifiers FromQualifiers = FromType.getQualifiers();
2127   
2128   // First, we handle all conversions on ObjC object pointer types.
2129   const ObjCObjectPointerType* ToObjCPtr =
2130     ToType->getAs<ObjCObjectPointerType>();
2131   const ObjCObjectPointerType *FromObjCPtr =
2132     FromType->getAs<ObjCObjectPointerType>();
2133
2134   if (ToObjCPtr && FromObjCPtr) {
2135     // If the pointee types are the same (ignoring qualifications),
2136     // then this is not a pointer conversion.
2137     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2138                                        FromObjCPtr->getPointeeType()))
2139       return false;
2140
2141     // Check for compatible 
2142     // Objective C++: We're able to convert between "id" or "Class" and a
2143     // pointer to any interface (in both directions).
2144     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2145       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2146       return true;
2147     }
2148     // Conversions with Objective-C's id<...>.
2149     if ((FromObjCPtr->isObjCQualifiedIdType() ||
2150          ToObjCPtr->isObjCQualifiedIdType()) &&
2151         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2152                                                   /*compare=*/false)) {
2153       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2154       return true;
2155     }
2156     // Objective C++: We're able to convert from a pointer to an
2157     // interface to a pointer to a different interface.
2158     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2159       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2160       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2161       if (getLangOpts().CPlusPlus && LHS && RHS &&
2162           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2163                                                 FromObjCPtr->getPointeeType()))
2164         return false;
2165       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2166                                                    ToObjCPtr->getPointeeType(),
2167                                                          ToType, Context);
2168       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2169       return true;
2170     }
2171
2172     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2173       // Okay: this is some kind of implicit downcast of Objective-C
2174       // interfaces, which is permitted. However, we're going to
2175       // complain about it.
2176       IncompatibleObjC = true;
2177       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2178                                                    ToObjCPtr->getPointeeType(),
2179                                                          ToType, Context);
2180       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2181       return true;
2182     }
2183   }
2184   // Beyond this point, both types need to be C pointers or block pointers.
2185   QualType ToPointeeType;
2186   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2187     ToPointeeType = ToCPtr->getPointeeType();
2188   else if (const BlockPointerType *ToBlockPtr =
2189             ToType->getAs<BlockPointerType>()) {
2190     // Objective C++: We're able to convert from a pointer to any object
2191     // to a block pointer type.
2192     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2193       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2194       return true;
2195     }
2196     ToPointeeType = ToBlockPtr->getPointeeType();
2197   }
2198   else if (FromType->getAs<BlockPointerType>() &&
2199            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2200     // Objective C++: We're able to convert from a block pointer type to a
2201     // pointer to any object.
2202     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2203     return true;
2204   }
2205   else
2206     return false;
2207
2208   QualType FromPointeeType;
2209   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2210     FromPointeeType = FromCPtr->getPointeeType();
2211   else if (const BlockPointerType *FromBlockPtr =
2212            FromType->getAs<BlockPointerType>())
2213     FromPointeeType = FromBlockPtr->getPointeeType();
2214   else
2215     return false;
2216
2217   // If we have pointers to pointers, recursively check whether this
2218   // is an Objective-C conversion.
2219   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2220       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2221                               IncompatibleObjC)) {
2222     // We always complain about this conversion.
2223     IncompatibleObjC = true;
2224     ConvertedType = Context.getPointerType(ConvertedType);
2225     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2226     return true;
2227   }
2228   // Allow conversion of pointee being objective-c pointer to another one;
2229   // as in I* to id.
2230   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2231       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2232       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2233                               IncompatibleObjC)) {
2234         
2235     ConvertedType = Context.getPointerType(ConvertedType);
2236     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2237     return true;
2238   }
2239
2240   // If we have pointers to functions or blocks, check whether the only
2241   // differences in the argument and result types are in Objective-C
2242   // pointer conversions. If so, we permit the conversion (but
2243   // complain about it).
2244   const FunctionProtoType *FromFunctionType
2245     = FromPointeeType->getAs<FunctionProtoType>();
2246   const FunctionProtoType *ToFunctionType
2247     = ToPointeeType->getAs<FunctionProtoType>();
2248   if (FromFunctionType && ToFunctionType) {
2249     // If the function types are exactly the same, this isn't an
2250     // Objective-C pointer conversion.
2251     if (Context.getCanonicalType(FromPointeeType)
2252           == Context.getCanonicalType(ToPointeeType))
2253       return false;
2254
2255     // Perform the quick checks that will tell us whether these
2256     // function types are obviously different.
2257     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2258         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2259         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2260       return false;
2261
2262     bool HasObjCConversion = false;
2263     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2264         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2265       // Okay, the types match exactly. Nothing to do.
2266     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2267                                        ToFunctionType->getReturnType(),
2268                                        ConvertedType, IncompatibleObjC)) {
2269       // Okay, we have an Objective-C pointer conversion.
2270       HasObjCConversion = true;
2271     } else {
2272       // Function types are too different. Abort.
2273       return false;
2274     }
2275
2276     // Check argument types.
2277     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2278          ArgIdx != NumArgs; ++ArgIdx) {
2279       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2280       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2281       if (Context.getCanonicalType(FromArgType)
2282             == Context.getCanonicalType(ToArgType)) {
2283         // Okay, the types match exactly. Nothing to do.
2284       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2285                                          ConvertedType, IncompatibleObjC)) {
2286         // Okay, we have an Objective-C pointer conversion.
2287         HasObjCConversion = true;
2288       } else {
2289         // Argument types are too different. Abort.
2290         return false;
2291       }
2292     }
2293
2294     if (HasObjCConversion) {
2295       // We had an Objective-C conversion. Allow this pointer
2296       // conversion, but complain about it.
2297       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2298       IncompatibleObjC = true;
2299       return true;
2300     }
2301   }
2302
2303   return false;
2304 }
2305
2306 /// \brief Determine whether this is an Objective-C writeback conversion,
2307 /// used for parameter passing when performing automatic reference counting.
2308 ///
2309 /// \param FromType The type we're converting form.
2310 ///
2311 /// \param ToType The type we're converting to.
2312 ///
2313 /// \param ConvertedType The type that will be produced after applying
2314 /// this conversion.
2315 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2316                                      QualType &ConvertedType) {
2317   if (!getLangOpts().ObjCAutoRefCount || 
2318       Context.hasSameUnqualifiedType(FromType, ToType))
2319     return false;
2320   
2321   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2322   QualType ToPointee;
2323   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2324     ToPointee = ToPointer->getPointeeType();
2325   else
2326     return false;
2327   
2328   Qualifiers ToQuals = ToPointee.getQualifiers();
2329   if (!ToPointee->isObjCLifetimeType() || 
2330       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2331       !ToQuals.withoutObjCLifetime().empty())
2332     return false;
2333   
2334   // Argument must be a pointer to __strong to __weak.
2335   QualType FromPointee;
2336   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2337     FromPointee = FromPointer->getPointeeType();
2338   else
2339     return false;
2340   
2341   Qualifiers FromQuals = FromPointee.getQualifiers();
2342   if (!FromPointee->isObjCLifetimeType() ||
2343       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2344        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2345     return false;
2346   
2347   // Make sure that we have compatible qualifiers.
2348   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2349   if (!ToQuals.compatiblyIncludes(FromQuals))
2350     return false;
2351   
2352   // Remove qualifiers from the pointee type we're converting from; they
2353   // aren't used in the compatibility check belong, and we'll be adding back
2354   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2355   FromPointee = FromPointee.getUnqualifiedType();
2356   
2357   // The unqualified form of the pointee types must be compatible.
2358   ToPointee = ToPointee.getUnqualifiedType();
2359   bool IncompatibleObjC;
2360   if (Context.typesAreCompatible(FromPointee, ToPointee))
2361     FromPointee = ToPointee;
2362   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2363                                     IncompatibleObjC))
2364     return false;
2365   
2366   /// \brief Construct the type we're converting to, which is a pointer to
2367   /// __autoreleasing pointee.
2368   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2369   ConvertedType = Context.getPointerType(FromPointee);
2370   return true;
2371 }
2372
2373 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2374                                     QualType& ConvertedType) {
2375   QualType ToPointeeType;
2376   if (const BlockPointerType *ToBlockPtr =
2377         ToType->getAs<BlockPointerType>())
2378     ToPointeeType = ToBlockPtr->getPointeeType();
2379   else
2380     return false;
2381   
2382   QualType FromPointeeType;
2383   if (const BlockPointerType *FromBlockPtr =
2384       FromType->getAs<BlockPointerType>())
2385     FromPointeeType = FromBlockPtr->getPointeeType();
2386   else
2387     return false;
2388   // We have pointer to blocks, check whether the only
2389   // differences in the argument and result types are in Objective-C
2390   // pointer conversions. If so, we permit the conversion.
2391   
2392   const FunctionProtoType *FromFunctionType
2393     = FromPointeeType->getAs<FunctionProtoType>();
2394   const FunctionProtoType *ToFunctionType
2395     = ToPointeeType->getAs<FunctionProtoType>();
2396   
2397   if (!FromFunctionType || !ToFunctionType)
2398     return false;
2399
2400   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2401     return true;
2402     
2403   // Perform the quick checks that will tell us whether these
2404   // function types are obviously different.
2405   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2406       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2407     return false;
2408     
2409   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2410   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2411   if (FromEInfo != ToEInfo)
2412     return false;
2413
2414   bool IncompatibleObjC = false;
2415   if (Context.hasSameType(FromFunctionType->getReturnType(),
2416                           ToFunctionType->getReturnType())) {
2417     // Okay, the types match exactly. Nothing to do.
2418   } else {
2419     QualType RHS = FromFunctionType->getReturnType();
2420     QualType LHS = ToFunctionType->getReturnType();
2421     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2422         !RHS.hasQualifiers() && LHS.hasQualifiers())
2423        LHS = LHS.getUnqualifiedType();
2424
2425      if (Context.hasSameType(RHS,LHS)) {
2426        // OK exact match.
2427      } else if (isObjCPointerConversion(RHS, LHS,
2428                                         ConvertedType, IncompatibleObjC)) {
2429      if (IncompatibleObjC)
2430        return false;
2431      // Okay, we have an Objective-C pointer conversion.
2432      }
2433      else
2434        return false;
2435    }
2436     
2437    // Check argument types.
2438    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2439         ArgIdx != NumArgs; ++ArgIdx) {
2440      IncompatibleObjC = false;
2441      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2442      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2443      if (Context.hasSameType(FromArgType, ToArgType)) {
2444        // Okay, the types match exactly. Nothing to do.
2445      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2446                                         ConvertedType, IncompatibleObjC)) {
2447        if (IncompatibleObjC)
2448          return false;
2449        // Okay, we have an Objective-C pointer conversion.
2450      } else
2451        // Argument types are too different. Abort.
2452        return false;
2453    }
2454    if (LangOpts.ObjCAutoRefCount && 
2455        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 
2456                                                     ToFunctionType))
2457      return false;
2458    
2459    ConvertedType = ToType;
2460    return true;
2461 }
2462
2463 enum {
2464   ft_default,
2465   ft_different_class,
2466   ft_parameter_arity,
2467   ft_parameter_mismatch,
2468   ft_return_type,
2469   ft_qualifer_mismatch
2470 };
2471
2472 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2473 /// function types.  Catches different number of parameter, mismatch in
2474 /// parameter types, and different return types.
2475 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2476                                       QualType FromType, QualType ToType) {
2477   // If either type is not valid, include no extra info.
2478   if (FromType.isNull() || ToType.isNull()) {
2479     PDiag << ft_default;
2480     return;
2481   }
2482
2483   // Get the function type from the pointers.
2484   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2485     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2486                             *ToMember = ToType->getAs<MemberPointerType>();
2487     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2488       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2489             << QualType(FromMember->getClass(), 0);
2490       return;
2491     }
2492     FromType = FromMember->getPointeeType();
2493     ToType = ToMember->getPointeeType();
2494   }
2495
2496   if (FromType->isPointerType())
2497     FromType = FromType->getPointeeType();
2498   if (ToType->isPointerType())
2499     ToType = ToType->getPointeeType();
2500
2501   // Remove references.
2502   FromType = FromType.getNonReferenceType();
2503   ToType = ToType.getNonReferenceType();
2504
2505   // Don't print extra info for non-specialized template functions.
2506   if (FromType->isInstantiationDependentType() &&
2507       !FromType->getAs<TemplateSpecializationType>()) {
2508     PDiag << ft_default;
2509     return;
2510   }
2511
2512   // No extra info for same types.
2513   if (Context.hasSameType(FromType, ToType)) {
2514     PDiag << ft_default;
2515     return;
2516   }
2517
2518   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2519                           *ToFunction = ToType->getAs<FunctionProtoType>();
2520
2521   // Both types need to be function types.
2522   if (!FromFunction || !ToFunction) {
2523     PDiag << ft_default;
2524     return;
2525   }
2526
2527   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2528     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2529           << FromFunction->getNumParams();
2530     return;
2531   }
2532
2533   // Handle different parameter types.
2534   unsigned ArgPos;
2535   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2536     PDiag << ft_parameter_mismatch << ArgPos + 1
2537           << ToFunction->getParamType(ArgPos)
2538           << FromFunction->getParamType(ArgPos);
2539     return;
2540   }
2541
2542   // Handle different return type.
2543   if (!Context.hasSameType(FromFunction->getReturnType(),
2544                            ToFunction->getReturnType())) {
2545     PDiag << ft_return_type << ToFunction->getReturnType()
2546           << FromFunction->getReturnType();
2547     return;
2548   }
2549
2550   unsigned FromQuals = FromFunction->getTypeQuals(),
2551            ToQuals = ToFunction->getTypeQuals();
2552   if (FromQuals != ToQuals) {
2553     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2554     return;
2555   }
2556
2557   // Unable to find a difference, so add no extra info.
2558   PDiag << ft_default;
2559 }
2560
2561 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2562 /// for equality of their argument types. Caller has already checked that
2563 /// they have same number of arguments.  If the parameters are different,
2564 /// ArgPos will have the parameter index of the first different parameter.
2565 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2566                                       const FunctionProtoType *NewType,
2567                                       unsigned *ArgPos) {
2568   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2569                                               N = NewType->param_type_begin(),
2570                                               E = OldType->param_type_end();
2571        O && (O != E); ++O, ++N) {
2572     if (!Context.hasSameType(O->getUnqualifiedType(),
2573                              N->getUnqualifiedType())) {
2574       if (ArgPos)
2575         *ArgPos = O - OldType->param_type_begin();
2576       return false;
2577     }
2578   }
2579   return true;
2580 }
2581
2582 /// CheckPointerConversion - Check the pointer conversion from the
2583 /// expression From to the type ToType. This routine checks for
2584 /// ambiguous or inaccessible derived-to-base pointer
2585 /// conversions for which IsPointerConversion has already returned
2586 /// true. It returns true and produces a diagnostic if there was an
2587 /// error, or returns false otherwise.
2588 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2589                                   CastKind &Kind,
2590                                   CXXCastPath& BasePath,
2591                                   bool IgnoreBaseAccess) {
2592   QualType FromType = From->getType();
2593   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2594
2595   Kind = CK_BitCast;
2596
2597   if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2598       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2599       Expr::NPCK_ZeroExpression) {
2600     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2601       DiagRuntimeBehavior(From->getExprLoc(), From,
2602                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2603                             << ToType << From->getSourceRange());
2604     else if (!isUnevaluatedContext())
2605       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2606         << ToType << From->getSourceRange();
2607   }
2608   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2609     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2610       QualType FromPointeeType = FromPtrType->getPointeeType(),
2611                ToPointeeType   = ToPtrType->getPointeeType();
2612
2613       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2614           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2615         // We must have a derived-to-base conversion. Check an
2616         // ambiguous or inaccessible conversion.
2617         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2618                                          From->getExprLoc(),
2619                                          From->getSourceRange(), &BasePath,
2620                                          IgnoreBaseAccess))
2621           return true;
2622
2623         // The conversion was successful.
2624         Kind = CK_DerivedToBase;
2625       }
2626     }
2627   } else if (const ObjCObjectPointerType *ToPtrType =
2628                ToType->getAs<ObjCObjectPointerType>()) {
2629     if (const ObjCObjectPointerType *FromPtrType =
2630           FromType->getAs<ObjCObjectPointerType>()) {
2631       // Objective-C++ conversions are always okay.
2632       // FIXME: We should have a different class of conversions for the
2633       // Objective-C++ implicit conversions.
2634       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2635         return false;
2636     } else if (FromType->isBlockPointerType()) {
2637       Kind = CK_BlockPointerToObjCPointerCast;
2638     } else {
2639       Kind = CK_CPointerToObjCPointerCast;
2640     }
2641   } else if (ToType->isBlockPointerType()) {
2642     if (!FromType->isBlockPointerType())
2643       Kind = CK_AnyPointerToBlockPointerCast;
2644   }
2645
2646   // We shouldn't fall into this case unless it's valid for other
2647   // reasons.
2648   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2649     Kind = CK_NullToPointer;
2650
2651   return false;
2652 }
2653
2654 /// IsMemberPointerConversion - Determines whether the conversion of the
2655 /// expression From, which has the (possibly adjusted) type FromType, can be
2656 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2657 /// If so, returns true and places the converted type (that might differ from
2658 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2659 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2660                                      QualType ToType,
2661                                      bool InOverloadResolution,
2662                                      QualType &ConvertedType) {
2663   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2664   if (!ToTypePtr)
2665     return false;
2666
2667   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2668   if (From->isNullPointerConstant(Context,
2669                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2670                                         : Expr::NPC_ValueDependentIsNull)) {
2671     ConvertedType = ToType;
2672     return true;
2673   }
2674
2675   // Otherwise, both types have to be member pointers.
2676   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2677   if (!FromTypePtr)
2678     return false;
2679
2680   // A pointer to member of B can be converted to a pointer to member of D,
2681   // where D is derived from B (C++ 4.11p2).
2682   QualType FromClass(FromTypePtr->getClass(), 0);
2683   QualType ToClass(ToTypePtr->getClass(), 0);
2684
2685   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2686       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2687       IsDerivedFrom(ToClass, FromClass)) {
2688     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2689                                                  ToClass.getTypePtr());
2690     return true;
2691   }
2692
2693   return false;
2694 }
2695
2696 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2697 /// expression From to the type ToType. This routine checks for ambiguous or
2698 /// virtual or inaccessible base-to-derived member pointer conversions
2699 /// for which IsMemberPointerConversion has already returned true. It returns
2700 /// true and produces a diagnostic if there was an error, or returns false
2701 /// otherwise.
2702 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2703                                         CastKind &Kind,
2704                                         CXXCastPath &BasePath,
2705                                         bool IgnoreBaseAccess) {
2706   QualType FromType = From->getType();
2707   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2708   if (!FromPtrType) {
2709     // This must be a null pointer to member pointer conversion
2710     assert(From->isNullPointerConstant(Context,
2711                                        Expr::NPC_ValueDependentIsNull) &&
2712            "Expr must be null pointer constant!");
2713     Kind = CK_NullToMemberPointer;
2714     return false;
2715   }
2716
2717   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2718   assert(ToPtrType && "No member pointer cast has a target type "
2719                       "that is not a member pointer.");
2720
2721   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2722   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2723
2724   // FIXME: What about dependent types?
2725   assert(FromClass->isRecordType() && "Pointer into non-class.");
2726   assert(ToClass->isRecordType() && "Pointer into non-class.");
2727
2728   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2729                      /*DetectVirtual=*/true);
2730   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2731   assert(DerivationOkay &&
2732          "Should not have been called if derivation isn't OK.");
2733   (void)DerivationOkay;
2734
2735   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2736                                   getUnqualifiedType())) {
2737     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2738     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2739       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2740     return true;
2741   }
2742
2743   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2744     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2745       << FromClass << ToClass << QualType(VBase, 0)
2746       << From->getSourceRange();
2747     return true;
2748   }
2749
2750   if (!IgnoreBaseAccess)
2751     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2752                          Paths.front(),
2753                          diag::err_downcast_from_inaccessible_base);
2754
2755   // Must be a base to derived member conversion.
2756   BuildBasePathArray(Paths, BasePath);
2757   Kind = CK_BaseToDerivedMemberPointer;
2758   return false;
2759 }
2760
2761 /// Determine whether the lifetime conversion between the two given
2762 /// qualifiers sets is nontrivial.
2763 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2764                                                Qualifiers ToQuals) {
2765   // Converting anything to const __unsafe_unretained is trivial.
2766   if (ToQuals.hasConst() && 
2767       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2768     return false;
2769
2770   return true;
2771 }
2772
2773 /// IsQualificationConversion - Determines whether the conversion from
2774 /// an rvalue of type FromType to ToType is a qualification conversion
2775 /// (C++ 4.4).
2776 ///
2777 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2778 /// when the qualification conversion involves a change in the Objective-C
2779 /// object lifetime.
2780 bool
2781 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2782                                 bool CStyle, bool &ObjCLifetimeConversion) {
2783   FromType = Context.getCanonicalType(FromType);
2784   ToType = Context.getCanonicalType(ToType);
2785   ObjCLifetimeConversion = false;
2786   
2787   // If FromType and ToType are the same type, this is not a
2788   // qualification conversion.
2789   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2790     return false;
2791
2792   // (C++ 4.4p4):
2793   //   A conversion can add cv-qualifiers at levels other than the first
2794   //   in multi-level pointers, subject to the following rules: [...]
2795   bool PreviousToQualsIncludeConst = true;
2796   bool UnwrappedAnyPointer = false;
2797   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2798     // Within each iteration of the loop, we check the qualifiers to
2799     // determine if this still looks like a qualification
2800     // conversion. Then, if all is well, we unwrap one more level of
2801     // pointers or pointers-to-members and do it all again
2802     // until there are no more pointers or pointers-to-members left to
2803     // unwrap.
2804     UnwrappedAnyPointer = true;
2805
2806     Qualifiers FromQuals = FromType.getQualifiers();
2807     Qualifiers ToQuals = ToType.getQualifiers();
2808     
2809     // Objective-C ARC:
2810     //   Check Objective-C lifetime conversions.
2811     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2812         UnwrappedAnyPointer) {
2813       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2814         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2815           ObjCLifetimeConversion = true;
2816         FromQuals.removeObjCLifetime();
2817         ToQuals.removeObjCLifetime();
2818       } else {
2819         // Qualification conversions cannot cast between different
2820         // Objective-C lifetime qualifiers.
2821         return false;
2822       }
2823     }
2824     
2825     // Allow addition/removal of GC attributes but not changing GC attributes.
2826     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2827         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2828       FromQuals.removeObjCGCAttr();
2829       ToQuals.removeObjCGCAttr();
2830     }
2831     
2832     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2833     //      2,j, and similarly for volatile.
2834     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2835       return false;
2836
2837     //   -- if the cv 1,j and cv 2,j are different, then const is in
2838     //      every cv for 0 < k < j.
2839     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2840         && !PreviousToQualsIncludeConst)
2841       return false;
2842
2843     // Keep track of whether all prior cv-qualifiers in the "to" type
2844     // include const.
2845     PreviousToQualsIncludeConst
2846       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2847   }
2848
2849   // We are left with FromType and ToType being the pointee types
2850   // after unwrapping the original FromType and ToType the same number
2851   // of types. If we unwrapped any pointers, and if FromType and
2852   // ToType have the same unqualified type (since we checked
2853   // qualifiers above), then this is a qualification conversion.
2854   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2855 }
2856
2857 /// \brief - Determine whether this is a conversion from a scalar type to an
2858 /// atomic type.
2859 ///
2860 /// If successful, updates \c SCS's second and third steps in the conversion
2861 /// sequence to finish the conversion.
2862 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2863                                 bool InOverloadResolution,
2864                                 StandardConversionSequence &SCS,
2865                                 bool CStyle) {
2866   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2867   if (!ToAtomic)
2868     return false;
2869   
2870   StandardConversionSequence InnerSCS;
2871   if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 
2872                             InOverloadResolution, InnerSCS,
2873                             CStyle, /*AllowObjCWritebackConversion=*/false))
2874     return false;
2875   
2876   SCS.Second = InnerSCS.Second;
2877   SCS.setToType(1, InnerSCS.getToType(1));
2878   SCS.Third = InnerSCS.Third;
2879   SCS.QualificationIncludesObjCLifetime
2880     = InnerSCS.QualificationIncludesObjCLifetime;
2881   SCS.setToType(2, InnerSCS.getToType(2));
2882   return true;
2883 }
2884
2885 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2886                                               CXXConstructorDecl *Constructor,
2887                                               QualType Type) {
2888   const FunctionProtoType *CtorType =
2889       Constructor->getType()->getAs<FunctionProtoType>();
2890   if (CtorType->getNumParams() > 0) {
2891     QualType FirstArg = CtorType->getParamType(0);
2892     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2893       return true;
2894   }
2895   return false;
2896 }
2897
2898 static OverloadingResult
2899 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2900                                        CXXRecordDecl *To,
2901                                        UserDefinedConversionSequence &User,
2902                                        OverloadCandidateSet &CandidateSet,
2903                                        bool AllowExplicit) {
2904   DeclContext::lookup_result R = S.LookupConstructors(To);
2905   for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2906        Con != ConEnd; ++Con) {
2907     NamedDecl *D = *Con;
2908     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2909
2910     // Find the constructor (which may be a template).
2911     CXXConstructorDecl *Constructor = nullptr;
2912     FunctionTemplateDecl *ConstructorTmpl
2913       = dyn_cast<FunctionTemplateDecl>(D);
2914     if (ConstructorTmpl)
2915       Constructor
2916         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2917     else
2918       Constructor = cast<CXXConstructorDecl>(D);
2919
2920     bool Usable = !Constructor->isInvalidDecl() &&
2921                   S.isInitListConstructor(Constructor) &&
2922                   (AllowExplicit || !Constructor->isExplicit());
2923     if (Usable) {
2924       // If the first argument is (a reference to) the target type,
2925       // suppress conversions.
2926       bool SuppressUserConversions =
2927           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2928       if (ConstructorTmpl)
2929         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2930                                        /*ExplicitArgs*/ nullptr,
2931                                        From, CandidateSet,
2932                                        SuppressUserConversions);
2933       else
2934         S.AddOverloadCandidate(Constructor, FoundDecl,
2935                                From, CandidateSet,
2936                                SuppressUserConversions);
2937     }
2938   }
2939
2940   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2941
2942   OverloadCandidateSet::iterator Best;
2943   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2944   case OR_Success: {
2945     // Record the standard conversion we used and the conversion function.
2946     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2947     QualType ThisType = Constructor->getThisType(S.Context);
2948     // Initializer lists don't have conversions as such.
2949     User.Before.setAsIdentityConversion();
2950     User.HadMultipleCandidates = HadMultipleCandidates;
2951     User.ConversionFunction = Constructor;
2952     User.FoundConversionFunction = Best->FoundDecl;
2953     User.After.setAsIdentityConversion();
2954     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2955     User.After.setAllToTypes(ToType);
2956     return OR_Success;
2957   }
2958
2959   case OR_No_Viable_Function:
2960     return OR_No_Viable_Function;
2961   case OR_Deleted:
2962     return OR_Deleted;
2963   case OR_Ambiguous:
2964     return OR_Ambiguous;
2965   }
2966
2967   llvm_unreachable("Invalid OverloadResult!");
2968 }
2969
2970 /// Determines whether there is a user-defined conversion sequence
2971 /// (C++ [over.ics.user]) that converts expression From to the type
2972 /// ToType. If such a conversion exists, User will contain the
2973 /// user-defined conversion sequence that performs such a conversion
2974 /// and this routine will return true. Otherwise, this routine returns
2975 /// false and User is unspecified.
2976 ///
2977 /// \param AllowExplicit  true if the conversion should consider C++0x
2978 /// "explicit" conversion functions as well as non-explicit conversion
2979 /// functions (C++0x [class.conv.fct]p2).
2980 ///
2981 /// \param AllowObjCConversionOnExplicit true if the conversion should
2982 /// allow an extra Objective-C pointer conversion on uses of explicit
2983 /// constructors. Requires \c AllowExplicit to also be set.
2984 static OverloadingResult
2985 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2986                         UserDefinedConversionSequence &User,
2987                         OverloadCandidateSet &CandidateSet,
2988                         bool AllowExplicit,
2989                         bool AllowObjCConversionOnExplicit) {
2990   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
2991
2992   // Whether we will only visit constructors.
2993   bool ConstructorsOnly = false;
2994
2995   // If the type we are conversion to is a class type, enumerate its
2996   // constructors.
2997   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2998     // C++ [over.match.ctor]p1:
2999     //   When objects of class type are direct-initialized (8.5), or
3000     //   copy-initialized from an expression of the same or a
3001     //   derived class type (8.5), overload resolution selects the
3002     //   constructor. [...] For copy-initialization, the candidate
3003     //   functions are all the converting constructors (12.3.1) of
3004     //   that class. The argument list is the expression-list within
3005     //   the parentheses of the initializer.
3006     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3007         (From->getType()->getAs<RecordType>() &&
3008          S.IsDerivedFrom(From->getType(), ToType)))
3009       ConstructorsOnly = true;
3010
3011     S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3012     // RequireCompleteType may have returned true due to some invalid decl
3013     // during template instantiation, but ToType may be complete enough now
3014     // to try to recover.
3015     if (ToType->isIncompleteType()) {
3016       // We're not going to find any constructors.
3017     } else if (CXXRecordDecl *ToRecordDecl
3018                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3019
3020       Expr **Args = &From;
3021       unsigned NumArgs = 1;
3022       bool ListInitializing = false;
3023       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3024         // But first, see if there is an init-list-constructor that will work.
3025         OverloadingResult Result = IsInitializerListConstructorConversion(
3026             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3027         if (Result != OR_No_Viable_Function)
3028           return Result;
3029         // Never mind.
3030         CandidateSet.clear();
3031
3032         // If we're list-initializing, we pass the individual elements as
3033         // arguments, not the entire list.
3034         Args = InitList->getInits();
3035         NumArgs = InitList->getNumInits();
3036         ListInitializing = true;
3037       }
3038
3039       DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3040       for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3041            Con != ConEnd; ++Con) {
3042         NamedDecl *D = *Con;
3043         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3044
3045         // Find the constructor (which may be a template).
3046         CXXConstructorDecl *Constructor = nullptr;
3047         FunctionTemplateDecl *ConstructorTmpl
3048           = dyn_cast<FunctionTemplateDecl>(D);
3049         if (ConstructorTmpl)
3050           Constructor
3051             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3052         else
3053           Constructor = cast<CXXConstructorDecl>(D);
3054
3055         bool Usable = !Constructor->isInvalidDecl();
3056         if (ListInitializing)
3057           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3058         else
3059           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3060         if (Usable) {
3061           bool SuppressUserConversions = !ConstructorsOnly;
3062           if (SuppressUserConversions && ListInitializing) {
3063             SuppressUserConversions = false;
3064             if (NumArgs == 1) {
3065               // If the first argument is (a reference to) the target type,
3066               // suppress conversions.
3067               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3068                                                 S.Context, Constructor, ToType);
3069             }
3070           }
3071           if (ConstructorTmpl)
3072             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3073                                            /*ExplicitArgs*/ nullptr,
3074                                            llvm::makeArrayRef(Args, NumArgs),
3075                                            CandidateSet, SuppressUserConversions);
3076           else
3077             // Allow one user-defined conversion when user specifies a
3078             // From->ToType conversion via an static cast (c-style, etc).
3079             S.AddOverloadCandidate(Constructor, FoundDecl,
3080                                    llvm::makeArrayRef(Args, NumArgs),
3081                                    CandidateSet, SuppressUserConversions);
3082         }
3083       }
3084     }
3085   }
3086
3087   // Enumerate conversion functions, if we're allowed to.
3088   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3089   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3090     // No conversion functions from incomplete types.
3091   } else if (const RecordType *FromRecordType
3092                                    = From->getType()->getAs<RecordType>()) {
3093     if (CXXRecordDecl *FromRecordDecl
3094          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3095       // Add all of the conversion functions as candidates.
3096       std::pair<CXXRecordDecl::conversion_iterator,
3097                 CXXRecordDecl::conversion_iterator>
3098         Conversions = FromRecordDecl->getVisibleConversionFunctions();
3099       for (CXXRecordDecl::conversion_iterator
3100              I = Conversions.first, E = Conversions.second; I != E; ++I) {
3101         DeclAccessPair FoundDecl = I.getPair();
3102         NamedDecl *D = FoundDecl.getDecl();
3103         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3104         if (isa<UsingShadowDecl>(D))
3105           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3106
3107         CXXConversionDecl *Conv;
3108         FunctionTemplateDecl *ConvTemplate;
3109         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3110           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3111         else
3112           Conv = cast<CXXConversionDecl>(D);
3113
3114         if (AllowExplicit || !Conv->isExplicit()) {
3115           if (ConvTemplate)
3116             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3117                                              ActingContext, From, ToType,
3118                                              CandidateSet,
3119                                              AllowObjCConversionOnExplicit);
3120           else
3121             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3122                                      From, ToType, CandidateSet,
3123                                      AllowObjCConversionOnExplicit);
3124         }
3125       }
3126     }
3127   }
3128
3129   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3130
3131   OverloadCandidateSet::iterator Best;
3132   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3133   case OR_Success:
3134     // Record the standard conversion we used and the conversion function.
3135     if (CXXConstructorDecl *Constructor
3136           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3137       // C++ [over.ics.user]p1:
3138       //   If the user-defined conversion is specified by a
3139       //   constructor (12.3.1), the initial standard conversion
3140       //   sequence converts the source type to the type required by
3141       //   the argument of the constructor.
3142       //
3143       QualType ThisType = Constructor->getThisType(S.Context);
3144       if (isa<InitListExpr>(From)) {
3145         // Initializer lists don't have conversions as such.
3146         User.Before.setAsIdentityConversion();
3147       } else {
3148         if (Best->Conversions[0].isEllipsis())
3149           User.EllipsisConversion = true;
3150         else {
3151           User.Before = Best->Conversions[0].Standard;
3152           User.EllipsisConversion = false;
3153         }
3154       }
3155       User.HadMultipleCandidates = HadMultipleCandidates;
3156       User.ConversionFunction = Constructor;
3157       User.FoundConversionFunction = Best->FoundDecl;
3158       User.After.setAsIdentityConversion();
3159       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3160       User.After.setAllToTypes(ToType);
3161       return OR_Success;
3162     }
3163     if (CXXConversionDecl *Conversion
3164                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3165       // C++ [over.ics.user]p1:
3166       //
3167       //   [...] If the user-defined conversion is specified by a
3168       //   conversion function (12.3.2), the initial standard
3169       //   conversion sequence converts the source type to the
3170       //   implicit object parameter of the conversion function.
3171       User.Before = Best->Conversions[0].Standard;
3172       User.HadMultipleCandidates = HadMultipleCandidates;
3173       User.ConversionFunction = Conversion;
3174       User.FoundConversionFunction = Best->FoundDecl;
3175       User.EllipsisConversion = false;
3176
3177       // C++ [over.ics.user]p2:
3178       //   The second standard conversion sequence converts the
3179       //   result of the user-defined conversion to the target type
3180       //   for the sequence. Since an implicit conversion sequence
3181       //   is an initialization, the special rules for
3182       //   initialization by user-defined conversion apply when
3183       //   selecting the best user-defined conversion for a
3184       //   user-defined conversion sequence (see 13.3.3 and
3185       //   13.3.3.1).
3186       User.After = Best->FinalConversion;
3187       return OR_Success;
3188     }
3189     llvm_unreachable("Not a constructor or conversion function?");
3190
3191   case OR_No_Viable_Function:
3192     return OR_No_Viable_Function;
3193   case OR_Deleted:
3194     // No conversion here! We're done.
3195     return OR_Deleted;
3196
3197   case OR_Ambiguous:
3198     return OR_Ambiguous;
3199   }
3200
3201   llvm_unreachable("Invalid OverloadResult!");
3202 }
3203
3204 bool
3205 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3206   ImplicitConversionSequence ICS;
3207   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3208                                     OverloadCandidateSet::CSK_Normal);
3209   OverloadingResult OvResult =
3210     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3211                             CandidateSet, false, false);
3212   if (OvResult == OR_Ambiguous)
3213     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3214         << From->getType() << ToType << From->getSourceRange();
3215   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3216     if (!RequireCompleteType(From->getLocStart(), ToType,
3217                              diag::err_typecheck_nonviable_condition_incomplete,
3218                              From->getType(), From->getSourceRange()))
3219       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3220           << From->getType() << From->getSourceRange() << ToType;
3221   } else
3222     return false;
3223   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3224   return true;
3225 }
3226
3227 /// \brief Compare the user-defined conversion functions or constructors
3228 /// of two user-defined conversion sequences to determine whether any ordering
3229 /// is possible.
3230 static ImplicitConversionSequence::CompareKind
3231 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3232                            FunctionDecl *Function2) {
3233   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3234     return ImplicitConversionSequence::Indistinguishable;
3235
3236   // Objective-C++:
3237   //   If both conversion functions are implicitly-declared conversions from
3238   //   a lambda closure type to a function pointer and a block pointer,
3239   //   respectively, always prefer the conversion to a function pointer,
3240   //   because the function pointer is more lightweight and is more likely
3241   //   to keep code working.
3242   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3243   if (!Conv1)
3244     return ImplicitConversionSequence::Indistinguishable;
3245
3246   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3247   if (!Conv2)
3248     return ImplicitConversionSequence::Indistinguishable;
3249
3250   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3251     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3252     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3253     if (Block1 != Block2)
3254       return Block1 ? ImplicitConversionSequence::Worse
3255                     : ImplicitConversionSequence::Better;
3256   }
3257
3258   return ImplicitConversionSequence::Indistinguishable;
3259 }
3260
3261 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3262     const ImplicitConversionSequence &ICS) {
3263   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3264          (ICS.isUserDefined() &&
3265           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3266 }
3267
3268 /// CompareImplicitConversionSequences - Compare two implicit
3269 /// conversion sequences to determine whether one is better than the
3270 /// other or if they are indistinguishable (C++ 13.3.3.2).
3271 static ImplicitConversionSequence::CompareKind
3272 CompareImplicitConversionSequences(Sema &S,
3273                                    const ImplicitConversionSequence& ICS1,
3274                                    const ImplicitConversionSequence& ICS2)
3275 {
3276   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3277   // conversion sequences (as defined in 13.3.3.1)
3278   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3279   //      conversion sequence than a user-defined conversion sequence or
3280   //      an ellipsis conversion sequence, and
3281   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3282   //      conversion sequence than an ellipsis conversion sequence
3283   //      (13.3.3.1.3).
3284   //
3285   // C++0x [over.best.ics]p10:
3286   //   For the purpose of ranking implicit conversion sequences as
3287   //   described in 13.3.3.2, the ambiguous conversion sequence is
3288   //   treated as a user-defined sequence that is indistinguishable
3289   //   from any other user-defined conversion sequence.
3290
3291   // String literal to 'char *' conversion has been deprecated in C++03. It has
3292   // been removed from C++11. We still accept this conversion, if it happens at
3293   // the best viable function. Otherwise, this conversion is considered worse
3294   // than ellipsis conversion. Consider this as an extension; this is not in the
3295   // standard. For example:
3296   //
3297   // int &f(...);    // #1
3298   // void f(char*);  // #2
3299   // void g() { int &r = f("foo"); }
3300   //
3301   // In C++03, we pick #2 as the best viable function.
3302   // In C++11, we pick #1 as the best viable function, because ellipsis
3303   // conversion is better than string-literal to char* conversion (since there
3304   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3305   // convert arguments, #2 would be the best viable function in C++11.
3306   // If the best viable function has this conversion, a warning will be issued
3307   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3308
3309   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3310       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3311       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3312     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3313                ? ImplicitConversionSequence::Worse
3314                : ImplicitConversionSequence::Better;
3315
3316   if (ICS1.getKindRank() < ICS2.getKindRank())
3317     return ImplicitConversionSequence::Better;
3318   if (ICS2.getKindRank() < ICS1.getKindRank())
3319     return ImplicitConversionSequence::Worse;
3320
3321   // The following checks require both conversion sequences to be of
3322   // the same kind.
3323   if (ICS1.getKind() != ICS2.getKind())
3324     return ImplicitConversionSequence::Indistinguishable;
3325
3326   ImplicitConversionSequence::CompareKind Result =
3327       ImplicitConversionSequence::Indistinguishable;
3328
3329   // Two implicit conversion sequences of the same form are
3330   // indistinguishable conversion sequences unless one of the
3331   // following rules apply: (C++ 13.3.3.2p3):
3332   if (ICS1.isStandard())
3333     Result = CompareStandardConversionSequences(S,
3334                                                 ICS1.Standard, ICS2.Standard);
3335   else if (ICS1.isUserDefined()) {
3336     // User-defined conversion sequence U1 is a better conversion
3337     // sequence than another user-defined conversion sequence U2 if
3338     // they contain the same user-defined conversion function or
3339     // constructor and if the second standard conversion sequence of
3340     // U1 is better than the second standard conversion sequence of
3341     // U2 (C++ 13.3.3.2p3).
3342     if (ICS1.UserDefined.ConversionFunction ==
3343           ICS2.UserDefined.ConversionFunction)
3344       Result = CompareStandardConversionSequences(S,
3345                                                   ICS1.UserDefined.After,
3346                                                   ICS2.UserDefined.After);
3347     else
3348       Result = compareConversionFunctions(S, 
3349                                           ICS1.UserDefined.ConversionFunction,
3350                                           ICS2.UserDefined.ConversionFunction);
3351   }
3352
3353   // List-initialization sequence L1 is a better conversion sequence than
3354   // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3355   // for some X and L2 does not.
3356   if (Result == ImplicitConversionSequence::Indistinguishable &&
3357       !ICS1.isBad()) {
3358     if (ICS1.isStdInitializerListElement() &&
3359         !ICS2.isStdInitializerListElement())
3360       return ImplicitConversionSequence::Better;
3361     if (!ICS1.isStdInitializerListElement() &&
3362         ICS2.isStdInitializerListElement())
3363       return ImplicitConversionSequence::Worse;
3364   }
3365
3366   return Result;
3367 }
3368
3369 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3370   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3371     Qualifiers Quals;
3372     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3373     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3374   }
3375
3376   return Context.hasSameUnqualifiedType(T1, T2);
3377 }
3378
3379 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3380 // determine if one is a proper subset of the other.
3381 static ImplicitConversionSequence::CompareKind
3382 compareStandardConversionSubsets(ASTContext &Context,
3383                                  const StandardConversionSequence& SCS1,
3384                                  const StandardConversionSequence& SCS2) {
3385   ImplicitConversionSequence::CompareKind Result
3386     = ImplicitConversionSequence::Indistinguishable;
3387
3388   // the identity conversion sequence is considered to be a subsequence of
3389   // any non-identity conversion sequence
3390   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3391     return ImplicitConversionSequence::Better;
3392   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3393     return ImplicitConversionSequence::Worse;
3394
3395   if (SCS1.Second != SCS2.Second) {
3396     if (SCS1.Second == ICK_Identity)
3397       Result = ImplicitConversionSequence::Better;
3398     else if (SCS2.Second == ICK_Identity)
3399       Result = ImplicitConversionSequence::Worse;
3400     else
3401       return ImplicitConversionSequence::Indistinguishable;
3402   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3403     return ImplicitConversionSequence::Indistinguishable;
3404
3405   if (SCS1.Third == SCS2.Third) {
3406     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3407                              : ImplicitConversionSequence::Indistinguishable;
3408   }
3409
3410   if (SCS1.Third == ICK_Identity)
3411     return Result == ImplicitConversionSequence::Worse
3412              ? ImplicitConversionSequence::Indistinguishable
3413              : ImplicitConversionSequence::Better;
3414
3415   if (SCS2.Third == ICK_Identity)
3416     return Result == ImplicitConversionSequence::Better
3417              ? ImplicitConversionSequence::Indistinguishable
3418              : ImplicitConversionSequence::Worse;
3419
3420   return ImplicitConversionSequence::Indistinguishable;
3421 }
3422
3423 /// \brief Determine whether one of the given reference bindings is better
3424 /// than the other based on what kind of bindings they are.
3425 static bool
3426 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3427                              const StandardConversionSequence &SCS2) {
3428   // C++0x [over.ics.rank]p3b4:
3429   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3430   //      implicit object parameter of a non-static member function declared
3431   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3432   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3433   //      lvalue reference to a function lvalue and S2 binds an rvalue
3434   //      reference*.
3435   //
3436   // FIXME: Rvalue references. We're going rogue with the above edits,
3437   // because the semantics in the current C++0x working paper (N3225 at the
3438   // time of this writing) break the standard definition of std::forward
3439   // and std::reference_wrapper when dealing with references to functions.
3440   // Proposed wording changes submitted to CWG for consideration.
3441   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3442       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3443     return false;
3444
3445   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3446           SCS2.IsLvalueReference) ||
3447          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3448           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3449 }
3450
3451 /// CompareStandardConversionSequences - Compare two standard
3452 /// conversion sequences to determine whether one is better than the
3453 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3454 static ImplicitConversionSequence::CompareKind
3455 CompareStandardConversionSequences(Sema &S,
3456                                    const StandardConversionSequence& SCS1,
3457                                    const StandardConversionSequence& SCS2)
3458 {
3459   // Standard conversion sequence S1 is a better conversion sequence
3460   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3461
3462   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3463   //     sequences in the canonical form defined by 13.3.3.1.1,
3464   //     excluding any Lvalue Transformation; the identity conversion
3465   //     sequence is considered to be a subsequence of any
3466   //     non-identity conversion sequence) or, if not that,
3467   if (ImplicitConversionSequence::CompareKind CK
3468         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3469     return CK;
3470
3471   //  -- the rank of S1 is better than the rank of S2 (by the rules
3472   //     defined below), or, if not that,
3473   ImplicitConversionRank Rank1 = SCS1.getRank();
3474   ImplicitConversionRank Rank2 = SCS2.getRank();
3475   if (Rank1 < Rank2)
3476     return ImplicitConversionSequence::Better;
3477   else if (Rank2 < Rank1)
3478     return ImplicitConversionSequence::Worse;
3479
3480   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3481   // are indistinguishable unless one of the following rules
3482   // applies:
3483
3484   //   A conversion that is not a conversion of a pointer, or
3485   //   pointer to member, to bool is better than another conversion
3486   //   that is such a conversion.
3487   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3488     return SCS2.isPointerConversionToBool()
3489              ? ImplicitConversionSequence::Better
3490              : ImplicitConversionSequence::Worse;
3491
3492   // C++ [over.ics.rank]p4b2:
3493   //
3494   //   If class B is derived directly or indirectly from class A,
3495   //   conversion of B* to A* is better than conversion of B* to
3496   //   void*, and conversion of A* to void* is better than conversion
3497   //   of B* to void*.
3498   bool SCS1ConvertsToVoid
3499     = SCS1.isPointerConversionToVoidPointer(S.Context);
3500   bool SCS2ConvertsToVoid
3501     = SCS2.isPointerConversionToVoidPointer(S.Context);
3502   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3503     // Exactly one of the conversion sequences is a conversion to
3504     // a void pointer; it's the worse conversion.
3505     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3506                               : ImplicitConversionSequence::Worse;
3507   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3508     // Neither conversion sequence converts to a void pointer; compare
3509     // their derived-to-base conversions.
3510     if (ImplicitConversionSequence::CompareKind DerivedCK
3511           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3512       return DerivedCK;
3513   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3514              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3515     // Both conversion sequences are conversions to void
3516     // pointers. Compare the source types to determine if there's an
3517     // inheritance relationship in their sources.
3518     QualType FromType1 = SCS1.getFromType();
3519     QualType FromType2 = SCS2.getFromType();
3520
3521     // Adjust the types we're converting from via the array-to-pointer
3522     // conversion, if we need to.
3523     if (SCS1.First == ICK_Array_To_Pointer)
3524       FromType1 = S.Context.getArrayDecayedType(FromType1);
3525     if (SCS2.First == ICK_Array_To_Pointer)
3526       FromType2 = S.Context.getArrayDecayedType(FromType2);
3527
3528     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3529     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3530
3531     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3532       return ImplicitConversionSequence::Better;
3533     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3534       return ImplicitConversionSequence::Worse;
3535
3536     // Objective-C++: If one interface is more specific than the
3537     // other, it is the better one.
3538     const ObjCObjectPointerType* FromObjCPtr1
3539       = FromType1->getAs<ObjCObjectPointerType>();
3540     const ObjCObjectPointerType* FromObjCPtr2
3541       = FromType2->getAs<ObjCObjectPointerType>();
3542     if (FromObjCPtr1 && FromObjCPtr2) {
3543       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 
3544                                                           FromObjCPtr2);
3545       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 
3546                                                            FromObjCPtr1);
3547       if (AssignLeft != AssignRight) {
3548         return AssignLeft? ImplicitConversionSequence::Better
3549                          : ImplicitConversionSequence::Worse;
3550       }
3551     }
3552   }
3553
3554   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3555   // bullet 3).
3556   if (ImplicitConversionSequence::CompareKind QualCK
3557         = CompareQualificationConversions(S, SCS1, SCS2))
3558     return QualCK;
3559
3560   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3561     // Check for a better reference binding based on the kind of bindings.
3562     if (isBetterReferenceBindingKind(SCS1, SCS2))
3563       return ImplicitConversionSequence::Better;
3564     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3565       return ImplicitConversionSequence::Worse;
3566
3567     // C++ [over.ics.rank]p3b4:
3568     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3569     //      which the references refer are the same type except for
3570     //      top-level cv-qualifiers, and the type to which the reference
3571     //      initialized by S2 refers is more cv-qualified than the type
3572     //      to which the reference initialized by S1 refers.
3573     QualType T1 = SCS1.getToType(2);
3574     QualType T2 = SCS2.getToType(2);
3575     T1 = S.Context.getCanonicalType(T1);
3576     T2 = S.Context.getCanonicalType(T2);
3577     Qualifiers T1Quals, T2Quals;
3578     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3579     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3580     if (UnqualT1 == UnqualT2) {
3581       // Objective-C++ ARC: If the references refer to objects with different
3582       // lifetimes, prefer bindings that don't change lifetime.
3583       if (SCS1.ObjCLifetimeConversionBinding != 
3584                                           SCS2.ObjCLifetimeConversionBinding) {
3585         return SCS1.ObjCLifetimeConversionBinding
3586                                            ? ImplicitConversionSequence::Worse
3587                                            : ImplicitConversionSequence::Better;
3588       }
3589       
3590       // If the type is an array type, promote the element qualifiers to the
3591       // type for comparison.
3592       if (isa<ArrayType>(T1) && T1Quals)
3593         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3594       if (isa<ArrayType>(T2) && T2Quals)
3595         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3596       if (T2.isMoreQualifiedThan(T1))
3597         return ImplicitConversionSequence::Better;
3598       else if (T1.isMoreQualifiedThan(T2))
3599         return ImplicitConversionSequence::Worse;      
3600     }
3601   }
3602
3603   // In Microsoft mode, prefer an integral conversion to a
3604   // floating-to-integral conversion if the integral conversion
3605   // is between types of the same size.
3606   // For example:
3607   // void f(float);
3608   // void f(int);
3609   // int main {
3610   //    long a;
3611   //    f(a);
3612   // }
3613   // Here, MSVC will call f(int) instead of generating a compile error
3614   // as clang will do in standard mode.
3615   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3616       SCS2.Second == ICK_Floating_Integral &&
3617       S.Context.getTypeSize(SCS1.getFromType()) ==
3618           S.Context.getTypeSize(SCS1.getToType(2)))
3619     return ImplicitConversionSequence::Better;
3620
3621   return ImplicitConversionSequence::Indistinguishable;
3622 }
3623
3624 /// CompareQualificationConversions - Compares two standard conversion
3625 /// sequences to determine whether they can be ranked based on their
3626 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3627 static ImplicitConversionSequence::CompareKind
3628 CompareQualificationConversions(Sema &S,
3629                                 const StandardConversionSequence& SCS1,
3630                                 const StandardConversionSequence& SCS2) {
3631   // C++ 13.3.3.2p3:
3632   //  -- S1 and S2 differ only in their qualification conversion and
3633   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3634   //     cv-qualification signature of type T1 is a proper subset of
3635   //     the cv-qualification signature of type T2, and S1 is not the
3636   //     deprecated string literal array-to-pointer conversion (4.2).
3637   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3638       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3639     return ImplicitConversionSequence::Indistinguishable;
3640
3641   // FIXME: the example in the standard doesn't use a qualification
3642   // conversion (!)
3643   QualType T1 = SCS1.getToType(2);
3644   QualType T2 = SCS2.getToType(2);
3645   T1 = S.Context.getCanonicalType(T1);
3646   T2 = S.Context.getCanonicalType(T2);
3647   Qualifiers T1Quals, T2Quals;
3648   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3649   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3650
3651   // If the types are the same, we won't learn anything by unwrapped
3652   // them.
3653   if (UnqualT1 == UnqualT2)
3654     return ImplicitConversionSequence::Indistinguishable;
3655
3656   // If the type is an array type, promote the element qualifiers to the type
3657   // for comparison.
3658   if (isa<ArrayType>(T1) && T1Quals)
3659     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3660   if (isa<ArrayType>(T2) && T2Quals)
3661     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3662
3663   ImplicitConversionSequence::CompareKind Result
3664     = ImplicitConversionSequence::Indistinguishable;
3665   
3666   // Objective-C++ ARC:
3667   //   Prefer qualification conversions not involving a change in lifetime
3668   //   to qualification conversions that do not change lifetime.
3669   if (SCS1.QualificationIncludesObjCLifetime != 
3670                                       SCS2.QualificationIncludesObjCLifetime) {
3671     Result = SCS1.QualificationIncludesObjCLifetime
3672                ? ImplicitConversionSequence::Worse
3673                : ImplicitConversionSequence::Better;
3674   }
3675   
3676   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3677     // Within each iteration of the loop, we check the qualifiers to
3678     // determine if this still looks like a qualification
3679     // conversion. Then, if all is well, we unwrap one more level of
3680     // pointers or pointers-to-members and do it all again
3681     // until there are no more pointers or pointers-to-members left
3682     // to unwrap. This essentially mimics what
3683     // IsQualificationConversion does, but here we're checking for a
3684     // strict subset of qualifiers.
3685     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3686       // The qualifiers are the same, so this doesn't tell us anything
3687       // about how the sequences rank.
3688       ;
3689     else if (T2.isMoreQualifiedThan(T1)) {
3690       // T1 has fewer qualifiers, so it could be the better sequence.
3691       if (Result == ImplicitConversionSequence::Worse)
3692         // Neither has qualifiers that are a subset of the other's
3693         // qualifiers.
3694         return ImplicitConversionSequence::Indistinguishable;
3695
3696       Result = ImplicitConversionSequence::Better;
3697     } else if (T1.isMoreQualifiedThan(T2)) {
3698       // T2 has fewer qualifiers, so it could be the better sequence.
3699       if (Result == ImplicitConversionSequence::Better)
3700         // Neither has qualifiers that are a subset of the other's
3701         // qualifiers.
3702         return ImplicitConversionSequence::Indistinguishable;
3703
3704       Result = ImplicitConversionSequence::Worse;
3705     } else {
3706       // Qualifiers are disjoint.
3707       return ImplicitConversionSequence::Indistinguishable;
3708     }
3709
3710     // If the types after this point are equivalent, we're done.
3711     if (S.Context.hasSameUnqualifiedType(T1, T2))
3712       break;
3713   }
3714
3715   // Check that the winning standard conversion sequence isn't using
3716   // the deprecated string literal array to pointer conversion.
3717   switch (Result) {
3718   case ImplicitConversionSequence::Better:
3719     if (SCS1.DeprecatedStringLiteralToCharPtr)
3720       Result = ImplicitConversionSequence::Indistinguishable;
3721     break;
3722
3723   case ImplicitConversionSequence::Indistinguishable:
3724     break;
3725
3726   case ImplicitConversionSequence::Worse:
3727     if (SCS2.DeprecatedStringLiteralToCharPtr)
3728       Result = ImplicitConversionSequence::Indistinguishable;
3729     break;
3730   }
3731
3732   return Result;
3733 }
3734
3735 /// CompareDerivedToBaseConversions - Compares two standard conversion
3736 /// sequences to determine whether they can be ranked based on their
3737 /// various kinds of derived-to-base conversions (C++
3738 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3739 /// conversions between Objective-C interface types.
3740 static ImplicitConversionSequence::CompareKind
3741 CompareDerivedToBaseConversions(Sema &S,
3742                                 const StandardConversionSequence& SCS1,
3743                                 const StandardConversionSequence& SCS2) {
3744   QualType FromType1 = SCS1.getFromType();
3745   QualType ToType1 = SCS1.getToType(1);
3746   QualType FromType2 = SCS2.getFromType();
3747   QualType ToType2 = SCS2.getToType(1);
3748
3749   // Adjust the types we're converting from via the array-to-pointer
3750   // conversion, if we need to.
3751   if (SCS1.First == ICK_Array_To_Pointer)
3752     FromType1 = S.Context.getArrayDecayedType(FromType1);
3753   if (SCS2.First == ICK_Array_To_Pointer)
3754     FromType2 = S.Context.getArrayDecayedType(FromType2);
3755
3756   // Canonicalize all of the types.
3757   FromType1 = S.Context.getCanonicalType(FromType1);
3758   ToType1 = S.Context.getCanonicalType(ToType1);
3759   FromType2 = S.Context.getCanonicalType(FromType2);
3760   ToType2 = S.Context.getCanonicalType(ToType2);
3761
3762   // C++ [over.ics.rank]p4b3:
3763   //
3764   //   If class B is derived directly or indirectly from class A and
3765   //   class C is derived directly or indirectly from B,
3766   //
3767   // Compare based on pointer conversions.
3768   if (SCS1.Second == ICK_Pointer_Conversion &&
3769       SCS2.Second == ICK_Pointer_Conversion &&
3770       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3771       FromType1->isPointerType() && FromType2->isPointerType() &&
3772       ToType1->isPointerType() && ToType2->isPointerType()) {
3773     QualType FromPointee1
3774       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3775     QualType ToPointee1
3776       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3777     QualType FromPointee2
3778       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3779     QualType ToPointee2
3780       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3781
3782     //   -- conversion of C* to B* is better than conversion of C* to A*,
3783     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3784       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3785         return ImplicitConversionSequence::Better;
3786       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3787         return ImplicitConversionSequence::Worse;
3788     }
3789
3790     //   -- conversion of B* to A* is better than conversion of C* to A*,
3791     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3792       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3793         return ImplicitConversionSequence::Better;
3794       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3795         return ImplicitConversionSequence::Worse;
3796     }
3797   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3798              SCS2.Second == ICK_Pointer_Conversion) {
3799     const ObjCObjectPointerType *FromPtr1
3800       = FromType1->getAs<ObjCObjectPointerType>();
3801     const ObjCObjectPointerType *FromPtr2
3802       = FromType2->getAs<ObjCObjectPointerType>();
3803     const ObjCObjectPointerType *ToPtr1
3804       = ToType1->getAs<ObjCObjectPointerType>();
3805     const ObjCObjectPointerType *ToPtr2
3806       = ToType2->getAs<ObjCObjectPointerType>();
3807     
3808     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3809       // Apply the same conversion ranking rules for Objective-C pointer types
3810       // that we do for C++ pointers to class types. However, we employ the
3811       // Objective-C pseudo-subtyping relationship used for assignment of
3812       // Objective-C pointer types.
3813       bool FromAssignLeft
3814         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3815       bool FromAssignRight
3816         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3817       bool ToAssignLeft
3818         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3819       bool ToAssignRight
3820         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3821       
3822       // A conversion to an a non-id object pointer type or qualified 'id' 
3823       // type is better than a conversion to 'id'.
3824       if (ToPtr1->isObjCIdType() &&
3825           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3826         return ImplicitConversionSequence::Worse;
3827       if (ToPtr2->isObjCIdType() &&
3828           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3829         return ImplicitConversionSequence::Better;
3830       
3831       // A conversion to a non-id object pointer type is better than a 
3832       // conversion to a qualified 'id' type 
3833       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3834         return ImplicitConversionSequence::Worse;
3835       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3836         return ImplicitConversionSequence::Better;
3837   
3838       // A conversion to an a non-Class object pointer type or qualified 'Class' 
3839       // type is better than a conversion to 'Class'.
3840       if (ToPtr1->isObjCClassType() &&
3841           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3842         return ImplicitConversionSequence::Worse;
3843       if (ToPtr2->isObjCClassType() &&
3844           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3845         return ImplicitConversionSequence::Better;
3846       
3847       // A conversion to a non-Class object pointer type is better than a 
3848       // conversion to a qualified 'Class' type.
3849       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3850         return ImplicitConversionSequence::Worse;
3851       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3852         return ImplicitConversionSequence::Better;
3853
3854       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3855       if (S.Context.hasSameType(FromType1, FromType2) && 
3856           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3857           (ToAssignLeft != ToAssignRight))
3858         return ToAssignLeft? ImplicitConversionSequence::Worse
3859                            : ImplicitConversionSequence::Better;
3860
3861       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3862       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3863           (FromAssignLeft != FromAssignRight))
3864         return FromAssignLeft? ImplicitConversionSequence::Better
3865         : ImplicitConversionSequence::Worse;
3866     }
3867   }
3868   
3869   // Ranking of member-pointer types.
3870   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3871       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3872       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3873     const MemberPointerType * FromMemPointer1 =
3874                                         FromType1->getAs<MemberPointerType>();
3875     const MemberPointerType * ToMemPointer1 =
3876                                           ToType1->getAs<MemberPointerType>();
3877     const MemberPointerType * FromMemPointer2 =
3878                                           FromType2->getAs<MemberPointerType>();
3879     const MemberPointerType * ToMemPointer2 =
3880                                           ToType2->getAs<MemberPointerType>();
3881     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3882     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3883     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3884     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3885     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3886     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3887     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3888     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3889     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3890     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3891       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3892         return ImplicitConversionSequence::Worse;
3893       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3894         return ImplicitConversionSequence::Better;
3895     }
3896     // conversion of B::* to C::* is better than conversion of A::* to C::*
3897     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3898       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3899         return ImplicitConversionSequence::Better;
3900       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3901         return ImplicitConversionSequence::Worse;
3902     }
3903   }
3904
3905   if (SCS1.Second == ICK_Derived_To_Base) {
3906     //   -- conversion of C to B is better than conversion of C to A,
3907     //   -- binding of an expression of type C to a reference of type
3908     //      B& is better than binding an expression of type C to a
3909     //      reference of type A&,
3910     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3911         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3912       if (S.IsDerivedFrom(ToType1, ToType2))
3913         return ImplicitConversionSequence::Better;
3914       else if (S.IsDerivedFrom(ToType2, ToType1))
3915         return ImplicitConversionSequence::Worse;
3916     }
3917
3918     //   -- conversion of B to A is better than conversion of C to A.
3919     //   -- binding of an expression of type B to a reference of type
3920     //      A& is better than binding an expression of type C to a
3921     //      reference of type A&,
3922     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3923         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3924       if (S.IsDerivedFrom(FromType2, FromType1))
3925         return ImplicitConversionSequence::Better;
3926       else if (S.IsDerivedFrom(FromType1, FromType2))
3927         return ImplicitConversionSequence::Worse;
3928     }
3929   }
3930
3931   return ImplicitConversionSequence::Indistinguishable;
3932 }
3933
3934 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
3935 /// C++ class.
3936 static bool isTypeValid(QualType T) {
3937   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3938     return !Record->isInvalidDecl();
3939
3940   return true;
3941 }
3942
3943 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3944 /// determine whether they are reference-related,
3945 /// reference-compatible, reference-compatible with added
3946 /// qualification, or incompatible, for use in C++ initialization by
3947 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3948 /// type, and the first type (T1) is the pointee type of the reference
3949 /// type being initialized.
3950 Sema::ReferenceCompareResult
3951 Sema::CompareReferenceRelationship(SourceLocation Loc,
3952                                    QualType OrigT1, QualType OrigT2,
3953                                    bool &DerivedToBase,
3954                                    bool &ObjCConversion,
3955                                    bool &ObjCLifetimeConversion) {
3956   assert(!OrigT1->isReferenceType() &&
3957     "T1 must be the pointee type of the reference type");
3958   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3959
3960   QualType T1 = Context.getCanonicalType(OrigT1);
3961   QualType T2 = Context.getCanonicalType(OrigT2);
3962   Qualifiers T1Quals, T2Quals;
3963   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3964   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3965
3966   // C++ [dcl.init.ref]p4:
3967   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3968   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3969   //   T1 is a base class of T2.
3970   DerivedToBase = false;
3971   ObjCConversion = false;
3972   ObjCLifetimeConversion = false;
3973   if (UnqualT1 == UnqualT2) {
3974     // Nothing to do.
3975   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3976              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3977              IsDerivedFrom(UnqualT2, UnqualT1))
3978     DerivedToBase = true;
3979   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3980            UnqualT2->isObjCObjectOrInterfaceType() &&
3981            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3982     ObjCConversion = true;
3983   else
3984     return Ref_Incompatible;
3985
3986   // At this point, we know that T1 and T2 are reference-related (at
3987   // least).
3988
3989   // If the type is an array type, promote the element qualifiers to the type
3990   // for comparison.
3991   if (isa<ArrayType>(T1) && T1Quals)
3992     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3993   if (isa<ArrayType>(T2) && T2Quals)
3994     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3995
3996   // C++ [dcl.init.ref]p4:
3997   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3998   //   reference-related to T2 and cv1 is the same cv-qualification
3999   //   as, or greater cv-qualification than, cv2. For purposes of
4000   //   overload resolution, cases for which cv1 is greater
4001   //   cv-qualification than cv2 are identified as
4002   //   reference-compatible with added qualification (see 13.3.3.2).
4003   //
4004   // Note that we also require equivalence of Objective-C GC and address-space
4005   // qualifiers when performing these computations, so that e.g., an int in
4006   // address space 1 is not reference-compatible with an int in address
4007   // space 2.
4008   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4009       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4010     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4011       ObjCLifetimeConversion = true;
4012
4013     T1Quals.removeObjCLifetime();
4014     T2Quals.removeObjCLifetime();    
4015   }
4016     
4017   if (T1Quals == T2Quals)
4018     return Ref_Compatible;
4019   else if (T1Quals.compatiblyIncludes(T2Quals))
4020     return Ref_Compatible_With_Added_Qualification;
4021   else
4022     return Ref_Related;
4023 }
4024
4025 /// \brief Look for a user-defined conversion to an value reference-compatible
4026 ///        with DeclType. Return true if something definite is found.
4027 static bool
4028 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4029                          QualType DeclType, SourceLocation DeclLoc,
4030                          Expr *Init, QualType T2, bool AllowRvalues,
4031                          bool AllowExplicit) {
4032   assert(T2->isRecordType() && "Can only find conversions of record types.");
4033   CXXRecordDecl *T2RecordDecl
4034     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4035
4036   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4037   std::pair<CXXRecordDecl::conversion_iterator,
4038             CXXRecordDecl::conversion_iterator>
4039     Conversions = T2RecordDecl->getVisibleConversionFunctions();
4040   for (CXXRecordDecl::conversion_iterator
4041          I = Conversions.first, E = Conversions.second; I != E; ++I) {
4042     NamedDecl *D = *I;
4043     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4044     if (isa<UsingShadowDecl>(D))
4045       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4046
4047     FunctionTemplateDecl *ConvTemplate
4048       = dyn_cast<FunctionTemplateDecl>(D);
4049     CXXConversionDecl *Conv;
4050     if (ConvTemplate)
4051       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4052     else
4053       Conv = cast<CXXConversionDecl>(D);
4054
4055     // If this is an explicit conversion, and we're not allowed to consider
4056     // explicit conversions, skip it.
4057     if (!AllowExplicit && Conv->isExplicit())
4058       continue;
4059
4060     if (AllowRvalues) {
4061       bool DerivedToBase = false;
4062       bool ObjCConversion = false;
4063       bool ObjCLifetimeConversion = false;
4064       
4065       // If we are initializing an rvalue reference, don't permit conversion
4066       // functions that return lvalues.
4067       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4068         const ReferenceType *RefType
4069           = Conv->getConversionType()->getAs<LValueReferenceType>();
4070         if (RefType && !RefType->getPointeeType()->isFunctionType())
4071           continue;
4072       }
4073       
4074       if (!ConvTemplate &&
4075           S.CompareReferenceRelationship(
4076             DeclLoc,
4077             Conv->getConversionType().getNonReferenceType()
4078               .getUnqualifiedType(),
4079             DeclType.getNonReferenceType().getUnqualifiedType(),
4080             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4081           Sema::Ref_Incompatible)
4082         continue;
4083     } else {
4084       // If the conversion function doesn't return a reference type,
4085       // it can't be considered for this conversion. An rvalue reference
4086       // is only acceptable if its referencee is a function type.
4087
4088       const ReferenceType *RefType =
4089         Conv->getConversionType()->getAs<ReferenceType>();
4090       if (!RefType ||
4091           (!RefType->isLValueReferenceType() &&
4092            !RefType->getPointeeType()->isFunctionType()))
4093         continue;
4094     }
4095
4096     if (ConvTemplate)
4097       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4098                                        Init, DeclType, CandidateSet,
4099                                        /*AllowObjCConversionOnExplicit=*/false);
4100     else
4101       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4102                                DeclType, CandidateSet,
4103                                /*AllowObjCConversionOnExplicit=*/false);
4104   }
4105
4106   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4107
4108   OverloadCandidateSet::iterator Best;
4109   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4110   case OR_Success:
4111     // C++ [over.ics.ref]p1:
4112     //
4113     //   [...] If the parameter binds directly to the result of
4114     //   applying a conversion function to the argument
4115     //   expression, the implicit conversion sequence is a
4116     //   user-defined conversion sequence (13.3.3.1.2), with the
4117     //   second standard conversion sequence either an identity
4118     //   conversion or, if the conversion function returns an
4119     //   entity of a type that is a derived class of the parameter
4120     //   type, a derived-to-base Conversion.
4121     if (!Best->FinalConversion.DirectBinding)
4122       return false;
4123
4124     ICS.setUserDefined();
4125     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4126     ICS.UserDefined.After = Best->FinalConversion;
4127     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4128     ICS.UserDefined.ConversionFunction = Best->Function;
4129     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4130     ICS.UserDefined.EllipsisConversion = false;
4131     assert(ICS.UserDefined.After.ReferenceBinding &&
4132            ICS.UserDefined.After.DirectBinding &&
4133            "Expected a direct reference binding!");
4134     return true;
4135
4136   case OR_Ambiguous:
4137     ICS.setAmbiguous();
4138     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4139          Cand != CandidateSet.end(); ++Cand)
4140       if (Cand->Viable)
4141         ICS.Ambiguous.addConversion(Cand->Function);
4142     return true;
4143
4144   case OR_No_Viable_Function:
4145   case OR_Deleted:
4146     // There was no suitable conversion, or we found a deleted
4147     // conversion; continue with other checks.
4148     return false;
4149   }
4150
4151   llvm_unreachable("Invalid OverloadResult!");
4152 }
4153
4154 /// \brief Compute an implicit conversion sequence for reference
4155 /// initialization.
4156 static ImplicitConversionSequence
4157 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4158                  SourceLocation DeclLoc,
4159                  bool SuppressUserConversions,
4160                  bool AllowExplicit) {
4161   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4162
4163   // Most paths end in a failed conversion.
4164   ImplicitConversionSequence ICS;
4165   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4166
4167   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4168   QualType T2 = Init->getType();
4169
4170   // If the initializer is the address of an overloaded function, try
4171   // to resolve the overloaded function. If all goes well, T2 is the
4172   // type of the resulting function.
4173   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4174     DeclAccessPair Found;
4175     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4176                                                                 false, Found))
4177       T2 = Fn->getType();
4178   }
4179
4180   // Compute some basic properties of the types and the initializer.
4181   bool isRValRef = DeclType->isRValueReferenceType();
4182   bool DerivedToBase = false;
4183   bool ObjCConversion = false;
4184   bool ObjCLifetimeConversion = false;
4185   Expr::Classification InitCategory = Init->Classify(S.Context);
4186   Sema::ReferenceCompareResult RefRelationship
4187     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4188                                      ObjCConversion, ObjCLifetimeConversion);
4189
4190
4191   // C++0x [dcl.init.ref]p5:
4192   //   A reference to type "cv1 T1" is initialized by an expression
4193   //   of type "cv2 T2" as follows:
4194
4195   //     -- If reference is an lvalue reference and the initializer expression
4196   if (!isRValRef) {
4197     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4198     //        reference-compatible with "cv2 T2," or
4199     //
4200     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4201     if (InitCategory.isLValue() &&
4202         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4203       // C++ [over.ics.ref]p1:
4204       //   When a parameter of reference type binds directly (8.5.3)
4205       //   to an argument expression, the implicit conversion sequence
4206       //   is the identity conversion, unless the argument expression
4207       //   has a type that is a derived class of the parameter type,
4208       //   in which case the implicit conversion sequence is a
4209       //   derived-to-base Conversion (13.3.3.1).
4210       ICS.setStandard();
4211       ICS.Standard.First = ICK_Identity;
4212       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4213                          : ObjCConversion? ICK_Compatible_Conversion
4214                          : ICK_Identity;
4215       ICS.Standard.Third = ICK_Identity;
4216       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4217       ICS.Standard.setToType(0, T2);
4218       ICS.Standard.setToType(1, T1);
4219       ICS.Standard.setToType(2, T1);
4220       ICS.Standard.ReferenceBinding = true;
4221       ICS.Standard.DirectBinding = true;
4222       ICS.Standard.IsLvalueReference = !isRValRef;
4223       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4224       ICS.Standard.BindsToRvalue = false;
4225       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4226       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4227       ICS.Standard.CopyConstructor = nullptr;
4228       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4229
4230       // Nothing more to do: the inaccessibility/ambiguity check for
4231       // derived-to-base conversions is suppressed when we're
4232       // computing the implicit conversion sequence (C++
4233       // [over.best.ics]p2).
4234       return ICS;
4235     }
4236
4237     //       -- has a class type (i.e., T2 is a class type), where T1 is
4238     //          not reference-related to T2, and can be implicitly
4239     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4240     //          is reference-compatible with "cv3 T3" 92) (this
4241     //          conversion is selected by enumerating the applicable
4242     //          conversion functions (13.3.1.6) and choosing the best
4243     //          one through overload resolution (13.3)),
4244     if (!SuppressUserConversions && T2->isRecordType() &&
4245         !S.RequireCompleteType(DeclLoc, T2, 0) &&
4246         RefRelationship == Sema::Ref_Incompatible) {
4247       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4248                                    Init, T2, /*AllowRvalues=*/false,
4249                                    AllowExplicit))
4250         return ICS;
4251     }
4252   }
4253
4254   //     -- Otherwise, the reference shall be an lvalue reference to a
4255   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4256   //        shall be an rvalue reference.
4257   //
4258   // We actually handle one oddity of C++ [over.ics.ref] at this
4259   // point, which is that, due to p2 (which short-circuits reference
4260   // binding by only attempting a simple conversion for non-direct
4261   // bindings) and p3's strange wording, we allow a const volatile
4262   // reference to bind to an rvalue. Hence the check for the presence
4263   // of "const" rather than checking for "const" being the only
4264   // qualifier.
4265   // This is also the point where rvalue references and lvalue inits no longer
4266   // go together.
4267   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4268     return ICS;
4269
4270   //       -- If the initializer expression
4271   //
4272   //            -- is an xvalue, class prvalue, array prvalue or function
4273   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4274   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4275       (InitCategory.isXValue() ||
4276       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4277       (InitCategory.isLValue() && T2->isFunctionType()))) {
4278     ICS.setStandard();
4279     ICS.Standard.First = ICK_Identity;
4280     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4281                       : ObjCConversion? ICK_Compatible_Conversion
4282                       : ICK_Identity;
4283     ICS.Standard.Third = ICK_Identity;
4284     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4285     ICS.Standard.setToType(0, T2);
4286     ICS.Standard.setToType(1, T1);
4287     ICS.Standard.setToType(2, T1);
4288     ICS.Standard.ReferenceBinding = true;
4289     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4290     // binding unless we're binding to a class prvalue.
4291     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4292     // allow the use of rvalue references in C++98/03 for the benefit of
4293     // standard library implementors; therefore, we need the xvalue check here.
4294     ICS.Standard.DirectBinding =
4295       S.getLangOpts().CPlusPlus11 ||
4296       !(InitCategory.isPRValue() || T2->isRecordType());
4297     ICS.Standard.IsLvalueReference = !isRValRef;
4298     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4299     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4300     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4301     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4302     ICS.Standard.CopyConstructor = nullptr;
4303     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4304     return ICS;
4305   }
4306
4307   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4308   //               reference-related to T2, and can be implicitly converted to
4309   //               an xvalue, class prvalue, or function lvalue of type
4310   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4311   //               "cv3 T3",
4312   //
4313   //          then the reference is bound to the value of the initializer
4314   //          expression in the first case and to the result of the conversion
4315   //          in the second case (or, in either case, to an appropriate base
4316   //          class subobject).
4317   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4318       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4319       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4320                                Init, T2, /*AllowRvalues=*/true,
4321                                AllowExplicit)) {
4322     // In the second case, if the reference is an rvalue reference
4323     // and the second standard conversion sequence of the
4324     // user-defined conversion sequence includes an lvalue-to-rvalue
4325     // conversion, the program is ill-formed.
4326     if (ICS.isUserDefined() && isRValRef &&
4327         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4328       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4329
4330     return ICS;
4331   }
4332
4333   // A temporary of function type cannot be created; don't even try.
4334   if (T1->isFunctionType())
4335     return ICS;
4336
4337   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4338   //          initialized from the initializer expression using the
4339   //          rules for a non-reference copy initialization (8.5). The
4340   //          reference is then bound to the temporary. If T1 is
4341   //          reference-related to T2, cv1 must be the same
4342   //          cv-qualification as, or greater cv-qualification than,
4343   //          cv2; otherwise, the program is ill-formed.
4344   if (RefRelationship == Sema::Ref_Related) {
4345     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4346     // we would be reference-compatible or reference-compatible with
4347     // added qualification. But that wasn't the case, so the reference
4348     // initialization fails.
4349     //
4350     // Note that we only want to check address spaces and cvr-qualifiers here.
4351     // ObjC GC and lifetime qualifiers aren't important.
4352     Qualifiers T1Quals = T1.getQualifiers();
4353     Qualifiers T2Quals = T2.getQualifiers();
4354     T1Quals.removeObjCGCAttr();
4355     T1Quals.removeObjCLifetime();
4356     T2Quals.removeObjCGCAttr();
4357     T2Quals.removeObjCLifetime();
4358     if (!T1Quals.compatiblyIncludes(T2Quals))
4359       return ICS;
4360   }
4361
4362   // If at least one of the types is a class type, the types are not
4363   // related, and we aren't allowed any user conversions, the
4364   // reference binding fails. This case is important for breaking
4365   // recursion, since TryImplicitConversion below will attempt to
4366   // create a temporary through the use of a copy constructor.
4367   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4368       (T1->isRecordType() || T2->isRecordType()))
4369     return ICS;
4370
4371   // If T1 is reference-related to T2 and the reference is an rvalue
4372   // reference, the initializer expression shall not be an lvalue.
4373   if (RefRelationship >= Sema::Ref_Related &&
4374       isRValRef && Init->Classify(S.Context).isLValue())
4375     return ICS;
4376
4377   // C++ [over.ics.ref]p2:
4378   //   When a parameter of reference type is not bound directly to
4379   //   an argument expression, the conversion sequence is the one
4380   //   required to convert the argument expression to the
4381   //   underlying type of the reference according to
4382   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4383   //   to copy-initializing a temporary of the underlying type with
4384   //   the argument expression. Any difference in top-level
4385   //   cv-qualification is subsumed by the initialization itself
4386   //   and does not constitute a conversion.
4387   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4388                               /*AllowExplicit=*/false,
4389                               /*InOverloadResolution=*/false,
4390                               /*CStyle=*/false,
4391                               /*AllowObjCWritebackConversion=*/false,
4392                               /*AllowObjCConversionOnExplicit=*/false);
4393
4394   // Of course, that's still a reference binding.
4395   if (ICS.isStandard()) {
4396     ICS.Standard.ReferenceBinding = true;
4397     ICS.Standard.IsLvalueReference = !isRValRef;
4398     ICS.Standard.BindsToFunctionLvalue = false;
4399     ICS.Standard.BindsToRvalue = true;
4400     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4401     ICS.Standard.ObjCLifetimeConversionBinding = false;
4402   } else if (ICS.isUserDefined()) {
4403     const ReferenceType *LValRefType =
4404         ICS.UserDefined.ConversionFunction->getReturnType()
4405             ->getAs<LValueReferenceType>();
4406
4407     // C++ [over.ics.ref]p3:
4408     //   Except for an implicit object parameter, for which see 13.3.1, a
4409     //   standard conversion sequence cannot be formed if it requires [...]
4410     //   binding an rvalue reference to an lvalue other than a function
4411     //   lvalue.
4412     // Note that the function case is not possible here.
4413     if (DeclType->isRValueReferenceType() && LValRefType) {
4414       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4415       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4416       // reference to an rvalue!
4417       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4418       return ICS;
4419     }
4420
4421     ICS.UserDefined.Before.setAsIdentityConversion();
4422     ICS.UserDefined.After.ReferenceBinding = true;
4423     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4424     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4425     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4426     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4427     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4428   }
4429
4430   return ICS;
4431 }
4432
4433 static ImplicitConversionSequence
4434 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4435                       bool SuppressUserConversions,
4436                       bool InOverloadResolution,
4437                       bool AllowObjCWritebackConversion,
4438                       bool AllowExplicit = false);
4439
4440 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4441 /// initializer list From.
4442 static ImplicitConversionSequence
4443 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4444                   bool SuppressUserConversions,
4445                   bool InOverloadResolution,
4446                   bool AllowObjCWritebackConversion) {
4447   // C++11 [over.ics.list]p1:
4448   //   When an argument is an initializer list, it is not an expression and
4449   //   special rules apply for converting it to a parameter type.
4450
4451   ImplicitConversionSequence Result;
4452   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4453
4454   // We need a complete type for what follows. Incomplete types can never be
4455   // initialized from init lists.
4456   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4457     return Result;
4458
4459   // C++11 [over.ics.list]p2:
4460   //   If the parameter type is std::initializer_list<X> or "array of X" and
4461   //   all the elements can be implicitly converted to X, the implicit
4462   //   conversion sequence is the worst conversion necessary to convert an
4463   //   element of the list to X.
4464   bool toStdInitializerList = false;
4465   QualType X;
4466   if (ToType->isArrayType())
4467     X = S.Context.getAsArrayType(ToType)->getElementType();
4468   else
4469     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4470   if (!X.isNull()) {
4471     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4472       Expr *Init = From->getInit(i);
4473       ImplicitConversionSequence ICS =
4474           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4475                                 InOverloadResolution,
4476                                 AllowObjCWritebackConversion);
4477       // If a single element isn't convertible, fail.
4478       if (ICS.isBad()) {
4479         Result = ICS;
4480         break;
4481       }
4482       // Otherwise, look for the worst conversion.
4483       if (Result.isBad() ||
4484           CompareImplicitConversionSequences(S, ICS, Result) ==
4485               ImplicitConversionSequence::Worse)
4486         Result = ICS;
4487     }
4488
4489     // For an empty list, we won't have computed any conversion sequence.
4490     // Introduce the identity conversion sequence.
4491     if (From->getNumInits() == 0) {
4492       Result.setStandard();
4493       Result.Standard.setAsIdentityConversion();
4494       Result.Standard.setFromType(ToType);
4495       Result.Standard.setAllToTypes(ToType);
4496     }
4497
4498     Result.setStdInitializerListElement(toStdInitializerList);
4499     return Result;
4500   }
4501
4502   // C++11 [over.ics.list]p3:
4503   //   Otherwise, if the parameter is a non-aggregate class X and overload
4504   //   resolution chooses a single best constructor [...] the implicit
4505   //   conversion sequence is a user-defined conversion sequence. If multiple
4506   //   constructors are viable but none is better than the others, the
4507   //   implicit conversion sequence is a user-defined conversion sequence.
4508   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4509     // This function can deal with initializer lists.
4510     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4511                                     /*AllowExplicit=*/false,
4512                                     InOverloadResolution, /*CStyle=*/false,
4513                                     AllowObjCWritebackConversion,
4514                                     /*AllowObjCConversionOnExplicit=*/false);
4515   }
4516
4517   // C++11 [over.ics.list]p4:
4518   //   Otherwise, if the parameter has an aggregate type which can be
4519   //   initialized from the initializer list [...] the implicit conversion
4520   //   sequence is a user-defined conversion sequence.
4521   if (ToType->isAggregateType()) {
4522     // Type is an aggregate, argument is an init list. At this point it comes
4523     // down to checking whether the initialization works.
4524     // FIXME: Find out whether this parameter is consumed or not.
4525     InitializedEntity Entity =
4526         InitializedEntity::InitializeParameter(S.Context, ToType,
4527                                                /*Consumed=*/false);
4528     if (S.CanPerformCopyInitialization(Entity, From)) {
4529       Result.setUserDefined();
4530       Result.UserDefined.Before.setAsIdentityConversion();
4531       // Initializer lists don't have a type.
4532       Result.UserDefined.Before.setFromType(QualType());
4533       Result.UserDefined.Before.setAllToTypes(QualType());
4534
4535       Result.UserDefined.After.setAsIdentityConversion();
4536       Result.UserDefined.After.setFromType(ToType);
4537       Result.UserDefined.After.setAllToTypes(ToType);
4538       Result.UserDefined.ConversionFunction = nullptr;
4539     }
4540     return Result;
4541   }
4542
4543   // C++11 [over.ics.list]p5:
4544   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4545   if (ToType->isReferenceType()) {
4546     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4547     // mention initializer lists in any way. So we go by what list-
4548     // initialization would do and try to extrapolate from that.
4549
4550     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4551
4552     // If the initializer list has a single element that is reference-related
4553     // to the parameter type, we initialize the reference from that.
4554     if (From->getNumInits() == 1) {
4555       Expr *Init = From->getInit(0);
4556
4557       QualType T2 = Init->getType();
4558
4559       // If the initializer is the address of an overloaded function, try
4560       // to resolve the overloaded function. If all goes well, T2 is the
4561       // type of the resulting function.
4562       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4563         DeclAccessPair Found;
4564         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4565                                    Init, ToType, false, Found))
4566           T2 = Fn->getType();
4567       }
4568
4569       // Compute some basic properties of the types and the initializer.
4570       bool dummy1 = false;
4571       bool dummy2 = false;
4572       bool dummy3 = false;
4573       Sema::ReferenceCompareResult RefRelationship
4574         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4575                                          dummy2, dummy3);
4576
4577       if (RefRelationship >= Sema::Ref_Related) {
4578         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4579                                 SuppressUserConversions,
4580                                 /*AllowExplicit=*/false);
4581       }
4582     }
4583
4584     // Otherwise, we bind the reference to a temporary created from the
4585     // initializer list.
4586     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4587                                InOverloadResolution,
4588                                AllowObjCWritebackConversion);
4589     if (Result.isFailure())
4590       return Result;
4591     assert(!Result.isEllipsis() &&
4592            "Sub-initialization cannot result in ellipsis conversion.");
4593
4594     // Can we even bind to a temporary?
4595     if (ToType->isRValueReferenceType() ||
4596         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4597       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4598                                             Result.UserDefined.After;
4599       SCS.ReferenceBinding = true;
4600       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4601       SCS.BindsToRvalue = true;
4602       SCS.BindsToFunctionLvalue = false;
4603       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4604       SCS.ObjCLifetimeConversionBinding = false;
4605     } else
4606       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4607                     From, ToType);
4608     return Result;
4609   }
4610
4611   // C++11 [over.ics.list]p6:
4612   //   Otherwise, if the parameter type is not a class:
4613   if (!ToType->isRecordType()) {
4614     //    - if the initializer list has one element, the implicit conversion
4615     //      sequence is the one required to convert the element to the
4616     //      parameter type.
4617     unsigned NumInits = From->getNumInits();
4618     if (NumInits == 1)
4619       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4620                                      SuppressUserConversions,
4621                                      InOverloadResolution,
4622                                      AllowObjCWritebackConversion);
4623     //    - if the initializer list has no elements, the implicit conversion
4624     //      sequence is the identity conversion.
4625     else if (NumInits == 0) {
4626       Result.setStandard();
4627       Result.Standard.setAsIdentityConversion();
4628       Result.Standard.setFromType(ToType);
4629       Result.Standard.setAllToTypes(ToType);
4630     }
4631     return Result;
4632   }
4633
4634   // C++11 [over.ics.list]p7:
4635   //   In all cases other than those enumerated above, no conversion is possible
4636   return Result;
4637 }
4638
4639 /// TryCopyInitialization - Try to copy-initialize a value of type
4640 /// ToType from the expression From. Return the implicit conversion
4641 /// sequence required to pass this argument, which may be a bad
4642 /// conversion sequence (meaning that the argument cannot be passed to
4643 /// a parameter of this type). If @p SuppressUserConversions, then we
4644 /// do not permit any user-defined conversion sequences.
4645 static ImplicitConversionSequence
4646 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4647                       bool SuppressUserConversions,
4648                       bool InOverloadResolution,
4649                       bool AllowObjCWritebackConversion,
4650                       bool AllowExplicit) {
4651   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4652     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4653                              InOverloadResolution,AllowObjCWritebackConversion);
4654
4655   if (ToType->isReferenceType())
4656     return TryReferenceInit(S, From, ToType,
4657                             /*FIXME:*/From->getLocStart(),
4658                             SuppressUserConversions,
4659                             AllowExplicit);
4660
4661   return TryImplicitConversion(S, From, ToType,
4662                                SuppressUserConversions,
4663                                /*AllowExplicit=*/false,
4664                                InOverloadResolution,
4665                                /*CStyle=*/false,
4666                                AllowObjCWritebackConversion,
4667                                /*AllowObjCConversionOnExplicit=*/false);
4668 }
4669
4670 static bool TryCopyInitialization(const CanQualType FromQTy,
4671                                   const CanQualType ToQTy,
4672                                   Sema &S,
4673                                   SourceLocation Loc,
4674                                   ExprValueKind FromVK) {
4675   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4676   ImplicitConversionSequence ICS =
4677     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4678
4679   return !ICS.isBad();
4680 }
4681
4682 /// TryObjectArgumentInitialization - Try to initialize the object
4683 /// parameter of the given member function (@c Method) from the
4684 /// expression @p From.
4685 static ImplicitConversionSequence
4686 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4687                                 Expr::Classification FromClassification,
4688                                 CXXMethodDecl *Method,
4689                                 CXXRecordDecl *ActingContext) {
4690   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4691   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4692   //                 const volatile object.
4693   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4694     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4695   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4696
4697   // Set up the conversion sequence as a "bad" conversion, to allow us
4698   // to exit early.
4699   ImplicitConversionSequence ICS;
4700
4701   // We need to have an object of class type.
4702   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4703     FromType = PT->getPointeeType();
4704
4705     // When we had a pointer, it's implicitly dereferenced, so we
4706     // better have an lvalue.
4707     assert(FromClassification.isLValue());
4708   }
4709
4710   assert(FromType->isRecordType());
4711
4712   // C++0x [over.match.funcs]p4:
4713   //   For non-static member functions, the type of the implicit object
4714   //   parameter is
4715   //
4716   //     - "lvalue reference to cv X" for functions declared without a
4717   //        ref-qualifier or with the & ref-qualifier
4718   //     - "rvalue reference to cv X" for functions declared with the &&
4719   //        ref-qualifier
4720   //
4721   // where X is the class of which the function is a member and cv is the
4722   // cv-qualification on the member function declaration.
4723   //
4724   // However, when finding an implicit conversion sequence for the argument, we
4725   // are not allowed to create temporaries or perform user-defined conversions
4726   // (C++ [over.match.funcs]p5). We perform a simplified version of
4727   // reference binding here, that allows class rvalues to bind to
4728   // non-constant references.
4729
4730   // First check the qualifiers.
4731   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4732   if (ImplicitParamType.getCVRQualifiers()
4733                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4734       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4735     ICS.setBad(BadConversionSequence::bad_qualifiers,
4736                FromType, ImplicitParamType);
4737     return ICS;
4738   }
4739
4740   // Check that we have either the same type or a derived type. It
4741   // affects the conversion rank.
4742   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4743   ImplicitConversionKind SecondKind;
4744   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4745     SecondKind = ICK_Identity;
4746   } else if (S.IsDerivedFrom(FromType, ClassType))
4747     SecondKind = ICK_Derived_To_Base;
4748   else {
4749     ICS.setBad(BadConversionSequence::unrelated_class,
4750                FromType, ImplicitParamType);
4751     return ICS;
4752   }
4753
4754   // Check the ref-qualifier.
4755   switch (Method->getRefQualifier()) {
4756   case RQ_None:
4757     // Do nothing; we don't care about lvalueness or rvalueness.
4758     break;
4759
4760   case RQ_LValue:
4761     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4762       // non-const lvalue reference cannot bind to an rvalue
4763       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4764                  ImplicitParamType);
4765       return ICS;
4766     }
4767     break;
4768
4769   case RQ_RValue:
4770     if (!FromClassification.isRValue()) {
4771       // rvalue reference cannot bind to an lvalue
4772       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4773                  ImplicitParamType);
4774       return ICS;
4775     }
4776     break;
4777   }
4778
4779   // Success. Mark this as a reference binding.
4780   ICS.setStandard();
4781   ICS.Standard.setAsIdentityConversion();
4782   ICS.Standard.Second = SecondKind;
4783   ICS.Standard.setFromType(FromType);
4784   ICS.Standard.setAllToTypes(ImplicitParamType);
4785   ICS.Standard.ReferenceBinding = true;
4786   ICS.Standard.DirectBinding = true;
4787   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4788   ICS.Standard.BindsToFunctionLvalue = false;
4789   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4790   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4791     = (Method->getRefQualifier() == RQ_None);
4792   return ICS;
4793 }
4794
4795 /// PerformObjectArgumentInitialization - Perform initialization of
4796 /// the implicit object parameter for the given Method with the given
4797 /// expression.
4798 ExprResult
4799 Sema::PerformObjectArgumentInitialization(Expr *From,
4800                                           NestedNameSpecifier *Qualifier,
4801                                           NamedDecl *FoundDecl,
4802                                           CXXMethodDecl *Method) {
4803   QualType FromRecordType, DestType;
4804   QualType ImplicitParamRecordType  =
4805     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4806
4807   Expr::Classification FromClassification;
4808   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4809     FromRecordType = PT->getPointeeType();
4810     DestType = Method->getThisType(Context);
4811     FromClassification = Expr::Classification::makeSimpleLValue();
4812   } else {
4813     FromRecordType = From->getType();
4814     DestType = ImplicitParamRecordType;
4815     FromClassification = From->Classify(Context);
4816   }
4817
4818   // Note that we always use the true parent context when performing
4819   // the actual argument initialization.
4820   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4821       *this, From->getType(), FromClassification, Method, Method->getParent());
4822   if (ICS.isBad()) {
4823     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4824       Qualifiers FromQs = FromRecordType.getQualifiers();
4825       Qualifiers ToQs = DestType.getQualifiers();
4826       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4827       if (CVR) {
4828         Diag(From->getLocStart(),
4829              diag::err_member_function_call_bad_cvr)
4830           << Method->getDeclName() << FromRecordType << (CVR - 1)
4831           << From->getSourceRange();
4832         Diag(Method->getLocation(), diag::note_previous_decl)
4833           << Method->getDeclName();
4834         return ExprError();
4835       }
4836     }
4837
4838     return Diag(From->getLocStart(),
4839                 diag::err_implicit_object_parameter_init)
4840        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4841   }
4842
4843   if (ICS.Standard.Second == ICK_Derived_To_Base) {
4844     ExprResult FromRes =
4845       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4846     if (FromRes.isInvalid())
4847       return ExprError();
4848     From = FromRes.get();
4849   }
4850
4851   if (!Context.hasSameType(From->getType(), DestType))
4852     From = ImpCastExprToType(From, DestType, CK_NoOp,
4853                              From->getValueKind()).get();
4854   return From;
4855 }
4856
4857 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4858 /// expression From to bool (C++0x [conv]p3).
4859 static ImplicitConversionSequence
4860 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4861   return TryImplicitConversion(S, From, S.Context.BoolTy,
4862                                /*SuppressUserConversions=*/false,
4863                                /*AllowExplicit=*/true,
4864                                /*InOverloadResolution=*/false,
4865                                /*CStyle=*/false,
4866                                /*AllowObjCWritebackConversion=*/false,
4867                                /*AllowObjCConversionOnExplicit=*/false);
4868 }
4869
4870 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4871 /// of the expression From to bool (C++0x [conv]p3).
4872 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4873   if (checkPlaceholderForOverload(*this, From))
4874     return ExprError();
4875
4876   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4877   if (!ICS.isBad())
4878     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4879
4880   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4881     return Diag(From->getLocStart(),
4882                 diag::err_typecheck_bool_condition)
4883                   << From->getType() << From->getSourceRange();
4884   return ExprError();
4885 }
4886
4887 /// Check that the specified conversion is permitted in a converted constant
4888 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4889 /// is acceptable.
4890 static bool CheckConvertedConstantConversions(Sema &S,
4891                                               StandardConversionSequence &SCS) {
4892   // Since we know that the target type is an integral or unscoped enumeration
4893   // type, most conversion kinds are impossible. All possible First and Third
4894   // conversions are fine.
4895   switch (SCS.Second) {
4896   case ICK_Identity:
4897   case ICK_NoReturn_Adjustment:
4898   case ICK_Integral_Promotion:
4899   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
4900     return true;
4901
4902   case ICK_Boolean_Conversion:
4903     // Conversion from an integral or unscoped enumeration type to bool is
4904     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4905     // conversion, so we allow it in a converted constant expression.
4906     //
4907     // FIXME: Per core issue 1407, we should not allow this, but that breaks
4908     // a lot of popular code. We should at least add a warning for this
4909     // (non-conforming) extension.
4910     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4911            SCS.getToType(2)->isBooleanType();
4912
4913   case ICK_Pointer_Conversion:
4914   case ICK_Pointer_Member:
4915     // C++1z: null pointer conversions and null member pointer conversions are
4916     // only permitted if the source type is std::nullptr_t.
4917     return SCS.getFromType()->isNullPtrType();
4918
4919   case ICK_Floating_Promotion:
4920   case ICK_Complex_Promotion:
4921   case ICK_Floating_Conversion:
4922   case ICK_Complex_Conversion:
4923   case ICK_Floating_Integral:
4924   case ICK_Compatible_Conversion:
4925   case ICK_Derived_To_Base:
4926   case ICK_Vector_Conversion:
4927   case ICK_Vector_Splat:
4928   case ICK_Complex_Real:
4929   case ICK_Block_Pointer_Conversion:
4930   case ICK_TransparentUnionConversion:
4931   case ICK_Writeback_Conversion:
4932   case ICK_Zero_Event_Conversion:
4933     return false;
4934
4935   case ICK_Lvalue_To_Rvalue:
4936   case ICK_Array_To_Pointer:
4937   case ICK_Function_To_Pointer:
4938     llvm_unreachable("found a first conversion kind in Second");
4939
4940   case ICK_Qualification:
4941     llvm_unreachable("found a third conversion kind in Second");
4942
4943   case ICK_Num_Conversion_Kinds:
4944     break;
4945   }
4946
4947   llvm_unreachable("unknown conversion kind");
4948 }
4949
4950 /// CheckConvertedConstantExpression - Check that the expression From is a
4951 /// converted constant expression of type T, perform the conversion and produce
4952 /// the converted expression, per C++11 [expr.const]p3.
4953 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
4954                                                    QualType T, APValue &Value,
4955                                                    Sema::CCEKind CCE,
4956                                                    bool RequireInt) {
4957   assert(S.getLangOpts().CPlusPlus11 &&
4958          "converted constant expression outside C++11");
4959
4960   if (checkPlaceholderForOverload(S, From))
4961     return ExprError();
4962
4963   // C++1z [expr.const]p3:
4964   //  A converted constant expression of type T is an expression,
4965   //  implicitly converted to type T, where the converted
4966   //  expression is a constant expression and the implicit conversion
4967   //  sequence contains only [... list of conversions ...].
4968   ImplicitConversionSequence ICS =
4969     TryCopyInitialization(S, From, T,
4970                           /*SuppressUserConversions=*/false,
4971                           /*InOverloadResolution=*/false,
4972                           /*AllowObjcWritebackConversion=*/false,
4973                           /*AllowExplicit=*/false);
4974   StandardConversionSequence *SCS = nullptr;
4975   switch (ICS.getKind()) {
4976   case ImplicitConversionSequence::StandardConversion:
4977     SCS = &ICS.Standard;
4978     break;
4979   case ImplicitConversionSequence::UserDefinedConversion:
4980     // We are converting to a non-class type, so the Before sequence
4981     // must be trivial.
4982     SCS = &ICS.UserDefined.After;
4983     break;
4984   case ImplicitConversionSequence::AmbiguousConversion:
4985   case ImplicitConversionSequence::BadConversion:
4986     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
4987       return S.Diag(From->getLocStart(),
4988                     diag::err_typecheck_converted_constant_expression)
4989                 << From->getType() << From->getSourceRange() << T;
4990     return ExprError();
4991
4992   case ImplicitConversionSequence::EllipsisConversion:
4993     llvm_unreachable("ellipsis conversion in converted constant expression");
4994   }
4995
4996   // Check that we would only use permitted conversions.
4997   if (!CheckConvertedConstantConversions(S, *SCS)) {
4998     return S.Diag(From->getLocStart(),
4999                   diag::err_typecheck_converted_constant_expression_disallowed)
5000              << From->getType() << From->getSourceRange() << T;
5001   }
5002   // [...] and where the reference binding (if any) binds directly.
5003   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5004     return S.Diag(From->getLocStart(),
5005                   diag::err_typecheck_converted_constant_expression_indirect)
5006              << From->getType() << From->getSourceRange() << T;
5007   }
5008
5009   ExprResult Result =
5010       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5011   if (Result.isInvalid())
5012     return Result;
5013
5014   // Check for a narrowing implicit conversion.
5015   APValue PreNarrowingValue;
5016   QualType PreNarrowingType;
5017   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5018                                 PreNarrowingType)) {
5019   case NK_Variable_Narrowing:
5020     // Implicit conversion to a narrower type, and the value is not a constant
5021     // expression. We'll diagnose this in a moment.
5022   case NK_Not_Narrowing:
5023     break;
5024
5025   case NK_Constant_Narrowing:
5026     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5027       << CCE << /*Constant*/1
5028       << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5029     break;
5030
5031   case NK_Type_Narrowing:
5032     S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5033       << CCE << /*Constant*/0 << From->getType() << T;
5034     break;
5035   }
5036
5037   // Check the expression is a constant expression.
5038   SmallVector<PartialDiagnosticAt, 8> Notes;
5039   Expr::EvalResult Eval;
5040   Eval.Diag = &Notes;
5041
5042   if ((T->isReferenceType()
5043            ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5044            : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5045       (RequireInt && !Eval.Val.isInt())) {
5046     // The expression can't be folded, so we can't keep it at this position in
5047     // the AST.
5048     Result = ExprError();
5049   } else {
5050     Value = Eval.Val;
5051
5052     if (Notes.empty()) {
5053       // It's a constant expression.
5054       return Result;
5055     }
5056   }
5057
5058   // It's not a constant expression. Produce an appropriate diagnostic.
5059   if (Notes.size() == 1 &&
5060       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5061     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5062   else {
5063     S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5064       << CCE << From->getSourceRange();
5065     for (unsigned I = 0; I < Notes.size(); ++I)
5066       S.Diag(Notes[I].first, Notes[I].second);
5067   }
5068   return ExprError();
5069 }
5070
5071 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5072                                                   APValue &Value, CCEKind CCE) {
5073   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5074 }
5075
5076 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5077                                                   llvm::APSInt &Value,
5078                                                   CCEKind CCE) {
5079   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5080
5081   APValue V;
5082   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5083   if (!R.isInvalid())
5084     Value = V.getInt();
5085   return R;
5086 }
5087
5088
5089 /// dropPointerConversions - If the given standard conversion sequence
5090 /// involves any pointer conversions, remove them.  This may change
5091 /// the result type of the conversion sequence.
5092 static void dropPointerConversion(StandardConversionSequence &SCS) {
5093   if (SCS.Second == ICK_Pointer_Conversion) {
5094     SCS.Second = ICK_Identity;
5095     SCS.Third = ICK_Identity;
5096     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5097   }
5098 }
5099
5100 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5101 /// convert the expression From to an Objective-C pointer type.
5102 static ImplicitConversionSequence
5103 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5104   // Do an implicit conversion to 'id'.
5105   QualType Ty = S.Context.getObjCIdType();
5106   ImplicitConversionSequence ICS
5107     = TryImplicitConversion(S, From, Ty,
5108                             // FIXME: Are these flags correct?
5109                             /*SuppressUserConversions=*/false,
5110                             /*AllowExplicit=*/true,
5111                             /*InOverloadResolution=*/false,
5112                             /*CStyle=*/false,
5113                             /*AllowObjCWritebackConversion=*/false,
5114                             /*AllowObjCConversionOnExplicit=*/true);
5115
5116   // Strip off any final conversions to 'id'.
5117   switch (ICS.getKind()) {
5118   case ImplicitConversionSequence::BadConversion:
5119   case ImplicitConversionSequence::AmbiguousConversion:
5120   case ImplicitConversionSequence::EllipsisConversion:
5121     break;
5122
5123   case ImplicitConversionSequence::UserDefinedConversion:
5124     dropPointerConversion(ICS.UserDefined.After);
5125     break;
5126
5127   case ImplicitConversionSequence::StandardConversion:
5128     dropPointerConversion(ICS.Standard);
5129     break;
5130   }
5131
5132   return ICS;
5133 }
5134
5135 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5136 /// conversion of the expression From to an Objective-C pointer type.
5137 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5138   if (checkPlaceholderForOverload(*this, From))
5139     return ExprError();
5140
5141   QualType Ty = Context.getObjCIdType();
5142   ImplicitConversionSequence ICS =
5143     TryContextuallyConvertToObjCPointer(*this, From);
5144   if (!ICS.isBad())
5145     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5146   return ExprError();
5147 }
5148
5149 /// Determine whether the provided type is an integral type, or an enumeration
5150 /// type of a permitted flavor.
5151 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5152   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5153                                  : T->isIntegralOrUnscopedEnumerationType();
5154 }
5155
5156 static ExprResult
5157 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5158                             Sema::ContextualImplicitConverter &Converter,
5159                             QualType T, UnresolvedSetImpl &ViableConversions) {
5160
5161   if (Converter.Suppress)
5162     return ExprError();
5163
5164   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5165   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5166     CXXConversionDecl *Conv =
5167         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5168     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5169     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5170   }
5171   return From;
5172 }
5173
5174 static bool
5175 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5176                            Sema::ContextualImplicitConverter &Converter,
5177                            QualType T, bool HadMultipleCandidates,
5178                            UnresolvedSetImpl &ExplicitConversions) {
5179   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5180     DeclAccessPair Found = ExplicitConversions[0];
5181     CXXConversionDecl *Conversion =
5182         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5183
5184     // The user probably meant to invoke the given explicit
5185     // conversion; use it.
5186     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5187     std::string TypeStr;
5188     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5189
5190     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5191         << FixItHint::CreateInsertion(From->getLocStart(),
5192                                       "static_cast<" + TypeStr + ">(")
5193         << FixItHint::CreateInsertion(
5194                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5195     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5196
5197     // If we aren't in a SFINAE context, build a call to the
5198     // explicit conversion function.
5199     if (SemaRef.isSFINAEContext())
5200       return true;
5201
5202     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5203     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5204                                                        HadMultipleCandidates);
5205     if (Result.isInvalid())
5206       return true;
5207     // Record usage of conversion in an implicit cast.
5208     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5209                                     CK_UserDefinedConversion, Result.get(),
5210                                     nullptr, Result.get()->getValueKind());
5211   }
5212   return false;
5213 }
5214
5215 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5216                              Sema::ContextualImplicitConverter &Converter,
5217                              QualType T, bool HadMultipleCandidates,
5218                              DeclAccessPair &Found) {
5219   CXXConversionDecl *Conversion =
5220       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5221   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5222
5223   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5224   if (!Converter.SuppressConversion) {
5225     if (SemaRef.isSFINAEContext())
5226       return true;
5227
5228     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5229         << From->getSourceRange();
5230   }
5231
5232   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5233                                                      HadMultipleCandidates);
5234   if (Result.isInvalid())
5235     return true;
5236   // Record usage of conversion in an implicit cast.
5237   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5238                                   CK_UserDefinedConversion, Result.get(),
5239                                   nullptr, Result.get()->getValueKind());
5240   return false;
5241 }
5242
5243 static ExprResult finishContextualImplicitConversion(
5244     Sema &SemaRef, SourceLocation Loc, Expr *From,
5245     Sema::ContextualImplicitConverter &Converter) {
5246   if (!Converter.match(From->getType()) && !Converter.Suppress)
5247     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5248         << From->getSourceRange();
5249
5250   return SemaRef.DefaultLvalueConversion(From);
5251 }
5252
5253 static void
5254 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5255                                   UnresolvedSetImpl &ViableConversions,
5256                                   OverloadCandidateSet &CandidateSet) {
5257   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5258     DeclAccessPair FoundDecl = ViableConversions[I];
5259     NamedDecl *D = FoundDecl.getDecl();
5260     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5261     if (isa<UsingShadowDecl>(D))
5262       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5263
5264     CXXConversionDecl *Conv;
5265     FunctionTemplateDecl *ConvTemplate;
5266     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5267       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5268     else
5269       Conv = cast<CXXConversionDecl>(D);
5270
5271     if (ConvTemplate)
5272       SemaRef.AddTemplateConversionCandidate(
5273         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5274         /*AllowObjCConversionOnExplicit=*/false);
5275     else
5276       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5277                                      ToType, CandidateSet,
5278                                      /*AllowObjCConversionOnExplicit=*/false);
5279   }
5280 }
5281
5282 /// \brief Attempt to convert the given expression to a type which is accepted
5283 /// by the given converter.
5284 ///
5285 /// This routine will attempt to convert an expression of class type to a
5286 /// type accepted by the specified converter. In C++11 and before, the class
5287 /// must have a single non-explicit conversion function converting to a matching
5288 /// type. In C++1y, there can be multiple such conversion functions, but only
5289 /// one target type.
5290 ///
5291 /// \param Loc The source location of the construct that requires the
5292 /// conversion.
5293 ///
5294 /// \param From The expression we're converting from.
5295 ///
5296 /// \param Converter Used to control and diagnose the conversion process.
5297 ///
5298 /// \returns The expression, converted to an integral or enumeration type if
5299 /// successful.
5300 ExprResult Sema::PerformContextualImplicitConversion(
5301     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5302   // We can't perform any more checking for type-dependent expressions.
5303   if (From->isTypeDependent())
5304     return From;
5305
5306   // Process placeholders immediately.
5307   if (From->hasPlaceholderType()) {
5308     ExprResult result = CheckPlaceholderExpr(From);
5309     if (result.isInvalid())
5310       return result;
5311     From = result.get();
5312   }
5313
5314   // If the expression already has a matching type, we're golden.
5315   QualType T = From->getType();
5316   if (Converter.match(T))
5317     return DefaultLvalueConversion(From);
5318
5319   // FIXME: Check for missing '()' if T is a function type?
5320
5321   // We can only perform contextual implicit conversions on objects of class
5322   // type.
5323   const RecordType *RecordTy = T->getAs<RecordType>();
5324   if (!RecordTy || !getLangOpts().CPlusPlus) {
5325     if (!Converter.Suppress)
5326       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5327     return From;
5328   }
5329
5330   // We must have a complete class type.
5331   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5332     ContextualImplicitConverter &Converter;
5333     Expr *From;
5334
5335     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5336         : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5337
5338     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5339       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5340     }
5341   } IncompleteDiagnoser(Converter, From);
5342
5343   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5344     return From;
5345
5346   // Look for a conversion to an integral or enumeration type.
5347   UnresolvedSet<4>
5348       ViableConversions; // These are *potentially* viable in C++1y.
5349   UnresolvedSet<4> ExplicitConversions;
5350   std::pair<CXXRecordDecl::conversion_iterator,
5351             CXXRecordDecl::conversion_iterator> Conversions =
5352       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5353
5354   bool HadMultipleCandidates =
5355       (std::distance(Conversions.first, Conversions.second) > 1);
5356
5357   // To check that there is only one target type, in C++1y:
5358   QualType ToType;
5359   bool HasUniqueTargetType = true;
5360
5361   // Collect explicit or viable (potentially in C++1y) conversions.
5362   for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5363                                           E = Conversions.second;
5364        I != E; ++I) {
5365     NamedDecl *D = (*I)->getUnderlyingDecl();
5366     CXXConversionDecl *Conversion;
5367     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5368     if (ConvTemplate) {
5369       if (getLangOpts().CPlusPlus14)
5370         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5371       else
5372         continue; // C++11 does not consider conversion operator templates(?).
5373     } else
5374       Conversion = cast<CXXConversionDecl>(D);
5375
5376     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5377            "Conversion operator templates are considered potentially "
5378            "viable in C++1y");
5379
5380     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5381     if (Converter.match(CurToType) || ConvTemplate) {
5382
5383       if (Conversion->isExplicit()) {
5384         // FIXME: For C++1y, do we need this restriction?
5385         // cf. diagnoseNoViableConversion()
5386         if (!ConvTemplate)
5387           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5388       } else {
5389         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5390           if (ToType.isNull())
5391             ToType = CurToType.getUnqualifiedType();
5392           else if (HasUniqueTargetType &&
5393                    (CurToType.getUnqualifiedType() != ToType))
5394             HasUniqueTargetType = false;
5395         }
5396         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5397       }
5398     }
5399   }
5400
5401   if (getLangOpts().CPlusPlus14) {
5402     // C++1y [conv]p6:
5403     // ... An expression e of class type E appearing in such a context
5404     // is said to be contextually implicitly converted to a specified
5405     // type T and is well-formed if and only if e can be implicitly
5406     // converted to a type T that is determined as follows: E is searched
5407     // for conversion functions whose return type is cv T or reference to
5408     // cv T such that T is allowed by the context. There shall be
5409     // exactly one such T.
5410
5411     // If no unique T is found:
5412     if (ToType.isNull()) {
5413       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5414                                      HadMultipleCandidates,
5415                                      ExplicitConversions))
5416         return ExprError();
5417       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5418     }
5419
5420     // If more than one unique Ts are found:
5421     if (!HasUniqueTargetType)
5422       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5423                                          ViableConversions);
5424
5425     // If one unique T is found:
5426     // First, build a candidate set from the previously recorded
5427     // potentially viable conversions.
5428     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5429     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5430                                       CandidateSet);
5431
5432     // Then, perform overload resolution over the candidate set.
5433     OverloadCandidateSet::iterator Best;
5434     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5435     case OR_Success: {
5436       // Apply this conversion.
5437       DeclAccessPair Found =
5438           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5439       if (recordConversion(*this, Loc, From, Converter, T,
5440                            HadMultipleCandidates, Found))
5441         return ExprError();
5442       break;
5443     }
5444     case OR_Ambiguous:
5445       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5446                                          ViableConversions);
5447     case OR_No_Viable_Function:
5448       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5449                                      HadMultipleCandidates,
5450                                      ExplicitConversions))
5451         return ExprError();
5452     // fall through 'OR_Deleted' case.
5453     case OR_Deleted:
5454       // We'll complain below about a non-integral condition type.
5455       break;
5456     }
5457   } else {
5458     switch (ViableConversions.size()) {
5459     case 0: {
5460       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5461                                      HadMultipleCandidates,
5462                                      ExplicitConversions))
5463         return ExprError();
5464
5465       // We'll complain below about a non-integral condition type.
5466       break;
5467     }
5468     case 1: {
5469       // Apply this conversion.
5470       DeclAccessPair Found = ViableConversions[0];
5471       if (recordConversion(*this, Loc, From, Converter, T,
5472                            HadMultipleCandidates, Found))
5473         return ExprError();
5474       break;
5475     }
5476     default:
5477       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5478                                          ViableConversions);
5479     }
5480   }
5481
5482   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5483 }
5484
5485 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5486 /// an acceptable non-member overloaded operator for a call whose
5487 /// arguments have types T1 (and, if non-empty, T2). This routine
5488 /// implements the check in C++ [over.match.oper]p3b2 concerning
5489 /// enumeration types.
5490 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5491                                                    FunctionDecl *Fn,
5492                                                    ArrayRef<Expr *> Args) {
5493   QualType T1 = Args[0]->getType();
5494   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5495
5496   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5497     return true;
5498
5499   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5500     return true;
5501
5502   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5503   if (Proto->getNumParams() < 1)
5504     return false;
5505
5506   if (T1->isEnumeralType()) {
5507     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5508     if (Context.hasSameUnqualifiedType(T1, ArgType))
5509       return true;
5510   }
5511
5512   if (Proto->getNumParams() < 2)
5513     return false;
5514
5515   if (!T2.isNull() && T2->isEnumeralType()) {
5516     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5517     if (Context.hasSameUnqualifiedType(T2, ArgType))
5518       return true;
5519   }
5520
5521   return false;
5522 }
5523
5524 /// AddOverloadCandidate - Adds the given function to the set of
5525 /// candidate functions, using the given function call arguments.  If
5526 /// @p SuppressUserConversions, then don't allow user-defined
5527 /// conversions via constructors or conversion operators.
5528 ///
5529 /// \param PartialOverloading true if we are performing "partial" overloading
5530 /// based on an incomplete set of function arguments. This feature is used by
5531 /// code completion.
5532 void
5533 Sema::AddOverloadCandidate(FunctionDecl *Function,
5534                            DeclAccessPair FoundDecl,
5535                            ArrayRef<Expr *> Args,
5536                            OverloadCandidateSet &CandidateSet,
5537                            bool SuppressUserConversions,
5538                            bool PartialOverloading,
5539                            bool AllowExplicit) {
5540   const FunctionProtoType *Proto
5541     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5542   assert(Proto && "Functions without a prototype cannot be overloaded");
5543   assert(!Function->getDescribedFunctionTemplate() &&
5544          "Use AddTemplateOverloadCandidate for function templates");
5545
5546   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5547     if (!isa<CXXConstructorDecl>(Method)) {
5548       // If we get here, it's because we're calling a member function
5549       // that is named without a member access expression (e.g.,
5550       // "this->f") that was either written explicitly or created
5551       // implicitly. This can happen with a qualified call to a member
5552       // function, e.g., X::f(). We use an empty type for the implied
5553       // object argument (C++ [over.call.func]p3), and the acting context
5554       // is irrelevant.
5555       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5556                          QualType(), Expr::Classification::makeSimpleLValue(),
5557                          Args, CandidateSet, SuppressUserConversions);
5558       return;
5559     }
5560     // We treat a constructor like a non-member function, since its object
5561     // argument doesn't participate in overload resolution.
5562   }
5563
5564   if (!CandidateSet.isNewCandidate(Function))
5565     return;
5566
5567   // C++ [over.match.oper]p3:
5568   //   if no operand has a class type, only those non-member functions in the
5569   //   lookup set that have a first parameter of type T1 or "reference to
5570   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5571   //   is a right operand) a second parameter of type T2 or "reference to
5572   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5573   //   candidate functions.
5574   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5575       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5576     return;
5577
5578   // C++11 [class.copy]p11: [DR1402]
5579   //   A defaulted move constructor that is defined as deleted is ignored by
5580   //   overload resolution.
5581   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5582   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5583       Constructor->isMoveConstructor())
5584     return;
5585
5586   // Overload resolution is always an unevaluated context.
5587   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5588
5589   // Add this candidate
5590   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5591   Candidate.FoundDecl = FoundDecl;
5592   Candidate.Function = Function;
5593   Candidate.Viable = true;
5594   Candidate.IsSurrogate = false;
5595   Candidate.IgnoreObjectArgument = false;
5596   Candidate.ExplicitCallArguments = Args.size();
5597
5598   if (Constructor) {
5599     // C++ [class.copy]p3:
5600     //   A member function template is never instantiated to perform the copy
5601     //   of a class object to an object of its class type.
5602     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5603     if (Args.size() == 1 &&
5604         Constructor->isSpecializationCopyingObject() &&
5605         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5606          IsDerivedFrom(Args[0]->getType(), ClassType))) {
5607       Candidate.Viable = false;
5608       Candidate.FailureKind = ovl_fail_illegal_constructor;
5609       return;
5610     }
5611   }
5612
5613   unsigned NumParams = Proto->getNumParams();
5614
5615   // (C++ 13.3.2p2): A candidate function having fewer than m
5616   // parameters is viable only if it has an ellipsis in its parameter
5617   // list (8.3.5).
5618   if ((Args.size() + (PartialOverloading && Args.size())) > NumParams &&
5619       !Proto->isVariadic()) {
5620     Candidate.Viable = false;
5621     Candidate.FailureKind = ovl_fail_too_many_arguments;
5622     return;
5623   }
5624
5625   // (C++ 13.3.2p2): A candidate function having more than m parameters
5626   // is viable only if the (m+1)st parameter has a default argument
5627   // (8.3.6). For the purposes of overload resolution, the
5628   // parameter list is truncated on the right, so that there are
5629   // exactly m parameters.
5630   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5631   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5632     // Not enough arguments.
5633     Candidate.Viable = false;
5634     Candidate.FailureKind = ovl_fail_too_few_arguments;
5635     return;
5636   }
5637
5638   // (CUDA B.1): Check for invalid calls between targets.
5639   if (getLangOpts().CUDA)
5640     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5641       // Skip the check for callers that are implicit members, because in this
5642       // case we may not yet know what the member's target is; the target is
5643       // inferred for the member automatically, based on the bases and fields of
5644       // the class.
5645       if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
5646         Candidate.Viable = false;
5647         Candidate.FailureKind = ovl_fail_bad_target;
5648         return;
5649       }
5650
5651   // Determine the implicit conversion sequences for each of the
5652   // arguments.
5653   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5654     if (ArgIdx < NumParams) {
5655       // (C++ 13.3.2p3): for F to be a viable function, there shall
5656       // exist for each argument an implicit conversion sequence
5657       // (13.3.3.1) that converts that argument to the corresponding
5658       // parameter of F.
5659       QualType ParamType = Proto->getParamType(ArgIdx);
5660       Candidate.Conversions[ArgIdx]
5661         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5662                                 SuppressUserConversions,
5663                                 /*InOverloadResolution=*/true,
5664                                 /*AllowObjCWritebackConversion=*/
5665                                   getLangOpts().ObjCAutoRefCount,
5666                                 AllowExplicit);
5667       if (Candidate.Conversions[ArgIdx].isBad()) {
5668         Candidate.Viable = false;
5669         Candidate.FailureKind = ovl_fail_bad_conversion;
5670         return;
5671       }
5672     } else {
5673       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5674       // argument for which there is no corresponding parameter is
5675       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5676       Candidate.Conversions[ArgIdx].setEllipsis();
5677     }
5678   }
5679
5680   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5681     Candidate.Viable = false;
5682     Candidate.FailureKind = ovl_fail_enable_if;
5683     Candidate.DeductionFailure.Data = FailedAttr;
5684     return;
5685   }
5686 }
5687
5688 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
5689                                        bool IsInstance) {
5690   SmallVector<ObjCMethodDecl*, 4> Methods;
5691   if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5692     return nullptr;
5693     
5694   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5695     bool Match = true;
5696     ObjCMethodDecl *Method = Methods[b];
5697     unsigned NumNamedArgs = Sel.getNumArgs();
5698     // Method might have more arguments than selector indicates. This is due
5699     // to addition of c-style arguments in method.
5700     if (Method->param_size() > NumNamedArgs)
5701       NumNamedArgs = Method->param_size();
5702     if (Args.size() < NumNamedArgs)
5703       continue;
5704             
5705     for (unsigned i = 0; i < NumNamedArgs; i++) {
5706       // We can't do any type-checking on a type-dependent argument.
5707       if (Args[i]->isTypeDependent()) {
5708         Match = false;
5709         break;
5710       }
5711         
5712       ParmVarDecl *param = Method->parameters()[i];
5713       Expr *argExpr = Args[i];
5714       assert(argExpr && "SelectBestMethod(): missing expression");
5715                 
5716       // Strip the unbridged-cast placeholder expression off unless it's
5717       // a consumed argument.
5718       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5719           !param->hasAttr<CFConsumedAttr>())
5720         argExpr = stripARCUnbridgedCast(argExpr);
5721                 
5722       // If the parameter is __unknown_anytype, move on to the next method.
5723       if (param->getType() == Context.UnknownAnyTy) {
5724         Match = false;
5725         break;
5726       }
5727                 
5728       ImplicitConversionSequence ConversionState
5729         = TryCopyInitialization(*this, argExpr, param->getType(),
5730                                 /*SuppressUserConversions*/false,
5731                                 /*InOverloadResolution=*/true,
5732                                 /*AllowObjCWritebackConversion=*/
5733                                 getLangOpts().ObjCAutoRefCount,
5734                                 /*AllowExplicit*/false);
5735         if (ConversionState.isBad()) {
5736           Match = false;
5737           break;
5738         }
5739     }
5740     // Promote additional arguments to variadic methods.
5741     if (Match && Method->isVariadic()) {
5742       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5743         if (Args[i]->isTypeDependent()) {
5744           Match = false;
5745           break;
5746         }
5747         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5748                                                           nullptr);
5749         if (Arg.isInvalid()) {
5750           Match = false;
5751           break;
5752         }
5753       }
5754     } else {
5755       // Check for extra arguments to non-variadic methods.
5756       if (Args.size() != NumNamedArgs)
5757         Match = false;
5758       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5759         // Special case when selectors have no argument. In this case, select
5760         // one with the most general result type of 'id'.
5761         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5762           QualType ReturnT = Methods[b]->getReturnType();
5763           if (ReturnT->isObjCIdType())
5764             return Methods[b];
5765         }
5766       }
5767     }
5768
5769     if (Match)
5770       return Method;
5771   }
5772   return nullptr;
5773 }
5774
5775 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5776
5777 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5778                                   bool MissingImplicitThis) {
5779   // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5780   // we need to find the first failing one.
5781   if (!Function->hasAttrs())
5782     return nullptr;
5783   AttrVec Attrs = Function->getAttrs();
5784   AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5785                                        IsNotEnableIfAttr);
5786   if (Attrs.begin() == E)
5787     return nullptr;
5788   std::reverse(Attrs.begin(), E);
5789
5790   SFINAETrap Trap(*this);
5791
5792   // Convert the arguments.
5793   SmallVector<Expr *, 16> ConvertedArgs;
5794   bool InitializationFailed = false;
5795   bool ContainsValueDependentExpr = false;
5796   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5797     if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5798         !cast<CXXMethodDecl>(Function)->isStatic() &&
5799         !isa<CXXConstructorDecl>(Function)) {
5800       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5801       ExprResult R =
5802         PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5803                                             Method, Method);
5804       if (R.isInvalid()) {
5805         InitializationFailed = true;
5806         break;
5807       }
5808       ContainsValueDependentExpr |= R.get()->isValueDependent();
5809       ConvertedArgs.push_back(R.get());
5810     } else {
5811       ExprResult R =
5812         PerformCopyInitialization(InitializedEntity::InitializeParameter(
5813                                                 Context,
5814                                                 Function->getParamDecl(i)),
5815                                   SourceLocation(),
5816                                   Args[i]);
5817       if (R.isInvalid()) {
5818         InitializationFailed = true;
5819         break;
5820       }
5821       ContainsValueDependentExpr |= R.get()->isValueDependent();
5822       ConvertedArgs.push_back(R.get());
5823     }
5824   }
5825
5826   if (InitializationFailed || Trap.hasErrorOccurred())
5827     return cast<EnableIfAttr>(Attrs[0]);
5828
5829   for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5830     APValue Result;
5831     EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5832     if (EIA->getCond()->isValueDependent()) {
5833       // Don't even try now, we'll examine it after instantiation.
5834       continue;
5835     }
5836
5837     if (!EIA->getCond()->EvaluateWithSubstitution(
5838             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5839       if (!ContainsValueDependentExpr)
5840         return EIA;
5841     } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
5842       return EIA;
5843     }
5844   }
5845   return nullptr;
5846 }
5847
5848 /// \brief Add all of the function declarations in the given function set to
5849 /// the overload candidate set.
5850 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5851                                  ArrayRef<Expr *> Args,
5852                                  OverloadCandidateSet& CandidateSet,
5853                                  bool SuppressUserConversions,
5854                                TemplateArgumentListInfo *ExplicitTemplateArgs) {
5855   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5856     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5857     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5858       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5859         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5860                            cast<CXXMethodDecl>(FD)->getParent(),
5861                            Args[0]->getType(), Args[0]->Classify(Context),
5862                            Args.slice(1), CandidateSet,
5863                            SuppressUserConversions);
5864       else
5865         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5866                              SuppressUserConversions);
5867     } else {
5868       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5869       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5870           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5871         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5872                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5873                                    ExplicitTemplateArgs,
5874                                    Args[0]->getType(),
5875                                    Args[0]->Classify(Context), Args.slice(1),
5876                                    CandidateSet, SuppressUserConversions);
5877       else
5878         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5879                                      ExplicitTemplateArgs, Args,
5880                                      CandidateSet, SuppressUserConversions);
5881     }
5882   }
5883 }
5884
5885 /// AddMethodCandidate - Adds a named decl (which is some kind of
5886 /// method) as a method candidate to the given overload set.
5887 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5888                               QualType ObjectType,
5889                               Expr::Classification ObjectClassification,
5890                               ArrayRef<Expr *> Args,
5891                               OverloadCandidateSet& CandidateSet,
5892                               bool SuppressUserConversions) {
5893   NamedDecl *Decl = FoundDecl.getDecl();
5894   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5895
5896   if (isa<UsingShadowDecl>(Decl))
5897     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5898
5899   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5900     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5901            "Expected a member function template");
5902     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5903                                /*ExplicitArgs*/ nullptr,
5904                                ObjectType, ObjectClassification,
5905                                Args, CandidateSet,
5906                                SuppressUserConversions);
5907   } else {
5908     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5909                        ObjectType, ObjectClassification,
5910                        Args,
5911                        CandidateSet, SuppressUserConversions);
5912   }
5913 }
5914
5915 /// AddMethodCandidate - Adds the given C++ member function to the set
5916 /// of candidate functions, using the given function call arguments
5917 /// and the object argument (@c Object). For example, in a call
5918 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5919 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5920 /// allow user-defined conversions via constructors or conversion
5921 /// operators.
5922 void
5923 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5924                          CXXRecordDecl *ActingContext, QualType ObjectType,
5925                          Expr::Classification ObjectClassification,
5926                          ArrayRef<Expr *> Args,
5927                          OverloadCandidateSet &CandidateSet,
5928                          bool SuppressUserConversions) {
5929   const FunctionProtoType *Proto
5930     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5931   assert(Proto && "Methods without a prototype cannot be overloaded");
5932   assert(!isa<CXXConstructorDecl>(Method) &&
5933          "Use AddOverloadCandidate for constructors");
5934
5935   if (!CandidateSet.isNewCandidate(Method))
5936     return;
5937
5938   // C++11 [class.copy]p23: [DR1402]
5939   //   A defaulted move assignment operator that is defined as deleted is
5940   //   ignored by overload resolution.
5941   if (Method->isDefaulted() && Method->isDeleted() &&
5942       Method->isMoveAssignmentOperator())
5943     return;
5944
5945   // Overload resolution is always an unevaluated context.
5946   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5947
5948   // Add this candidate
5949   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5950   Candidate.FoundDecl = FoundDecl;
5951   Candidate.Function = Method;
5952   Candidate.IsSurrogate = false;
5953   Candidate.IgnoreObjectArgument = false;
5954   Candidate.ExplicitCallArguments = Args.size();
5955
5956   unsigned NumParams = Proto->getNumParams();
5957
5958   // (C++ 13.3.2p2): A candidate function having fewer than m
5959   // parameters is viable only if it has an ellipsis in its parameter
5960   // list (8.3.5).
5961   if (Args.size() > NumParams && !Proto->isVariadic()) {
5962     Candidate.Viable = false;
5963     Candidate.FailureKind = ovl_fail_too_many_arguments;
5964     return;
5965   }
5966
5967   // (C++ 13.3.2p2): A candidate function having more than m parameters
5968   // is viable only if the (m+1)st parameter has a default argument
5969   // (8.3.6). For the purposes of overload resolution, the
5970   // parameter list is truncated on the right, so that there are
5971   // exactly m parameters.
5972   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5973   if (Args.size() < MinRequiredArgs) {
5974     // Not enough arguments.
5975     Candidate.Viable = false;
5976     Candidate.FailureKind = ovl_fail_too_few_arguments;
5977     return;
5978   }
5979
5980   Candidate.Viable = true;
5981
5982   if (Method->isStatic() || ObjectType.isNull())
5983     // The implicit object argument is ignored.
5984     Candidate.IgnoreObjectArgument = true;
5985   else {
5986     // Determine the implicit conversion sequence for the object
5987     // parameter.
5988     Candidate.Conversions[0]
5989       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5990                                         Method, ActingContext);
5991     if (Candidate.Conversions[0].isBad()) {
5992       Candidate.Viable = false;
5993       Candidate.FailureKind = ovl_fail_bad_conversion;
5994       return;
5995     }
5996   }
5997
5998   // (CUDA B.1): Check for invalid calls between targets.
5999   if (getLangOpts().CUDA)
6000     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6001       if (CheckCUDATarget(Caller, Method)) {
6002         Candidate.Viable = false;
6003         Candidate.FailureKind = ovl_fail_bad_target;
6004         return;
6005       }
6006
6007   // Determine the implicit conversion sequences for each of the
6008   // arguments.
6009   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6010     if (ArgIdx < NumParams) {
6011       // (C++ 13.3.2p3): for F to be a viable function, there shall
6012       // exist for each argument an implicit conversion sequence
6013       // (13.3.3.1) that converts that argument to the corresponding
6014       // parameter of F.
6015       QualType ParamType = Proto->getParamType(ArgIdx);
6016       Candidate.Conversions[ArgIdx + 1]
6017         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6018                                 SuppressUserConversions,
6019                                 /*InOverloadResolution=*/true,
6020                                 /*AllowObjCWritebackConversion=*/
6021                                   getLangOpts().ObjCAutoRefCount);
6022       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6023         Candidate.Viable = false;
6024         Candidate.FailureKind = ovl_fail_bad_conversion;
6025         return;
6026       }
6027     } else {
6028       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6029       // argument for which there is no corresponding parameter is
6030       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6031       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6032     }
6033   }
6034
6035   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6036     Candidate.Viable = false;
6037     Candidate.FailureKind = ovl_fail_enable_if;
6038     Candidate.DeductionFailure.Data = FailedAttr;
6039     return;
6040   }
6041 }
6042
6043 /// \brief Add a C++ member function template as a candidate to the candidate
6044 /// set, using template argument deduction to produce an appropriate member
6045 /// function template specialization.
6046 void
6047 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6048                                  DeclAccessPair FoundDecl,
6049                                  CXXRecordDecl *ActingContext,
6050                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6051                                  QualType ObjectType,
6052                                  Expr::Classification ObjectClassification,
6053                                  ArrayRef<Expr *> Args,
6054                                  OverloadCandidateSet& CandidateSet,
6055                                  bool SuppressUserConversions) {
6056   if (!CandidateSet.isNewCandidate(MethodTmpl))
6057     return;
6058
6059   // C++ [over.match.funcs]p7:
6060   //   In each case where a candidate is a function template, candidate
6061   //   function template specializations are generated using template argument
6062   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6063   //   candidate functions in the usual way.113) A given name can refer to one
6064   //   or more function templates and also to a set of overloaded non-template
6065   //   functions. In such a case, the candidate functions generated from each
6066   //   function template are combined with the set of non-template candidate
6067   //   functions.
6068   TemplateDeductionInfo Info(CandidateSet.getLocation());
6069   FunctionDecl *Specialization = nullptr;
6070   if (TemplateDeductionResult Result
6071       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6072                                 Specialization, Info)) {
6073     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6074     Candidate.FoundDecl = FoundDecl;
6075     Candidate.Function = MethodTmpl->getTemplatedDecl();
6076     Candidate.Viable = false;
6077     Candidate.FailureKind = ovl_fail_bad_deduction;
6078     Candidate.IsSurrogate = false;
6079     Candidate.IgnoreObjectArgument = false;
6080     Candidate.ExplicitCallArguments = Args.size();
6081     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6082                                                           Info);
6083     return;
6084   }
6085
6086   // Add the function template specialization produced by template argument
6087   // deduction as a candidate.
6088   assert(Specialization && "Missing member function template specialization?");
6089   assert(isa<CXXMethodDecl>(Specialization) &&
6090          "Specialization is not a member function?");
6091   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6092                      ActingContext, ObjectType, ObjectClassification, Args,
6093                      CandidateSet, SuppressUserConversions);
6094 }
6095
6096 /// \brief Add a C++ function template specialization as a candidate
6097 /// in the candidate set, using template argument deduction to produce
6098 /// an appropriate function template specialization.
6099 void
6100 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6101                                    DeclAccessPair FoundDecl,
6102                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6103                                    ArrayRef<Expr *> Args,
6104                                    OverloadCandidateSet& CandidateSet,
6105                                    bool SuppressUserConversions) {
6106   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6107     return;
6108
6109   // C++ [over.match.funcs]p7:
6110   //   In each case where a candidate is a function template, candidate
6111   //   function template specializations are generated using template argument
6112   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6113   //   candidate functions in the usual way.113) A given name can refer to one
6114   //   or more function templates and also to a set of overloaded non-template
6115   //   functions. In such a case, the candidate functions generated from each
6116   //   function template are combined with the set of non-template candidate
6117   //   functions.
6118   TemplateDeductionInfo Info(CandidateSet.getLocation());
6119   FunctionDecl *Specialization = nullptr;
6120   if (TemplateDeductionResult Result
6121         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6122                                   Specialization, Info)) {
6123     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6124     Candidate.FoundDecl = FoundDecl;
6125     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6126     Candidate.Viable = false;
6127     Candidate.FailureKind = ovl_fail_bad_deduction;
6128     Candidate.IsSurrogate = false;
6129     Candidate.IgnoreObjectArgument = false;
6130     Candidate.ExplicitCallArguments = Args.size();
6131     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6132                                                           Info);
6133     return;
6134   }
6135
6136   // Add the function template specialization produced by template argument
6137   // deduction as a candidate.
6138   assert(Specialization && "Missing function template specialization?");
6139   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6140                        SuppressUserConversions);
6141 }
6142
6143 /// Determine whether this is an allowable conversion from the result
6144 /// of an explicit conversion operator to the expected type, per C++
6145 /// [over.match.conv]p1 and [over.match.ref]p1.
6146 ///
6147 /// \param ConvType The return type of the conversion function.
6148 ///
6149 /// \param ToType The type we are converting to.
6150 ///
6151 /// \param AllowObjCPointerConversion Allow a conversion from one
6152 /// Objective-C pointer to another.
6153 ///
6154 /// \returns true if the conversion is allowable, false otherwise.
6155 static bool isAllowableExplicitConversion(Sema &S,
6156                                           QualType ConvType, QualType ToType,
6157                                           bool AllowObjCPointerConversion) {
6158   QualType ToNonRefType = ToType.getNonReferenceType();
6159
6160   // Easy case: the types are the same.
6161   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6162     return true;
6163
6164   // Allow qualification conversions.
6165   bool ObjCLifetimeConversion;
6166   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6167                                   ObjCLifetimeConversion))
6168     return true;
6169
6170   // If we're not allowed to consider Objective-C pointer conversions,
6171   // we're done.
6172   if (!AllowObjCPointerConversion)
6173     return false;
6174
6175   // Is this an Objective-C pointer conversion?
6176   bool IncompatibleObjC = false;
6177   QualType ConvertedType;
6178   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6179                                    IncompatibleObjC);
6180 }
6181                                           
6182 /// AddConversionCandidate - Add a C++ conversion function as a
6183 /// candidate in the candidate set (C++ [over.match.conv],
6184 /// C++ [over.match.copy]). From is the expression we're converting from,
6185 /// and ToType is the type that we're eventually trying to convert to
6186 /// (which may or may not be the same type as the type that the
6187 /// conversion function produces).
6188 void
6189 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6190                              DeclAccessPair FoundDecl,
6191                              CXXRecordDecl *ActingContext,
6192                              Expr *From, QualType ToType,
6193                              OverloadCandidateSet& CandidateSet,
6194                              bool AllowObjCConversionOnExplicit) {
6195   assert(!Conversion->getDescribedFunctionTemplate() &&
6196          "Conversion function templates use AddTemplateConversionCandidate");
6197   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6198   if (!CandidateSet.isNewCandidate(Conversion))
6199     return;
6200
6201   // If the conversion function has an undeduced return type, trigger its
6202   // deduction now.
6203   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6204     if (DeduceReturnType(Conversion, From->getExprLoc()))
6205       return;
6206     ConvType = Conversion->getConversionType().getNonReferenceType();
6207   }
6208
6209   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6210   // operator is only a candidate if its return type is the target type or
6211   // can be converted to the target type with a qualification conversion.
6212   if (Conversion->isExplicit() && 
6213       !isAllowableExplicitConversion(*this, ConvType, ToType, 
6214                                      AllowObjCConversionOnExplicit))
6215     return;
6216
6217   // Overload resolution is always an unevaluated context.
6218   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6219
6220   // Add this candidate
6221   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6222   Candidate.FoundDecl = FoundDecl;
6223   Candidate.Function = Conversion;
6224   Candidate.IsSurrogate = false;
6225   Candidate.IgnoreObjectArgument = false;
6226   Candidate.FinalConversion.setAsIdentityConversion();
6227   Candidate.FinalConversion.setFromType(ConvType);
6228   Candidate.FinalConversion.setAllToTypes(ToType);
6229   Candidate.Viable = true;
6230   Candidate.ExplicitCallArguments = 1;
6231
6232   // C++ [over.match.funcs]p4:
6233   //   For conversion functions, the function is considered to be a member of
6234   //   the class of the implicit implied object argument for the purpose of
6235   //   defining the type of the implicit object parameter.
6236   //
6237   // Determine the implicit conversion sequence for the implicit
6238   // object parameter.
6239   QualType ImplicitParamType = From->getType();
6240   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6241     ImplicitParamType = FromPtrType->getPointeeType();
6242   CXXRecordDecl *ConversionContext
6243     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6244
6245   Candidate.Conversions[0]
6246     = TryObjectArgumentInitialization(*this, From->getType(),
6247                                       From->Classify(Context),
6248                                       Conversion, ConversionContext);
6249
6250   if (Candidate.Conversions[0].isBad()) {
6251     Candidate.Viable = false;
6252     Candidate.FailureKind = ovl_fail_bad_conversion;
6253     return;
6254   }
6255
6256   // We won't go through a user-defined type conversion function to convert a
6257   // derived to base as such conversions are given Conversion Rank. They only
6258   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6259   QualType FromCanon
6260     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6261   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6262   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6263     Candidate.Viable = false;
6264     Candidate.FailureKind = ovl_fail_trivial_conversion;
6265     return;
6266   }
6267
6268   // To determine what the conversion from the result of calling the
6269   // conversion function to the type we're eventually trying to
6270   // convert to (ToType), we need to synthesize a call to the
6271   // conversion function and attempt copy initialization from it. This
6272   // makes sure that we get the right semantics with respect to
6273   // lvalues/rvalues and the type. Fortunately, we can allocate this
6274   // call on the stack and we don't need its arguments to be
6275   // well-formed.
6276   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6277                             VK_LValue, From->getLocStart());
6278   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6279                                 Context.getPointerType(Conversion->getType()),
6280                                 CK_FunctionToPointerDecay,
6281                                 &ConversionRef, VK_RValue);
6282
6283   QualType ConversionType = Conversion->getConversionType();
6284   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
6285     Candidate.Viable = false;
6286     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6287     return;
6288   }
6289
6290   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6291
6292   // Note that it is safe to allocate CallExpr on the stack here because
6293   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6294   // allocator).
6295   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6296   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6297                 From->getLocStart());
6298   ImplicitConversionSequence ICS =
6299     TryCopyInitialization(*this, &Call, ToType,
6300                           /*SuppressUserConversions=*/true,
6301                           /*InOverloadResolution=*/false,
6302                           /*AllowObjCWritebackConversion=*/false);
6303
6304   switch (ICS.getKind()) {
6305   case ImplicitConversionSequence::StandardConversion:
6306     Candidate.FinalConversion = ICS.Standard;
6307
6308     // C++ [over.ics.user]p3:
6309     //   If the user-defined conversion is specified by a specialization of a
6310     //   conversion function template, the second standard conversion sequence
6311     //   shall have exact match rank.
6312     if (Conversion->getPrimaryTemplate() &&
6313         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6314       Candidate.Viable = false;
6315       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6316       return;
6317     }
6318
6319     // C++0x [dcl.init.ref]p5:
6320     //    In the second case, if the reference is an rvalue reference and
6321     //    the second standard conversion sequence of the user-defined
6322     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6323     //    program is ill-formed.
6324     if (ToType->isRValueReferenceType() &&
6325         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6326       Candidate.Viable = false;
6327       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6328       return;
6329     }
6330     break;
6331
6332   case ImplicitConversionSequence::BadConversion:
6333     Candidate.Viable = false;
6334     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6335     return;
6336
6337   default:
6338     llvm_unreachable(
6339            "Can only end up with a standard conversion sequence or failure");
6340   }
6341
6342   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6343     Candidate.Viable = false;
6344     Candidate.FailureKind = ovl_fail_enable_if;
6345     Candidate.DeductionFailure.Data = FailedAttr;
6346     return;
6347   }
6348 }
6349
6350 /// \brief Adds a conversion function template specialization
6351 /// candidate to the overload set, using template argument deduction
6352 /// to deduce the template arguments of the conversion function
6353 /// template from the type that we are converting to (C++
6354 /// [temp.deduct.conv]).
6355 void
6356 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6357                                      DeclAccessPair FoundDecl,
6358                                      CXXRecordDecl *ActingDC,
6359                                      Expr *From, QualType ToType,
6360                                      OverloadCandidateSet &CandidateSet,
6361                                      bool AllowObjCConversionOnExplicit) {
6362   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6363          "Only conversion function templates permitted here");
6364
6365   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6366     return;
6367
6368   TemplateDeductionInfo Info(CandidateSet.getLocation());
6369   CXXConversionDecl *Specialization = nullptr;
6370   if (TemplateDeductionResult Result
6371         = DeduceTemplateArguments(FunctionTemplate, ToType,
6372                                   Specialization, Info)) {
6373     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6374     Candidate.FoundDecl = FoundDecl;
6375     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6376     Candidate.Viable = false;
6377     Candidate.FailureKind = ovl_fail_bad_deduction;
6378     Candidate.IsSurrogate = false;
6379     Candidate.IgnoreObjectArgument = false;
6380     Candidate.ExplicitCallArguments = 1;
6381     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6382                                                           Info);
6383     return;
6384   }
6385
6386   // Add the conversion function template specialization produced by
6387   // template argument deduction as a candidate.
6388   assert(Specialization && "Missing function template specialization?");
6389   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6390                          CandidateSet, AllowObjCConversionOnExplicit);
6391 }
6392
6393 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6394 /// converts the given @c Object to a function pointer via the
6395 /// conversion function @c Conversion, and then attempts to call it
6396 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6397 /// the type of function that we'll eventually be calling.
6398 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6399                                  DeclAccessPair FoundDecl,
6400                                  CXXRecordDecl *ActingContext,
6401                                  const FunctionProtoType *Proto,
6402                                  Expr *Object,
6403                                  ArrayRef<Expr *> Args,
6404                                  OverloadCandidateSet& CandidateSet) {
6405   if (!CandidateSet.isNewCandidate(Conversion))
6406     return;
6407
6408   // Overload resolution is always an unevaluated context.
6409   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6410
6411   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6412   Candidate.FoundDecl = FoundDecl;
6413   Candidate.Function = nullptr;
6414   Candidate.Surrogate = Conversion;
6415   Candidate.Viable = true;
6416   Candidate.IsSurrogate = true;
6417   Candidate.IgnoreObjectArgument = false;
6418   Candidate.ExplicitCallArguments = Args.size();
6419
6420   // Determine the implicit conversion sequence for the implicit
6421   // object parameter.
6422   ImplicitConversionSequence ObjectInit
6423     = TryObjectArgumentInitialization(*this, Object->getType(),
6424                                       Object->Classify(Context),
6425                                       Conversion, ActingContext);
6426   if (ObjectInit.isBad()) {
6427     Candidate.Viable = false;
6428     Candidate.FailureKind = ovl_fail_bad_conversion;
6429     Candidate.Conversions[0] = ObjectInit;
6430     return;
6431   }
6432
6433   // The first conversion is actually a user-defined conversion whose
6434   // first conversion is ObjectInit's standard conversion (which is
6435   // effectively a reference binding). Record it as such.
6436   Candidate.Conversions[0].setUserDefined();
6437   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6438   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6439   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6440   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6441   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6442   Candidate.Conversions[0].UserDefined.After
6443     = Candidate.Conversions[0].UserDefined.Before;
6444   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6445
6446   // Find the
6447   unsigned NumParams = Proto->getNumParams();
6448
6449   // (C++ 13.3.2p2): A candidate function having fewer than m
6450   // parameters is viable only if it has an ellipsis in its parameter
6451   // list (8.3.5).
6452   if (Args.size() > NumParams && !Proto->isVariadic()) {
6453     Candidate.Viable = false;
6454     Candidate.FailureKind = ovl_fail_too_many_arguments;
6455     return;
6456   }
6457
6458   // Function types don't have any default arguments, so just check if
6459   // we have enough arguments.
6460   if (Args.size() < NumParams) {
6461     // Not enough arguments.
6462     Candidate.Viable = false;
6463     Candidate.FailureKind = ovl_fail_too_few_arguments;
6464     return;
6465   }
6466
6467   // Determine the implicit conversion sequences for each of the
6468   // arguments.
6469   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6470     if (ArgIdx < NumParams) {
6471       // (C++ 13.3.2p3): for F to be a viable function, there shall
6472       // exist for each argument an implicit conversion sequence
6473       // (13.3.3.1) that converts that argument to the corresponding
6474       // parameter of F.
6475       QualType ParamType = Proto->getParamType(ArgIdx);
6476       Candidate.Conversions[ArgIdx + 1]
6477         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6478                                 /*SuppressUserConversions=*/false,
6479                                 /*InOverloadResolution=*/false,
6480                                 /*AllowObjCWritebackConversion=*/
6481                                   getLangOpts().ObjCAutoRefCount);
6482       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6483         Candidate.Viable = false;
6484         Candidate.FailureKind = ovl_fail_bad_conversion;
6485         return;
6486       }
6487     } else {
6488       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6489       // argument for which there is no corresponding parameter is
6490       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6491       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6492     }
6493   }
6494
6495   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6496     Candidate.Viable = false;
6497     Candidate.FailureKind = ovl_fail_enable_if;
6498     Candidate.DeductionFailure.Data = FailedAttr;
6499     return;
6500   }
6501 }
6502
6503 /// \brief Add overload candidates for overloaded operators that are
6504 /// member functions.
6505 ///
6506 /// Add the overloaded operator candidates that are member functions
6507 /// for the operator Op that was used in an operator expression such
6508 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6509 /// CandidateSet will store the added overload candidates. (C++
6510 /// [over.match.oper]).
6511 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6512                                        SourceLocation OpLoc,
6513                                        ArrayRef<Expr *> Args,
6514                                        OverloadCandidateSet& CandidateSet,
6515                                        SourceRange OpRange) {
6516   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6517
6518   // C++ [over.match.oper]p3:
6519   //   For a unary operator @ with an operand of a type whose
6520   //   cv-unqualified version is T1, and for a binary operator @ with
6521   //   a left operand of a type whose cv-unqualified version is T1 and
6522   //   a right operand of a type whose cv-unqualified version is T2,
6523   //   three sets of candidate functions, designated member
6524   //   candidates, non-member candidates and built-in candidates, are
6525   //   constructed as follows:
6526   QualType T1 = Args[0]->getType();
6527
6528   //     -- If T1 is a complete class type or a class currently being
6529   //        defined, the set of member candidates is the result of the
6530   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6531   //        the set of member candidates is empty.
6532   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6533     // Complete the type if it can be completed.
6534     RequireCompleteType(OpLoc, T1, 0);
6535     // If the type is neither complete nor being defined, bail out now.
6536     if (!T1Rec->getDecl()->getDefinition())
6537       return;
6538
6539     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6540     LookupQualifiedName(Operators, T1Rec->getDecl());
6541     Operators.suppressDiagnostics();
6542
6543     for (LookupResult::iterator Oper = Operators.begin(),
6544                              OperEnd = Operators.end();
6545          Oper != OperEnd;
6546          ++Oper)
6547       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6548                          Args[0]->Classify(Context), 
6549                          Args.slice(1),
6550                          CandidateSet,
6551                          /* SuppressUserConversions = */ false);
6552   }
6553 }
6554
6555 /// AddBuiltinCandidate - Add a candidate for a built-in
6556 /// operator. ResultTy and ParamTys are the result and parameter types
6557 /// of the built-in candidate, respectively. Args and NumArgs are the
6558 /// arguments being passed to the candidate. IsAssignmentOperator
6559 /// should be true when this built-in candidate is an assignment
6560 /// operator. NumContextualBoolArguments is the number of arguments
6561 /// (at the beginning of the argument list) that will be contextually
6562 /// converted to bool.
6563 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6564                                ArrayRef<Expr *> Args,
6565                                OverloadCandidateSet& CandidateSet,
6566                                bool IsAssignmentOperator,
6567                                unsigned NumContextualBoolArguments) {
6568   // Overload resolution is always an unevaluated context.
6569   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6570
6571   // Add this candidate
6572   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6573   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6574   Candidate.Function = nullptr;
6575   Candidate.IsSurrogate = false;
6576   Candidate.IgnoreObjectArgument = false;
6577   Candidate.BuiltinTypes.ResultTy = ResultTy;
6578   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6579     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6580
6581   // Determine the implicit conversion sequences for each of the
6582   // arguments.
6583   Candidate.Viable = true;
6584   Candidate.ExplicitCallArguments = Args.size();
6585   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6586     // C++ [over.match.oper]p4:
6587     //   For the built-in assignment operators, conversions of the
6588     //   left operand are restricted as follows:
6589     //     -- no temporaries are introduced to hold the left operand, and
6590     //     -- no user-defined conversions are applied to the left
6591     //        operand to achieve a type match with the left-most
6592     //        parameter of a built-in candidate.
6593     //
6594     // We block these conversions by turning off user-defined
6595     // conversions, since that is the only way that initialization of
6596     // a reference to a non-class type can occur from something that
6597     // is not of the same type.
6598     if (ArgIdx < NumContextualBoolArguments) {
6599       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6600              "Contextual conversion to bool requires bool type");
6601       Candidate.Conversions[ArgIdx]
6602         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6603     } else {
6604       Candidate.Conversions[ArgIdx]
6605         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6606                                 ArgIdx == 0 && IsAssignmentOperator,
6607                                 /*InOverloadResolution=*/false,
6608                                 /*AllowObjCWritebackConversion=*/
6609                                   getLangOpts().ObjCAutoRefCount);
6610     }
6611     if (Candidate.Conversions[ArgIdx].isBad()) {
6612       Candidate.Viable = false;
6613       Candidate.FailureKind = ovl_fail_bad_conversion;
6614       break;
6615     }
6616   }
6617 }
6618
6619 namespace {
6620
6621 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6622 /// candidate operator functions for built-in operators (C++
6623 /// [over.built]). The types are separated into pointer types and
6624 /// enumeration types.
6625 class BuiltinCandidateTypeSet  {
6626   /// TypeSet - A set of types.
6627   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6628
6629   /// PointerTypes - The set of pointer types that will be used in the
6630   /// built-in candidates.
6631   TypeSet PointerTypes;
6632
6633   /// MemberPointerTypes - The set of member pointer types that will be
6634   /// used in the built-in candidates.
6635   TypeSet MemberPointerTypes;
6636
6637   /// EnumerationTypes - The set of enumeration types that will be
6638   /// used in the built-in candidates.
6639   TypeSet EnumerationTypes;
6640
6641   /// \brief The set of vector types that will be used in the built-in
6642   /// candidates.
6643   TypeSet VectorTypes;
6644
6645   /// \brief A flag indicating non-record types are viable candidates
6646   bool HasNonRecordTypes;
6647
6648   /// \brief A flag indicating whether either arithmetic or enumeration types
6649   /// were present in the candidate set.
6650   bool HasArithmeticOrEnumeralTypes;
6651
6652   /// \brief A flag indicating whether the nullptr type was present in the
6653   /// candidate set.
6654   bool HasNullPtrType;
6655   
6656   /// Sema - The semantic analysis instance where we are building the
6657   /// candidate type set.
6658   Sema &SemaRef;
6659
6660   /// Context - The AST context in which we will build the type sets.
6661   ASTContext &Context;
6662
6663   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6664                                                const Qualifiers &VisibleQuals);
6665   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6666
6667 public:
6668   /// iterator - Iterates through the types that are part of the set.
6669   typedef TypeSet::iterator iterator;
6670
6671   BuiltinCandidateTypeSet(Sema &SemaRef)
6672     : HasNonRecordTypes(false),
6673       HasArithmeticOrEnumeralTypes(false),
6674       HasNullPtrType(false),
6675       SemaRef(SemaRef),
6676       Context(SemaRef.Context) { }
6677
6678   void AddTypesConvertedFrom(QualType Ty,
6679                              SourceLocation Loc,
6680                              bool AllowUserConversions,
6681                              bool AllowExplicitConversions,
6682                              const Qualifiers &VisibleTypeConversionsQuals);
6683
6684   /// pointer_begin - First pointer type found;
6685   iterator pointer_begin() { return PointerTypes.begin(); }
6686
6687   /// pointer_end - Past the last pointer type found;
6688   iterator pointer_end() { return PointerTypes.end(); }
6689
6690   /// member_pointer_begin - First member pointer type found;
6691   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6692
6693   /// member_pointer_end - Past the last member pointer type found;
6694   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6695
6696   /// enumeration_begin - First enumeration type found;
6697   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6698
6699   /// enumeration_end - Past the last enumeration type found;
6700   iterator enumeration_end() { return EnumerationTypes.end(); }
6701
6702   iterator vector_begin() { return VectorTypes.begin(); }
6703   iterator vector_end() { return VectorTypes.end(); }
6704
6705   bool hasNonRecordTypes() { return HasNonRecordTypes; }
6706   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6707   bool hasNullPtrType() const { return HasNullPtrType; }
6708 };
6709
6710 } // end anonymous namespace
6711
6712 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6713 /// the set of pointer types along with any more-qualified variants of
6714 /// that type. For example, if @p Ty is "int const *", this routine
6715 /// will add "int const *", "int const volatile *", "int const
6716 /// restrict *", and "int const volatile restrict *" to the set of
6717 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6718 /// false otherwise.
6719 ///
6720 /// FIXME: what to do about extended qualifiers?
6721 bool
6722 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6723                                              const Qualifiers &VisibleQuals) {
6724
6725   // Insert this type.
6726   if (!PointerTypes.insert(Ty).second)
6727     return false;
6728
6729   QualType PointeeTy;
6730   const PointerType *PointerTy = Ty->getAs<PointerType>();
6731   bool buildObjCPtr = false;
6732   if (!PointerTy) {
6733     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6734     PointeeTy = PTy->getPointeeType();
6735     buildObjCPtr = true;
6736   } else {
6737     PointeeTy = PointerTy->getPointeeType();
6738   }
6739   
6740   // Don't add qualified variants of arrays. For one, they're not allowed
6741   // (the qualifier would sink to the element type), and for another, the
6742   // only overload situation where it matters is subscript or pointer +- int,
6743   // and those shouldn't have qualifier variants anyway.
6744   if (PointeeTy->isArrayType())
6745     return true;
6746   
6747   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6748   bool hasVolatile = VisibleQuals.hasVolatile();
6749   bool hasRestrict = VisibleQuals.hasRestrict();
6750
6751   // Iterate through all strict supersets of BaseCVR.
6752   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6753     if ((CVR | BaseCVR) != CVR) continue;
6754     // Skip over volatile if no volatile found anywhere in the types.
6755     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6756     
6757     // Skip over restrict if no restrict found anywhere in the types, or if
6758     // the type cannot be restrict-qualified.
6759     if ((CVR & Qualifiers::Restrict) &&
6760         (!hasRestrict ||
6761          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6762       continue;
6763   
6764     // Build qualified pointee type.
6765     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6766     
6767     // Build qualified pointer type.
6768     QualType QPointerTy;
6769     if (!buildObjCPtr)
6770       QPointerTy = Context.getPointerType(QPointeeTy);
6771     else
6772       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6773     
6774     // Insert qualified pointer type.
6775     PointerTypes.insert(QPointerTy);
6776   }
6777
6778   return true;
6779 }
6780
6781 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6782 /// to the set of pointer types along with any more-qualified variants of
6783 /// that type. For example, if @p Ty is "int const *", this routine
6784 /// will add "int const *", "int const volatile *", "int const
6785 /// restrict *", and "int const volatile restrict *" to the set of
6786 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6787 /// false otherwise.
6788 ///
6789 /// FIXME: what to do about extended qualifiers?
6790 bool
6791 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6792     QualType Ty) {
6793   // Insert this type.
6794   if (!MemberPointerTypes.insert(Ty).second)
6795     return false;
6796
6797   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6798   assert(PointerTy && "type was not a member pointer type!");
6799
6800   QualType PointeeTy = PointerTy->getPointeeType();
6801   // Don't add qualified variants of arrays. For one, they're not allowed
6802   // (the qualifier would sink to the element type), and for another, the
6803   // only overload situation where it matters is subscript or pointer +- int,
6804   // and those shouldn't have qualifier variants anyway.
6805   if (PointeeTy->isArrayType())
6806     return true;
6807   const Type *ClassTy = PointerTy->getClass();
6808
6809   // Iterate through all strict supersets of the pointee type's CVR
6810   // qualifiers.
6811   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6812   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6813     if ((CVR | BaseCVR) != CVR) continue;
6814
6815     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6816     MemberPointerTypes.insert(
6817       Context.getMemberPointerType(QPointeeTy, ClassTy));
6818   }
6819
6820   return true;
6821 }
6822
6823 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6824 /// Ty can be implicit converted to the given set of @p Types. We're
6825 /// primarily interested in pointer types and enumeration types. We also
6826 /// take member pointer types, for the conditional operator.
6827 /// AllowUserConversions is true if we should look at the conversion
6828 /// functions of a class type, and AllowExplicitConversions if we
6829 /// should also include the explicit conversion functions of a class
6830 /// type.
6831 void
6832 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6833                                                SourceLocation Loc,
6834                                                bool AllowUserConversions,
6835                                                bool AllowExplicitConversions,
6836                                                const Qualifiers &VisibleQuals) {
6837   // Only deal with canonical types.
6838   Ty = Context.getCanonicalType(Ty);
6839
6840   // Look through reference types; they aren't part of the type of an
6841   // expression for the purposes of conversions.
6842   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6843     Ty = RefTy->getPointeeType();
6844
6845   // If we're dealing with an array type, decay to the pointer.
6846   if (Ty->isArrayType())
6847     Ty = SemaRef.Context.getArrayDecayedType(Ty);
6848
6849   // Otherwise, we don't care about qualifiers on the type.
6850   Ty = Ty.getLocalUnqualifiedType();
6851
6852   // Flag if we ever add a non-record type.
6853   const RecordType *TyRec = Ty->getAs<RecordType>();
6854   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6855
6856   // Flag if we encounter an arithmetic type.
6857   HasArithmeticOrEnumeralTypes =
6858     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6859
6860   if (Ty->isObjCIdType() || Ty->isObjCClassType())
6861     PointerTypes.insert(Ty);
6862   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6863     // Insert our type, and its more-qualified variants, into the set
6864     // of types.
6865     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6866       return;
6867   } else if (Ty->isMemberPointerType()) {
6868     // Member pointers are far easier, since the pointee can't be converted.
6869     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6870       return;
6871   } else if (Ty->isEnumeralType()) {
6872     HasArithmeticOrEnumeralTypes = true;
6873     EnumerationTypes.insert(Ty);
6874   } else if (Ty->isVectorType()) {
6875     // We treat vector types as arithmetic types in many contexts as an
6876     // extension.
6877     HasArithmeticOrEnumeralTypes = true;
6878     VectorTypes.insert(Ty);
6879   } else if (Ty->isNullPtrType()) {
6880     HasNullPtrType = true;
6881   } else if (AllowUserConversions && TyRec) {
6882     // No conversion functions in incomplete types.
6883     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6884       return;
6885
6886     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6887     std::pair<CXXRecordDecl::conversion_iterator,
6888               CXXRecordDecl::conversion_iterator>
6889       Conversions = ClassDecl->getVisibleConversionFunctions();
6890     for (CXXRecordDecl::conversion_iterator
6891            I = Conversions.first, E = Conversions.second; I != E; ++I) {
6892       NamedDecl *D = I.getDecl();
6893       if (isa<UsingShadowDecl>(D))
6894         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6895
6896       // Skip conversion function templates; they don't tell us anything
6897       // about which builtin types we can convert to.
6898       if (isa<FunctionTemplateDecl>(D))
6899         continue;
6900
6901       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6902       if (AllowExplicitConversions || !Conv->isExplicit()) {
6903         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6904                               VisibleQuals);
6905       }
6906     }
6907   }
6908 }
6909
6910 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6911 /// the volatile- and non-volatile-qualified assignment operators for the
6912 /// given type to the candidate set.
6913 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6914                                                    QualType T,
6915                                                    ArrayRef<Expr *> Args,
6916                                     OverloadCandidateSet &CandidateSet) {
6917   QualType ParamTypes[2];
6918
6919   // T& operator=(T&, T)
6920   ParamTypes[0] = S.Context.getLValueReferenceType(T);
6921   ParamTypes[1] = T;
6922   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6923                         /*IsAssignmentOperator=*/true);
6924
6925   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6926     // volatile T& operator=(volatile T&, T)
6927     ParamTypes[0]
6928       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6929     ParamTypes[1] = T;
6930     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6931                           /*IsAssignmentOperator=*/true);
6932   }
6933 }
6934
6935 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6936 /// if any, found in visible type conversion functions found in ArgExpr's type.
6937 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6938     Qualifiers VRQuals;
6939     const RecordType *TyRec;
6940     if (const MemberPointerType *RHSMPType =
6941         ArgExpr->getType()->getAs<MemberPointerType>())
6942       TyRec = RHSMPType->getClass()->getAs<RecordType>();
6943     else
6944       TyRec = ArgExpr->getType()->getAs<RecordType>();
6945     if (!TyRec) {
6946       // Just to be safe, assume the worst case.
6947       VRQuals.addVolatile();
6948       VRQuals.addRestrict();
6949       return VRQuals;
6950     }
6951
6952     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6953     if (!ClassDecl->hasDefinition())
6954       return VRQuals;
6955
6956     std::pair<CXXRecordDecl::conversion_iterator,
6957               CXXRecordDecl::conversion_iterator>
6958       Conversions = ClassDecl->getVisibleConversionFunctions();
6959
6960     for (CXXRecordDecl::conversion_iterator
6961            I = Conversions.first, E = Conversions.second; I != E; ++I) {
6962       NamedDecl *D = I.getDecl();
6963       if (isa<UsingShadowDecl>(D))
6964         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6965       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6966         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6967         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6968           CanTy = ResTypeRef->getPointeeType();
6969         // Need to go down the pointer/mempointer chain and add qualifiers
6970         // as see them.
6971         bool done = false;
6972         while (!done) {
6973           if (CanTy.isRestrictQualified())
6974             VRQuals.addRestrict();
6975           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6976             CanTy = ResTypePtr->getPointeeType();
6977           else if (const MemberPointerType *ResTypeMPtr =
6978                 CanTy->getAs<MemberPointerType>())
6979             CanTy = ResTypeMPtr->getPointeeType();
6980           else
6981             done = true;
6982           if (CanTy.isVolatileQualified())
6983             VRQuals.addVolatile();
6984           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6985             return VRQuals;
6986         }
6987       }
6988     }
6989     return VRQuals;
6990 }
6991
6992 namespace {
6993
6994 /// \brief Helper class to manage the addition of builtin operator overload
6995 /// candidates. It provides shared state and utility methods used throughout
6996 /// the process, as well as a helper method to add each group of builtin
6997 /// operator overloads from the standard to a candidate set.
6998 class BuiltinOperatorOverloadBuilder {
6999   // Common instance state available to all overload candidate addition methods.
7000   Sema &S;
7001   ArrayRef<Expr *> Args;
7002   Qualifiers VisibleTypeConversionsQuals;
7003   bool HasArithmeticOrEnumeralCandidateType;
7004   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7005   OverloadCandidateSet &CandidateSet;
7006
7007   // Define some constants used to index and iterate over the arithemetic types
7008   // provided via the getArithmeticType() method below.
7009   // The "promoted arithmetic types" are the arithmetic
7010   // types are that preserved by promotion (C++ [over.built]p2).
7011   static const unsigned FirstIntegralType = 3;
7012   static const unsigned LastIntegralType = 20;
7013   static const unsigned FirstPromotedIntegralType = 3,
7014                         LastPromotedIntegralType = 11;
7015   static const unsigned FirstPromotedArithmeticType = 0,
7016                         LastPromotedArithmeticType = 11;
7017   static const unsigned NumArithmeticTypes = 20;
7018
7019   /// \brief Get the canonical type for a given arithmetic type index.
7020   CanQualType getArithmeticType(unsigned index) {
7021     assert(index < NumArithmeticTypes);
7022     static CanQualType ASTContext::* const
7023       ArithmeticTypes[NumArithmeticTypes] = {
7024       // Start of promoted types.
7025       &ASTContext::FloatTy,
7026       &ASTContext::DoubleTy,
7027       &ASTContext::LongDoubleTy,
7028
7029       // Start of integral types.
7030       &ASTContext::IntTy,
7031       &ASTContext::LongTy,
7032       &ASTContext::LongLongTy,
7033       &ASTContext::Int128Ty,
7034       &ASTContext::UnsignedIntTy,
7035       &ASTContext::UnsignedLongTy,
7036       &ASTContext::UnsignedLongLongTy,
7037       &ASTContext::UnsignedInt128Ty,
7038       // End of promoted types.
7039
7040       &ASTContext::BoolTy,
7041       &ASTContext::CharTy,
7042       &ASTContext::WCharTy,
7043       &ASTContext::Char16Ty,
7044       &ASTContext::Char32Ty,
7045       &ASTContext::SignedCharTy,
7046       &ASTContext::ShortTy,
7047       &ASTContext::UnsignedCharTy,
7048       &ASTContext::UnsignedShortTy,
7049       // End of integral types.
7050       // FIXME: What about complex? What about half?
7051     };
7052     return S.Context.*ArithmeticTypes[index];
7053   }
7054
7055   /// \brief Gets the canonical type resulting from the usual arithemetic
7056   /// converions for the given arithmetic types.
7057   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7058     // Accelerator table for performing the usual arithmetic conversions.
7059     // The rules are basically:
7060     //   - if either is floating-point, use the wider floating-point
7061     //   - if same signedness, use the higher rank
7062     //   - if same size, use unsigned of the higher rank
7063     //   - use the larger type
7064     // These rules, together with the axiom that higher ranks are
7065     // never smaller, are sufficient to precompute all of these results
7066     // *except* when dealing with signed types of higher rank.
7067     // (we could precompute SLL x UI for all known platforms, but it's
7068     // better not to make any assumptions).
7069     // We assume that int128 has a higher rank than long long on all platforms.
7070     enum PromotedType {
7071             Dep=-1,
7072             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
7073     };
7074     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7075                                         [LastPromotedArithmeticType] = {
7076 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
7077 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
7078 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7079 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
7080 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
7081 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
7082 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7083 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
7084 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
7085 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
7086 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7087     };
7088
7089     assert(L < LastPromotedArithmeticType);
7090     assert(R < LastPromotedArithmeticType);
7091     int Idx = ConversionsTable[L][R];
7092
7093     // Fast path: the table gives us a concrete answer.
7094     if (Idx != Dep) return getArithmeticType(Idx);
7095
7096     // Slow path: we need to compare widths.
7097     // An invariant is that the signed type has higher rank.
7098     CanQualType LT = getArithmeticType(L),
7099                 RT = getArithmeticType(R);
7100     unsigned LW = S.Context.getIntWidth(LT),
7101              RW = S.Context.getIntWidth(RT);
7102
7103     // If they're different widths, use the signed type.
7104     if (LW > RW) return LT;
7105     else if (LW < RW) return RT;
7106
7107     // Otherwise, use the unsigned type of the signed type's rank.
7108     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7109     assert(L == SLL || R == SLL);
7110     return S.Context.UnsignedLongLongTy;
7111   }
7112
7113   /// \brief Helper method to factor out the common pattern of adding overloads
7114   /// for '++' and '--' builtin operators.
7115   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7116                                            bool HasVolatile,
7117                                            bool HasRestrict) {
7118     QualType ParamTypes[2] = {
7119       S.Context.getLValueReferenceType(CandidateTy),
7120       S.Context.IntTy
7121     };
7122
7123     // Non-volatile version.
7124     if (Args.size() == 1)
7125       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7126     else
7127       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7128
7129     // Use a heuristic to reduce number of builtin candidates in the set:
7130     // add volatile version only if there are conversions to a volatile type.
7131     if (HasVolatile) {
7132       ParamTypes[0] =
7133         S.Context.getLValueReferenceType(
7134           S.Context.getVolatileType(CandidateTy));
7135       if (Args.size() == 1)
7136         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7137       else
7138         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7139     }
7140     
7141     // Add restrict version only if there are conversions to a restrict type
7142     // and our candidate type is a non-restrict-qualified pointer.
7143     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7144         !CandidateTy.isRestrictQualified()) {
7145       ParamTypes[0]
7146         = S.Context.getLValueReferenceType(
7147             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7148       if (Args.size() == 1)
7149         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7150       else
7151         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7152       
7153       if (HasVolatile) {
7154         ParamTypes[0]
7155           = S.Context.getLValueReferenceType(
7156               S.Context.getCVRQualifiedType(CandidateTy,
7157                                             (Qualifiers::Volatile |
7158                                              Qualifiers::Restrict)));
7159         if (Args.size() == 1)
7160           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7161         else
7162           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7163       }
7164     }
7165
7166   }
7167
7168 public:
7169   BuiltinOperatorOverloadBuilder(
7170     Sema &S, ArrayRef<Expr *> Args,
7171     Qualifiers VisibleTypeConversionsQuals,
7172     bool HasArithmeticOrEnumeralCandidateType,
7173     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7174     OverloadCandidateSet &CandidateSet)
7175     : S(S), Args(Args),
7176       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7177       HasArithmeticOrEnumeralCandidateType(
7178         HasArithmeticOrEnumeralCandidateType),
7179       CandidateTypes(CandidateTypes),
7180       CandidateSet(CandidateSet) {
7181     // Validate some of our static helper constants in debug builds.
7182     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7183            "Invalid first promoted integral type");
7184     assert(getArithmeticType(LastPromotedIntegralType - 1)
7185              == S.Context.UnsignedInt128Ty &&
7186            "Invalid last promoted integral type");
7187     assert(getArithmeticType(FirstPromotedArithmeticType)
7188              == S.Context.FloatTy &&
7189            "Invalid first promoted arithmetic type");
7190     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7191              == S.Context.UnsignedInt128Ty &&
7192            "Invalid last promoted arithmetic type");
7193   }
7194
7195   // C++ [over.built]p3:
7196   //
7197   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7198   //   is either volatile or empty, there exist candidate operator
7199   //   functions of the form
7200   //
7201   //       VQ T&      operator++(VQ T&);
7202   //       T          operator++(VQ T&, int);
7203   //
7204   // C++ [over.built]p4:
7205   //
7206   //   For every pair (T, VQ), where T is an arithmetic type other
7207   //   than bool, and VQ is either volatile or empty, there exist
7208   //   candidate operator functions of the form
7209   //
7210   //       VQ T&      operator--(VQ T&);
7211   //       T          operator--(VQ T&, int);
7212   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7213     if (!HasArithmeticOrEnumeralCandidateType)
7214       return;
7215
7216     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7217          Arith < NumArithmeticTypes; ++Arith) {
7218       addPlusPlusMinusMinusStyleOverloads(
7219         getArithmeticType(Arith),
7220         VisibleTypeConversionsQuals.hasVolatile(),
7221         VisibleTypeConversionsQuals.hasRestrict());
7222     }
7223   }
7224
7225   // C++ [over.built]p5:
7226   //
7227   //   For every pair (T, VQ), where T is a cv-qualified or
7228   //   cv-unqualified object type, and VQ is either volatile or
7229   //   empty, there exist candidate operator functions of the form
7230   //
7231   //       T*VQ&      operator++(T*VQ&);
7232   //       T*VQ&      operator--(T*VQ&);
7233   //       T*         operator++(T*VQ&, int);
7234   //       T*         operator--(T*VQ&, int);
7235   void addPlusPlusMinusMinusPointerOverloads() {
7236     for (BuiltinCandidateTypeSet::iterator
7237               Ptr = CandidateTypes[0].pointer_begin(),
7238            PtrEnd = CandidateTypes[0].pointer_end();
7239          Ptr != PtrEnd; ++Ptr) {
7240       // Skip pointer types that aren't pointers to object types.
7241       if (!(*Ptr)->getPointeeType()->isObjectType())
7242         continue;
7243
7244       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7245         (!(*Ptr).isVolatileQualified() &&
7246          VisibleTypeConversionsQuals.hasVolatile()),
7247         (!(*Ptr).isRestrictQualified() &&
7248          VisibleTypeConversionsQuals.hasRestrict()));
7249     }
7250   }
7251
7252   // C++ [over.built]p6:
7253   //   For every cv-qualified or cv-unqualified object type T, there
7254   //   exist candidate operator functions of the form
7255   //
7256   //       T&         operator*(T*);
7257   //
7258   // C++ [over.built]p7:
7259   //   For every function type T that does not have cv-qualifiers or a
7260   //   ref-qualifier, there exist candidate operator functions of the form
7261   //       T&         operator*(T*);
7262   void addUnaryStarPointerOverloads() {
7263     for (BuiltinCandidateTypeSet::iterator
7264               Ptr = CandidateTypes[0].pointer_begin(),
7265            PtrEnd = CandidateTypes[0].pointer_end();
7266          Ptr != PtrEnd; ++Ptr) {
7267       QualType ParamTy = *Ptr;
7268       QualType PointeeTy = ParamTy->getPointeeType();
7269       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7270         continue;
7271
7272       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7273         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7274           continue;
7275
7276       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7277                             &ParamTy, Args, CandidateSet);
7278     }
7279   }
7280
7281   // C++ [over.built]p9:
7282   //  For every promoted arithmetic type T, there exist candidate
7283   //  operator functions of the form
7284   //
7285   //       T         operator+(T);
7286   //       T         operator-(T);
7287   void addUnaryPlusOrMinusArithmeticOverloads() {
7288     if (!HasArithmeticOrEnumeralCandidateType)
7289       return;
7290
7291     for (unsigned Arith = FirstPromotedArithmeticType;
7292          Arith < LastPromotedArithmeticType; ++Arith) {
7293       QualType ArithTy = getArithmeticType(Arith);
7294       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7295     }
7296
7297     // Extension: We also add these operators for vector types.
7298     for (BuiltinCandidateTypeSet::iterator
7299               Vec = CandidateTypes[0].vector_begin(),
7300            VecEnd = CandidateTypes[0].vector_end();
7301          Vec != VecEnd; ++Vec) {
7302       QualType VecTy = *Vec;
7303       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7304     }
7305   }
7306
7307   // C++ [over.built]p8:
7308   //   For every type T, there exist candidate operator functions of
7309   //   the form
7310   //
7311   //       T*         operator+(T*);
7312   void addUnaryPlusPointerOverloads() {
7313     for (BuiltinCandidateTypeSet::iterator
7314               Ptr = CandidateTypes[0].pointer_begin(),
7315            PtrEnd = CandidateTypes[0].pointer_end();
7316          Ptr != PtrEnd; ++Ptr) {
7317       QualType ParamTy = *Ptr;
7318       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7319     }
7320   }
7321
7322   // C++ [over.built]p10:
7323   //   For every promoted integral type T, there exist candidate
7324   //   operator functions of the form
7325   //
7326   //        T         operator~(T);
7327   void addUnaryTildePromotedIntegralOverloads() {
7328     if (!HasArithmeticOrEnumeralCandidateType)
7329       return;
7330
7331     for (unsigned Int = FirstPromotedIntegralType;
7332          Int < LastPromotedIntegralType; ++Int) {
7333       QualType IntTy = getArithmeticType(Int);
7334       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7335     }
7336
7337     // Extension: We also add this operator for vector types.
7338     for (BuiltinCandidateTypeSet::iterator
7339               Vec = CandidateTypes[0].vector_begin(),
7340            VecEnd = CandidateTypes[0].vector_end();
7341          Vec != VecEnd; ++Vec) {
7342       QualType VecTy = *Vec;
7343       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7344     }
7345   }
7346
7347   // C++ [over.match.oper]p16:
7348   //   For every pointer to member type T, there exist candidate operator
7349   //   functions of the form
7350   //
7351   //        bool operator==(T,T);
7352   //        bool operator!=(T,T);
7353   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7354     /// Set of (canonical) types that we've already handled.
7355     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7356
7357     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7358       for (BuiltinCandidateTypeSet::iterator
7359                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7360              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7361            MemPtr != MemPtrEnd;
7362            ++MemPtr) {
7363         // Don't add the same builtin candidate twice.
7364         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7365           continue;
7366
7367         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7368         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7369       }
7370     }
7371   }
7372
7373   // C++ [over.built]p15:
7374   //
7375   //   For every T, where T is an enumeration type, a pointer type, or 
7376   //   std::nullptr_t, there exist candidate operator functions of the form
7377   //
7378   //        bool       operator<(T, T);
7379   //        bool       operator>(T, T);
7380   //        bool       operator<=(T, T);
7381   //        bool       operator>=(T, T);
7382   //        bool       operator==(T, T);
7383   //        bool       operator!=(T, T);
7384   void addRelationalPointerOrEnumeralOverloads() {
7385     // C++ [over.match.oper]p3:
7386     //   [...]the built-in candidates include all of the candidate operator
7387     //   functions defined in 13.6 that, compared to the given operator, [...]
7388     //   do not have the same parameter-type-list as any non-template non-member
7389     //   candidate.
7390     //
7391     // Note that in practice, this only affects enumeration types because there
7392     // aren't any built-in candidates of record type, and a user-defined operator
7393     // must have an operand of record or enumeration type. Also, the only other
7394     // overloaded operator with enumeration arguments, operator=,
7395     // cannot be overloaded for enumeration types, so this is the only place
7396     // where we must suppress candidates like this.
7397     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7398       UserDefinedBinaryOperators;
7399
7400     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7401       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7402           CandidateTypes[ArgIdx].enumeration_end()) {
7403         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7404                                          CEnd = CandidateSet.end();
7405              C != CEnd; ++C) {
7406           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7407             continue;
7408
7409           if (C->Function->isFunctionTemplateSpecialization())
7410             continue;
7411
7412           QualType FirstParamType =
7413             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7414           QualType SecondParamType =
7415             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7416
7417           // Skip if either parameter isn't of enumeral type.
7418           if (!FirstParamType->isEnumeralType() ||
7419               !SecondParamType->isEnumeralType())
7420             continue;
7421
7422           // Add this operator to the set of known user-defined operators.
7423           UserDefinedBinaryOperators.insert(
7424             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7425                            S.Context.getCanonicalType(SecondParamType)));
7426         }
7427       }
7428     }
7429
7430     /// Set of (canonical) types that we've already handled.
7431     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7432
7433     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7434       for (BuiltinCandidateTypeSet::iterator
7435                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7436              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7437            Ptr != PtrEnd; ++Ptr) {
7438         // Don't add the same builtin candidate twice.
7439         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7440           continue;
7441
7442         QualType ParamTypes[2] = { *Ptr, *Ptr };
7443         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7444       }
7445       for (BuiltinCandidateTypeSet::iterator
7446                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7447              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7448            Enum != EnumEnd; ++Enum) {
7449         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7450
7451         // Don't add the same builtin candidate twice, or if a user defined
7452         // candidate exists.
7453         if (!AddedTypes.insert(CanonType).second ||
7454             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7455                                                             CanonType)))
7456           continue;
7457
7458         QualType ParamTypes[2] = { *Enum, *Enum };
7459         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7460       }
7461       
7462       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7463         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7464         if (AddedTypes.insert(NullPtrTy).second &&
7465             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7466                                                              NullPtrTy))) {
7467           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7468           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7469                                 CandidateSet);
7470         }
7471       }
7472     }
7473   }
7474
7475   // C++ [over.built]p13:
7476   //
7477   //   For every cv-qualified or cv-unqualified object type T
7478   //   there exist candidate operator functions of the form
7479   //
7480   //      T*         operator+(T*, ptrdiff_t);
7481   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7482   //      T*         operator-(T*, ptrdiff_t);
7483   //      T*         operator+(ptrdiff_t, T*);
7484   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7485   //
7486   // C++ [over.built]p14:
7487   //
7488   //   For every T, where T is a pointer to object type, there
7489   //   exist candidate operator functions of the form
7490   //
7491   //      ptrdiff_t  operator-(T, T);
7492   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7493     /// Set of (canonical) types that we've already handled.
7494     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7495
7496     for (int Arg = 0; Arg < 2; ++Arg) {
7497       QualType AsymetricParamTypes[2] = {
7498         S.Context.getPointerDiffType(),
7499         S.Context.getPointerDiffType(),
7500       };
7501       for (BuiltinCandidateTypeSet::iterator
7502                 Ptr = CandidateTypes[Arg].pointer_begin(),
7503              PtrEnd = CandidateTypes[Arg].pointer_end();
7504            Ptr != PtrEnd; ++Ptr) {
7505         QualType PointeeTy = (*Ptr)->getPointeeType();
7506         if (!PointeeTy->isObjectType())
7507           continue;
7508
7509         AsymetricParamTypes[Arg] = *Ptr;
7510         if (Arg == 0 || Op == OO_Plus) {
7511           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7512           // T* operator+(ptrdiff_t, T*);
7513           S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7514         }
7515         if (Op == OO_Minus) {
7516           // ptrdiff_t operator-(T, T);
7517           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7518             continue;
7519
7520           QualType ParamTypes[2] = { *Ptr, *Ptr };
7521           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7522                                 Args, CandidateSet);
7523         }
7524       }
7525     }
7526   }
7527
7528   // C++ [over.built]p12:
7529   //
7530   //   For every pair of promoted arithmetic types L and R, there
7531   //   exist candidate operator functions of the form
7532   //
7533   //        LR         operator*(L, R);
7534   //        LR         operator/(L, R);
7535   //        LR         operator+(L, R);
7536   //        LR         operator-(L, R);
7537   //        bool       operator<(L, R);
7538   //        bool       operator>(L, R);
7539   //        bool       operator<=(L, R);
7540   //        bool       operator>=(L, R);
7541   //        bool       operator==(L, R);
7542   //        bool       operator!=(L, R);
7543   //
7544   //   where LR is the result of the usual arithmetic conversions
7545   //   between types L and R.
7546   //
7547   // C++ [over.built]p24:
7548   //
7549   //   For every pair of promoted arithmetic types L and R, there exist
7550   //   candidate operator functions of the form
7551   //
7552   //        LR       operator?(bool, L, R);
7553   //
7554   //   where LR is the result of the usual arithmetic conversions
7555   //   between types L and R.
7556   // Our candidates ignore the first parameter.
7557   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7558     if (!HasArithmeticOrEnumeralCandidateType)
7559       return;
7560
7561     for (unsigned Left = FirstPromotedArithmeticType;
7562          Left < LastPromotedArithmeticType; ++Left) {
7563       for (unsigned Right = FirstPromotedArithmeticType;
7564            Right < LastPromotedArithmeticType; ++Right) {
7565         QualType LandR[2] = { getArithmeticType(Left),
7566                               getArithmeticType(Right) };
7567         QualType Result =
7568           isComparison ? S.Context.BoolTy
7569                        : getUsualArithmeticConversions(Left, Right);
7570         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7571       }
7572     }
7573
7574     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7575     // conditional operator for vector types.
7576     for (BuiltinCandidateTypeSet::iterator
7577               Vec1 = CandidateTypes[0].vector_begin(),
7578            Vec1End = CandidateTypes[0].vector_end();
7579          Vec1 != Vec1End; ++Vec1) {
7580       for (BuiltinCandidateTypeSet::iterator
7581                 Vec2 = CandidateTypes[1].vector_begin(),
7582              Vec2End = CandidateTypes[1].vector_end();
7583            Vec2 != Vec2End; ++Vec2) {
7584         QualType LandR[2] = { *Vec1, *Vec2 };
7585         QualType Result = S.Context.BoolTy;
7586         if (!isComparison) {
7587           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7588             Result = *Vec1;
7589           else
7590             Result = *Vec2;
7591         }
7592
7593         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7594       }
7595     }
7596   }
7597
7598   // C++ [over.built]p17:
7599   //
7600   //   For every pair of promoted integral types L and R, there
7601   //   exist candidate operator functions of the form
7602   //
7603   //      LR         operator%(L, R);
7604   //      LR         operator&(L, R);
7605   //      LR         operator^(L, R);
7606   //      LR         operator|(L, R);
7607   //      L          operator<<(L, R);
7608   //      L          operator>>(L, R);
7609   //
7610   //   where LR is the result of the usual arithmetic conversions
7611   //   between types L and R.
7612   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7613     if (!HasArithmeticOrEnumeralCandidateType)
7614       return;
7615
7616     for (unsigned Left = FirstPromotedIntegralType;
7617          Left < LastPromotedIntegralType; ++Left) {
7618       for (unsigned Right = FirstPromotedIntegralType;
7619            Right < LastPromotedIntegralType; ++Right) {
7620         QualType LandR[2] = { getArithmeticType(Left),
7621                               getArithmeticType(Right) };
7622         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7623             ? LandR[0]
7624             : getUsualArithmeticConversions(Left, Right);
7625         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7626       }
7627     }
7628   }
7629
7630   // C++ [over.built]p20:
7631   //
7632   //   For every pair (T, VQ), where T is an enumeration or
7633   //   pointer to member type and VQ is either volatile or
7634   //   empty, there exist candidate operator functions of the form
7635   //
7636   //        VQ T&      operator=(VQ T&, T);
7637   void addAssignmentMemberPointerOrEnumeralOverloads() {
7638     /// Set of (canonical) types that we've already handled.
7639     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7640
7641     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7642       for (BuiltinCandidateTypeSet::iterator
7643                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7644              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7645            Enum != EnumEnd; ++Enum) {
7646         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7647           continue;
7648
7649         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7650       }
7651
7652       for (BuiltinCandidateTypeSet::iterator
7653                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7654              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7655            MemPtr != MemPtrEnd; ++MemPtr) {
7656         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7657           continue;
7658
7659         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7660       }
7661     }
7662   }
7663
7664   // C++ [over.built]p19:
7665   //
7666   //   For every pair (T, VQ), where T is any type and VQ is either
7667   //   volatile or empty, there exist candidate operator functions
7668   //   of the form
7669   //
7670   //        T*VQ&      operator=(T*VQ&, T*);
7671   //
7672   // C++ [over.built]p21:
7673   //
7674   //   For every pair (T, VQ), where T is a cv-qualified or
7675   //   cv-unqualified object type and VQ is either volatile or
7676   //   empty, there exist candidate operator functions of the form
7677   //
7678   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7679   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
7680   void addAssignmentPointerOverloads(bool isEqualOp) {
7681     /// Set of (canonical) types that we've already handled.
7682     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7683
7684     for (BuiltinCandidateTypeSet::iterator
7685               Ptr = CandidateTypes[0].pointer_begin(),
7686            PtrEnd = CandidateTypes[0].pointer_end();
7687          Ptr != PtrEnd; ++Ptr) {
7688       // If this is operator=, keep track of the builtin candidates we added.
7689       if (isEqualOp)
7690         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7691       else if (!(*Ptr)->getPointeeType()->isObjectType())
7692         continue;
7693
7694       // non-volatile version
7695       QualType ParamTypes[2] = {
7696         S.Context.getLValueReferenceType(*Ptr),
7697         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7698       };
7699       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7700                             /*IsAssigmentOperator=*/ isEqualOp);
7701
7702       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7703                           VisibleTypeConversionsQuals.hasVolatile();
7704       if (NeedVolatile) {
7705         // volatile version
7706         ParamTypes[0] =
7707           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7708         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7709                               /*IsAssigmentOperator=*/isEqualOp);
7710       }
7711       
7712       if (!(*Ptr).isRestrictQualified() &&
7713           VisibleTypeConversionsQuals.hasRestrict()) {
7714         // restrict version
7715         ParamTypes[0]
7716           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7717         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7718                               /*IsAssigmentOperator=*/isEqualOp);
7719         
7720         if (NeedVolatile) {
7721           // volatile restrict version
7722           ParamTypes[0]
7723             = S.Context.getLValueReferenceType(
7724                 S.Context.getCVRQualifiedType(*Ptr,
7725                                               (Qualifiers::Volatile |
7726                                                Qualifiers::Restrict)));
7727           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7728                                 /*IsAssigmentOperator=*/isEqualOp);
7729         }
7730       }
7731     }
7732
7733     if (isEqualOp) {
7734       for (BuiltinCandidateTypeSet::iterator
7735                 Ptr = CandidateTypes[1].pointer_begin(),
7736              PtrEnd = CandidateTypes[1].pointer_end();
7737            Ptr != PtrEnd; ++Ptr) {
7738         // Make sure we don't add the same candidate twice.
7739         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7740           continue;
7741
7742         QualType ParamTypes[2] = {
7743           S.Context.getLValueReferenceType(*Ptr),
7744           *Ptr,
7745         };
7746
7747         // non-volatile version
7748         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7749                               /*IsAssigmentOperator=*/true);
7750
7751         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7752                            VisibleTypeConversionsQuals.hasVolatile();
7753         if (NeedVolatile) {
7754           // volatile version
7755           ParamTypes[0] =
7756             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7757           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7758                                 /*IsAssigmentOperator=*/true);
7759         }
7760       
7761         if (!(*Ptr).isRestrictQualified() &&
7762             VisibleTypeConversionsQuals.hasRestrict()) {
7763           // restrict version
7764           ParamTypes[0]
7765             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7766           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7767                                 /*IsAssigmentOperator=*/true);
7768           
7769           if (NeedVolatile) {
7770             // volatile restrict version
7771             ParamTypes[0]
7772               = S.Context.getLValueReferenceType(
7773                   S.Context.getCVRQualifiedType(*Ptr,
7774                                                 (Qualifiers::Volatile |
7775                                                  Qualifiers::Restrict)));
7776             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7777                                   /*IsAssigmentOperator=*/true);
7778           }
7779         }
7780       }
7781     }
7782   }
7783
7784   // C++ [over.built]p18:
7785   //
7786   //   For every triple (L, VQ, R), where L is an arithmetic type,
7787   //   VQ is either volatile or empty, and R is a promoted
7788   //   arithmetic type, there exist candidate operator functions of
7789   //   the form
7790   //
7791   //        VQ L&      operator=(VQ L&, R);
7792   //        VQ L&      operator*=(VQ L&, R);
7793   //        VQ L&      operator/=(VQ L&, R);
7794   //        VQ L&      operator+=(VQ L&, R);
7795   //        VQ L&      operator-=(VQ L&, R);
7796   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7797     if (!HasArithmeticOrEnumeralCandidateType)
7798       return;
7799
7800     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7801       for (unsigned Right = FirstPromotedArithmeticType;
7802            Right < LastPromotedArithmeticType; ++Right) {
7803         QualType ParamTypes[2];
7804         ParamTypes[1] = getArithmeticType(Right);
7805
7806         // Add this built-in operator as a candidate (VQ is empty).
7807         ParamTypes[0] =
7808           S.Context.getLValueReferenceType(getArithmeticType(Left));
7809         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7810                               /*IsAssigmentOperator=*/isEqualOp);
7811
7812         // Add this built-in operator as a candidate (VQ is 'volatile').
7813         if (VisibleTypeConversionsQuals.hasVolatile()) {
7814           ParamTypes[0] =
7815             S.Context.getVolatileType(getArithmeticType(Left));
7816           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7817           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7818                                 /*IsAssigmentOperator=*/isEqualOp);
7819         }
7820       }
7821     }
7822
7823     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7824     for (BuiltinCandidateTypeSet::iterator
7825               Vec1 = CandidateTypes[0].vector_begin(),
7826            Vec1End = CandidateTypes[0].vector_end();
7827          Vec1 != Vec1End; ++Vec1) {
7828       for (BuiltinCandidateTypeSet::iterator
7829                 Vec2 = CandidateTypes[1].vector_begin(),
7830              Vec2End = CandidateTypes[1].vector_end();
7831            Vec2 != Vec2End; ++Vec2) {
7832         QualType ParamTypes[2];
7833         ParamTypes[1] = *Vec2;
7834         // Add this built-in operator as a candidate (VQ is empty).
7835         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7836         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7837                               /*IsAssigmentOperator=*/isEqualOp);
7838
7839         // Add this built-in operator as a candidate (VQ is 'volatile').
7840         if (VisibleTypeConversionsQuals.hasVolatile()) {
7841           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7842           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7843           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7844                                 /*IsAssigmentOperator=*/isEqualOp);
7845         }
7846       }
7847     }
7848   }
7849
7850   // C++ [over.built]p22:
7851   //
7852   //   For every triple (L, VQ, R), where L is an integral type, VQ
7853   //   is either volatile or empty, and R is a promoted integral
7854   //   type, there exist candidate operator functions of the form
7855   //
7856   //        VQ L&       operator%=(VQ L&, R);
7857   //        VQ L&       operator<<=(VQ L&, R);
7858   //        VQ L&       operator>>=(VQ L&, R);
7859   //        VQ L&       operator&=(VQ L&, R);
7860   //        VQ L&       operator^=(VQ L&, R);
7861   //        VQ L&       operator|=(VQ L&, R);
7862   void addAssignmentIntegralOverloads() {
7863     if (!HasArithmeticOrEnumeralCandidateType)
7864       return;
7865
7866     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7867       for (unsigned Right = FirstPromotedIntegralType;
7868            Right < LastPromotedIntegralType; ++Right) {
7869         QualType ParamTypes[2];
7870         ParamTypes[1] = getArithmeticType(Right);
7871
7872         // Add this built-in operator as a candidate (VQ is empty).
7873         ParamTypes[0] =
7874           S.Context.getLValueReferenceType(getArithmeticType(Left));
7875         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7876         if (VisibleTypeConversionsQuals.hasVolatile()) {
7877           // Add this built-in operator as a candidate (VQ is 'volatile').
7878           ParamTypes[0] = getArithmeticType(Left);
7879           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7880           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7881           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7882         }
7883       }
7884     }
7885   }
7886
7887   // C++ [over.operator]p23:
7888   //
7889   //   There also exist candidate operator functions of the form
7890   //
7891   //        bool        operator!(bool);
7892   //        bool        operator&&(bool, bool);
7893   //        bool        operator||(bool, bool);
7894   void addExclaimOverload() {
7895     QualType ParamTy = S.Context.BoolTy;
7896     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7897                           /*IsAssignmentOperator=*/false,
7898                           /*NumContextualBoolArguments=*/1);
7899   }
7900   void addAmpAmpOrPipePipeOverload() {
7901     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7902     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7903                           /*IsAssignmentOperator=*/false,
7904                           /*NumContextualBoolArguments=*/2);
7905   }
7906
7907   // C++ [over.built]p13:
7908   //
7909   //   For every cv-qualified or cv-unqualified object type T there
7910   //   exist candidate operator functions of the form
7911   //
7912   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7913   //        T&         operator[](T*, ptrdiff_t);
7914   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7915   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7916   //        T&         operator[](ptrdiff_t, T*);
7917   void addSubscriptOverloads() {
7918     for (BuiltinCandidateTypeSet::iterator
7919               Ptr = CandidateTypes[0].pointer_begin(),
7920            PtrEnd = CandidateTypes[0].pointer_end();
7921          Ptr != PtrEnd; ++Ptr) {
7922       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7923       QualType PointeeType = (*Ptr)->getPointeeType();
7924       if (!PointeeType->isObjectType())
7925         continue;
7926
7927       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7928
7929       // T& operator[](T*, ptrdiff_t)
7930       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7931     }
7932
7933     for (BuiltinCandidateTypeSet::iterator
7934               Ptr = CandidateTypes[1].pointer_begin(),
7935            PtrEnd = CandidateTypes[1].pointer_end();
7936          Ptr != PtrEnd; ++Ptr) {
7937       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7938       QualType PointeeType = (*Ptr)->getPointeeType();
7939       if (!PointeeType->isObjectType())
7940         continue;
7941
7942       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7943
7944       // T& operator[](ptrdiff_t, T*)
7945       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7946     }
7947   }
7948
7949   // C++ [over.built]p11:
7950   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7951   //    C1 is the same type as C2 or is a derived class of C2, T is an object
7952   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7953   //    there exist candidate operator functions of the form
7954   //
7955   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7956   //
7957   //    where CV12 is the union of CV1 and CV2.
7958   void addArrowStarOverloads() {
7959     for (BuiltinCandidateTypeSet::iterator
7960              Ptr = CandidateTypes[0].pointer_begin(),
7961            PtrEnd = CandidateTypes[0].pointer_end();
7962          Ptr != PtrEnd; ++Ptr) {
7963       QualType C1Ty = (*Ptr);
7964       QualType C1;
7965       QualifierCollector Q1;
7966       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7967       if (!isa<RecordType>(C1))
7968         continue;
7969       // heuristic to reduce number of builtin candidates in the set.
7970       // Add volatile/restrict version only if there are conversions to a
7971       // volatile/restrict type.
7972       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7973         continue;
7974       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7975         continue;
7976       for (BuiltinCandidateTypeSet::iterator
7977                 MemPtr = CandidateTypes[1].member_pointer_begin(),
7978              MemPtrEnd = CandidateTypes[1].member_pointer_end();
7979            MemPtr != MemPtrEnd; ++MemPtr) {
7980         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7981         QualType C2 = QualType(mptr->getClass(), 0);
7982         C2 = C2.getUnqualifiedType();
7983         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7984           break;
7985         QualType ParamTypes[2] = { *Ptr, *MemPtr };
7986         // build CV12 T&
7987         QualType T = mptr->getPointeeType();
7988         if (!VisibleTypeConversionsQuals.hasVolatile() &&
7989             T.isVolatileQualified())
7990           continue;
7991         if (!VisibleTypeConversionsQuals.hasRestrict() &&
7992             T.isRestrictQualified())
7993           continue;
7994         T = Q1.apply(S.Context, T);
7995         QualType ResultTy = S.Context.getLValueReferenceType(T);
7996         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7997       }
7998     }
7999   }
8000
8001   // Note that we don't consider the first argument, since it has been
8002   // contextually converted to bool long ago. The candidates below are
8003   // therefore added as binary.
8004   //
8005   // C++ [over.built]p25:
8006   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8007   //   enumeration type, there exist candidate operator functions of the form
8008   //
8009   //        T        operator?(bool, T, T);
8010   //
8011   void addConditionalOperatorOverloads() {
8012     /// Set of (canonical) types that we've already handled.
8013     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8014
8015     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8016       for (BuiltinCandidateTypeSet::iterator
8017                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8018              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8019            Ptr != PtrEnd; ++Ptr) {
8020         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8021           continue;
8022
8023         QualType ParamTypes[2] = { *Ptr, *Ptr };
8024         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8025       }
8026
8027       for (BuiltinCandidateTypeSet::iterator
8028                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8029              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8030            MemPtr != MemPtrEnd; ++MemPtr) {
8031         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8032           continue;
8033
8034         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8035         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8036       }
8037
8038       if (S.getLangOpts().CPlusPlus11) {
8039         for (BuiltinCandidateTypeSet::iterator
8040                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8041                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8042              Enum != EnumEnd; ++Enum) {
8043           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8044             continue;
8045
8046           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8047             continue;
8048
8049           QualType ParamTypes[2] = { *Enum, *Enum };
8050           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8051         }
8052       }
8053     }
8054   }
8055 };
8056
8057 } // end anonymous namespace
8058
8059 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8060 /// operator overloads to the candidate set (C++ [over.built]), based
8061 /// on the operator @p Op and the arguments given. For example, if the
8062 /// operator is a binary '+', this routine might add "int
8063 /// operator+(int, int)" to cover integer addition.
8064 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8065                                         SourceLocation OpLoc,
8066                                         ArrayRef<Expr *> Args,
8067                                         OverloadCandidateSet &CandidateSet) {
8068   // Find all of the types that the arguments can convert to, but only
8069   // if the operator we're looking at has built-in operator candidates
8070   // that make use of these types. Also record whether we encounter non-record
8071   // candidate types or either arithmetic or enumeral candidate types.
8072   Qualifiers VisibleTypeConversionsQuals;
8073   VisibleTypeConversionsQuals.addConst();
8074   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8075     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8076
8077   bool HasNonRecordCandidateType = false;
8078   bool HasArithmeticOrEnumeralCandidateType = false;
8079   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8080   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8081     CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
8082     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8083                                                  OpLoc,
8084                                                  true,
8085                                                  (Op == OO_Exclaim ||
8086                                                   Op == OO_AmpAmp ||
8087                                                   Op == OO_PipePipe),
8088                                                  VisibleTypeConversionsQuals);
8089     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8090         CandidateTypes[ArgIdx].hasNonRecordTypes();
8091     HasArithmeticOrEnumeralCandidateType =
8092         HasArithmeticOrEnumeralCandidateType ||
8093         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8094   }
8095
8096   // Exit early when no non-record types have been added to the candidate set
8097   // for any of the arguments to the operator.
8098   //
8099   // We can't exit early for !, ||, or &&, since there we have always have
8100   // 'bool' overloads.
8101   if (!HasNonRecordCandidateType &&
8102       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8103     return;
8104
8105   // Setup an object to manage the common state for building overloads.
8106   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8107                                            VisibleTypeConversionsQuals,
8108                                            HasArithmeticOrEnumeralCandidateType,
8109                                            CandidateTypes, CandidateSet);
8110
8111   // Dispatch over the operation to add in only those overloads which apply.
8112   switch (Op) {
8113   case OO_None:
8114   case NUM_OVERLOADED_OPERATORS:
8115     llvm_unreachable("Expected an overloaded operator");
8116
8117   case OO_New:
8118   case OO_Delete:
8119   case OO_Array_New:
8120   case OO_Array_Delete:
8121   case OO_Call:
8122     llvm_unreachable(
8123                     "Special operators don't use AddBuiltinOperatorCandidates");
8124
8125   case OO_Comma:
8126   case OO_Arrow:
8127     // C++ [over.match.oper]p3:
8128     //   -- For the operator ',', the unary operator '&', or the
8129     //      operator '->', the built-in candidates set is empty.
8130     break;
8131
8132   case OO_Plus: // '+' is either unary or binary
8133     if (Args.size() == 1)
8134       OpBuilder.addUnaryPlusPointerOverloads();
8135     // Fall through.
8136
8137   case OO_Minus: // '-' is either unary or binary
8138     if (Args.size() == 1) {
8139       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8140     } else {
8141       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8142       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8143     }
8144     break;
8145
8146   case OO_Star: // '*' is either unary or binary
8147     if (Args.size() == 1)
8148       OpBuilder.addUnaryStarPointerOverloads();
8149     else
8150       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8151     break;
8152
8153   case OO_Slash:
8154     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8155     break;
8156
8157   case OO_PlusPlus:
8158   case OO_MinusMinus:
8159     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8160     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8161     break;
8162
8163   case OO_EqualEqual:
8164   case OO_ExclaimEqual:
8165     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8166     // Fall through.
8167
8168   case OO_Less:
8169   case OO_Greater:
8170   case OO_LessEqual:
8171   case OO_GreaterEqual:
8172     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8173     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8174     break;
8175
8176   case OO_Percent:
8177   case OO_Caret:
8178   case OO_Pipe:
8179   case OO_LessLess:
8180   case OO_GreaterGreater:
8181     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8182     break;
8183
8184   case OO_Amp: // '&' is either unary or binary
8185     if (Args.size() == 1)
8186       // C++ [over.match.oper]p3:
8187       //   -- For the operator ',', the unary operator '&', or the
8188       //      operator '->', the built-in candidates set is empty.
8189       break;
8190
8191     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8192     break;
8193
8194   case OO_Tilde:
8195     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8196     break;
8197
8198   case OO_Equal:
8199     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8200     // Fall through.
8201
8202   case OO_PlusEqual:
8203   case OO_MinusEqual:
8204     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8205     // Fall through.
8206
8207   case OO_StarEqual:
8208   case OO_SlashEqual:
8209     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8210     break;
8211
8212   case OO_PercentEqual:
8213   case OO_LessLessEqual:
8214   case OO_GreaterGreaterEqual:
8215   case OO_AmpEqual:
8216   case OO_CaretEqual:
8217   case OO_PipeEqual:
8218     OpBuilder.addAssignmentIntegralOverloads();
8219     break;
8220
8221   case OO_Exclaim:
8222     OpBuilder.addExclaimOverload();
8223     break;
8224
8225   case OO_AmpAmp:
8226   case OO_PipePipe:
8227     OpBuilder.addAmpAmpOrPipePipeOverload();
8228     break;
8229
8230   case OO_Subscript:
8231     OpBuilder.addSubscriptOverloads();
8232     break;
8233
8234   case OO_ArrowStar:
8235     OpBuilder.addArrowStarOverloads();
8236     break;
8237
8238   case OO_Conditional:
8239     OpBuilder.addConditionalOperatorOverloads();
8240     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8241     break;
8242   }
8243 }
8244
8245 /// \brief Add function candidates found via argument-dependent lookup
8246 /// to the set of overloading candidates.
8247 ///
8248 /// This routine performs argument-dependent name lookup based on the
8249 /// given function name (which may also be an operator name) and adds
8250 /// all of the overload candidates found by ADL to the overload
8251 /// candidate set (C++ [basic.lookup.argdep]).
8252 void
8253 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8254                                            SourceLocation Loc,
8255                                            ArrayRef<Expr *> Args,
8256                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8257                                            OverloadCandidateSet& CandidateSet,
8258                                            bool PartialOverloading) {
8259   ADLResult Fns;
8260
8261   // FIXME: This approach for uniquing ADL results (and removing
8262   // redundant candidates from the set) relies on pointer-equality,
8263   // which means we need to key off the canonical decl.  However,
8264   // always going back to the canonical decl might not get us the
8265   // right set of default arguments.  What default arguments are
8266   // we supposed to consider on ADL candidates, anyway?
8267
8268   // FIXME: Pass in the explicit template arguments?
8269   ArgumentDependentLookup(Name, Loc, Args, Fns);
8270
8271   // Erase all of the candidates we already knew about.
8272   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8273                                    CandEnd = CandidateSet.end();
8274        Cand != CandEnd; ++Cand)
8275     if (Cand->Function) {
8276       Fns.erase(Cand->Function);
8277       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8278         Fns.erase(FunTmpl);
8279     }
8280
8281   // For each of the ADL candidates we found, add it to the overload
8282   // set.
8283   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8284     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8285     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8286       if (ExplicitTemplateArgs)
8287         continue;
8288
8289       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8290                            PartialOverloading);
8291     } else
8292       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8293                                    FoundDecl, ExplicitTemplateArgs,
8294                                    Args, CandidateSet);
8295   }
8296 }
8297
8298 /// isBetterOverloadCandidate - Determines whether the first overload
8299 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8300 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8301                                       const OverloadCandidate &Cand2,
8302                                       SourceLocation Loc,
8303                                       bool UserDefinedConversion) {
8304   // Define viable functions to be better candidates than non-viable
8305   // functions.
8306   if (!Cand2.Viable)
8307     return Cand1.Viable;
8308   else if (!Cand1.Viable)
8309     return false;
8310
8311   // C++ [over.match.best]p1:
8312   //
8313   //   -- if F is a static member function, ICS1(F) is defined such
8314   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8315   //      any function G, and, symmetrically, ICS1(G) is neither
8316   //      better nor worse than ICS1(F).
8317   unsigned StartArg = 0;
8318   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8319     StartArg = 1;
8320
8321   // C++ [over.match.best]p1:
8322   //   A viable function F1 is defined to be a better function than another
8323   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8324   //   conversion sequence than ICSi(F2), and then...
8325   unsigned NumArgs = Cand1.NumConversions;
8326   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8327   bool HasBetterConversion = false;
8328   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8329     switch (CompareImplicitConversionSequences(S,
8330                                                Cand1.Conversions[ArgIdx],
8331                                                Cand2.Conversions[ArgIdx])) {
8332     case ImplicitConversionSequence::Better:
8333       // Cand1 has a better conversion sequence.
8334       HasBetterConversion = true;
8335       break;
8336
8337     case ImplicitConversionSequence::Worse:
8338       // Cand1 can't be better than Cand2.
8339       return false;
8340
8341     case ImplicitConversionSequence::Indistinguishable:
8342       // Do nothing.
8343       break;
8344     }
8345   }
8346
8347   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8348   //       ICSj(F2), or, if not that,
8349   if (HasBetterConversion)
8350     return true;
8351
8352   //   -- the context is an initialization by user-defined conversion
8353   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8354   //      from the return type of F1 to the destination type (i.e.,
8355   //      the type of the entity being initialized) is a better
8356   //      conversion sequence than the standard conversion sequence
8357   //      from the return type of F2 to the destination type.
8358   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8359       isa<CXXConversionDecl>(Cand1.Function) &&
8360       isa<CXXConversionDecl>(Cand2.Function)) {
8361     // First check whether we prefer one of the conversion functions over the
8362     // other. This only distinguishes the results in non-standard, extension
8363     // cases such as the conversion from a lambda closure type to a function
8364     // pointer or block.
8365     ImplicitConversionSequence::CompareKind Result =
8366         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8367     if (Result == ImplicitConversionSequence::Indistinguishable)
8368       Result = CompareStandardConversionSequences(S,
8369                                                   Cand1.FinalConversion,
8370                                                   Cand2.FinalConversion);
8371
8372     if (Result != ImplicitConversionSequence::Indistinguishable)
8373       return Result == ImplicitConversionSequence::Better;
8374
8375     // FIXME: Compare kind of reference binding if conversion functions
8376     // convert to a reference type used in direct reference binding, per
8377     // C++14 [over.match.best]p1 section 2 bullet 3.
8378   }
8379
8380   //    -- F1 is a non-template function and F2 is a function template
8381   //       specialization, or, if not that,
8382   bool Cand1IsSpecialization = Cand1.Function &&
8383                                Cand1.Function->getPrimaryTemplate();
8384   bool Cand2IsSpecialization = Cand2.Function &&
8385                                Cand2.Function->getPrimaryTemplate();
8386   if (Cand1IsSpecialization != Cand2IsSpecialization)
8387     return Cand2IsSpecialization;
8388
8389   //   -- F1 and F2 are function template specializations, and the function
8390   //      template for F1 is more specialized than the template for F2
8391   //      according to the partial ordering rules described in 14.5.5.2, or,
8392   //      if not that,
8393   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8394     if (FunctionTemplateDecl *BetterTemplate
8395           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8396                                          Cand2.Function->getPrimaryTemplate(),
8397                                          Loc,
8398                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8399                                                              : TPOC_Call,
8400                                          Cand1.ExplicitCallArguments,
8401                                          Cand2.ExplicitCallArguments))
8402       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8403   }
8404
8405   // Check for enable_if value-based overload resolution.
8406   if (Cand1.Function && Cand2.Function &&
8407       (Cand1.Function->hasAttr<EnableIfAttr>() ||
8408        Cand2.Function->hasAttr<EnableIfAttr>())) {
8409     // FIXME: The next several lines are just
8410     // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8411     // instead of reverse order which is how they're stored in the AST.
8412     AttrVec Cand1Attrs;
8413     if (Cand1.Function->hasAttrs()) {
8414       Cand1Attrs = Cand1.Function->getAttrs();
8415       Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8416                                       IsNotEnableIfAttr),
8417                        Cand1Attrs.end());
8418       std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
8419     }
8420
8421     AttrVec Cand2Attrs;
8422     if (Cand2.Function->hasAttrs()) {
8423       Cand2Attrs = Cand2.Function->getAttrs();
8424       Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8425                                       IsNotEnableIfAttr),
8426                        Cand2Attrs.end());
8427       std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
8428     }
8429
8430     // Candidate 1 is better if it has strictly more attributes and
8431     // the common sequence is identical.
8432     if (Cand1Attrs.size() <= Cand2Attrs.size())
8433       return false;
8434
8435     auto Cand1I = Cand1Attrs.begin();
8436     for (auto &Cand2A : Cand2Attrs) {
8437       auto &Cand1A = *Cand1I++;
8438       llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8439       cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8440                                                      S.getASTContext(), true);
8441       cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8442                                                      S.getASTContext(), true);
8443       if (Cand1ID != Cand2ID)
8444         return false;
8445     }
8446
8447     return true;
8448   }
8449
8450   return false;
8451 }
8452
8453 /// \brief Computes the best viable function (C++ 13.3.3)
8454 /// within an overload candidate set.
8455 ///
8456 /// \param Loc The location of the function name (or operator symbol) for
8457 /// which overload resolution occurs.
8458 ///
8459 /// \param Best If overload resolution was successful or found a deleted
8460 /// function, \p Best points to the candidate function found.
8461 ///
8462 /// \returns The result of overload resolution.
8463 OverloadingResult
8464 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8465                                          iterator &Best,
8466                                          bool UserDefinedConversion) {
8467   // Find the best viable function.
8468   Best = end();
8469   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8470     if (Cand->Viable)
8471       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8472                                                      UserDefinedConversion))
8473         Best = Cand;
8474   }
8475
8476   // If we didn't find any viable functions, abort.
8477   if (Best == end())
8478     return OR_No_Viable_Function;
8479
8480   // Make sure that this function is better than every other viable
8481   // function. If not, we have an ambiguity.
8482   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8483     if (Cand->Viable &&
8484         Cand != Best &&
8485         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8486                                    UserDefinedConversion)) {
8487       Best = end();
8488       return OR_Ambiguous;
8489     }
8490   }
8491
8492   // Best is the best viable function.
8493   if (Best->Function &&
8494       (Best->Function->isDeleted() ||
8495        S.isFunctionConsideredUnavailable(Best->Function)))
8496     return OR_Deleted;
8497
8498   return OR_Success;
8499 }
8500
8501 namespace {
8502
8503 enum OverloadCandidateKind {
8504   oc_function,
8505   oc_method,
8506   oc_constructor,
8507   oc_function_template,
8508   oc_method_template,
8509   oc_constructor_template,
8510   oc_implicit_default_constructor,
8511   oc_implicit_copy_constructor,
8512   oc_implicit_move_constructor,
8513   oc_implicit_copy_assignment,
8514   oc_implicit_move_assignment,
8515   oc_implicit_inherited_constructor
8516 };
8517
8518 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8519                                                 FunctionDecl *Fn,
8520                                                 std::string &Description) {
8521   bool isTemplate = false;
8522
8523   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8524     isTemplate = true;
8525     Description = S.getTemplateArgumentBindingsText(
8526       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8527   }
8528
8529   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8530     if (!Ctor->isImplicit())
8531       return isTemplate ? oc_constructor_template : oc_constructor;
8532
8533     if (Ctor->getInheritedConstructor())
8534       return oc_implicit_inherited_constructor;
8535
8536     if (Ctor->isDefaultConstructor())
8537       return oc_implicit_default_constructor;
8538
8539     if (Ctor->isMoveConstructor())
8540       return oc_implicit_move_constructor;
8541
8542     assert(Ctor->isCopyConstructor() &&
8543            "unexpected sort of implicit constructor");
8544     return oc_implicit_copy_constructor;
8545   }
8546
8547   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8548     // This actually gets spelled 'candidate function' for now, but
8549     // it doesn't hurt to split it out.
8550     if (!Meth->isImplicit())
8551       return isTemplate ? oc_method_template : oc_method;
8552
8553     if (Meth->isMoveAssignmentOperator())
8554       return oc_implicit_move_assignment;
8555
8556     if (Meth->isCopyAssignmentOperator())
8557       return oc_implicit_copy_assignment;
8558
8559     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8560     return oc_method;
8561   }
8562
8563   return isTemplate ? oc_function_template : oc_function;
8564 }
8565
8566 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8567   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8568   if (!Ctor) return;
8569
8570   Ctor = Ctor->getInheritedConstructor();
8571   if (!Ctor) return;
8572
8573   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8574 }
8575
8576 } // end anonymous namespace
8577
8578 // Notes the location of an overload candidate.
8579 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8580   std::string FnDesc;
8581   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8582   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8583                              << (unsigned) K << FnDesc;
8584   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8585   Diag(Fn->getLocation(), PD);
8586   MaybeEmitInheritedConstructorNote(*this, Fn);
8587 }
8588
8589 // Notes the location of all overload candidates designated through
8590 // OverloadedExpr
8591 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8592   assert(OverloadedExpr->getType() == Context.OverloadTy);
8593
8594   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8595   OverloadExpr *OvlExpr = Ovl.Expression;
8596
8597   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8598                             IEnd = OvlExpr->decls_end(); 
8599        I != IEnd; ++I) {
8600     if (FunctionTemplateDecl *FunTmpl = 
8601                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8602       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8603     } else if (FunctionDecl *Fun 
8604                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8605       NoteOverloadCandidate(Fun, DestType);
8606     }
8607   }
8608 }
8609
8610 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8611 /// "lead" diagnostic; it will be given two arguments, the source and
8612 /// target types of the conversion.
8613 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8614                                  Sema &S,
8615                                  SourceLocation CaretLoc,
8616                                  const PartialDiagnostic &PDiag) const {
8617   S.Diag(CaretLoc, PDiag)
8618     << Ambiguous.getFromType() << Ambiguous.getToType();
8619   // FIXME: The note limiting machinery is borrowed from
8620   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8621   // refactoring here.
8622   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8623   unsigned CandsShown = 0;
8624   AmbiguousConversionSequence::const_iterator I, E;
8625   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8626     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8627       break;
8628     ++CandsShown;
8629     S.NoteOverloadCandidate(*I);
8630   }
8631   if (I != E)
8632     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8633 }
8634
8635 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8636                                   unsigned I) {
8637   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8638   assert(Conv.isBad());
8639   assert(Cand->Function && "for now, candidate must be a function");
8640   FunctionDecl *Fn = Cand->Function;
8641
8642   // There's a conversion slot for the object argument if this is a
8643   // non-constructor method.  Note that 'I' corresponds the
8644   // conversion-slot index.
8645   bool isObjectArgument = false;
8646   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8647     if (I == 0)
8648       isObjectArgument = true;
8649     else
8650       I--;
8651   }
8652
8653   std::string FnDesc;
8654   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8655
8656   Expr *FromExpr = Conv.Bad.FromExpr;
8657   QualType FromTy = Conv.Bad.getFromType();
8658   QualType ToTy = Conv.Bad.getToType();
8659
8660   if (FromTy == S.Context.OverloadTy) {
8661     assert(FromExpr && "overload set argument came from implicit argument?");
8662     Expr *E = FromExpr->IgnoreParens();
8663     if (isa<UnaryOperator>(E))
8664       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8665     DeclarationName Name = cast<OverloadExpr>(E)->getName();
8666
8667     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8668       << (unsigned) FnKind << FnDesc
8669       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8670       << ToTy << Name << I+1;
8671     MaybeEmitInheritedConstructorNote(S, Fn);
8672     return;
8673   }
8674
8675   // Do some hand-waving analysis to see if the non-viability is due
8676   // to a qualifier mismatch.
8677   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8678   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8679   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8680     CToTy = RT->getPointeeType();
8681   else {
8682     // TODO: detect and diagnose the full richness of const mismatches.
8683     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8684       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8685         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8686   }
8687
8688   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8689       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8690     Qualifiers FromQs = CFromTy.getQualifiers();
8691     Qualifiers ToQs = CToTy.getQualifiers();
8692
8693     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8694       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8695         << (unsigned) FnKind << FnDesc
8696         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8697         << FromTy
8698         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8699         << (unsigned) isObjectArgument << I+1;
8700       MaybeEmitInheritedConstructorNote(S, Fn);
8701       return;
8702     }
8703
8704     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8705       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8706         << (unsigned) FnKind << FnDesc
8707         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8708         << FromTy
8709         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8710         << (unsigned) isObjectArgument << I+1;
8711       MaybeEmitInheritedConstructorNote(S, Fn);
8712       return;
8713     }
8714
8715     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8716       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8717       << (unsigned) FnKind << FnDesc
8718       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8719       << FromTy
8720       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8721       << (unsigned) isObjectArgument << I+1;
8722       MaybeEmitInheritedConstructorNote(S, Fn);
8723       return;
8724     }
8725
8726     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8727     assert(CVR && "unexpected qualifiers mismatch");
8728
8729     if (isObjectArgument) {
8730       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8731         << (unsigned) FnKind << FnDesc
8732         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8733         << FromTy << (CVR - 1);
8734     } else {
8735       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8736         << (unsigned) FnKind << FnDesc
8737         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8738         << FromTy << (CVR - 1) << I+1;
8739     }
8740     MaybeEmitInheritedConstructorNote(S, Fn);
8741     return;
8742   }
8743
8744   // Special diagnostic for failure to convert an initializer list, since
8745   // telling the user that it has type void is not useful.
8746   if (FromExpr && isa<InitListExpr>(FromExpr)) {
8747     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8748       << (unsigned) FnKind << FnDesc
8749       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8750       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8751     MaybeEmitInheritedConstructorNote(S, Fn);
8752     return;
8753   }
8754
8755   // Diagnose references or pointers to incomplete types differently,
8756   // since it's far from impossible that the incompleteness triggered
8757   // the failure.
8758   QualType TempFromTy = FromTy.getNonReferenceType();
8759   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8760     TempFromTy = PTy->getPointeeType();
8761   if (TempFromTy->isIncompleteType()) {
8762     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8763       << (unsigned) FnKind << FnDesc
8764       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8765       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8766     MaybeEmitInheritedConstructorNote(S, Fn);
8767     return;
8768   }
8769
8770   // Diagnose base -> derived pointer conversions.
8771   unsigned BaseToDerivedConversion = 0;
8772   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8773     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8774       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8775                                                FromPtrTy->getPointeeType()) &&
8776           !FromPtrTy->getPointeeType()->isIncompleteType() &&
8777           !ToPtrTy->getPointeeType()->isIncompleteType() &&
8778           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8779                           FromPtrTy->getPointeeType()))
8780         BaseToDerivedConversion = 1;
8781     }
8782   } else if (const ObjCObjectPointerType *FromPtrTy
8783                                     = FromTy->getAs<ObjCObjectPointerType>()) {
8784     if (const ObjCObjectPointerType *ToPtrTy
8785                                         = ToTy->getAs<ObjCObjectPointerType>())
8786       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8787         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8788           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8789                                                 FromPtrTy->getPointeeType()) &&
8790               FromIface->isSuperClassOf(ToIface))
8791             BaseToDerivedConversion = 2;
8792   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8793     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8794         !FromTy->isIncompleteType() &&
8795         !ToRefTy->getPointeeType()->isIncompleteType() &&
8796         S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8797       BaseToDerivedConversion = 3;
8798     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8799                ToTy.getNonReferenceType().getCanonicalType() ==
8800                FromTy.getNonReferenceType().getCanonicalType()) {
8801       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8802         << (unsigned) FnKind << FnDesc
8803         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8804         << (unsigned) isObjectArgument << I + 1;
8805       MaybeEmitInheritedConstructorNote(S, Fn);
8806       return;
8807     }
8808   }
8809
8810   if (BaseToDerivedConversion) {
8811     S.Diag(Fn->getLocation(),
8812            diag::note_ovl_candidate_bad_base_to_derived_conv)
8813       << (unsigned) FnKind << FnDesc
8814       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8815       << (BaseToDerivedConversion - 1)
8816       << FromTy << ToTy << I+1;
8817     MaybeEmitInheritedConstructorNote(S, Fn);
8818     return;
8819   }
8820
8821   if (isa<ObjCObjectPointerType>(CFromTy) &&
8822       isa<PointerType>(CToTy)) {
8823       Qualifiers FromQs = CFromTy.getQualifiers();
8824       Qualifiers ToQs = CToTy.getQualifiers();
8825       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8826         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8827         << (unsigned) FnKind << FnDesc
8828         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8829         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8830         MaybeEmitInheritedConstructorNote(S, Fn);
8831         return;
8832       }
8833   }
8834   
8835   // Emit the generic diagnostic and, optionally, add the hints to it.
8836   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8837   FDiag << (unsigned) FnKind << FnDesc
8838     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8839     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8840     << (unsigned) (Cand->Fix.Kind);
8841
8842   // If we can fix the conversion, suggest the FixIts.
8843   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8844        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8845     FDiag << *HI;
8846   S.Diag(Fn->getLocation(), FDiag);
8847
8848   MaybeEmitInheritedConstructorNote(S, Fn);
8849 }
8850
8851 /// Additional arity mismatch diagnosis specific to a function overload
8852 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
8853 /// over a candidate in any candidate set.
8854 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8855                                unsigned NumArgs) {
8856   FunctionDecl *Fn = Cand->Function;
8857   unsigned MinParams = Fn->getMinRequiredArguments();
8858
8859   // With invalid overloaded operators, it's possible that we think we
8860   // have an arity mismatch when in fact it looks like we have the
8861   // right number of arguments, because only overloaded operators have
8862   // the weird behavior of overloading member and non-member functions.
8863   // Just don't report anything.
8864   if (Fn->isInvalidDecl() && 
8865       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8866     return true;
8867
8868   if (NumArgs < MinParams) {
8869     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8870            (Cand->FailureKind == ovl_fail_bad_deduction &&
8871             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8872   } else {
8873     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8874            (Cand->FailureKind == ovl_fail_bad_deduction &&
8875             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8876   }
8877
8878   return false;
8879 }
8880
8881 /// General arity mismatch diagnosis over a candidate in a candidate set.
8882 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8883   assert(isa<FunctionDecl>(D) &&
8884       "The templated declaration should at least be a function"
8885       " when diagnosing bad template argument deduction due to too many"
8886       " or too few arguments");
8887   
8888   FunctionDecl *Fn = cast<FunctionDecl>(D);
8889   
8890   // TODO: treat calls to a missing default constructor as a special case
8891   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8892   unsigned MinParams = Fn->getMinRequiredArguments();
8893
8894   // at least / at most / exactly
8895   unsigned mode, modeCount;
8896   if (NumFormalArgs < MinParams) {
8897     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8898         FnTy->isTemplateVariadic())
8899       mode = 0; // "at least"
8900     else
8901       mode = 2; // "exactly"
8902     modeCount = MinParams;
8903   } else {
8904     if (MinParams != FnTy->getNumParams())
8905       mode = 1; // "at most"
8906     else
8907       mode = 2; // "exactly"
8908     modeCount = FnTy->getNumParams();
8909   }
8910
8911   std::string Description;
8912   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8913
8914   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8915     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8916       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8917       << mode << Fn->getParamDecl(0) << NumFormalArgs;
8918   else
8919     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8920       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8921       << mode << modeCount << NumFormalArgs;
8922   MaybeEmitInheritedConstructorNote(S, Fn);
8923 }
8924
8925 /// Arity mismatch diagnosis specific to a function overload candidate.
8926 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8927                                   unsigned NumFormalArgs) {
8928   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8929     DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8930 }
8931
8932 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
8933   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8934     return FD->getDescribedFunctionTemplate();
8935   else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8936     return RD->getDescribedClassTemplate();
8937
8938   llvm_unreachable("Unsupported: Getting the described template declaration"
8939                    " for bad deduction diagnosis");
8940 }
8941
8942 /// Diagnose a failed template-argument deduction.
8943 static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8944                                  DeductionFailureInfo &DeductionFailure,
8945                                  unsigned NumArgs) {
8946   TemplateParameter Param = DeductionFailure.getTemplateParameter();
8947   NamedDecl *ParamD;
8948   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8949   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8950   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8951   switch (DeductionFailure.Result) {
8952   case Sema::TDK_Success:
8953     llvm_unreachable("TDK_success while diagnosing bad deduction");
8954
8955   case Sema::TDK_Incomplete: {
8956     assert(ParamD && "no parameter found for incomplete deduction result");
8957     S.Diag(Templated->getLocation(),
8958            diag::note_ovl_candidate_incomplete_deduction)
8959         << ParamD->getDeclName();
8960     MaybeEmitInheritedConstructorNote(S, Templated);
8961     return;
8962   }
8963
8964   case Sema::TDK_Underqualified: {
8965     assert(ParamD && "no parameter found for bad qualifiers deduction result");
8966     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8967
8968     QualType Param = DeductionFailure.getFirstArg()->getAsType();
8969
8970     // Param will have been canonicalized, but it should just be a
8971     // qualified version of ParamD, so move the qualifiers to that.
8972     QualifierCollector Qs;
8973     Qs.strip(Param);
8974     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8975     assert(S.Context.hasSameType(Param, NonCanonParam));
8976
8977     // Arg has also been canonicalized, but there's nothing we can do
8978     // about that.  It also doesn't matter as much, because it won't
8979     // have any template parameters in it (because deduction isn't
8980     // done on dependent types).
8981     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
8982
8983     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8984         << ParamD->getDeclName() << Arg << NonCanonParam;
8985     MaybeEmitInheritedConstructorNote(S, Templated);
8986     return;
8987   }
8988
8989   case Sema::TDK_Inconsistent: {
8990     assert(ParamD && "no parameter found for inconsistent deduction result");
8991     int which = 0;
8992     if (isa<TemplateTypeParmDecl>(ParamD))
8993       which = 0;
8994     else if (isa<NonTypeTemplateParmDecl>(ParamD))
8995       which = 1;
8996     else {
8997       which = 2;
8998     }
8999
9000     S.Diag(Templated->getLocation(),
9001            diag::note_ovl_candidate_inconsistent_deduction)
9002         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9003         << *DeductionFailure.getSecondArg();
9004     MaybeEmitInheritedConstructorNote(S, Templated);
9005     return;
9006   }
9007
9008   case Sema::TDK_InvalidExplicitArguments:
9009     assert(ParamD && "no parameter found for invalid explicit arguments");
9010     if (ParamD->getDeclName())
9011       S.Diag(Templated->getLocation(),
9012              diag::note_ovl_candidate_explicit_arg_mismatch_named)
9013           << ParamD->getDeclName();
9014     else {
9015       int index = 0;
9016       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9017         index = TTP->getIndex();
9018       else if (NonTypeTemplateParmDecl *NTTP
9019                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9020         index = NTTP->getIndex();
9021       else
9022         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9023       S.Diag(Templated->getLocation(),
9024              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9025           << (index + 1);
9026     }
9027     MaybeEmitInheritedConstructorNote(S, Templated);
9028     return;
9029
9030   case Sema::TDK_TooManyArguments:
9031   case Sema::TDK_TooFewArguments:
9032     DiagnoseArityMismatch(S, Templated, NumArgs);
9033     return;
9034
9035   case Sema::TDK_InstantiationDepth:
9036     S.Diag(Templated->getLocation(),
9037            diag::note_ovl_candidate_instantiation_depth);
9038     MaybeEmitInheritedConstructorNote(S, Templated);
9039     return;
9040
9041   case Sema::TDK_SubstitutionFailure: {
9042     // Format the template argument list into the argument string.
9043     SmallString<128> TemplateArgString;
9044     if (TemplateArgumentList *Args =
9045             DeductionFailure.getTemplateArgumentList()) {
9046       TemplateArgString = " ";
9047       TemplateArgString += S.getTemplateArgumentBindingsText(
9048           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9049     }
9050
9051     // If this candidate was disabled by enable_if, say so.
9052     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9053     if (PDiag && PDiag->second.getDiagID() ==
9054           diag::err_typename_nested_not_found_enable_if) {
9055       // FIXME: Use the source range of the condition, and the fully-qualified
9056       //        name of the enable_if template. These are both present in PDiag.
9057       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9058         << "'enable_if'" << TemplateArgString;
9059       return;
9060     }
9061
9062     // Format the SFINAE diagnostic into the argument string.
9063     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9064     //        formatted message in another diagnostic.
9065     SmallString<128> SFINAEArgString;
9066     SourceRange R;
9067     if (PDiag) {
9068       SFINAEArgString = ": ";
9069       R = SourceRange(PDiag->first, PDiag->first);
9070       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9071     }
9072
9073     S.Diag(Templated->getLocation(),
9074            diag::note_ovl_candidate_substitution_failure)
9075         << TemplateArgString << SFINAEArgString << R;
9076     MaybeEmitInheritedConstructorNote(S, Templated);
9077     return;
9078   }
9079
9080   case Sema::TDK_FailedOverloadResolution: {
9081     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9082     S.Diag(Templated->getLocation(),
9083            diag::note_ovl_candidate_failed_overload_resolution)
9084         << R.Expression->getName();
9085     return;
9086   }
9087
9088   case Sema::TDK_NonDeducedMismatch: {
9089     // FIXME: Provide a source location to indicate what we couldn't match.
9090     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9091     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9092     if (FirstTA.getKind() == TemplateArgument::Template &&
9093         SecondTA.getKind() == TemplateArgument::Template) {
9094       TemplateName FirstTN = FirstTA.getAsTemplate();
9095       TemplateName SecondTN = SecondTA.getAsTemplate();
9096       if (FirstTN.getKind() == TemplateName::Template &&
9097           SecondTN.getKind() == TemplateName::Template) {
9098         if (FirstTN.getAsTemplateDecl()->getName() ==
9099             SecondTN.getAsTemplateDecl()->getName()) {
9100           // FIXME: This fixes a bad diagnostic where both templates are named
9101           // the same.  This particular case is a bit difficult since:
9102           // 1) It is passed as a string to the diagnostic printer.
9103           // 2) The diagnostic printer only attempts to find a better
9104           //    name for types, not decls.
9105           // Ideally, this should folded into the diagnostic printer.
9106           S.Diag(Templated->getLocation(),
9107                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9108               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9109           return;
9110         }
9111       }
9112     }
9113     // FIXME: For generic lambda parameters, check if the function is a lambda
9114     // call operator, and if so, emit a prettier and more informative 
9115     // diagnostic that mentions 'auto' and lambda in addition to 
9116     // (or instead of?) the canonical template type parameters.
9117     S.Diag(Templated->getLocation(),
9118            diag::note_ovl_candidate_non_deduced_mismatch)
9119         << FirstTA << SecondTA;
9120     return;
9121   }
9122   // TODO: diagnose these individually, then kill off
9123   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9124   case Sema::TDK_MiscellaneousDeductionFailure:
9125     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9126     MaybeEmitInheritedConstructorNote(S, Templated);
9127     return;
9128   }
9129 }
9130
9131 /// Diagnose a failed template-argument deduction, for function calls.
9132 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9133                                  unsigned NumArgs) {
9134   unsigned TDK = Cand->DeductionFailure.Result;
9135   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9136     if (CheckArityMismatch(S, Cand, NumArgs))
9137       return;
9138   }
9139   DiagnoseBadDeduction(S, Cand->Function, // pattern
9140                        Cand->DeductionFailure, NumArgs);
9141 }
9142
9143 /// CUDA: diagnose an invalid call across targets.
9144 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9145   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9146   FunctionDecl *Callee = Cand->Function;
9147
9148   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9149                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9150
9151   std::string FnDesc;
9152   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9153
9154   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9155       << (unsigned)FnKind << CalleeTarget << CallerTarget;
9156
9157   // This could be an implicit constructor for which we could not infer the
9158   // target due to a collsion. Diagnose that case.
9159   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9160   if (Meth != nullptr && Meth->isImplicit()) {
9161     CXXRecordDecl *ParentClass = Meth->getParent();
9162     Sema::CXXSpecialMember CSM;
9163
9164     switch (FnKind) {
9165     default:
9166       return;
9167     case oc_implicit_default_constructor:
9168       CSM = Sema::CXXDefaultConstructor;
9169       break;
9170     case oc_implicit_copy_constructor:
9171       CSM = Sema::CXXCopyConstructor;
9172       break;
9173     case oc_implicit_move_constructor:
9174       CSM = Sema::CXXMoveConstructor;
9175       break;
9176     case oc_implicit_copy_assignment:
9177       CSM = Sema::CXXCopyAssignment;
9178       break;
9179     case oc_implicit_move_assignment:
9180       CSM = Sema::CXXMoveAssignment;
9181       break;
9182     };
9183
9184     bool ConstRHS = false;
9185     if (Meth->getNumParams()) {
9186       if (const ReferenceType *RT =
9187               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9188         ConstRHS = RT->getPointeeType().isConstQualified();
9189       }
9190     }
9191
9192     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9193                                               /* ConstRHS */ ConstRHS,
9194                                               /* Diagnose */ true);
9195   }
9196 }
9197
9198 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9199   FunctionDecl *Callee = Cand->Function;
9200   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9201
9202   S.Diag(Callee->getLocation(),
9203          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9204       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9205 }
9206
9207 /// Generates a 'note' diagnostic for an overload candidate.  We've
9208 /// already generated a primary error at the call site.
9209 ///
9210 /// It really does need to be a single diagnostic with its caret
9211 /// pointed at the candidate declaration.  Yes, this creates some
9212 /// major challenges of technical writing.  Yes, this makes pointing
9213 /// out problems with specific arguments quite awkward.  It's still
9214 /// better than generating twenty screens of text for every failed
9215 /// overload.
9216 ///
9217 /// It would be great to be able to express per-candidate problems
9218 /// more richly for those diagnostic clients that cared, but we'd
9219 /// still have to be just as careful with the default diagnostics.
9220 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9221                                   unsigned NumArgs) {
9222   FunctionDecl *Fn = Cand->Function;
9223
9224   // Note deleted candidates, but only if they're viable.
9225   if (Cand->Viable && (Fn->isDeleted() ||
9226       S.isFunctionConsideredUnavailable(Fn))) {
9227     std::string FnDesc;
9228     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9229
9230     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9231       << FnKind << FnDesc
9232       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9233     MaybeEmitInheritedConstructorNote(S, Fn);
9234     return;
9235   }
9236
9237   // We don't really have anything else to say about viable candidates.
9238   if (Cand->Viable) {
9239     S.NoteOverloadCandidate(Fn);
9240     return;
9241   }
9242
9243   switch (Cand->FailureKind) {
9244   case ovl_fail_too_many_arguments:
9245   case ovl_fail_too_few_arguments:
9246     return DiagnoseArityMismatch(S, Cand, NumArgs);
9247
9248   case ovl_fail_bad_deduction:
9249     return DiagnoseBadDeduction(S, Cand, NumArgs);
9250
9251   case ovl_fail_illegal_constructor: {
9252     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9253       << (Fn->getPrimaryTemplate() ? 1 : 0);
9254     MaybeEmitInheritedConstructorNote(S, Fn);
9255     return;
9256   }
9257
9258   case ovl_fail_trivial_conversion:
9259   case ovl_fail_bad_final_conversion:
9260   case ovl_fail_final_conversion_not_exact:
9261     return S.NoteOverloadCandidate(Fn);
9262
9263   case ovl_fail_bad_conversion: {
9264     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9265     for (unsigned N = Cand->NumConversions; I != N; ++I)
9266       if (Cand->Conversions[I].isBad())
9267         return DiagnoseBadConversion(S, Cand, I);
9268
9269     // FIXME: this currently happens when we're called from SemaInit
9270     // when user-conversion overload fails.  Figure out how to handle
9271     // those conditions and diagnose them well.
9272     return S.NoteOverloadCandidate(Fn);
9273   }
9274
9275   case ovl_fail_bad_target:
9276     return DiagnoseBadTarget(S, Cand);
9277
9278   case ovl_fail_enable_if:
9279     return DiagnoseFailedEnableIfAttr(S, Cand);
9280   }
9281 }
9282
9283 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9284   // Desugar the type of the surrogate down to a function type,
9285   // retaining as many typedefs as possible while still showing
9286   // the function type (and, therefore, its parameter types).
9287   QualType FnType = Cand->Surrogate->getConversionType();
9288   bool isLValueReference = false;
9289   bool isRValueReference = false;
9290   bool isPointer = false;
9291   if (const LValueReferenceType *FnTypeRef =
9292         FnType->getAs<LValueReferenceType>()) {
9293     FnType = FnTypeRef->getPointeeType();
9294     isLValueReference = true;
9295   } else if (const RValueReferenceType *FnTypeRef =
9296                FnType->getAs<RValueReferenceType>()) {
9297     FnType = FnTypeRef->getPointeeType();
9298     isRValueReference = true;
9299   }
9300   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9301     FnType = FnTypePtr->getPointeeType();
9302     isPointer = true;
9303   }
9304   // Desugar down to a function type.
9305   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9306   // Reconstruct the pointer/reference as appropriate.
9307   if (isPointer) FnType = S.Context.getPointerType(FnType);
9308   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9309   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9310
9311   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9312     << FnType;
9313   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9314 }
9315
9316 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9317                                          SourceLocation OpLoc,
9318                                          OverloadCandidate *Cand) {
9319   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9320   std::string TypeStr("operator");
9321   TypeStr += Opc;
9322   TypeStr += "(";
9323   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9324   if (Cand->NumConversions == 1) {
9325     TypeStr += ")";
9326     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9327   } else {
9328     TypeStr += ", ";
9329     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9330     TypeStr += ")";
9331     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9332   }
9333 }
9334
9335 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9336                                          OverloadCandidate *Cand) {
9337   unsigned NoOperands = Cand->NumConversions;
9338   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9339     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9340     if (ICS.isBad()) break; // all meaningless after first invalid
9341     if (!ICS.isAmbiguous()) continue;
9342
9343     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9344                               S.PDiag(diag::note_ambiguous_type_conversion));
9345   }
9346 }
9347
9348 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9349   if (Cand->Function)
9350     return Cand->Function->getLocation();
9351   if (Cand->IsSurrogate)
9352     return Cand->Surrogate->getLocation();
9353   return SourceLocation();
9354 }
9355
9356 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9357   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9358   case Sema::TDK_Success:
9359     llvm_unreachable("TDK_success while diagnosing bad deduction");
9360
9361   case Sema::TDK_Invalid:
9362   case Sema::TDK_Incomplete:
9363     return 1;
9364
9365   case Sema::TDK_Underqualified:
9366   case Sema::TDK_Inconsistent:
9367     return 2;
9368
9369   case Sema::TDK_SubstitutionFailure:
9370   case Sema::TDK_NonDeducedMismatch:
9371   case Sema::TDK_MiscellaneousDeductionFailure:
9372     return 3;
9373
9374   case Sema::TDK_InstantiationDepth:
9375   case Sema::TDK_FailedOverloadResolution:
9376     return 4;
9377
9378   case Sema::TDK_InvalidExplicitArguments:
9379     return 5;
9380
9381   case Sema::TDK_TooManyArguments:
9382   case Sema::TDK_TooFewArguments:
9383     return 6;
9384   }
9385   llvm_unreachable("Unhandled deduction result");
9386 }
9387
9388 namespace {
9389 struct CompareOverloadCandidatesForDisplay {
9390   Sema &S;
9391   size_t NumArgs;
9392
9393   CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9394       : S(S), NumArgs(nArgs) {}
9395
9396   bool operator()(const OverloadCandidate *L,
9397                   const OverloadCandidate *R) {
9398     // Fast-path this check.
9399     if (L == R) return false;
9400
9401     // Order first by viability.
9402     if (L->Viable) {
9403       if (!R->Viable) return true;
9404
9405       // TODO: introduce a tri-valued comparison for overload
9406       // candidates.  Would be more worthwhile if we had a sort
9407       // that could exploit it.
9408       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9409       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9410     } else if (R->Viable)
9411       return false;
9412
9413     assert(L->Viable == R->Viable);
9414
9415     // Criteria by which we can sort non-viable candidates:
9416     if (!L->Viable) {
9417       // 1. Arity mismatches come after other candidates.
9418       if (L->FailureKind == ovl_fail_too_many_arguments ||
9419           L->FailureKind == ovl_fail_too_few_arguments) {
9420         if (R->FailureKind == ovl_fail_too_many_arguments ||
9421             R->FailureKind == ovl_fail_too_few_arguments) {
9422           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9423           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9424           if (LDist == RDist) {
9425             if (L->FailureKind == R->FailureKind)
9426               // Sort non-surrogates before surrogates.
9427               return !L->IsSurrogate && R->IsSurrogate;
9428             // Sort candidates requiring fewer parameters than there were
9429             // arguments given after candidates requiring more parameters
9430             // than there were arguments given.
9431             return L->FailureKind == ovl_fail_too_many_arguments;
9432           }
9433           return LDist < RDist;
9434         }
9435         return false;
9436       }
9437       if (R->FailureKind == ovl_fail_too_many_arguments ||
9438           R->FailureKind == ovl_fail_too_few_arguments)
9439         return true;
9440
9441       // 2. Bad conversions come first and are ordered by the number
9442       // of bad conversions and quality of good conversions.
9443       if (L->FailureKind == ovl_fail_bad_conversion) {
9444         if (R->FailureKind != ovl_fail_bad_conversion)
9445           return true;
9446
9447         // The conversion that can be fixed with a smaller number of changes,
9448         // comes first.
9449         unsigned numLFixes = L->Fix.NumConversionsFixed;
9450         unsigned numRFixes = R->Fix.NumConversionsFixed;
9451         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9452         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9453         if (numLFixes != numRFixes) {
9454           if (numLFixes < numRFixes)
9455             return true;
9456           else
9457             return false;
9458         }
9459
9460         // If there's any ordering between the defined conversions...
9461         // FIXME: this might not be transitive.
9462         assert(L->NumConversions == R->NumConversions);
9463
9464         int leftBetter = 0;
9465         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9466         for (unsigned E = L->NumConversions; I != E; ++I) {
9467           switch (CompareImplicitConversionSequences(S,
9468                                                      L->Conversions[I],
9469                                                      R->Conversions[I])) {
9470           case ImplicitConversionSequence::Better:
9471             leftBetter++;
9472             break;
9473
9474           case ImplicitConversionSequence::Worse:
9475             leftBetter--;
9476             break;
9477
9478           case ImplicitConversionSequence::Indistinguishable:
9479             break;
9480           }
9481         }
9482         if (leftBetter > 0) return true;
9483         if (leftBetter < 0) return false;
9484
9485       } else if (R->FailureKind == ovl_fail_bad_conversion)
9486         return false;
9487
9488       if (L->FailureKind == ovl_fail_bad_deduction) {
9489         if (R->FailureKind != ovl_fail_bad_deduction)
9490           return true;
9491
9492         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9493           return RankDeductionFailure(L->DeductionFailure)
9494                < RankDeductionFailure(R->DeductionFailure);
9495       } else if (R->FailureKind == ovl_fail_bad_deduction)
9496         return false;
9497
9498       // TODO: others?
9499     }
9500
9501     // Sort everything else by location.
9502     SourceLocation LLoc = GetLocationForCandidate(L);
9503     SourceLocation RLoc = GetLocationForCandidate(R);
9504
9505     // Put candidates without locations (e.g. builtins) at the end.
9506     if (LLoc.isInvalid()) return false;
9507     if (RLoc.isInvalid()) return true;
9508
9509     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9510   }
9511 };
9512 }
9513
9514 /// CompleteNonViableCandidate - Normally, overload resolution only
9515 /// computes up to the first. Produces the FixIt set if possible.
9516 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9517                                        ArrayRef<Expr *> Args) {
9518   assert(!Cand->Viable);
9519
9520   // Don't do anything on failures other than bad conversion.
9521   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9522
9523   // We only want the FixIts if all the arguments can be corrected.
9524   bool Unfixable = false;
9525   // Use a implicit copy initialization to check conversion fixes.
9526   Cand->Fix.setConversionChecker(TryCopyInitialization);
9527
9528   // Skip forward to the first bad conversion.
9529   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9530   unsigned ConvCount = Cand->NumConversions;
9531   while (true) {
9532     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9533     ConvIdx++;
9534     if (Cand->Conversions[ConvIdx - 1].isBad()) {
9535       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9536       break;
9537     }
9538   }
9539
9540   if (ConvIdx == ConvCount)
9541     return;
9542
9543   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9544          "remaining conversion is initialized?");
9545
9546   // FIXME: this should probably be preserved from the overload
9547   // operation somehow.
9548   bool SuppressUserConversions = false;
9549
9550   const FunctionProtoType* Proto;
9551   unsigned ArgIdx = ConvIdx;
9552
9553   if (Cand->IsSurrogate) {
9554     QualType ConvType
9555       = Cand->Surrogate->getConversionType().getNonReferenceType();
9556     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9557       ConvType = ConvPtrType->getPointeeType();
9558     Proto = ConvType->getAs<FunctionProtoType>();
9559     ArgIdx--;
9560   } else if (Cand->Function) {
9561     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9562     if (isa<CXXMethodDecl>(Cand->Function) &&
9563         !isa<CXXConstructorDecl>(Cand->Function))
9564       ArgIdx--;
9565   } else {
9566     // Builtin binary operator with a bad first conversion.
9567     assert(ConvCount <= 3);
9568     for (; ConvIdx != ConvCount; ++ConvIdx)
9569       Cand->Conversions[ConvIdx]
9570         = TryCopyInitialization(S, Args[ConvIdx],
9571                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9572                                 SuppressUserConversions,
9573                                 /*InOverloadResolution*/ true,
9574                                 /*AllowObjCWritebackConversion=*/
9575                                   S.getLangOpts().ObjCAutoRefCount);
9576     return;
9577   }
9578
9579   // Fill in the rest of the conversions.
9580   unsigned NumParams = Proto->getNumParams();
9581   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9582     if (ArgIdx < NumParams) {
9583       Cand->Conversions[ConvIdx] = TryCopyInitialization(
9584           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9585           /*InOverloadResolution=*/true,
9586           /*AllowObjCWritebackConversion=*/
9587           S.getLangOpts().ObjCAutoRefCount);
9588       // Store the FixIt in the candidate if it exists.
9589       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9590         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9591     }
9592     else
9593       Cand->Conversions[ConvIdx].setEllipsis();
9594   }
9595 }
9596
9597 /// PrintOverloadCandidates - When overload resolution fails, prints
9598 /// diagnostic messages containing the candidates in the candidate
9599 /// set.
9600 void OverloadCandidateSet::NoteCandidates(Sema &S,
9601                                           OverloadCandidateDisplayKind OCD,
9602                                           ArrayRef<Expr *> Args,
9603                                           StringRef Opc,
9604                                           SourceLocation OpLoc) {
9605   // Sort the candidates by viability and position.  Sorting directly would
9606   // be prohibitive, so we make a set of pointers and sort those.
9607   SmallVector<OverloadCandidate*, 32> Cands;
9608   if (OCD == OCD_AllCandidates) Cands.reserve(size());
9609   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9610     if (Cand->Viable)
9611       Cands.push_back(Cand);
9612     else if (OCD == OCD_AllCandidates) {
9613       CompleteNonViableCandidate(S, Cand, Args);
9614       if (Cand->Function || Cand->IsSurrogate)
9615         Cands.push_back(Cand);
9616       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
9617       // want to list every possible builtin candidate.
9618     }
9619   }
9620
9621   std::sort(Cands.begin(), Cands.end(),
9622             CompareOverloadCandidatesForDisplay(S, Args.size()));
9623
9624   bool ReportedAmbiguousConversions = false;
9625
9626   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9627   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9628   unsigned CandsShown = 0;
9629   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9630     OverloadCandidate *Cand = *I;
9631
9632     // Set an arbitrary limit on the number of candidate functions we'll spam
9633     // the user with.  FIXME: This limit should depend on details of the
9634     // candidate list.
9635     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9636       break;
9637     }
9638     ++CandsShown;
9639
9640     if (Cand->Function)
9641       NoteFunctionCandidate(S, Cand, Args.size());
9642     else if (Cand->IsSurrogate)
9643       NoteSurrogateCandidate(S, Cand);
9644     else {
9645       assert(Cand->Viable &&
9646              "Non-viable built-in candidates are not added to Cands.");
9647       // Generally we only see ambiguities including viable builtin
9648       // operators if overload resolution got screwed up by an
9649       // ambiguous user-defined conversion.
9650       //
9651       // FIXME: It's quite possible for different conversions to see
9652       // different ambiguities, though.
9653       if (!ReportedAmbiguousConversions) {
9654         NoteAmbiguousUserConversions(S, OpLoc, Cand);
9655         ReportedAmbiguousConversions = true;
9656       }
9657
9658       // If this is a viable builtin, print it.
9659       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9660     }
9661   }
9662
9663   if (I != E)
9664     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9665 }
9666
9667 static SourceLocation
9668 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9669   return Cand->Specialization ? Cand->Specialization->getLocation()
9670                               : SourceLocation();
9671 }
9672
9673 namespace {
9674 struct CompareTemplateSpecCandidatesForDisplay {
9675   Sema &S;
9676   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9677
9678   bool operator()(const TemplateSpecCandidate *L,
9679                   const TemplateSpecCandidate *R) {
9680     // Fast-path this check.
9681     if (L == R)
9682       return false;
9683
9684     // Assuming that both candidates are not matches...
9685
9686     // Sort by the ranking of deduction failures.
9687     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9688       return RankDeductionFailure(L->DeductionFailure) <
9689              RankDeductionFailure(R->DeductionFailure);
9690
9691     // Sort everything else by location.
9692     SourceLocation LLoc = GetLocationForCandidate(L);
9693     SourceLocation RLoc = GetLocationForCandidate(R);
9694
9695     // Put candidates without locations (e.g. builtins) at the end.
9696     if (LLoc.isInvalid())
9697       return false;
9698     if (RLoc.isInvalid())
9699       return true;
9700
9701     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9702   }
9703 };
9704 }
9705
9706 /// Diagnose a template argument deduction failure.
9707 /// We are treating these failures as overload failures due to bad
9708 /// deductions.
9709 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9710   DiagnoseBadDeduction(S, Specialization, // pattern
9711                        DeductionFailure, /*NumArgs=*/0);
9712 }
9713
9714 void TemplateSpecCandidateSet::destroyCandidates() {
9715   for (iterator i = begin(), e = end(); i != e; ++i) {
9716     i->DeductionFailure.Destroy();
9717   }
9718 }
9719
9720 void TemplateSpecCandidateSet::clear() {
9721   destroyCandidates();
9722   Candidates.clear();
9723 }
9724
9725 /// NoteCandidates - When no template specialization match is found, prints
9726 /// diagnostic messages containing the non-matching specializations that form
9727 /// the candidate set.
9728 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9729 /// OCD == OCD_AllCandidates and Cand->Viable == false.
9730 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9731   // Sort the candidates by position (assuming no candidate is a match).
9732   // Sorting directly would be prohibitive, so we make a set of pointers
9733   // and sort those.
9734   SmallVector<TemplateSpecCandidate *, 32> Cands;
9735   Cands.reserve(size());
9736   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9737     if (Cand->Specialization)
9738       Cands.push_back(Cand);
9739     // Otherwise, this is a non-matching builtin candidate.  We do not,
9740     // in general, want to list every possible builtin candidate.
9741   }
9742
9743   std::sort(Cands.begin(), Cands.end(),
9744             CompareTemplateSpecCandidatesForDisplay(S));
9745
9746   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9747   // for generalization purposes (?).
9748   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9749
9750   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9751   unsigned CandsShown = 0;
9752   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9753     TemplateSpecCandidate *Cand = *I;
9754
9755     // Set an arbitrary limit on the number of candidates we'll spam
9756     // the user with.  FIXME: This limit should depend on details of the
9757     // candidate list.
9758     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9759       break;
9760     ++CandsShown;
9761
9762     assert(Cand->Specialization &&
9763            "Non-matching built-in candidates are not added to Cands.");
9764     Cand->NoteDeductionFailure(S);
9765   }
9766
9767   if (I != E)
9768     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9769 }
9770
9771 // [PossiblyAFunctionType]  -->   [Return]
9772 // NonFunctionType --> NonFunctionType
9773 // R (A) --> R(A)
9774 // R (*)(A) --> R (A)
9775 // R (&)(A) --> R (A)
9776 // R (S::*)(A) --> R (A)
9777 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9778   QualType Ret = PossiblyAFunctionType;
9779   if (const PointerType *ToTypePtr = 
9780     PossiblyAFunctionType->getAs<PointerType>())
9781     Ret = ToTypePtr->getPointeeType();
9782   else if (const ReferenceType *ToTypeRef = 
9783     PossiblyAFunctionType->getAs<ReferenceType>())
9784     Ret = ToTypeRef->getPointeeType();
9785   else if (const MemberPointerType *MemTypePtr =
9786     PossiblyAFunctionType->getAs<MemberPointerType>()) 
9787     Ret = MemTypePtr->getPointeeType();   
9788   Ret = 
9789     Context.getCanonicalType(Ret).getUnqualifiedType();
9790   return Ret;
9791 }
9792
9793 namespace {
9794 // A helper class to help with address of function resolution
9795 // - allows us to avoid passing around all those ugly parameters
9796 class AddressOfFunctionResolver {
9797   Sema& S;
9798   Expr* SourceExpr;
9799   const QualType& TargetType; 
9800   QualType TargetFunctionType; // Extracted function type from target type 
9801    
9802   bool Complain;
9803   //DeclAccessPair& ResultFunctionAccessPair;
9804   ASTContext& Context;
9805
9806   bool TargetTypeIsNonStaticMemberFunction;
9807   bool FoundNonTemplateFunction;
9808   bool StaticMemberFunctionFromBoundPointer;
9809
9810   OverloadExpr::FindResult OvlExprInfo; 
9811   OverloadExpr *OvlExpr;
9812   TemplateArgumentListInfo OvlExplicitTemplateArgs;
9813   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9814   TemplateSpecCandidateSet FailedCandidates;
9815
9816 public:
9817   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9818                             const QualType &TargetType, bool Complain)
9819       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9820         Complain(Complain), Context(S.getASTContext()),
9821         TargetTypeIsNonStaticMemberFunction(
9822             !!TargetType->getAs<MemberPointerType>()),
9823         FoundNonTemplateFunction(false),
9824         StaticMemberFunctionFromBoundPointer(false),
9825         OvlExprInfo(OverloadExpr::find(SourceExpr)),
9826         OvlExpr(OvlExprInfo.Expression),
9827         FailedCandidates(OvlExpr->getNameLoc()) {
9828     ExtractUnqualifiedFunctionTypeFromTargetType();
9829
9830     if (TargetFunctionType->isFunctionType()) {
9831       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9832         if (!UME->isImplicitAccess() &&
9833             !S.ResolveSingleFunctionTemplateSpecialization(UME))
9834           StaticMemberFunctionFromBoundPointer = true;
9835     } else if (OvlExpr->hasExplicitTemplateArgs()) {
9836       DeclAccessPair dap;
9837       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9838               OvlExpr, false, &dap)) {
9839         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9840           if (!Method->isStatic()) {
9841             // If the target type is a non-function type and the function found
9842             // is a non-static member function, pretend as if that was the
9843             // target, it's the only possible type to end up with.
9844             TargetTypeIsNonStaticMemberFunction = true;
9845
9846             // And skip adding the function if its not in the proper form.
9847             // We'll diagnose this due to an empty set of functions.
9848             if (!OvlExprInfo.HasFormOfMemberPointer)
9849               return;
9850           }
9851
9852         Matches.push_back(std::make_pair(dap, Fn));
9853       }
9854       return;
9855     }
9856     
9857     if (OvlExpr->hasExplicitTemplateArgs())
9858       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9859
9860     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9861       // C++ [over.over]p4:
9862       //   If more than one function is selected, [...]
9863       if (Matches.size() > 1) {
9864         if (FoundNonTemplateFunction)
9865           EliminateAllTemplateMatches();
9866         else
9867           EliminateAllExceptMostSpecializedTemplate();
9868       }
9869     }
9870   }
9871   
9872 private:
9873   bool isTargetTypeAFunction() const {
9874     return TargetFunctionType->isFunctionType();
9875   }
9876
9877   // [ToType]     [Return]
9878
9879   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9880   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9881   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9882   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9883     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9884   }
9885
9886   // return true if any matching specializations were found
9887   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 
9888                                    const DeclAccessPair& CurAccessFunPair) {
9889     if (CXXMethodDecl *Method
9890               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9891       // Skip non-static function templates when converting to pointer, and
9892       // static when converting to member pointer.
9893       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9894         return false;
9895     } 
9896     else if (TargetTypeIsNonStaticMemberFunction)
9897       return false;
9898
9899     // C++ [over.over]p2:
9900     //   If the name is a function template, template argument deduction is
9901     //   done (14.8.2.2), and if the argument deduction succeeds, the
9902     //   resulting template argument list is used to generate a single
9903     //   function template specialization, which is added to the set of
9904     //   overloaded functions considered.
9905     FunctionDecl *Specialization = nullptr;
9906     TemplateDeductionInfo Info(FailedCandidates.getLocation());
9907     if (Sema::TemplateDeductionResult Result
9908           = S.DeduceTemplateArguments(FunctionTemplate, 
9909                                       &OvlExplicitTemplateArgs,
9910                                       TargetFunctionType, Specialization, 
9911                                       Info, /*InOverloadResolution=*/true)) {
9912       // Make a note of the failed deduction for diagnostics.
9913       FailedCandidates.addCandidate()
9914           .set(FunctionTemplate->getTemplatedDecl(),
9915                MakeDeductionFailureInfo(Context, Result, Info));
9916       return false;
9917     } 
9918     
9919     // Template argument deduction ensures that we have an exact match or
9920     // compatible pointer-to-function arguments that would be adjusted by ICS.
9921     // This function template specicalization works.
9922     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9923     assert(S.isSameOrCompatibleFunctionType(
9924               Context.getCanonicalType(Specialization->getType()),
9925               Context.getCanonicalType(TargetFunctionType)));
9926     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9927     return true;
9928   }
9929   
9930   bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 
9931                                       const DeclAccessPair& CurAccessFunPair) {
9932     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9933       // Skip non-static functions when converting to pointer, and static
9934       // when converting to member pointer.
9935       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9936         return false;
9937     } 
9938     else if (TargetTypeIsNonStaticMemberFunction)
9939       return false;
9940
9941     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9942       if (S.getLangOpts().CUDA)
9943         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9944           if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
9945             return false;
9946
9947       // If any candidate has a placeholder return type, trigger its deduction
9948       // now.
9949       if (S.getLangOpts().CPlusPlus14 &&
9950           FunDecl->getReturnType()->isUndeducedType() &&
9951           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9952         return false;
9953
9954       QualType ResultTy;
9955       if (Context.hasSameUnqualifiedType(TargetFunctionType, 
9956                                          FunDecl->getType()) ||
9957           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9958                                  ResultTy)) {
9959         Matches.push_back(std::make_pair(CurAccessFunPair,
9960           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9961         FoundNonTemplateFunction = true;
9962         return true;
9963       }
9964     }
9965     
9966     return false;
9967   }
9968   
9969   bool FindAllFunctionsThatMatchTargetTypeExactly() {
9970     bool Ret = false;
9971     
9972     // If the overload expression doesn't have the form of a pointer to
9973     // member, don't try to convert it to a pointer-to-member type.
9974     if (IsInvalidFormOfPointerToMemberFunction())
9975       return false;
9976
9977     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9978                                E = OvlExpr->decls_end(); 
9979          I != E; ++I) {
9980       // Look through any using declarations to find the underlying function.
9981       NamedDecl *Fn = (*I)->getUnderlyingDecl();
9982
9983       // C++ [over.over]p3:
9984       //   Non-member functions and static member functions match
9985       //   targets of type "pointer-to-function" or "reference-to-function."
9986       //   Nonstatic member functions match targets of
9987       //   type "pointer-to-member-function."
9988       // Note that according to DR 247, the containing class does not matter.
9989       if (FunctionTemplateDecl *FunctionTemplate
9990                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
9991         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9992           Ret = true;
9993       }
9994       // If we have explicit template arguments supplied, skip non-templates.
9995       else if (!OvlExpr->hasExplicitTemplateArgs() &&
9996                AddMatchingNonTemplateFunction(Fn, I.getPair()))
9997         Ret = true;
9998     }
9999     assert(Ret || Matches.empty());
10000     return Ret;
10001   }
10002
10003   void EliminateAllExceptMostSpecializedTemplate() {
10004     //   [...] and any given function template specialization F1 is
10005     //   eliminated if the set contains a second function template
10006     //   specialization whose function template is more specialized
10007     //   than the function template of F1 according to the partial
10008     //   ordering rules of 14.5.5.2.
10009
10010     // The algorithm specified above is quadratic. We instead use a
10011     // two-pass algorithm (similar to the one used to identify the
10012     // best viable function in an overload set) that identifies the
10013     // best function template (if it exists).
10014
10015     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10016     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10017       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10018
10019     // TODO: It looks like FailedCandidates does not serve much purpose
10020     // here, since the no_viable diagnostic has index 0.
10021     UnresolvedSetIterator Result = S.getMostSpecialized(
10022         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10023         SourceExpr->getLocStart(), S.PDiag(),
10024         S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10025                                                      .second->getDeclName(),
10026         S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10027         Complain, TargetFunctionType);
10028
10029     if (Result != MatchesCopy.end()) {
10030       // Make it the first and only element
10031       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10032       Matches[0].second = cast<FunctionDecl>(*Result);
10033       Matches.resize(1);
10034     }
10035   }
10036
10037   void EliminateAllTemplateMatches() {
10038     //   [...] any function template specializations in the set are
10039     //   eliminated if the set also contains a non-template function, [...]
10040     for (unsigned I = 0, N = Matches.size(); I != N; ) {
10041       if (Matches[I].second->getPrimaryTemplate() == nullptr)
10042         ++I;
10043       else {
10044         Matches[I] = Matches[--N];
10045         Matches.set_size(N);
10046       }
10047     }
10048   }
10049
10050 public:
10051   void ComplainNoMatchesFound() const {
10052     assert(Matches.empty());
10053     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10054         << OvlExpr->getName() << TargetFunctionType
10055         << OvlExpr->getSourceRange();
10056     if (FailedCandidates.empty())
10057       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10058     else {
10059       // We have some deduction failure messages. Use them to diagnose
10060       // the function templates, and diagnose the non-template candidates
10061       // normally.
10062       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10063                                  IEnd = OvlExpr->decls_end();
10064            I != IEnd; ++I)
10065         if (FunctionDecl *Fun =
10066                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10067           S.NoteOverloadCandidate(Fun, TargetFunctionType);
10068       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10069     }
10070   }
10071
10072   bool IsInvalidFormOfPointerToMemberFunction() const {
10073     return TargetTypeIsNonStaticMemberFunction &&
10074       !OvlExprInfo.HasFormOfMemberPointer;
10075   }
10076
10077   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10078       // TODO: Should we condition this on whether any functions might
10079       // have matched, or is it more appropriate to do that in callers?
10080       // TODO: a fixit wouldn't hurt.
10081       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10082         << TargetType << OvlExpr->getSourceRange();
10083   }
10084
10085   bool IsStaticMemberFunctionFromBoundPointer() const {
10086     return StaticMemberFunctionFromBoundPointer;
10087   }
10088
10089   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10090     S.Diag(OvlExpr->getLocStart(),
10091            diag::err_invalid_form_pointer_member_function)
10092       << OvlExpr->getSourceRange();
10093   }
10094
10095   void ComplainOfInvalidConversion() const {
10096     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10097       << OvlExpr->getName() << TargetType;
10098   }
10099
10100   void ComplainMultipleMatchesFound() const {
10101     assert(Matches.size() > 1);
10102     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10103       << OvlExpr->getName()
10104       << OvlExpr->getSourceRange();
10105     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10106   }
10107
10108   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10109
10110   int getNumMatches() const { return Matches.size(); }
10111   
10112   FunctionDecl* getMatchingFunctionDecl() const {
10113     if (Matches.size() != 1) return nullptr;
10114     return Matches[0].second;
10115   }
10116   
10117   const DeclAccessPair* getMatchingFunctionAccessPair() const {
10118     if (Matches.size() != 1) return nullptr;
10119     return &Matches[0].first;
10120   }
10121 };
10122 }
10123
10124 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10125 /// an overloaded function (C++ [over.over]), where @p From is an
10126 /// expression with overloaded function type and @p ToType is the type
10127 /// we're trying to resolve to. For example:
10128 ///
10129 /// @code
10130 /// int f(double);
10131 /// int f(int);
10132 ///
10133 /// int (*pfd)(double) = f; // selects f(double)
10134 /// @endcode
10135 ///
10136 /// This routine returns the resulting FunctionDecl if it could be
10137 /// resolved, and NULL otherwise. When @p Complain is true, this
10138 /// routine will emit diagnostics if there is an error.
10139 FunctionDecl *
10140 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10141                                          QualType TargetType,
10142                                          bool Complain,
10143                                          DeclAccessPair &FoundResult,
10144                                          bool *pHadMultipleCandidates) {
10145   assert(AddressOfExpr->getType() == Context.OverloadTy);
10146
10147   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10148                                      Complain);
10149   int NumMatches = Resolver.getNumMatches();
10150   FunctionDecl *Fn = nullptr;
10151   if (NumMatches == 0 && Complain) {
10152     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10153       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10154     else
10155       Resolver.ComplainNoMatchesFound();
10156   }
10157   else if (NumMatches > 1 && Complain)
10158     Resolver.ComplainMultipleMatchesFound();
10159   else if (NumMatches == 1) {
10160     Fn = Resolver.getMatchingFunctionDecl();
10161     assert(Fn);
10162     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10163     if (Complain) {
10164       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10165         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10166       else
10167         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10168     }
10169   }
10170
10171   if (pHadMultipleCandidates)
10172     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10173   return Fn;
10174 }
10175
10176 /// \brief Given an expression that refers to an overloaded function, try to
10177 /// resolve that overloaded function expression down to a single function.
10178 ///
10179 /// This routine can only resolve template-ids that refer to a single function
10180 /// template, where that template-id refers to a single template whose template
10181 /// arguments are either provided by the template-id or have defaults,
10182 /// as described in C++0x [temp.arg.explicit]p3.
10183 ///
10184 /// If no template-ids are found, no diagnostics are emitted and NULL is
10185 /// returned.
10186 FunctionDecl *
10187 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 
10188                                                   bool Complain,
10189                                                   DeclAccessPair *FoundResult) {
10190   // C++ [over.over]p1:
10191   //   [...] [Note: any redundant set of parentheses surrounding the
10192   //   overloaded function name is ignored (5.1). ]
10193   // C++ [over.over]p1:
10194   //   [...] The overloaded function name can be preceded by the &
10195   //   operator.
10196
10197   // If we didn't actually find any template-ids, we're done.
10198   if (!ovl->hasExplicitTemplateArgs())
10199     return nullptr;
10200
10201   TemplateArgumentListInfo ExplicitTemplateArgs;
10202   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
10203   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10204
10205   // Look through all of the overloaded functions, searching for one
10206   // whose type matches exactly.
10207   FunctionDecl *Matched = nullptr;
10208   for (UnresolvedSetIterator I = ovl->decls_begin(),
10209          E = ovl->decls_end(); I != E; ++I) {
10210     // C++0x [temp.arg.explicit]p3:
10211     //   [...] In contexts where deduction is done and fails, or in contexts
10212     //   where deduction is not done, if a template argument list is
10213     //   specified and it, along with any default template arguments,
10214     //   identifies a single function template specialization, then the
10215     //   template-id is an lvalue for the function template specialization.
10216     FunctionTemplateDecl *FunctionTemplate
10217       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10218
10219     // C++ [over.over]p2:
10220     //   If the name is a function template, template argument deduction is
10221     //   done (14.8.2.2), and if the argument deduction succeeds, the
10222     //   resulting template argument list is used to generate a single
10223     //   function template specialization, which is added to the set of
10224     //   overloaded functions considered.
10225     FunctionDecl *Specialization = nullptr;
10226     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10227     if (TemplateDeductionResult Result
10228           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10229                                     Specialization, Info,
10230                                     /*InOverloadResolution=*/true)) {
10231       // Make a note of the failed deduction for diagnostics.
10232       // TODO: Actually use the failed-deduction info?
10233       FailedCandidates.addCandidate()
10234           .set(FunctionTemplate->getTemplatedDecl(),
10235                MakeDeductionFailureInfo(Context, Result, Info));
10236       continue;
10237     }
10238
10239     assert(Specialization && "no specialization and no error?");
10240
10241     // Multiple matches; we can't resolve to a single declaration.
10242     if (Matched) {
10243       if (Complain) {
10244         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10245           << ovl->getName();
10246         NoteAllOverloadCandidates(ovl);
10247       }
10248       return nullptr;
10249     }
10250     
10251     Matched = Specialization;
10252     if (FoundResult) *FoundResult = I.getPair();    
10253   }
10254
10255   if (Matched && getLangOpts().CPlusPlus14 &&
10256       Matched->getReturnType()->isUndeducedType() &&
10257       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10258     return nullptr;
10259
10260   return Matched;
10261 }
10262
10263
10264
10265
10266 // Resolve and fix an overloaded expression that can be resolved
10267 // because it identifies a single function template specialization.
10268 //
10269 // Last three arguments should only be supplied if Complain = true
10270 //
10271 // Return true if it was logically possible to so resolve the
10272 // expression, regardless of whether or not it succeeded.  Always
10273 // returns true if 'complain' is set.
10274 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10275                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10276                    bool complain, const SourceRange& OpRangeForComplaining, 
10277                                            QualType DestTypeForComplaining, 
10278                                             unsigned DiagIDForComplaining) {
10279   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10280
10281   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10282
10283   DeclAccessPair found;
10284   ExprResult SingleFunctionExpression;
10285   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10286                            ovl.Expression, /*complain*/ false, &found)) {
10287     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10288       SrcExpr = ExprError();
10289       return true;
10290     }
10291
10292     // It is only correct to resolve to an instance method if we're
10293     // resolving a form that's permitted to be a pointer to member.
10294     // Otherwise we'll end up making a bound member expression, which
10295     // is illegal in all the contexts we resolve like this.
10296     if (!ovl.HasFormOfMemberPointer &&
10297         isa<CXXMethodDecl>(fn) &&
10298         cast<CXXMethodDecl>(fn)->isInstance()) {
10299       if (!complain) return false;
10300
10301       Diag(ovl.Expression->getExprLoc(),
10302            diag::err_bound_member_function)
10303         << 0 << ovl.Expression->getSourceRange();
10304
10305       // TODO: I believe we only end up here if there's a mix of
10306       // static and non-static candidates (otherwise the expression
10307       // would have 'bound member' type, not 'overload' type).
10308       // Ideally we would note which candidate was chosen and why
10309       // the static candidates were rejected.
10310       SrcExpr = ExprError();
10311       return true;
10312     }
10313
10314     // Fix the expression to refer to 'fn'.
10315     SingleFunctionExpression =
10316         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10317
10318     // If desired, do function-to-pointer decay.
10319     if (doFunctionPointerConverion) {
10320       SingleFunctionExpression =
10321         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10322       if (SingleFunctionExpression.isInvalid()) {
10323         SrcExpr = ExprError();
10324         return true;
10325       }
10326     }
10327   }
10328
10329   if (!SingleFunctionExpression.isUsable()) {
10330     if (complain) {
10331       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10332         << ovl.Expression->getName()
10333         << DestTypeForComplaining
10334         << OpRangeForComplaining 
10335         << ovl.Expression->getQualifierLoc().getSourceRange();
10336       NoteAllOverloadCandidates(SrcExpr.get());
10337
10338       SrcExpr = ExprError();
10339       return true;
10340     }
10341
10342     return false;
10343   }
10344
10345   SrcExpr = SingleFunctionExpression;
10346   return true;
10347 }
10348
10349 /// \brief Add a single candidate to the overload set.
10350 static void AddOverloadedCallCandidate(Sema &S,
10351                                        DeclAccessPair FoundDecl,
10352                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
10353                                        ArrayRef<Expr *> Args,
10354                                        OverloadCandidateSet &CandidateSet,
10355                                        bool PartialOverloading,
10356                                        bool KnownValid) {
10357   NamedDecl *Callee = FoundDecl.getDecl();
10358   if (isa<UsingShadowDecl>(Callee))
10359     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10360
10361   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10362     if (ExplicitTemplateArgs) {
10363       assert(!KnownValid && "Explicit template arguments?");
10364       return;
10365     }
10366     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10367                            PartialOverloading);
10368     return;
10369   }
10370
10371   if (FunctionTemplateDecl *FuncTemplate
10372       = dyn_cast<FunctionTemplateDecl>(Callee)) {
10373     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10374                                    ExplicitTemplateArgs, Args, CandidateSet);
10375     return;
10376   }
10377
10378   assert(!KnownValid && "unhandled case in overloaded call candidate");
10379 }
10380
10381 /// \brief Add the overload candidates named by callee and/or found by argument
10382 /// dependent lookup to the given overload set.
10383 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10384                                        ArrayRef<Expr *> Args,
10385                                        OverloadCandidateSet &CandidateSet,
10386                                        bool PartialOverloading) {
10387
10388 #ifndef NDEBUG
10389   // Verify that ArgumentDependentLookup is consistent with the rules
10390   // in C++0x [basic.lookup.argdep]p3:
10391   //
10392   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10393   //   and let Y be the lookup set produced by argument dependent
10394   //   lookup (defined as follows). If X contains
10395   //
10396   //     -- a declaration of a class member, or
10397   //
10398   //     -- a block-scope function declaration that is not a
10399   //        using-declaration, or
10400   //
10401   //     -- a declaration that is neither a function or a function
10402   //        template
10403   //
10404   //   then Y is empty.
10405
10406   if (ULE->requiresADL()) {
10407     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10408            E = ULE->decls_end(); I != E; ++I) {
10409       assert(!(*I)->getDeclContext()->isRecord());
10410       assert(isa<UsingShadowDecl>(*I) ||
10411              !(*I)->getDeclContext()->isFunctionOrMethod());
10412       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
10413     }
10414   }
10415 #endif
10416
10417   // It would be nice to avoid this copy.
10418   TemplateArgumentListInfo TABuffer;
10419   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10420   if (ULE->hasExplicitTemplateArgs()) {
10421     ULE->copyTemplateArgumentsInto(TABuffer);
10422     ExplicitTemplateArgs = &TABuffer;
10423   }
10424
10425   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10426          E = ULE->decls_end(); I != E; ++I)
10427     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10428                                CandidateSet, PartialOverloading,
10429                                /*KnownValid*/ true);
10430
10431   if (ULE->requiresADL())
10432     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10433                                          Args, ExplicitTemplateArgs,
10434                                          CandidateSet, PartialOverloading);
10435 }
10436
10437 /// Determine whether a declaration with the specified name could be moved into
10438 /// a different namespace.
10439 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10440   switch (Name.getCXXOverloadedOperator()) {
10441   case OO_New: case OO_Array_New:
10442   case OO_Delete: case OO_Array_Delete:
10443     return false;
10444
10445   default:
10446     return true;
10447   }
10448 }
10449
10450 /// Attempt to recover from an ill-formed use of a non-dependent name in a
10451 /// template, where the non-dependent name was declared after the template
10452 /// was defined. This is common in code written for a compilers which do not
10453 /// correctly implement two-stage name lookup.
10454 ///
10455 /// Returns true if a viable candidate was found and a diagnostic was issued.
10456 static bool
10457 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10458                        const CXXScopeSpec &SS, LookupResult &R,
10459                        OverloadCandidateSet::CandidateSetKind CSK,
10460                        TemplateArgumentListInfo *ExplicitTemplateArgs,
10461                        ArrayRef<Expr *> Args) {
10462   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10463     return false;
10464
10465   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10466     if (DC->isTransparentContext())
10467       continue;
10468
10469     SemaRef.LookupQualifiedName(R, DC);
10470
10471     if (!R.empty()) {
10472       R.suppressDiagnostics();
10473
10474       if (isa<CXXRecordDecl>(DC)) {
10475         // Don't diagnose names we find in classes; we get much better
10476         // diagnostics for these from DiagnoseEmptyLookup.
10477         R.clear();
10478         return false;
10479       }
10480
10481       OverloadCandidateSet Candidates(FnLoc, CSK);
10482       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10483         AddOverloadedCallCandidate(SemaRef, I.getPair(),
10484                                    ExplicitTemplateArgs, Args,
10485                                    Candidates, false, /*KnownValid*/ false);
10486
10487       OverloadCandidateSet::iterator Best;
10488       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10489         // No viable functions. Don't bother the user with notes for functions
10490         // which don't work and shouldn't be found anyway.
10491         R.clear();
10492         return false;
10493       }
10494
10495       // Find the namespaces where ADL would have looked, and suggest
10496       // declaring the function there instead.
10497       Sema::AssociatedNamespaceSet AssociatedNamespaces;
10498       Sema::AssociatedClassSet AssociatedClasses;
10499       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10500                                                  AssociatedNamespaces,
10501                                                  AssociatedClasses);
10502       Sema::AssociatedNamespaceSet SuggestedNamespaces;
10503       if (canBeDeclaredInNamespace(R.getLookupName())) {
10504         DeclContext *Std = SemaRef.getStdNamespace();
10505         for (Sema::AssociatedNamespaceSet::iterator
10506                it = AssociatedNamespaces.begin(),
10507                end = AssociatedNamespaces.end(); it != end; ++it) {
10508           // Never suggest declaring a function within namespace 'std'.
10509           if (Std && Std->Encloses(*it))
10510             continue;
10511
10512           // Never suggest declaring a function within a namespace with a
10513           // reserved name, like __gnu_cxx.
10514           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10515           if (NS &&
10516               NS->getQualifiedNameAsString().find("__") != std::string::npos)
10517             continue;
10518
10519           SuggestedNamespaces.insert(*it);
10520         }
10521       }
10522
10523       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10524         << R.getLookupName();
10525       if (SuggestedNamespaces.empty()) {
10526         SemaRef.Diag(Best->Function->getLocation(),
10527                      diag::note_not_found_by_two_phase_lookup)
10528           << R.getLookupName() << 0;
10529       } else if (SuggestedNamespaces.size() == 1) {
10530         SemaRef.Diag(Best->Function->getLocation(),
10531                      diag::note_not_found_by_two_phase_lookup)
10532           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10533       } else {
10534         // FIXME: It would be useful to list the associated namespaces here,
10535         // but the diagnostics infrastructure doesn't provide a way to produce
10536         // a localized representation of a list of items.
10537         SemaRef.Diag(Best->Function->getLocation(),
10538                      diag::note_not_found_by_two_phase_lookup)
10539           << R.getLookupName() << 2;
10540       }
10541
10542       // Try to recover by calling this function.
10543       return true;
10544     }
10545
10546     R.clear();
10547   }
10548
10549   return false;
10550 }
10551
10552 /// Attempt to recover from ill-formed use of a non-dependent operator in a
10553 /// template, where the non-dependent operator was declared after the template
10554 /// was defined.
10555 ///
10556 /// Returns true if a viable candidate was found and a diagnostic was issued.
10557 static bool
10558 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10559                                SourceLocation OpLoc,
10560                                ArrayRef<Expr *> Args) {
10561   DeclarationName OpName =
10562     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10563   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10564   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10565                                 OverloadCandidateSet::CSK_Operator,
10566                                 /*ExplicitTemplateArgs=*/nullptr, Args);
10567 }
10568
10569 namespace {
10570 class BuildRecoveryCallExprRAII {
10571   Sema &SemaRef;
10572 public:
10573   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10574     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10575     SemaRef.IsBuildingRecoveryCallExpr = true;
10576   }
10577
10578   ~BuildRecoveryCallExprRAII() {
10579     SemaRef.IsBuildingRecoveryCallExpr = false;
10580   }
10581 };
10582
10583 }
10584
10585 static std::unique_ptr<CorrectionCandidateCallback>
10586 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10587               bool HasTemplateArgs, bool AllowTypoCorrection) {
10588   if (!AllowTypoCorrection)
10589     return llvm::make_unique<NoTypoCorrectionCCC>();
10590   return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10591                                                   HasTemplateArgs, ME);
10592 }
10593
10594 /// Attempts to recover from a call where no functions were found.
10595 ///
10596 /// Returns true if new candidates were found.
10597 static ExprResult
10598 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10599                       UnresolvedLookupExpr *ULE,
10600                       SourceLocation LParenLoc,
10601                       MutableArrayRef<Expr *> Args,
10602                       SourceLocation RParenLoc,
10603                       bool EmptyLookup, bool AllowTypoCorrection) {
10604   // Do not try to recover if it is already building a recovery call.
10605   // This stops infinite loops for template instantiations like
10606   //
10607   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10608   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10609   //
10610   if (SemaRef.IsBuildingRecoveryCallExpr)
10611     return ExprError();
10612   BuildRecoveryCallExprRAII RCE(SemaRef);
10613
10614   CXXScopeSpec SS;
10615   SS.Adopt(ULE->getQualifierLoc());
10616   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10617
10618   TemplateArgumentListInfo TABuffer;
10619   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10620   if (ULE->hasExplicitTemplateArgs()) {
10621     ULE->copyTemplateArgumentsInto(TABuffer);
10622     ExplicitTemplateArgs = &TABuffer;
10623   }
10624
10625   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10626                  Sema::LookupOrdinaryName);
10627   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10628                               OverloadCandidateSet::CSK_Normal,
10629                               ExplicitTemplateArgs, Args) &&
10630       (!EmptyLookup ||
10631        SemaRef.DiagnoseEmptyLookup(
10632            S, SS, R,
10633            MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10634                          ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10635            ExplicitTemplateArgs, Args)))
10636     return ExprError();
10637
10638   assert(!R.empty() && "lookup results empty despite recovery");
10639
10640   // Build an implicit member call if appropriate.  Just drop the
10641   // casts and such from the call, we don't really care.
10642   ExprResult NewFn = ExprError();
10643   if ((*R.begin())->isCXXClassMember())
10644     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10645                                                     R, ExplicitTemplateArgs);
10646   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10647     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10648                                         ExplicitTemplateArgs);
10649   else
10650     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10651
10652   if (NewFn.isInvalid())
10653     return ExprError();
10654
10655   // This shouldn't cause an infinite loop because we're giving it
10656   // an expression with viable lookup results, which should never
10657   // end up here.
10658   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
10659                                MultiExprArg(Args.data(), Args.size()),
10660                                RParenLoc);
10661 }
10662
10663 /// \brief Constructs and populates an OverloadedCandidateSet from
10664 /// the given function.
10665 /// \returns true when an the ExprResult output parameter has been set.
10666 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10667                                   UnresolvedLookupExpr *ULE,
10668                                   MultiExprArg Args,
10669                                   SourceLocation RParenLoc,
10670                                   OverloadCandidateSet *CandidateSet,
10671                                   ExprResult *Result) {
10672 #ifndef NDEBUG
10673   if (ULE->requiresADL()) {
10674     // To do ADL, we must have found an unqualified name.
10675     assert(!ULE->getQualifier() && "qualified name with ADL");
10676
10677     // We don't perform ADL for implicit declarations of builtins.
10678     // Verify that this was correctly set up.
10679     FunctionDecl *F;
10680     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10681         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10682         F->getBuiltinID() && F->isImplicit())
10683       llvm_unreachable("performing ADL for builtin");
10684
10685     // We don't perform ADL in C.
10686     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10687   }
10688 #endif
10689
10690   UnbridgedCastsSet UnbridgedCasts;
10691   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10692     *Result = ExprError();
10693     return true;
10694   }
10695
10696   // Add the functions denoted by the callee to the set of candidate
10697   // functions, including those from argument-dependent lookup.
10698   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10699
10700   // If we found nothing, try to recover.
10701   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10702   // out if it fails.
10703   if (CandidateSet->empty()) {
10704     // In Microsoft mode, if we are inside a template class member function then
10705     // create a type dependent CallExpr. The goal is to postpone name lookup
10706     // to instantiation time to be able to search into type dependent base
10707     // classes.
10708     if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
10709         (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10710       CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10711                                             Context.DependentTy, VK_RValue,
10712                                             RParenLoc);
10713       CE->setTypeDependent(true);
10714       *Result = CE;
10715       return true;
10716     }
10717     return false;
10718   }
10719
10720   UnbridgedCasts.restore();
10721   return false;
10722 }
10723
10724 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10725 /// the completed call expression. If overload resolution fails, emits
10726 /// diagnostics and returns ExprError()
10727 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10728                                            UnresolvedLookupExpr *ULE,
10729                                            SourceLocation LParenLoc,
10730                                            MultiExprArg Args,
10731                                            SourceLocation RParenLoc,
10732                                            Expr *ExecConfig,
10733                                            OverloadCandidateSet *CandidateSet,
10734                                            OverloadCandidateSet::iterator *Best,
10735                                            OverloadingResult OverloadResult,
10736                                            bool AllowTypoCorrection) {
10737   if (CandidateSet->empty())
10738     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10739                                  RParenLoc, /*EmptyLookup=*/true,
10740                                  AllowTypoCorrection);
10741
10742   switch (OverloadResult) {
10743   case OR_Success: {
10744     FunctionDecl *FDecl = (*Best)->Function;
10745     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10746     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10747       return ExprError();
10748     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10749     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10750                                          ExecConfig);
10751   }
10752
10753   case OR_No_Viable_Function: {
10754     // Try to recover by looking for viable functions which the user might
10755     // have meant to call.
10756     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10757                                                 Args, RParenLoc,
10758                                                 /*EmptyLookup=*/false,
10759                                                 AllowTypoCorrection);
10760     if (!Recovery.isInvalid())
10761       return Recovery;
10762
10763     SemaRef.Diag(Fn->getLocStart(),
10764          diag::err_ovl_no_viable_function_in_call)
10765       << ULE->getName() << Fn->getSourceRange();
10766     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10767     break;
10768   }
10769
10770   case OR_Ambiguous:
10771     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10772       << ULE->getName() << Fn->getSourceRange();
10773     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10774     break;
10775
10776   case OR_Deleted: {
10777     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10778       << (*Best)->Function->isDeleted()
10779       << ULE->getName()
10780       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10781       << Fn->getSourceRange();
10782     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10783
10784     // We emitted an error for the unvailable/deleted function call but keep
10785     // the call in the AST.
10786     FunctionDecl *FDecl = (*Best)->Function;
10787     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10788     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10789                                          ExecConfig);
10790   }
10791   }
10792
10793   // Overload resolution failed.
10794   return ExprError();
10795 }
10796
10797 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10798 /// (which eventually refers to the declaration Func) and the call
10799 /// arguments Args/NumArgs, attempt to resolve the function call down
10800 /// to a specific function. If overload resolution succeeds, returns
10801 /// the call expression produced by overload resolution.
10802 /// Otherwise, emits diagnostics and returns ExprError.
10803 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10804                                          UnresolvedLookupExpr *ULE,
10805                                          SourceLocation LParenLoc,
10806                                          MultiExprArg Args,
10807                                          SourceLocation RParenLoc,
10808                                          Expr *ExecConfig,
10809                                          bool AllowTypoCorrection) {
10810   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10811                                     OverloadCandidateSet::CSK_Normal);
10812   ExprResult result;
10813
10814   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10815                              &result))
10816     return result;
10817
10818   OverloadCandidateSet::iterator Best;
10819   OverloadingResult OverloadResult =
10820       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10821
10822   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10823                                   RParenLoc, ExecConfig, &CandidateSet,
10824                                   &Best, OverloadResult,
10825                                   AllowTypoCorrection);
10826 }
10827
10828 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10829   return Functions.size() > 1 ||
10830     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10831 }
10832
10833 /// \brief Create a unary operation that may resolve to an overloaded
10834 /// operator.
10835 ///
10836 /// \param OpLoc The location of the operator itself (e.g., '*').
10837 ///
10838 /// \param OpcIn The UnaryOperator::Opcode that describes this
10839 /// operator.
10840 ///
10841 /// \param Fns The set of non-member functions that will be
10842 /// considered by overload resolution. The caller needs to build this
10843 /// set based on the context using, e.g.,
10844 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10845 /// set should not contain any member functions; those will be added
10846 /// by CreateOverloadedUnaryOp().
10847 ///
10848 /// \param Input The input argument.
10849 ExprResult
10850 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10851                               const UnresolvedSetImpl &Fns,
10852                               Expr *Input) {
10853   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10854
10855   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10856   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10857   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10858   // TODO: provide better source location info.
10859   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10860
10861   if (checkPlaceholderForOverload(*this, Input))
10862     return ExprError();
10863
10864   Expr *Args[2] = { Input, nullptr };
10865   unsigned NumArgs = 1;
10866
10867   // For post-increment and post-decrement, add the implicit '0' as
10868   // the second argument, so that we know this is a post-increment or
10869   // post-decrement.
10870   if (Opc == UO_PostInc || Opc == UO_PostDec) {
10871     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10872     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10873                                      SourceLocation());
10874     NumArgs = 2;
10875   }
10876
10877   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10878
10879   if (Input->isTypeDependent()) {
10880     if (Fns.empty())
10881       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10882                                          VK_RValue, OK_Ordinary, OpLoc);
10883
10884     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10885     UnresolvedLookupExpr *Fn
10886       = UnresolvedLookupExpr::Create(Context, NamingClass,
10887                                      NestedNameSpecifierLoc(), OpNameInfo,
10888                                      /*ADL*/ true, IsOverloaded(Fns),
10889                                      Fns.begin(), Fns.end());
10890     return new (Context)
10891         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10892                             VK_RValue, OpLoc, false);
10893   }
10894
10895   // Build an empty overload set.
10896   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
10897
10898   // Add the candidates from the given function set.
10899   AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
10900
10901   // Add operator candidates that are member functions.
10902   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10903
10904   // Add candidates from ADL.
10905   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
10906                                        /*ExplicitTemplateArgs*/nullptr,
10907                                        CandidateSet);
10908
10909   // Add builtin operator candidates.
10910   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10911
10912   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10913
10914   // Perform overload resolution.
10915   OverloadCandidateSet::iterator Best;
10916   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10917   case OR_Success: {
10918     // We found a built-in operator or an overloaded operator.
10919     FunctionDecl *FnDecl = Best->Function;
10920
10921     if (FnDecl) {
10922       // We matched an overloaded operator. Build a call to that
10923       // operator.
10924
10925       // Convert the arguments.
10926       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10927         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
10928
10929         ExprResult InputRes =
10930           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
10931                                               Best->FoundDecl, Method);
10932         if (InputRes.isInvalid())
10933           return ExprError();
10934         Input = InputRes.get();
10935       } else {
10936         // Convert the arguments.
10937         ExprResult InputInit
10938           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10939                                                       Context,
10940                                                       FnDecl->getParamDecl(0)),
10941                                       SourceLocation(),
10942                                       Input);
10943         if (InputInit.isInvalid())
10944           return ExprError();
10945         Input = InputInit.get();
10946       }
10947
10948       // Build the actual expression node.
10949       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10950                                                 HadMultipleCandidates, OpLoc);
10951       if (FnExpr.isInvalid())
10952         return ExprError();
10953
10954       // Determine the result type.
10955       QualType ResultTy = FnDecl->getReturnType();
10956       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10957       ResultTy = ResultTy.getNonLValueExprType(Context);
10958
10959       Args[0] = Input;
10960       CallExpr *TheCall =
10961         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
10962                                           ResultTy, VK, OpLoc, false);
10963
10964       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
10965         return ExprError();
10966
10967       return MaybeBindToTemporary(TheCall);
10968     } else {
10969       // We matched a built-in operator. Convert the arguments, then
10970       // break out so that we will build the appropriate built-in
10971       // operator node.
10972       ExprResult InputRes =
10973         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10974                                   Best->Conversions[0], AA_Passing);
10975       if (InputRes.isInvalid())
10976         return ExprError();
10977       Input = InputRes.get();
10978       break;
10979     }
10980   }
10981
10982   case OR_No_Viable_Function:
10983     // This is an erroneous use of an operator which can be overloaded by
10984     // a non-member function. Check for non-member operators which were
10985     // defined too late to be candidates.
10986     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
10987       // FIXME: Recover by calling the found function.
10988       return ExprError();
10989
10990     // No viable function; fall through to handling this as a
10991     // built-in operator, which will produce an error message for us.
10992     break;
10993
10994   case OR_Ambiguous:
10995     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10996         << UnaryOperator::getOpcodeStr(Opc)
10997         << Input->getType()
10998         << Input->getSourceRange();
10999     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11000                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11001     return ExprError();
11002
11003   case OR_Deleted:
11004     Diag(OpLoc, diag::err_ovl_deleted_oper)
11005       << Best->Function->isDeleted()
11006       << UnaryOperator::getOpcodeStr(Opc)
11007       << getDeletedOrUnavailableSuffix(Best->Function)
11008       << Input->getSourceRange();
11009     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11010                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11011     return ExprError();
11012   }
11013
11014   // Either we found no viable overloaded operator or we matched a
11015   // built-in operator. In either case, fall through to trying to
11016   // build a built-in operation.
11017   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11018 }
11019
11020 /// \brief Create a binary operation that may resolve to an overloaded
11021 /// operator.
11022 ///
11023 /// \param OpLoc The location of the operator itself (e.g., '+').
11024 ///
11025 /// \param OpcIn The BinaryOperator::Opcode that describes this
11026 /// operator.
11027 ///
11028 /// \param Fns The set of non-member functions that will be
11029 /// considered by overload resolution. The caller needs to build this
11030 /// set based on the context using, e.g.,
11031 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11032 /// set should not contain any member functions; those will be added
11033 /// by CreateOverloadedBinOp().
11034 ///
11035 /// \param LHS Left-hand argument.
11036 /// \param RHS Right-hand argument.
11037 ExprResult
11038 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11039                             unsigned OpcIn,
11040                             const UnresolvedSetImpl &Fns,
11041                             Expr *LHS, Expr *RHS) {
11042   Expr *Args[2] = { LHS, RHS };
11043   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11044
11045   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11046   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11047   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11048
11049   // If either side is type-dependent, create an appropriate dependent
11050   // expression.
11051   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11052     if (Fns.empty()) {
11053       // If there are no functions to store, just build a dependent
11054       // BinaryOperator or CompoundAssignment.
11055       if (Opc <= BO_Assign || Opc > BO_OrAssign)
11056         return new (Context) BinaryOperator(
11057             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11058             OpLoc, FPFeatures.fp_contract);
11059
11060       return new (Context) CompoundAssignOperator(
11061           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11062           Context.DependentTy, Context.DependentTy, OpLoc,
11063           FPFeatures.fp_contract);
11064     }
11065
11066     // FIXME: save results of ADL from here?
11067     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11068     // TODO: provide better source location info in DNLoc component.
11069     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11070     UnresolvedLookupExpr *Fn
11071       = UnresolvedLookupExpr::Create(Context, NamingClass, 
11072                                      NestedNameSpecifierLoc(), OpNameInfo, 
11073                                      /*ADL*/ true, IsOverloaded(Fns),
11074                                      Fns.begin(), Fns.end());
11075     return new (Context)
11076         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11077                             VK_RValue, OpLoc, FPFeatures.fp_contract);
11078   }
11079
11080   // Always do placeholder-like conversions on the RHS.
11081   if (checkPlaceholderForOverload(*this, Args[1]))
11082     return ExprError();
11083
11084   // Do placeholder-like conversion on the LHS; note that we should
11085   // not get here with a PseudoObject LHS.
11086   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11087   if (checkPlaceholderForOverload(*this, Args[0]))
11088     return ExprError();
11089
11090   // If this is the assignment operator, we only perform overload resolution
11091   // if the left-hand side is a class or enumeration type. This is actually
11092   // a hack. The standard requires that we do overload resolution between the
11093   // various built-in candidates, but as DR507 points out, this can lead to
11094   // problems. So we do it this way, which pretty much follows what GCC does.
11095   // Note that we go the traditional code path for compound assignment forms.
11096   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11097     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11098
11099   // If this is the .* operator, which is not overloadable, just
11100   // create a built-in binary operator.
11101   if (Opc == BO_PtrMemD)
11102     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11103
11104   // Build an empty overload set.
11105   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11106
11107   // Add the candidates from the given function set.
11108   AddFunctionCandidates(Fns, Args, CandidateSet, false);
11109
11110   // Add operator candidates that are member functions.
11111   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11112
11113   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11114   // performed for an assignment operator (nor for operator[] nor operator->,
11115   // which don't get here).
11116   if (Opc != BO_Assign)
11117     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11118                                          /*ExplicitTemplateArgs*/ nullptr,
11119                                          CandidateSet);
11120
11121   // Add builtin operator candidates.
11122   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11123
11124   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11125
11126   // Perform overload resolution.
11127   OverloadCandidateSet::iterator Best;
11128   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11129     case OR_Success: {
11130       // We found a built-in operator or an overloaded operator.
11131       FunctionDecl *FnDecl = Best->Function;
11132
11133       if (FnDecl) {
11134         // We matched an overloaded operator. Build a call to that
11135         // operator.
11136
11137         // Convert the arguments.
11138         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11139           // Best->Access is only meaningful for class members.
11140           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11141
11142           ExprResult Arg1 =
11143             PerformCopyInitialization(
11144               InitializedEntity::InitializeParameter(Context,
11145                                                      FnDecl->getParamDecl(0)),
11146               SourceLocation(), Args[1]);
11147           if (Arg1.isInvalid())
11148             return ExprError();
11149
11150           ExprResult Arg0 =
11151             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11152                                                 Best->FoundDecl, Method);
11153           if (Arg0.isInvalid())
11154             return ExprError();
11155           Args[0] = Arg0.getAs<Expr>();
11156           Args[1] = RHS = Arg1.getAs<Expr>();
11157         } else {
11158           // Convert the arguments.
11159           ExprResult Arg0 = PerformCopyInitialization(
11160             InitializedEntity::InitializeParameter(Context,
11161                                                    FnDecl->getParamDecl(0)),
11162             SourceLocation(), Args[0]);
11163           if (Arg0.isInvalid())
11164             return ExprError();
11165
11166           ExprResult Arg1 =
11167             PerformCopyInitialization(
11168               InitializedEntity::InitializeParameter(Context,
11169                                                      FnDecl->getParamDecl(1)),
11170               SourceLocation(), Args[1]);
11171           if (Arg1.isInvalid())
11172             return ExprError();
11173           Args[0] = LHS = Arg0.getAs<Expr>();
11174           Args[1] = RHS = Arg1.getAs<Expr>();
11175         }
11176
11177         // Build the actual expression node.
11178         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11179                                                   Best->FoundDecl,
11180                                                   HadMultipleCandidates, OpLoc);
11181         if (FnExpr.isInvalid())
11182           return ExprError();
11183
11184         // Determine the result type.
11185         QualType ResultTy = FnDecl->getReturnType();
11186         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11187         ResultTy = ResultTy.getNonLValueExprType(Context);
11188
11189         CXXOperatorCallExpr *TheCall =
11190           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11191                                             Args, ResultTy, VK, OpLoc,
11192                                             FPFeatures.fp_contract);
11193
11194         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11195                                 FnDecl))
11196           return ExprError();
11197
11198         ArrayRef<const Expr *> ArgsArray(Args, 2);
11199         // Cut off the implicit 'this'.
11200         if (isa<CXXMethodDecl>(FnDecl))
11201           ArgsArray = ArgsArray.slice(1);
11202
11203         // Check for a self move.
11204         if (Op == OO_Equal)
11205           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11206
11207         checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
11208                   TheCall->getSourceRange(), VariadicDoesNotApply);
11209
11210         return MaybeBindToTemporary(TheCall);
11211       } else {
11212         // We matched a built-in operator. Convert the arguments, then
11213         // break out so that we will build the appropriate built-in
11214         // operator node.
11215         ExprResult ArgsRes0 =
11216           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11217                                     Best->Conversions[0], AA_Passing);
11218         if (ArgsRes0.isInvalid())
11219           return ExprError();
11220         Args[0] = ArgsRes0.get();
11221
11222         ExprResult ArgsRes1 =
11223           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11224                                     Best->Conversions[1], AA_Passing);
11225         if (ArgsRes1.isInvalid())
11226           return ExprError();
11227         Args[1] = ArgsRes1.get();
11228         break;
11229       }
11230     }
11231
11232     case OR_No_Viable_Function: {
11233       // C++ [over.match.oper]p9:
11234       //   If the operator is the operator , [...] and there are no
11235       //   viable functions, then the operator is assumed to be the
11236       //   built-in operator and interpreted according to clause 5.
11237       if (Opc == BO_Comma)
11238         break;
11239
11240       // For class as left operand for assignment or compound assigment
11241       // operator do not fall through to handling in built-in, but report that
11242       // no overloaded assignment operator found
11243       ExprResult Result = ExprError();
11244       if (Args[0]->getType()->isRecordType() &&
11245           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11246         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11247              << BinaryOperator::getOpcodeStr(Opc)
11248              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11249         if (Args[0]->getType()->isIncompleteType()) {
11250           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11251             << Args[0]->getType()
11252             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11253         }
11254       } else {
11255         // This is an erroneous use of an operator which can be overloaded by
11256         // a non-member function. Check for non-member operators which were
11257         // defined too late to be candidates.
11258         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11259           // FIXME: Recover by calling the found function.
11260           return ExprError();
11261
11262         // No viable function; try to create a built-in operation, which will
11263         // produce an error. Then, show the non-viable candidates.
11264         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11265       }
11266       assert(Result.isInvalid() &&
11267              "C++ binary operator overloading is missing candidates!");
11268       if (Result.isInvalid())
11269         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11270                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11271       return Result;
11272     }
11273
11274     case OR_Ambiguous:
11275       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11276           << BinaryOperator::getOpcodeStr(Opc)
11277           << Args[0]->getType() << Args[1]->getType()
11278           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11279       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11280                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11281       return ExprError();
11282
11283     case OR_Deleted:
11284       if (isImplicitlyDeleted(Best->Function)) {
11285         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11286         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11287           << Context.getRecordType(Method->getParent())
11288           << getSpecialMember(Method);
11289
11290         // The user probably meant to call this special member. Just
11291         // explain why it's deleted.
11292         NoteDeletedFunction(Method);
11293         return ExprError();
11294       } else {
11295         Diag(OpLoc, diag::err_ovl_deleted_oper)
11296           << Best->Function->isDeleted()
11297           << BinaryOperator::getOpcodeStr(Opc)
11298           << getDeletedOrUnavailableSuffix(Best->Function)
11299           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11300       }
11301       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11302                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11303       return ExprError();
11304   }
11305
11306   // We matched a built-in operator; build it.
11307   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11308 }
11309
11310 ExprResult
11311 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11312                                          SourceLocation RLoc,
11313                                          Expr *Base, Expr *Idx) {
11314   Expr *Args[2] = { Base, Idx };
11315   DeclarationName OpName =
11316       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11317
11318   // If either side is type-dependent, create an appropriate dependent
11319   // expression.
11320   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11321
11322     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11323     // CHECKME: no 'operator' keyword?
11324     DeclarationNameInfo OpNameInfo(OpName, LLoc);
11325     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11326     UnresolvedLookupExpr *Fn
11327       = UnresolvedLookupExpr::Create(Context, NamingClass,
11328                                      NestedNameSpecifierLoc(), OpNameInfo,
11329                                      /*ADL*/ true, /*Overloaded*/ false,
11330                                      UnresolvedSetIterator(),
11331                                      UnresolvedSetIterator());
11332     // Can't add any actual overloads yet
11333
11334     return new (Context)
11335         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11336                             Context.DependentTy, VK_RValue, RLoc, false);
11337   }
11338
11339   // Handle placeholders on both operands.
11340   if (checkPlaceholderForOverload(*this, Args[0]))
11341     return ExprError();
11342   if (checkPlaceholderForOverload(*this, Args[1]))
11343     return ExprError();
11344
11345   // Build an empty overload set.
11346   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11347
11348   // Subscript can only be overloaded as a member function.
11349
11350   // Add operator candidates that are member functions.
11351   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11352
11353   // Add builtin operator candidates.
11354   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11355
11356   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11357
11358   // Perform overload resolution.
11359   OverloadCandidateSet::iterator Best;
11360   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11361     case OR_Success: {
11362       // We found a built-in operator or an overloaded operator.
11363       FunctionDecl *FnDecl = Best->Function;
11364
11365       if (FnDecl) {
11366         // We matched an overloaded operator. Build a call to that
11367         // operator.
11368
11369         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11370
11371         // Convert the arguments.
11372         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11373         ExprResult Arg0 =
11374           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11375                                               Best->FoundDecl, Method);
11376         if (Arg0.isInvalid())
11377           return ExprError();
11378         Args[0] = Arg0.get();
11379
11380         // Convert the arguments.
11381         ExprResult InputInit
11382           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11383                                                       Context,
11384                                                       FnDecl->getParamDecl(0)),
11385                                       SourceLocation(),
11386                                       Args[1]);
11387         if (InputInit.isInvalid())
11388           return ExprError();
11389
11390         Args[1] = InputInit.getAs<Expr>();
11391
11392         // Build the actual expression node.
11393         DeclarationNameInfo OpLocInfo(OpName, LLoc);
11394         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11395         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11396                                                   Best->FoundDecl,
11397                                                   HadMultipleCandidates,
11398                                                   OpLocInfo.getLoc(),
11399                                                   OpLocInfo.getInfo());
11400         if (FnExpr.isInvalid())
11401           return ExprError();
11402
11403         // Determine the result type
11404         QualType ResultTy = FnDecl->getReturnType();
11405         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11406         ResultTy = ResultTy.getNonLValueExprType(Context);
11407
11408         CXXOperatorCallExpr *TheCall =
11409           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11410                                             FnExpr.get(), Args,
11411                                             ResultTy, VK, RLoc,
11412                                             false);
11413
11414         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11415           return ExprError();
11416
11417         return MaybeBindToTemporary(TheCall);
11418       } else {
11419         // We matched a built-in operator. Convert the arguments, then
11420         // break out so that we will build the appropriate built-in
11421         // operator node.
11422         ExprResult ArgsRes0 =
11423           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11424                                     Best->Conversions[0], AA_Passing);
11425         if (ArgsRes0.isInvalid())
11426           return ExprError();
11427         Args[0] = ArgsRes0.get();
11428
11429         ExprResult ArgsRes1 =
11430           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11431                                     Best->Conversions[1], AA_Passing);
11432         if (ArgsRes1.isInvalid())
11433           return ExprError();
11434         Args[1] = ArgsRes1.get();
11435
11436         break;
11437       }
11438     }
11439
11440     case OR_No_Viable_Function: {
11441       if (CandidateSet.empty())
11442         Diag(LLoc, diag::err_ovl_no_oper)
11443           << Args[0]->getType() << /*subscript*/ 0
11444           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11445       else
11446         Diag(LLoc, diag::err_ovl_no_viable_subscript)
11447           << Args[0]->getType()
11448           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11449       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11450                                   "[]", LLoc);
11451       return ExprError();
11452     }
11453
11454     case OR_Ambiguous:
11455       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
11456           << "[]"
11457           << Args[0]->getType() << Args[1]->getType()
11458           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11459       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11460                                   "[]", LLoc);
11461       return ExprError();
11462
11463     case OR_Deleted:
11464       Diag(LLoc, diag::err_ovl_deleted_oper)
11465         << Best->Function->isDeleted() << "[]"
11466         << getDeletedOrUnavailableSuffix(Best->Function)
11467         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11468       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11469                                   "[]", LLoc);
11470       return ExprError();
11471     }
11472
11473   // We matched a built-in operator; build it.
11474   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11475 }
11476
11477 /// BuildCallToMemberFunction - Build a call to a member
11478 /// function. MemExpr is the expression that refers to the member
11479 /// function (and includes the object parameter), Args/NumArgs are the
11480 /// arguments to the function call (not including the object
11481 /// parameter). The caller needs to validate that the member
11482 /// expression refers to a non-static member function or an overloaded
11483 /// member function.
11484 ExprResult
11485 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11486                                 SourceLocation LParenLoc,
11487                                 MultiExprArg Args,
11488                                 SourceLocation RParenLoc) {
11489   assert(MemExprE->getType() == Context.BoundMemberTy ||
11490          MemExprE->getType() == Context.OverloadTy);
11491
11492   // Dig out the member expression. This holds both the object
11493   // argument and the member function we're referring to.
11494   Expr *NakedMemExpr = MemExprE->IgnoreParens();
11495
11496   // Determine whether this is a call to a pointer-to-member function.
11497   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11498     assert(op->getType() == Context.BoundMemberTy);
11499     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11500
11501     QualType fnType =
11502       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11503
11504     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11505     QualType resultType = proto->getCallResultType(Context);
11506     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
11507
11508     // Check that the object type isn't more qualified than the
11509     // member function we're calling.
11510     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11511
11512     QualType objectType = op->getLHS()->getType();
11513     if (op->getOpcode() == BO_PtrMemI)
11514       objectType = objectType->castAs<PointerType>()->getPointeeType();
11515     Qualifiers objectQuals = objectType.getQualifiers();
11516
11517     Qualifiers difference = objectQuals - funcQuals;
11518     difference.removeObjCGCAttr();
11519     difference.removeAddressSpace();
11520     if (difference) {
11521       std::string qualsString = difference.getAsString();
11522       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11523         << fnType.getUnqualifiedType()
11524         << qualsString
11525         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11526     }
11527
11528     if (resultType->isMemberPointerType())
11529       if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11530         RequireCompleteType(LParenLoc, resultType, 0);
11531
11532     CXXMemberCallExpr *call
11533       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11534                                         resultType, valueKind, RParenLoc);
11535
11536     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
11537                             call, nullptr))
11538       return ExprError();
11539
11540     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
11541       return ExprError();
11542
11543     if (CheckOtherCall(call, proto))
11544       return ExprError();
11545
11546     return MaybeBindToTemporary(call);
11547   }
11548
11549   UnbridgedCastsSet UnbridgedCasts;
11550   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11551     return ExprError();
11552
11553   MemberExpr *MemExpr;
11554   CXXMethodDecl *Method = nullptr;
11555   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11556   NestedNameSpecifier *Qualifier = nullptr;
11557   if (isa<MemberExpr>(NakedMemExpr)) {
11558     MemExpr = cast<MemberExpr>(NakedMemExpr);
11559     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11560     FoundDecl = MemExpr->getFoundDecl();
11561     Qualifier = MemExpr->getQualifier();
11562     UnbridgedCasts.restore();
11563   } else {
11564     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11565     Qualifier = UnresExpr->getQualifier();
11566
11567     QualType ObjectType = UnresExpr->getBaseType();
11568     Expr::Classification ObjectClassification
11569       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11570                             : UnresExpr->getBase()->Classify(Context);
11571
11572     // Add overload candidates
11573     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11574                                       OverloadCandidateSet::CSK_Normal);
11575
11576     // FIXME: avoid copy.
11577     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
11578     if (UnresExpr->hasExplicitTemplateArgs()) {
11579       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11580       TemplateArgs = &TemplateArgsBuffer;
11581     }
11582
11583     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11584            E = UnresExpr->decls_end(); I != E; ++I) {
11585
11586       NamedDecl *Func = *I;
11587       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11588       if (isa<UsingShadowDecl>(Func))
11589         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11590
11591
11592       // Microsoft supports direct constructor calls.
11593       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11594         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11595                              Args, CandidateSet);
11596       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11597         // If explicit template arguments were provided, we can't call a
11598         // non-template member function.
11599         if (TemplateArgs)
11600           continue;
11601
11602         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11603                            ObjectClassification, Args, CandidateSet,
11604                            /*SuppressUserConversions=*/false);
11605       } else {
11606         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11607                                    I.getPair(), ActingDC, TemplateArgs,
11608                                    ObjectType,  ObjectClassification,
11609                                    Args, CandidateSet,
11610                                    /*SuppressUsedConversions=*/false);
11611       }
11612     }
11613
11614     DeclarationName DeclName = UnresExpr->getMemberName();
11615
11616     UnbridgedCasts.restore();
11617
11618     OverloadCandidateSet::iterator Best;
11619     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11620                                             Best)) {
11621     case OR_Success:
11622       Method = cast<CXXMethodDecl>(Best->Function);
11623       FoundDecl = Best->FoundDecl;
11624       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11625       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11626         return ExprError();
11627       // If FoundDecl is different from Method (such as if one is a template
11628       // and the other a specialization), make sure DiagnoseUseOfDecl is 
11629       // called on both.
11630       // FIXME: This would be more comprehensively addressed by modifying
11631       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11632       // being used.
11633       if (Method != FoundDecl.getDecl() && 
11634                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11635         return ExprError();
11636       break;
11637
11638     case OR_No_Viable_Function:
11639       Diag(UnresExpr->getMemberLoc(),
11640            diag::err_ovl_no_viable_member_function_in_call)
11641         << DeclName << MemExprE->getSourceRange();
11642       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11643       // FIXME: Leaking incoming expressions!
11644       return ExprError();
11645
11646     case OR_Ambiguous:
11647       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11648         << DeclName << MemExprE->getSourceRange();
11649       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11650       // FIXME: Leaking incoming expressions!
11651       return ExprError();
11652
11653     case OR_Deleted:
11654       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11655         << Best->Function->isDeleted()
11656         << DeclName 
11657         << getDeletedOrUnavailableSuffix(Best->Function)
11658         << MemExprE->getSourceRange();
11659       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11660       // FIXME: Leaking incoming expressions!
11661       return ExprError();
11662     }
11663
11664     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11665
11666     // If overload resolution picked a static member, build a
11667     // non-member call based on that function.
11668     if (Method->isStatic()) {
11669       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11670                                    RParenLoc);
11671     }
11672
11673     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11674   }
11675
11676   QualType ResultType = Method->getReturnType();
11677   ExprValueKind VK = Expr::getValueKindForType(ResultType);
11678   ResultType = ResultType.getNonLValueExprType(Context);
11679
11680   assert(Method && "Member call to something that isn't a method?");
11681   CXXMemberCallExpr *TheCall =
11682     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11683                                     ResultType, VK, RParenLoc);
11684
11685   // (CUDA B.1): Check for invalid calls between targets.
11686   if (getLangOpts().CUDA) {
11687     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11688       if (CheckCUDATarget(Caller, Method)) {
11689         Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11690             << IdentifyCUDATarget(Method) << Method->getIdentifier()
11691             << IdentifyCUDATarget(Caller);
11692         return ExprError();
11693       }
11694     }
11695   }
11696
11697   // Check for a valid return type.
11698   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
11699                           TheCall, Method))
11700     return ExprError();
11701
11702   // Convert the object argument (for a non-static member function call).
11703   // We only need to do this if there was actually an overload; otherwise
11704   // it was done at lookup.
11705   if (!Method->isStatic()) {
11706     ExprResult ObjectArg =
11707       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11708                                           FoundDecl, Method);
11709     if (ObjectArg.isInvalid())
11710       return ExprError();
11711     MemExpr->setBase(ObjectArg.get());
11712   }
11713
11714   // Convert the rest of the arguments
11715   const FunctionProtoType *Proto =
11716     Method->getType()->getAs<FunctionProtoType>();
11717   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11718                               RParenLoc))
11719     return ExprError();
11720
11721   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11722
11723   if (CheckFunctionCall(Method, TheCall, Proto))
11724     return ExprError();
11725
11726   if ((isa<CXXConstructorDecl>(CurContext) || 
11727        isa<CXXDestructorDecl>(CurContext)) && 
11728       TheCall->getMethodDecl()->isPure()) {
11729     const CXXMethodDecl *MD = TheCall->getMethodDecl();
11730
11731     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11732       Diag(MemExpr->getLocStart(), 
11733            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11734         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11735         << MD->getParent()->getDeclName();
11736
11737       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11738     }
11739   }
11740   return MaybeBindToTemporary(TheCall);
11741 }
11742
11743 /// BuildCallToObjectOfClassType - Build a call to an object of class
11744 /// type (C++ [over.call.object]), which can end up invoking an
11745 /// overloaded function call operator (@c operator()) or performing a
11746 /// user-defined conversion on the object argument.
11747 ExprResult
11748 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11749                                    SourceLocation LParenLoc,
11750                                    MultiExprArg Args,
11751                                    SourceLocation RParenLoc) {
11752   if (checkPlaceholderForOverload(*this, Obj))
11753     return ExprError();
11754   ExprResult Object = Obj;
11755
11756   UnbridgedCastsSet UnbridgedCasts;
11757   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11758     return ExprError();
11759
11760   assert(Object.get()->getType()->isRecordType() &&
11761          "Requires object type argument");
11762   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11763
11764   // C++ [over.call.object]p1:
11765   //  If the primary-expression E in the function call syntax
11766   //  evaluates to a class object of type "cv T", then the set of
11767   //  candidate functions includes at least the function call
11768   //  operators of T. The function call operators of T are obtained by
11769   //  ordinary lookup of the name operator() in the context of
11770   //  (E).operator().
11771   OverloadCandidateSet CandidateSet(LParenLoc,
11772                                     OverloadCandidateSet::CSK_Operator);
11773   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11774
11775   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11776                           diag::err_incomplete_object_call, Object.get()))
11777     return true;
11778
11779   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11780   LookupQualifiedName(R, Record->getDecl());
11781   R.suppressDiagnostics();
11782
11783   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11784        Oper != OperEnd; ++Oper) {
11785     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11786                        Object.get()->Classify(Context),
11787                        Args, CandidateSet,
11788                        /*SuppressUserConversions=*/ false);
11789   }
11790
11791   // C++ [over.call.object]p2:
11792   //   In addition, for each (non-explicit in C++0x) conversion function 
11793   //   declared in T of the form
11794   //
11795   //        operator conversion-type-id () cv-qualifier;
11796   //
11797   //   where cv-qualifier is the same cv-qualification as, or a
11798   //   greater cv-qualification than, cv, and where conversion-type-id
11799   //   denotes the type "pointer to function of (P1,...,Pn) returning
11800   //   R", or the type "reference to pointer to function of
11801   //   (P1,...,Pn) returning R", or the type "reference to function
11802   //   of (P1,...,Pn) returning R", a surrogate call function [...]
11803   //   is also considered as a candidate function. Similarly,
11804   //   surrogate call functions are added to the set of candidate
11805   //   functions for each conversion function declared in an
11806   //   accessible base class provided the function is not hidden
11807   //   within T by another intervening declaration.
11808   std::pair<CXXRecordDecl::conversion_iterator,
11809             CXXRecordDecl::conversion_iterator> Conversions
11810     = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11811   for (CXXRecordDecl::conversion_iterator
11812          I = Conversions.first, E = Conversions.second; I != E; ++I) {
11813     NamedDecl *D = *I;
11814     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11815     if (isa<UsingShadowDecl>(D))
11816       D = cast<UsingShadowDecl>(D)->getTargetDecl();
11817
11818     // Skip over templated conversion functions; they aren't
11819     // surrogates.
11820     if (isa<FunctionTemplateDecl>(D))
11821       continue;
11822
11823     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11824     if (!Conv->isExplicit()) {
11825       // Strip the reference type (if any) and then the pointer type (if
11826       // any) to get down to what might be a function type.
11827       QualType ConvType = Conv->getConversionType().getNonReferenceType();
11828       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11829         ConvType = ConvPtrType->getPointeeType();
11830
11831       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11832       {
11833         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11834                               Object.get(), Args, CandidateSet);
11835       }
11836     }
11837   }
11838
11839   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11840
11841   // Perform overload resolution.
11842   OverloadCandidateSet::iterator Best;
11843   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11844                              Best)) {
11845   case OR_Success:
11846     // Overload resolution succeeded; we'll build the appropriate call
11847     // below.
11848     break;
11849
11850   case OR_No_Viable_Function:
11851     if (CandidateSet.empty())
11852       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11853         << Object.get()->getType() << /*call*/ 1
11854         << Object.get()->getSourceRange();
11855     else
11856       Diag(Object.get()->getLocStart(),
11857            diag::err_ovl_no_viable_object_call)
11858         << Object.get()->getType() << Object.get()->getSourceRange();
11859     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11860     break;
11861
11862   case OR_Ambiguous:
11863     Diag(Object.get()->getLocStart(),
11864          diag::err_ovl_ambiguous_object_call)
11865       << Object.get()->getType() << Object.get()->getSourceRange();
11866     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11867     break;
11868
11869   case OR_Deleted:
11870     Diag(Object.get()->getLocStart(),
11871          diag::err_ovl_deleted_object_call)
11872       << Best->Function->isDeleted()
11873       << Object.get()->getType() 
11874       << getDeletedOrUnavailableSuffix(Best->Function)
11875       << Object.get()->getSourceRange();
11876     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11877     break;
11878   }
11879
11880   if (Best == CandidateSet.end())
11881     return true;
11882
11883   UnbridgedCasts.restore();
11884
11885   if (Best->Function == nullptr) {
11886     // Since there is no function declaration, this is one of the
11887     // surrogate candidates. Dig out the conversion function.
11888     CXXConversionDecl *Conv
11889       = cast<CXXConversionDecl>(
11890                          Best->Conversions[0].UserDefined.ConversionFunction);
11891
11892     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11893                               Best->FoundDecl);
11894     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11895       return ExprError();
11896     assert(Conv == Best->FoundDecl.getDecl() && 
11897              "Found Decl & conversion-to-functionptr should be same, right?!");
11898     // We selected one of the surrogate functions that converts the
11899     // object parameter to a function pointer. Perform the conversion
11900     // on the object argument, then let ActOnCallExpr finish the job.
11901
11902     // Create an implicit member expr to refer to the conversion operator.
11903     // and then call it.
11904     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11905                                              Conv, HadMultipleCandidates);
11906     if (Call.isInvalid())
11907       return ExprError();
11908     // Record usage of conversion in an implicit cast.
11909     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11910                                     CK_UserDefinedConversion, Call.get(),
11911                                     nullptr, VK_RValue);
11912
11913     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11914   }
11915
11916   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
11917
11918   // We found an overloaded operator(). Build a CXXOperatorCallExpr
11919   // that calls this method, using Object for the implicit object
11920   // parameter and passing along the remaining arguments.
11921   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11922
11923   // An error diagnostic has already been printed when parsing the declaration.
11924   if (Method->isInvalidDecl())
11925     return ExprError();
11926
11927   const FunctionProtoType *Proto =
11928     Method->getType()->getAs<FunctionProtoType>();
11929
11930   unsigned NumParams = Proto->getNumParams();
11931
11932   DeclarationNameInfo OpLocInfo(
11933                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11934   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11935   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11936                                            HadMultipleCandidates,
11937                                            OpLocInfo.getLoc(),
11938                                            OpLocInfo.getInfo());
11939   if (NewFn.isInvalid())
11940     return true;
11941
11942   // Build the full argument list for the method call (the implicit object
11943   // parameter is placed at the beginning of the list).
11944   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
11945   MethodArgs[0] = Object.get();
11946   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11947
11948   // Once we've built TheCall, all of the expressions are properly
11949   // owned.
11950   QualType ResultTy = Method->getReturnType();
11951   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11952   ResultTy = ResultTy.getNonLValueExprType(Context);
11953
11954   CXXOperatorCallExpr *TheCall = new (Context)
11955       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
11956                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11957                           ResultTy, VK, RParenLoc, false);
11958   MethodArgs.reset();
11959
11960   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
11961     return true;
11962
11963   // We may have default arguments. If so, we need to allocate more
11964   // slots in the call for them.
11965   if (Args.size() < NumParams)
11966     TheCall->setNumArgs(Context, NumParams + 1);
11967
11968   bool IsError = false;
11969
11970   // Initialize the implicit object parameter.
11971   ExprResult ObjRes =
11972     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
11973                                         Best->FoundDecl, Method);
11974   if (ObjRes.isInvalid())
11975     IsError = true;
11976   else
11977     Object = ObjRes;
11978   TheCall->setArg(0, Object.get());
11979
11980   // Check the argument types.
11981   for (unsigned i = 0; i != NumParams; i++) {
11982     Expr *Arg;
11983     if (i < Args.size()) {
11984       Arg = Args[i];
11985
11986       // Pass the argument.
11987
11988       ExprResult InputInit
11989         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11990                                                     Context,
11991                                                     Method->getParamDecl(i)),
11992                                     SourceLocation(), Arg);
11993
11994       IsError |= InputInit.isInvalid();
11995       Arg = InputInit.getAs<Expr>();
11996     } else {
11997       ExprResult DefArg
11998         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11999       if (DefArg.isInvalid()) {
12000         IsError = true;
12001         break;
12002       }
12003
12004       Arg = DefArg.getAs<Expr>();
12005     }
12006
12007     TheCall->setArg(i + 1, Arg);
12008   }
12009
12010   // If this is a variadic call, handle args passed through "...".
12011   if (Proto->isVariadic()) {
12012     // Promote the arguments (C99 6.5.2.2p7).
12013     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12014       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12015                                                         nullptr);
12016       IsError |= Arg.isInvalid();
12017       TheCall->setArg(i + 1, Arg.get());
12018     }
12019   }
12020
12021   if (IsError) return true;
12022
12023   DiagnoseSentinelCalls(Method, LParenLoc, Args);
12024
12025   if (CheckFunctionCall(Method, TheCall, Proto))
12026     return true;
12027
12028   return MaybeBindToTemporary(TheCall);
12029 }
12030
12031 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12032 ///  (if one exists), where @c Base is an expression of class type and
12033 /// @c Member is the name of the member we're trying to find.
12034 ExprResult
12035 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12036                                bool *NoArrowOperatorFound) {
12037   assert(Base->getType()->isRecordType() &&
12038          "left-hand side must have class type");
12039
12040   if (checkPlaceholderForOverload(*this, Base))
12041     return ExprError();
12042
12043   SourceLocation Loc = Base->getExprLoc();
12044
12045   // C++ [over.ref]p1:
12046   //
12047   //   [...] An expression x->m is interpreted as (x.operator->())->m
12048   //   for a class object x of type T if T::operator->() exists and if
12049   //   the operator is selected as the best match function by the
12050   //   overload resolution mechanism (13.3).
12051   DeclarationName OpName =
12052     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12053   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12054   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12055
12056   if (RequireCompleteType(Loc, Base->getType(),
12057                           diag::err_typecheck_incomplete_tag, Base))
12058     return ExprError();
12059
12060   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12061   LookupQualifiedName(R, BaseRecord->getDecl());
12062   R.suppressDiagnostics();
12063
12064   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12065        Oper != OperEnd; ++Oper) {
12066     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12067                        None, CandidateSet, /*SuppressUserConversions=*/false);
12068   }
12069
12070   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12071
12072   // Perform overload resolution.
12073   OverloadCandidateSet::iterator Best;
12074   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12075   case OR_Success:
12076     // Overload resolution succeeded; we'll build the call below.
12077     break;
12078
12079   case OR_No_Viable_Function:
12080     if (CandidateSet.empty()) {
12081       QualType BaseType = Base->getType();
12082       if (NoArrowOperatorFound) {
12083         // Report this specific error to the caller instead of emitting a
12084         // diagnostic, as requested.
12085         *NoArrowOperatorFound = true;
12086         return ExprError();
12087       }
12088       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12089         << BaseType << Base->getSourceRange();
12090       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12091         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12092           << FixItHint::CreateReplacement(OpLoc, ".");
12093       }
12094     } else
12095       Diag(OpLoc, diag::err_ovl_no_viable_oper)
12096         << "operator->" << Base->getSourceRange();
12097     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12098     return ExprError();
12099
12100   case OR_Ambiguous:
12101     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
12102       << "->" << Base->getType() << Base->getSourceRange();
12103     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12104     return ExprError();
12105
12106   case OR_Deleted:
12107     Diag(OpLoc,  diag::err_ovl_deleted_oper)
12108       << Best->Function->isDeleted()
12109       << "->" 
12110       << getDeletedOrUnavailableSuffix(Best->Function)
12111       << Base->getSourceRange();
12112     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12113     return ExprError();
12114   }
12115
12116   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12117
12118   // Convert the object parameter.
12119   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12120   ExprResult BaseResult =
12121     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12122                                         Best->FoundDecl, Method);
12123   if (BaseResult.isInvalid())
12124     return ExprError();
12125   Base = BaseResult.get();
12126
12127   // Build the operator call.
12128   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12129                                             HadMultipleCandidates, OpLoc);
12130   if (FnExpr.isInvalid())
12131     return ExprError();
12132
12133   QualType ResultTy = Method->getReturnType();
12134   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12135   ResultTy = ResultTy.getNonLValueExprType(Context);
12136   CXXOperatorCallExpr *TheCall =
12137     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12138                                       Base, ResultTy, VK, OpLoc, false);
12139
12140   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12141           return ExprError();
12142
12143   return MaybeBindToTemporary(TheCall);
12144 }
12145
12146 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12147 /// a literal operator described by the provided lookup results.
12148 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12149                                           DeclarationNameInfo &SuffixInfo,
12150                                           ArrayRef<Expr*> Args,
12151                                           SourceLocation LitEndLoc,
12152                                        TemplateArgumentListInfo *TemplateArgs) {
12153   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12154
12155   OverloadCandidateSet CandidateSet(UDSuffixLoc,
12156                                     OverloadCandidateSet::CSK_Normal);
12157   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
12158                         TemplateArgs);
12159
12160   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12161
12162   // Perform overload resolution. This will usually be trivial, but might need
12163   // to perform substitutions for a literal operator template.
12164   OverloadCandidateSet::iterator Best;
12165   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12166   case OR_Success:
12167   case OR_Deleted:
12168     break;
12169
12170   case OR_No_Viable_Function:
12171     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12172       << R.getLookupName();
12173     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12174     return ExprError();
12175
12176   case OR_Ambiguous:
12177     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12178     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12179     return ExprError();
12180   }
12181
12182   FunctionDecl *FD = Best->Function;
12183   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12184                                         HadMultipleCandidates,
12185                                         SuffixInfo.getLoc(),
12186                                         SuffixInfo.getInfo());
12187   if (Fn.isInvalid())
12188     return true;
12189
12190   // Check the argument types. This should almost always be a no-op, except
12191   // that array-to-pointer decay is applied to string literals.
12192   Expr *ConvArgs[2];
12193   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12194     ExprResult InputInit = PerformCopyInitialization(
12195       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12196       SourceLocation(), Args[ArgIdx]);
12197     if (InputInit.isInvalid())
12198       return true;
12199     ConvArgs[ArgIdx] = InputInit.get();
12200   }
12201
12202   QualType ResultTy = FD->getReturnType();
12203   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12204   ResultTy = ResultTy.getNonLValueExprType(Context);
12205
12206   UserDefinedLiteral *UDL =
12207     new (Context) UserDefinedLiteral(Context, Fn.get(),
12208                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12209                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12210
12211   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12212     return ExprError();
12213
12214   if (CheckFunctionCall(FD, UDL, nullptr))
12215     return ExprError();
12216
12217   return MaybeBindToTemporary(UDL);
12218 }
12219
12220 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12221 /// given LookupResult is non-empty, it is assumed to describe a member which
12222 /// will be invoked. Otherwise, the function will be found via argument
12223 /// dependent lookup.
12224 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12225 /// otherwise CallExpr is set to ExprError() and some non-success value
12226 /// is returned.
12227 Sema::ForRangeStatus
12228 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12229                                 SourceLocation RangeLoc, VarDecl *Decl,
12230                                 BeginEndFunction BEF,
12231                                 const DeclarationNameInfo &NameInfo,
12232                                 LookupResult &MemberLookup,
12233                                 OverloadCandidateSet *CandidateSet,
12234                                 Expr *Range, ExprResult *CallExpr) {
12235   CandidateSet->clear();
12236   if (!MemberLookup.empty()) {
12237     ExprResult MemberRef =
12238         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12239                                  /*IsPtr=*/false, CXXScopeSpec(),
12240                                  /*TemplateKWLoc=*/SourceLocation(),
12241                                  /*FirstQualifierInScope=*/nullptr,
12242                                  MemberLookup,
12243                                  /*TemplateArgs=*/nullptr);
12244     if (MemberRef.isInvalid()) {
12245       *CallExpr = ExprError();
12246       Diag(Range->getLocStart(), diag::note_in_for_range)
12247           << RangeLoc << BEF << Range->getType();
12248       return FRS_DiagnosticIssued;
12249     }
12250     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12251     if (CallExpr->isInvalid()) {
12252       *CallExpr = ExprError();
12253       Diag(Range->getLocStart(), diag::note_in_for_range)
12254           << RangeLoc << BEF << Range->getType();
12255       return FRS_DiagnosticIssued;
12256     }
12257   } else {
12258     UnresolvedSet<0> FoundNames;
12259     UnresolvedLookupExpr *Fn =
12260       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12261                                    NestedNameSpecifierLoc(), NameInfo,
12262                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12263                                    FoundNames.begin(), FoundNames.end());
12264
12265     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12266                                                     CandidateSet, CallExpr);
12267     if (CandidateSet->empty() || CandidateSetError) {
12268       *CallExpr = ExprError();
12269       return FRS_NoViableFunction;
12270     }
12271     OverloadCandidateSet::iterator Best;
12272     OverloadingResult OverloadResult =
12273         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12274
12275     if (OverloadResult == OR_No_Viable_Function) {
12276       *CallExpr = ExprError();
12277       return FRS_NoViableFunction;
12278     }
12279     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12280                                          Loc, nullptr, CandidateSet, &Best,
12281                                          OverloadResult,
12282                                          /*AllowTypoCorrection=*/false);
12283     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12284       *CallExpr = ExprError();
12285       Diag(Range->getLocStart(), diag::note_in_for_range)
12286           << RangeLoc << BEF << Range->getType();
12287       return FRS_DiagnosticIssued;
12288     }
12289   }
12290   return FRS_Success;
12291 }
12292
12293
12294 /// FixOverloadedFunctionReference - E is an expression that refers to
12295 /// a C++ overloaded function (possibly with some parentheses and
12296 /// perhaps a '&' around it). We have resolved the overloaded function
12297 /// to the function declaration Fn, so patch up the expression E to
12298 /// refer (possibly indirectly) to Fn. Returns the new expr.
12299 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12300                                            FunctionDecl *Fn) {
12301   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12302     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12303                                                    Found, Fn);
12304     if (SubExpr == PE->getSubExpr())
12305       return PE;
12306
12307     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12308   }
12309
12310   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12311     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12312                                                    Found, Fn);
12313     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12314                                SubExpr->getType()) &&
12315            "Implicit cast type cannot be determined from overload");
12316     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12317     if (SubExpr == ICE->getSubExpr())
12318       return ICE;
12319
12320     return ImplicitCastExpr::Create(Context, ICE->getType(),
12321                                     ICE->getCastKind(),
12322                                     SubExpr, nullptr,
12323                                     ICE->getValueKind());
12324   }
12325
12326   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12327     assert(UnOp->getOpcode() == UO_AddrOf &&
12328            "Can only take the address of an overloaded function");
12329     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12330       if (Method->isStatic()) {
12331         // Do nothing: static member functions aren't any different
12332         // from non-member functions.
12333       } else {
12334         // Fix the subexpression, which really has to be an
12335         // UnresolvedLookupExpr holding an overloaded member function
12336         // or template.
12337         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12338                                                        Found, Fn);
12339         if (SubExpr == UnOp->getSubExpr())
12340           return UnOp;
12341
12342         assert(isa<DeclRefExpr>(SubExpr)
12343                && "fixed to something other than a decl ref");
12344         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12345                && "fixed to a member ref with no nested name qualifier");
12346
12347         // We have taken the address of a pointer to member
12348         // function. Perform the computation here so that we get the
12349         // appropriate pointer to member type.
12350         QualType ClassType
12351           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12352         QualType MemPtrType
12353           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12354
12355         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12356                                            VK_RValue, OK_Ordinary,
12357                                            UnOp->getOperatorLoc());
12358       }
12359     }
12360     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12361                                                    Found, Fn);
12362     if (SubExpr == UnOp->getSubExpr())
12363       return UnOp;
12364
12365     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12366                                      Context.getPointerType(SubExpr->getType()),
12367                                        VK_RValue, OK_Ordinary,
12368                                        UnOp->getOperatorLoc());
12369   }
12370
12371   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12372     // FIXME: avoid copy.
12373     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12374     if (ULE->hasExplicitTemplateArgs()) {
12375       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12376       TemplateArgs = &TemplateArgsBuffer;
12377     }
12378
12379     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12380                                            ULE->getQualifierLoc(),
12381                                            ULE->getTemplateKeywordLoc(),
12382                                            Fn,
12383                                            /*enclosing*/ false, // FIXME?
12384                                            ULE->getNameLoc(),
12385                                            Fn->getType(),
12386                                            VK_LValue,
12387                                            Found.getDecl(),
12388                                            TemplateArgs);
12389     MarkDeclRefReferenced(DRE);
12390     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12391     return DRE;
12392   }
12393
12394   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12395     // FIXME: avoid copy.
12396     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12397     if (MemExpr->hasExplicitTemplateArgs()) {
12398       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12399       TemplateArgs = &TemplateArgsBuffer;
12400     }
12401
12402     Expr *Base;
12403
12404     // If we're filling in a static method where we used to have an
12405     // implicit member access, rewrite to a simple decl ref.
12406     if (MemExpr->isImplicitAccess()) {
12407       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12408         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12409                                                MemExpr->getQualifierLoc(),
12410                                                MemExpr->getTemplateKeywordLoc(),
12411                                                Fn,
12412                                                /*enclosing*/ false,
12413                                                MemExpr->getMemberLoc(),
12414                                                Fn->getType(),
12415                                                VK_LValue,
12416                                                Found.getDecl(),
12417                                                TemplateArgs);
12418         MarkDeclRefReferenced(DRE);
12419         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12420         return DRE;
12421       } else {
12422         SourceLocation Loc = MemExpr->getMemberLoc();
12423         if (MemExpr->getQualifier())
12424           Loc = MemExpr->getQualifierLoc().getBeginLoc();
12425         CheckCXXThisCapture(Loc);
12426         Base = new (Context) CXXThisExpr(Loc,
12427                                          MemExpr->getBaseType(),
12428                                          /*isImplicit=*/true);
12429       }
12430     } else
12431       Base = MemExpr->getBase();
12432
12433     ExprValueKind valueKind;
12434     QualType type;
12435     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12436       valueKind = VK_LValue;
12437       type = Fn->getType();
12438     } else {
12439       valueKind = VK_RValue;
12440       type = Context.BoundMemberTy;
12441     }
12442
12443     MemberExpr *ME = MemberExpr::Create(Context, Base,
12444                                         MemExpr->isArrow(),
12445                                         MemExpr->getQualifierLoc(),
12446                                         MemExpr->getTemplateKeywordLoc(),
12447                                         Fn,
12448                                         Found,
12449                                         MemExpr->getMemberNameInfo(),
12450                                         TemplateArgs,
12451                                         type, valueKind, OK_Ordinary);
12452     ME->setHadMultipleCandidates(true);
12453     MarkMemberReferenced(ME);
12454     return ME;
12455   }
12456
12457   llvm_unreachable("Invalid reference to overloaded function");
12458 }
12459
12460 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12461                                                 DeclAccessPair Found,
12462                                                 FunctionDecl *Fn) {
12463   return FixOverloadedFunctionReference(E.get(), Found, Fn);
12464 }