• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include <algorithm>
36 #include <cstdlib>
37 
38 namespace clang {
39 using namespace sema;
40 
41 /// A convenience routine for creating a decayed reference to a function.
42 static ExprResult
CreateFunctionRefExpr(Sema & S,FunctionDecl * Fn,NamedDecl * FoundDecl,bool HadMultipleCandidates,SourceLocation Loc=SourceLocation (),const DeclarationNameLoc & LocInfo=DeclarationNameLoc ())43 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44                       bool HadMultipleCandidates,
45                       SourceLocation Loc = SourceLocation(),
46                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
47   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
48     return ExprError();
49   // If FoundDecl is different from Fn (such as if one is a template
50   // and the other a specialization), make sure DiagnoseUseOfDecl is
51   // called on both.
52   // FIXME: This would be more comprehensively addressed by modifying
53   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
54   // being used.
55   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
56     return ExprError();
57   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
58                                                  VK_LValue, Loc, LocInfo);
59   if (HadMultipleCandidates)
60     DRE->setHadMultipleCandidates(true);
61 
62   S.MarkDeclRefReferenced(DRE);
63 
64   ExprResult E = DRE;
65   E = S.DefaultFunctionArrayConversion(E.get());
66   if (E.isInvalid())
67     return ExprError();
68   return E;
69 }
70 
71 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72                                  bool InOverloadResolution,
73                                  StandardConversionSequence &SCS,
74                                  bool CStyle,
75                                  bool AllowObjCWritebackConversion);
76 
77 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
78                                                  QualType &ToType,
79                                                  bool InOverloadResolution,
80                                                  StandardConversionSequence &SCS,
81                                                  bool CStyle);
82 static OverloadingResult
83 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84                         UserDefinedConversionSequence& User,
85                         OverloadCandidateSet& Conversions,
86                         bool AllowExplicit,
87                         bool AllowObjCConversionOnExplicit);
88 
89 
90 static ImplicitConversionSequence::CompareKind
91 CompareStandardConversionSequences(Sema &S,
92                                    const StandardConversionSequence& SCS1,
93                                    const StandardConversionSequence& SCS2);
94 
95 static ImplicitConversionSequence::CompareKind
96 CompareQualificationConversions(Sema &S,
97                                 const StandardConversionSequence& SCS1,
98                                 const StandardConversionSequence& SCS2);
99 
100 static ImplicitConversionSequence::CompareKind
101 CompareDerivedToBaseConversions(Sema &S,
102                                 const StandardConversionSequence& SCS1,
103                                 const StandardConversionSequence& SCS2);
104 
105 
106 
107 /// GetConversionCategory - Retrieve the implicit conversion
108 /// category corresponding to the given implicit conversion kind.
109 ImplicitConversionCategory
GetConversionCategory(ImplicitConversionKind Kind)110 GetConversionCategory(ImplicitConversionKind Kind) {
111   static const ImplicitConversionCategory
112     Category[(int)ICK_Num_Conversion_Kinds] = {
113     ICC_Identity,
114     ICC_Lvalue_Transformation,
115     ICC_Lvalue_Transformation,
116     ICC_Lvalue_Transformation,
117     ICC_Identity,
118     ICC_Qualification_Adjustment,
119     ICC_Promotion,
120     ICC_Promotion,
121     ICC_Promotion,
122     ICC_Conversion,
123     ICC_Conversion,
124     ICC_Conversion,
125     ICC_Conversion,
126     ICC_Conversion,
127     ICC_Conversion,
128     ICC_Conversion,
129     ICC_Conversion,
130     ICC_Conversion,
131     ICC_Conversion,
132     ICC_Conversion,
133     ICC_Conversion,
134     ICC_Conversion
135   };
136   return Category[(int)Kind];
137 }
138 
139 /// GetConversionRank - Retrieve the implicit conversion rank
140 /// corresponding to the given implicit conversion kind.
GetConversionRank(ImplicitConversionKind Kind)141 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
142   static const ImplicitConversionRank
143     Rank[(int)ICK_Num_Conversion_Kinds] = {
144     ICR_Exact_Match,
145     ICR_Exact_Match,
146     ICR_Exact_Match,
147     ICR_Exact_Match,
148     ICR_Exact_Match,
149     ICR_Exact_Match,
150     ICR_Promotion,
151     ICR_Promotion,
152     ICR_Promotion,
153     ICR_Conversion,
154     ICR_Conversion,
155     ICR_Conversion,
156     ICR_Conversion,
157     ICR_Conversion,
158     ICR_Conversion,
159     ICR_Conversion,
160     ICR_Conversion,
161     ICR_Conversion,
162     ICR_Conversion,
163     ICR_Conversion,
164     ICR_Complex_Real_Conversion,
165     ICR_Conversion,
166     ICR_Conversion,
167     ICR_Writeback_Conversion
168   };
169   return Rank[(int)Kind];
170 }
171 
172 /// GetImplicitConversionName - Return the name of this kind of
173 /// implicit conversion.
GetImplicitConversionName(ImplicitConversionKind Kind)174 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
175   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
176     "No conversion",
177     "Lvalue-to-rvalue",
178     "Array-to-pointer",
179     "Function-to-pointer",
180     "Noreturn adjustment",
181     "Qualification",
182     "Integral promotion",
183     "Floating point promotion",
184     "Complex promotion",
185     "Integral conversion",
186     "Floating conversion",
187     "Complex conversion",
188     "Floating-integral conversion",
189     "Pointer conversion",
190     "Pointer-to-member conversion",
191     "Boolean conversion",
192     "Compatible-types conversion",
193     "Derived-to-base conversion",
194     "Vector conversion",
195     "Vector splat",
196     "Complex-real conversion",
197     "Block Pointer conversion",
198     "Transparent Union Conversion"
199     "Writeback conversion"
200   };
201   return Name[Kind];
202 }
203 
204 /// StandardConversionSequence - Set the standard conversion
205 /// sequence to the identity conversion.
setAsIdentityConversion()206 void StandardConversionSequence::setAsIdentityConversion() {
207   First = ICK_Identity;
208   Second = ICK_Identity;
209   Third = ICK_Identity;
210   DeprecatedStringLiteralToCharPtr = false;
211   QualificationIncludesObjCLifetime = false;
212   ReferenceBinding = false;
213   DirectBinding = false;
214   IsLvalueReference = true;
215   BindsToFunctionLvalue = false;
216   BindsToRvalue = false;
217   BindsImplicitObjectArgumentWithoutRefQualifier = false;
218   ObjCLifetimeConversionBinding = false;
219   CopyConstructor = nullptr;
220 }
221 
222 /// getRank - Retrieve the rank of this standard conversion sequence
223 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
224 /// implicit conversions.
getRank() const225 ImplicitConversionRank StandardConversionSequence::getRank() const {
226   ImplicitConversionRank Rank = ICR_Exact_Match;
227   if  (GetConversionRank(First) > Rank)
228     Rank = GetConversionRank(First);
229   if  (GetConversionRank(Second) > Rank)
230     Rank = GetConversionRank(Second);
231   if  (GetConversionRank(Third) > Rank)
232     Rank = GetConversionRank(Third);
233   return Rank;
234 }
235 
236 /// isPointerConversionToBool - Determines whether this conversion is
237 /// a conversion of a pointer or pointer-to-member to bool. This is
238 /// used as part of the ranking of standard conversion sequences
239 /// (C++ 13.3.3.2p4).
isPointerConversionToBool() const240 bool StandardConversionSequence::isPointerConversionToBool() const {
241   // Note that FromType has not necessarily been transformed by the
242   // array-to-pointer or function-to-pointer implicit conversions, so
243   // check for their presence as well as checking whether FromType is
244   // a pointer.
245   if (getToType(1)->isBooleanType() &&
246       (getFromType()->isPointerType() ||
247        getFromType()->isObjCObjectPointerType() ||
248        getFromType()->isBlockPointerType() ||
249        getFromType()->isNullPtrType() ||
250        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
251     return true;
252 
253   return false;
254 }
255 
256 /// isPointerConversionToVoidPointer - Determines whether this
257 /// conversion is a conversion of a pointer to a void pointer. This is
258 /// used as part of the ranking of standard conversion sequences (C++
259 /// 13.3.3.2p4).
260 bool
261 StandardConversionSequence::
isPointerConversionToVoidPointer(ASTContext & Context) const262 isPointerConversionToVoidPointer(ASTContext& Context) const {
263   QualType FromType = getFromType();
264   QualType ToType = getToType(1);
265 
266   // Note that FromType has not necessarily been transformed by the
267   // array-to-pointer implicit conversion, so check for its presence
268   // and redo the conversion to get a pointer.
269   if (First == ICK_Array_To_Pointer)
270     FromType = Context.getArrayDecayedType(FromType);
271 
272   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
273     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
274       return ToPtrType->getPointeeType()->isVoidType();
275 
276   return false;
277 }
278 
279 /// Skip any implicit casts which could be either part of a narrowing conversion
280 /// or after one in an implicit conversion.
IgnoreNarrowingConversion(const Expr * Converted)281 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
282   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
283     switch (ICE->getCastKind()) {
284     case CK_NoOp:
285     case CK_IntegralCast:
286     case CK_IntegralToBoolean:
287     case CK_IntegralToFloating:
288     case CK_FloatingToIntegral:
289     case CK_FloatingToBoolean:
290     case CK_FloatingCast:
291       Converted = ICE->getSubExpr();
292       continue;
293 
294     default:
295       return Converted;
296     }
297   }
298 
299   return Converted;
300 }
301 
302 /// Check if this standard conversion sequence represents a narrowing
303 /// conversion, according to C++11 [dcl.init.list]p7.
304 ///
305 /// \param Ctx  The AST context.
306 /// \param Converted  The result of applying this standard conversion sequence.
307 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
308 ///        value of the expression prior to the narrowing conversion.
309 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
310 ///        type of the expression prior to the narrowing conversion.
311 NarrowingKind
getNarrowingKind(ASTContext & Ctx,const Expr * Converted,APValue & ConstantValue,QualType & ConstantType) const312 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
313                                              const Expr *Converted,
314                                              APValue &ConstantValue,
315                                              QualType &ConstantType) const {
316   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
317 
318   // C++11 [dcl.init.list]p7:
319   //   A narrowing conversion is an implicit conversion ...
320   QualType FromType = getToType(0);
321   QualType ToType = getToType(1);
322   switch (Second) {
323   // -- from a floating-point type to an integer type, or
324   //
325   // -- from an integer type or unscoped enumeration type to a floating-point
326   //    type, except where the source is a constant expression and the actual
327   //    value after conversion will fit into the target type and will produce
328   //    the original value when converted back to the original type, or
329   case ICK_Floating_Integral:
330     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
331       return NK_Type_Narrowing;
332     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
333       llvm::APSInt IntConstantValue;
334       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
335       if (Initializer &&
336           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
337         // Convert the integer to the floating type.
338         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
339         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
340                                 llvm::APFloat::rmNearestTiesToEven);
341         // And back.
342         llvm::APSInt ConvertedValue = IntConstantValue;
343         bool ignored;
344         Result.convertToInteger(ConvertedValue,
345                                 llvm::APFloat::rmTowardZero, &ignored);
346         // If the resulting value is different, this was a narrowing conversion.
347         if (IntConstantValue != ConvertedValue) {
348           ConstantValue = APValue(IntConstantValue);
349           ConstantType = Initializer->getType();
350           return NK_Constant_Narrowing;
351         }
352       } else {
353         // Variables are always narrowings.
354         return NK_Variable_Narrowing;
355       }
356     }
357     return NK_Not_Narrowing;
358 
359   // -- from long double to double or float, or from double to float, except
360   //    where the source is a constant expression and the actual value after
361   //    conversion is within the range of values that can be represented (even
362   //    if it cannot be represented exactly), or
363   case ICK_Floating_Conversion:
364     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
365         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
366       // FromType is larger than ToType.
367       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
368       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
369         // Constant!
370         assert(ConstantValue.isFloat());
371         llvm::APFloat FloatVal = ConstantValue.getFloat();
372         // Convert the source value into the target type.
373         bool ignored;
374         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
375           Ctx.getFloatTypeSemantics(ToType),
376           llvm::APFloat::rmNearestTiesToEven, &ignored);
377         // If there was no overflow, the source value is within the range of
378         // values that can be represented.
379         if (ConvertStatus & llvm::APFloat::opOverflow) {
380           ConstantType = Initializer->getType();
381           return NK_Constant_Narrowing;
382         }
383       } else {
384         return NK_Variable_Narrowing;
385       }
386     }
387     return NK_Not_Narrowing;
388 
389   // -- from an integer type or unscoped enumeration type to an integer type
390   //    that cannot represent all the values of the original type, except where
391   //    the source is a constant expression and the actual value after
392   //    conversion will fit into the target type and will produce the original
393   //    value when converted back to the original type.
394   case ICK_Boolean_Conversion:  // Bools are integers too.
395     if (!FromType->isIntegralOrUnscopedEnumerationType()) {
396       // Boolean conversions can be from pointers and pointers to members
397       // [conv.bool], and those aren't considered narrowing conversions.
398       return NK_Not_Narrowing;
399     }  // Otherwise, fall through to the integral case.
400   case ICK_Integral_Conversion: {
401     assert(FromType->isIntegralOrUnscopedEnumerationType());
402     assert(ToType->isIntegralOrUnscopedEnumerationType());
403     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
404     const unsigned FromWidth = Ctx.getIntWidth(FromType);
405     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
406     const unsigned ToWidth = Ctx.getIntWidth(ToType);
407 
408     if (FromWidth > ToWidth ||
409         (FromWidth == ToWidth && FromSigned != ToSigned) ||
410         (FromSigned && !ToSigned)) {
411       // Not all values of FromType can be represented in ToType.
412       llvm::APSInt InitializerValue;
413       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
414       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
415         // Such conversions on variables are always narrowing.
416         return NK_Variable_Narrowing;
417       }
418       bool Narrowing = false;
419       if (FromWidth < ToWidth) {
420         // Negative -> unsigned is narrowing. Otherwise, more bits is never
421         // narrowing.
422         if (InitializerValue.isSigned() && InitializerValue.isNegative())
423           Narrowing = true;
424       } else {
425         // Add a bit to the InitializerValue so we don't have to worry about
426         // signed vs. unsigned comparisons.
427         InitializerValue = InitializerValue.extend(
428           InitializerValue.getBitWidth() + 1);
429         // Convert the initializer to and from the target width and signed-ness.
430         llvm::APSInt ConvertedValue = InitializerValue;
431         ConvertedValue = ConvertedValue.trunc(ToWidth);
432         ConvertedValue.setIsSigned(ToSigned);
433         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
434         ConvertedValue.setIsSigned(InitializerValue.isSigned());
435         // If the result is different, this was a narrowing conversion.
436         if (ConvertedValue != InitializerValue)
437           Narrowing = true;
438       }
439       if (Narrowing) {
440         ConstantType = Initializer->getType();
441         ConstantValue = APValue(InitializerValue);
442         return NK_Constant_Narrowing;
443       }
444     }
445     return NK_Not_Narrowing;
446   }
447 
448   default:
449     // Other kinds of conversions are not narrowings.
450     return NK_Not_Narrowing;
451   }
452 }
453 
454 /// dump - Print this standard conversion sequence to standard
455 /// error. Useful for debugging overloading issues.
dump() const456 void StandardConversionSequence::dump() const {
457   raw_ostream &OS = llvm::errs();
458   bool PrintedSomething = false;
459   if (First != ICK_Identity) {
460     OS << GetImplicitConversionName(First);
461     PrintedSomething = true;
462   }
463 
464   if (Second != ICK_Identity) {
465     if (PrintedSomething) {
466       OS << " -> ";
467     }
468     OS << GetImplicitConversionName(Second);
469 
470     if (CopyConstructor) {
471       OS << " (by copy constructor)";
472     } else if (DirectBinding) {
473       OS << " (direct reference binding)";
474     } else if (ReferenceBinding) {
475       OS << " (reference binding)";
476     }
477     PrintedSomething = true;
478   }
479 
480   if (Third != ICK_Identity) {
481     if (PrintedSomething) {
482       OS << " -> ";
483     }
484     OS << GetImplicitConversionName(Third);
485     PrintedSomething = true;
486   }
487 
488   if (!PrintedSomething) {
489     OS << "No conversions required";
490   }
491 }
492 
493 /// dump - Print this user-defined conversion sequence to standard
494 /// error. Useful for debugging overloading issues.
dump() const495 void UserDefinedConversionSequence::dump() const {
496   raw_ostream &OS = llvm::errs();
497   if (Before.First || Before.Second || Before.Third) {
498     Before.dump();
499     OS << " -> ";
500   }
501   if (ConversionFunction)
502     OS << '\'' << *ConversionFunction << '\'';
503   else
504     OS << "aggregate initialization";
505   if (After.First || After.Second || After.Third) {
506     OS << " -> ";
507     After.dump();
508   }
509 }
510 
511 /// dump - Print this implicit conversion sequence to standard
512 /// error. Useful for debugging overloading issues.
dump() const513 void ImplicitConversionSequence::dump() const {
514   raw_ostream &OS = llvm::errs();
515   if (isStdInitializerListElement())
516     OS << "Worst std::initializer_list element conversion: ";
517   switch (ConversionKind) {
518   case StandardConversion:
519     OS << "Standard conversion: ";
520     Standard.dump();
521     break;
522   case UserDefinedConversion:
523     OS << "User-defined conversion: ";
524     UserDefined.dump();
525     break;
526   case EllipsisConversion:
527     OS << "Ellipsis conversion";
528     break;
529   case AmbiguousConversion:
530     OS << "Ambiguous conversion";
531     break;
532   case BadConversion:
533     OS << "Bad conversion";
534     break;
535   }
536 
537   OS << "\n";
538 }
539 
construct()540 void AmbiguousConversionSequence::construct() {
541   new (&conversions()) ConversionSet();
542 }
543 
destruct()544 void AmbiguousConversionSequence::destruct() {
545   conversions().~ConversionSet();
546 }
547 
548 void
copyFrom(const AmbiguousConversionSequence & O)549 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
550   FromTypePtr = O.FromTypePtr;
551   ToTypePtr = O.ToTypePtr;
552   new (&conversions()) ConversionSet(O.conversions());
553 }
554 
555 namespace {
556   // Structure used by DeductionFailureInfo to store
557   // template argument information.
558   struct DFIArguments {
559     TemplateArgument FirstArg;
560     TemplateArgument SecondArg;
561   };
562   // Structure used by DeductionFailureInfo to store
563   // template parameter and template argument information.
564   struct DFIParamWithArguments : DFIArguments {
565     TemplateParameter Param;
566   };
567 }
568 
569 /// \brief Convert from Sema's representation of template deduction information
570 /// to the form used in overload-candidate information.
MakeDeductionFailureInfo(ASTContext & Context,Sema::TemplateDeductionResult TDK,TemplateDeductionInfo & Info)571 DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
572                                               Sema::TemplateDeductionResult TDK,
573                                               TemplateDeductionInfo &Info) {
574   DeductionFailureInfo Result;
575   Result.Result = static_cast<unsigned>(TDK);
576   Result.HasDiagnostic = false;
577   Result.Data = nullptr;
578   switch (TDK) {
579   case Sema::TDK_Success:
580   case Sema::TDK_Invalid:
581   case Sema::TDK_InstantiationDepth:
582   case Sema::TDK_TooManyArguments:
583   case Sema::TDK_TooFewArguments:
584     break;
585 
586   case Sema::TDK_Incomplete:
587   case Sema::TDK_InvalidExplicitArguments:
588     Result.Data = Info.Param.getOpaqueValue();
589     break;
590 
591   case Sema::TDK_NonDeducedMismatch: {
592     // FIXME: Should allocate from normal heap so that we can free this later.
593     DFIArguments *Saved = new (Context) DFIArguments;
594     Saved->FirstArg = Info.FirstArg;
595     Saved->SecondArg = Info.SecondArg;
596     Result.Data = Saved;
597     break;
598   }
599 
600   case Sema::TDK_Inconsistent:
601   case Sema::TDK_Underqualified: {
602     // FIXME: Should allocate from normal heap so that we can free this later.
603     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
604     Saved->Param = Info.Param;
605     Saved->FirstArg = Info.FirstArg;
606     Saved->SecondArg = Info.SecondArg;
607     Result.Data = Saved;
608     break;
609   }
610 
611   case Sema::TDK_SubstitutionFailure:
612     Result.Data = Info.take();
613     if (Info.hasSFINAEDiagnostic()) {
614       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
615           SourceLocation(), PartialDiagnostic::NullDiagnostic());
616       Info.takeSFINAEDiagnostic(*Diag);
617       Result.HasDiagnostic = true;
618     }
619     break;
620 
621   case Sema::TDK_FailedOverloadResolution:
622     Result.Data = Info.Expression;
623     break;
624 
625   case Sema::TDK_MiscellaneousDeductionFailure:
626     break;
627   }
628 
629   return Result;
630 }
631 
Destroy()632 void DeductionFailureInfo::Destroy() {
633   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
634   case Sema::TDK_Success:
635   case Sema::TDK_Invalid:
636   case Sema::TDK_InstantiationDepth:
637   case Sema::TDK_Incomplete:
638   case Sema::TDK_TooManyArguments:
639   case Sema::TDK_TooFewArguments:
640   case Sema::TDK_InvalidExplicitArguments:
641   case Sema::TDK_FailedOverloadResolution:
642     break;
643 
644   case Sema::TDK_Inconsistent:
645   case Sema::TDK_Underqualified:
646   case Sema::TDK_NonDeducedMismatch:
647     // FIXME: Destroy the data?
648     Data = nullptr;
649     break;
650 
651   case Sema::TDK_SubstitutionFailure:
652     // FIXME: Destroy the template argument list?
653     Data = nullptr;
654     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
655       Diag->~PartialDiagnosticAt();
656       HasDiagnostic = false;
657     }
658     break;
659 
660   // Unhandled
661   case Sema::TDK_MiscellaneousDeductionFailure:
662     break;
663   }
664 }
665 
getSFINAEDiagnostic()666 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
667   if (HasDiagnostic)
668     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
669   return nullptr;
670 }
671 
getTemplateParameter()672 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
673   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
674   case Sema::TDK_Success:
675   case Sema::TDK_Invalid:
676   case Sema::TDK_InstantiationDepth:
677   case Sema::TDK_TooManyArguments:
678   case Sema::TDK_TooFewArguments:
679   case Sema::TDK_SubstitutionFailure:
680   case Sema::TDK_NonDeducedMismatch:
681   case Sema::TDK_FailedOverloadResolution:
682     return TemplateParameter();
683 
684   case Sema::TDK_Incomplete:
685   case Sema::TDK_InvalidExplicitArguments:
686     return TemplateParameter::getFromOpaqueValue(Data);
687 
688   case Sema::TDK_Inconsistent:
689   case Sema::TDK_Underqualified:
690     return static_cast<DFIParamWithArguments*>(Data)->Param;
691 
692   // Unhandled
693   case Sema::TDK_MiscellaneousDeductionFailure:
694     break;
695   }
696 
697   return TemplateParameter();
698 }
699 
getTemplateArgumentList()700 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
701   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702   case Sema::TDK_Success:
703   case Sema::TDK_Invalid:
704   case Sema::TDK_InstantiationDepth:
705   case Sema::TDK_TooManyArguments:
706   case Sema::TDK_TooFewArguments:
707   case Sema::TDK_Incomplete:
708   case Sema::TDK_InvalidExplicitArguments:
709   case Sema::TDK_Inconsistent:
710   case Sema::TDK_Underqualified:
711   case Sema::TDK_NonDeducedMismatch:
712   case Sema::TDK_FailedOverloadResolution:
713     return nullptr;
714 
715   case Sema::TDK_SubstitutionFailure:
716     return static_cast<TemplateArgumentList*>(Data);
717 
718   // Unhandled
719   case Sema::TDK_MiscellaneousDeductionFailure:
720     break;
721   }
722 
723   return nullptr;
724 }
725 
getFirstArg()726 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
727   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
728   case Sema::TDK_Success:
729   case Sema::TDK_Invalid:
730   case Sema::TDK_InstantiationDepth:
731   case Sema::TDK_Incomplete:
732   case Sema::TDK_TooManyArguments:
733   case Sema::TDK_TooFewArguments:
734   case Sema::TDK_InvalidExplicitArguments:
735   case Sema::TDK_SubstitutionFailure:
736   case Sema::TDK_FailedOverloadResolution:
737     return nullptr;
738 
739   case Sema::TDK_Inconsistent:
740   case Sema::TDK_Underqualified:
741   case Sema::TDK_NonDeducedMismatch:
742     return &static_cast<DFIArguments*>(Data)->FirstArg;
743 
744   // Unhandled
745   case Sema::TDK_MiscellaneousDeductionFailure:
746     break;
747   }
748 
749   return nullptr;
750 }
751 
getSecondArg()752 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
753   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
754   case Sema::TDK_Success:
755   case Sema::TDK_Invalid:
756   case Sema::TDK_InstantiationDepth:
757   case Sema::TDK_Incomplete:
758   case Sema::TDK_TooManyArguments:
759   case Sema::TDK_TooFewArguments:
760   case Sema::TDK_InvalidExplicitArguments:
761   case Sema::TDK_SubstitutionFailure:
762   case Sema::TDK_FailedOverloadResolution:
763     return nullptr;
764 
765   case Sema::TDK_Inconsistent:
766   case Sema::TDK_Underqualified:
767   case Sema::TDK_NonDeducedMismatch:
768     return &static_cast<DFIArguments*>(Data)->SecondArg;
769 
770   // Unhandled
771   case Sema::TDK_MiscellaneousDeductionFailure:
772     break;
773   }
774 
775   return nullptr;
776 }
777 
getExpr()778 Expr *DeductionFailureInfo::getExpr() {
779   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
780         Sema::TDK_FailedOverloadResolution)
781     return static_cast<Expr*>(Data);
782 
783   return nullptr;
784 }
785 
destroyCandidates()786 void OverloadCandidateSet::destroyCandidates() {
787   for (iterator i = begin(), e = end(); i != e; ++i) {
788     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
789       i->Conversions[ii].~ImplicitConversionSequence();
790     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
791       i->DeductionFailure.Destroy();
792   }
793 }
794 
clear()795 void OverloadCandidateSet::clear() {
796   destroyCandidates();
797   NumInlineSequences = 0;
798   Candidates.clear();
799   Functions.clear();
800 }
801 
802 namespace {
803   class UnbridgedCastsSet {
804     struct Entry {
805       Expr **Addr;
806       Expr *Saved;
807     };
808     SmallVector<Entry, 2> Entries;
809 
810   public:
save(Sema & S,Expr * & E)811     void save(Sema &S, Expr *&E) {
812       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
813       Entry entry = { &E, E };
814       Entries.push_back(entry);
815       E = S.stripARCUnbridgedCast(E);
816     }
817 
restore()818     void restore() {
819       for (SmallVectorImpl<Entry>::iterator
820              i = Entries.begin(), e = Entries.end(); i != e; ++i)
821         *i->Addr = i->Saved;
822     }
823   };
824 }
825 
826 /// checkPlaceholderForOverload - Do any interesting placeholder-like
827 /// preprocessing on the given expression.
828 ///
829 /// \param unbridgedCasts a collection to which to add unbridged casts;
830 ///   without this, they will be immediately diagnosed as errors
831 ///
832 /// Return true on unrecoverable error.
833 static bool
checkPlaceholderForOverload(Sema & S,Expr * & E,UnbridgedCastsSet * unbridgedCasts=nullptr)834 checkPlaceholderForOverload(Sema &S, Expr *&E,
835                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
836   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
837     // We can't handle overloaded expressions here because overload
838     // resolution might reasonably tweak them.
839     if (placeholder->getKind() == BuiltinType::Overload) return false;
840 
841     // If the context potentially accepts unbridged ARC casts, strip
842     // the unbridged cast and add it to the collection for later restoration.
843     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
844         unbridgedCasts) {
845       unbridgedCasts->save(S, E);
846       return false;
847     }
848 
849     // Go ahead and check everything else.
850     ExprResult result = S.CheckPlaceholderExpr(E);
851     if (result.isInvalid())
852       return true;
853 
854     E = result.get();
855     return false;
856   }
857 
858   // Nothing to do.
859   return false;
860 }
861 
862 /// checkArgPlaceholdersForOverload - Check a set of call operands for
863 /// placeholders.
checkArgPlaceholdersForOverload(Sema & S,MultiExprArg Args,UnbridgedCastsSet & unbridged)864 static bool checkArgPlaceholdersForOverload(Sema &S,
865                                             MultiExprArg Args,
866                                             UnbridgedCastsSet &unbridged) {
867   for (unsigned i = 0, e = Args.size(); i != e; ++i)
868     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
869       return true;
870 
871   return false;
872 }
873 
874 // IsOverload - Determine whether the given New declaration is an
875 // overload of the declarations in Old. This routine returns false if
876 // New and Old cannot be overloaded, e.g., if New has the same
877 // signature as some function in Old (C++ 1.3.10) or if the Old
878 // declarations aren't functions (or function templates) at all. When
879 // it does return false, MatchedDecl will point to the decl that New
880 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
881 // top of the underlying declaration.
882 //
883 // Example: Given the following input:
884 //
885 //   void f(int, float); // #1
886 //   void f(int, int); // #2
887 //   int f(int, int); // #3
888 //
889 // When we process #1, there is no previous declaration of "f",
890 // so IsOverload will not be used.
891 //
892 // When we process #2, Old contains only the FunctionDecl for #1.  By
893 // comparing the parameter types, we see that #1 and #2 are overloaded
894 // (since they have different signatures), so this routine returns
895 // false; MatchedDecl is unchanged.
896 //
897 // When we process #3, Old is an overload set containing #1 and #2. We
898 // compare the signatures of #3 to #1 (they're overloaded, so we do
899 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
900 // identical (return types of functions are not part of the
901 // signature), IsOverload returns false and MatchedDecl will be set to
902 // point to the FunctionDecl for #2.
903 //
904 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
905 // into a class by a using declaration.  The rules for whether to hide
906 // shadow declarations ignore some properties which otherwise figure
907 // into a function template's signature.
908 Sema::OverloadKind
CheckOverload(Scope * S,FunctionDecl * New,const LookupResult & Old,NamedDecl * & Match,bool NewIsUsingDecl)909 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
910                     NamedDecl *&Match, bool NewIsUsingDecl) {
911   for (LookupResult::iterator I = Old.begin(), E = Old.end();
912          I != E; ++I) {
913     NamedDecl *OldD = *I;
914 
915     bool OldIsUsingDecl = false;
916     if (isa<UsingShadowDecl>(OldD)) {
917       OldIsUsingDecl = true;
918 
919       // We can always introduce two using declarations into the same
920       // context, even if they have identical signatures.
921       if (NewIsUsingDecl) continue;
922 
923       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
924     }
925 
926     // If either declaration was introduced by a using declaration,
927     // we'll need to use slightly different rules for matching.
928     // Essentially, these rules are the normal rules, except that
929     // function templates hide function templates with different
930     // return types or template parameter lists.
931     bool UseMemberUsingDeclRules =
932       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
933       !New->getFriendObjectKind();
934 
935     if (FunctionDecl *OldF = OldD->getAsFunction()) {
936       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
937         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
938           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
939           continue;
940         }
941 
942         if (!isa<FunctionTemplateDecl>(OldD) &&
943             !shouldLinkPossiblyHiddenDecl(*I, New))
944           continue;
945 
946         Match = *I;
947         return Ovl_Match;
948       }
949     } else if (isa<UsingDecl>(OldD)) {
950       // We can overload with these, which can show up when doing
951       // redeclaration checks for UsingDecls.
952       assert(Old.getLookupKind() == LookupUsingDeclName);
953     } else if (isa<TagDecl>(OldD)) {
954       // We can always overload with tags by hiding them.
955     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
956       // Optimistically assume that an unresolved using decl will
957       // overload; if it doesn't, we'll have to diagnose during
958       // template instantiation.
959     } else {
960       // (C++ 13p1):
961       //   Only function declarations can be overloaded; object and type
962       //   declarations cannot be overloaded.
963       Match = *I;
964       return Ovl_NonFunction;
965     }
966   }
967 
968   return Ovl_Overload;
969 }
970 
IsOverload(FunctionDecl * New,FunctionDecl * Old,bool UseUsingDeclRules)971 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
972                       bool UseUsingDeclRules) {
973   // C++ [basic.start.main]p2: This function shall not be overloaded.
974   if (New->isMain())
975     return false;
976 
977   // MSVCRT user defined entry points cannot be overloaded.
978   if (New->isMSVCRTEntryPoint())
979     return false;
980 
981   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
982   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
983 
984   // C++ [temp.fct]p2:
985   //   A function template can be overloaded with other function templates
986   //   and with normal (non-template) functions.
987   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
988     return true;
989 
990   // Is the function New an overload of the function Old?
991   QualType OldQType = Context.getCanonicalType(Old->getType());
992   QualType NewQType = Context.getCanonicalType(New->getType());
993 
994   // Compare the signatures (C++ 1.3.10) of the two functions to
995   // determine whether they are overloads. If we find any mismatch
996   // in the signature, they are overloads.
997 
998   // If either of these functions is a K&R-style function (no
999   // prototype), then we consider them to have matching signatures.
1000   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1001       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1002     return false;
1003 
1004   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1005   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1006 
1007   // The signature of a function includes the types of its
1008   // parameters (C++ 1.3.10), which includes the presence or absence
1009   // of the ellipsis; see C++ DR 357).
1010   if (OldQType != NewQType &&
1011       (OldType->getNumParams() != NewType->getNumParams() ||
1012        OldType->isVariadic() != NewType->isVariadic() ||
1013        !FunctionParamTypesAreEqual(OldType, NewType)))
1014     return true;
1015 
1016   // C++ [temp.over.link]p4:
1017   //   The signature of a function template consists of its function
1018   //   signature, its return type and its template parameter list. The names
1019   //   of the template parameters are significant only for establishing the
1020   //   relationship between the template parameters and the rest of the
1021   //   signature.
1022   //
1023   // We check the return type and template parameter lists for function
1024   // templates first; the remaining checks follow.
1025   //
1026   // However, we don't consider either of these when deciding whether
1027   // a member introduced by a shadow declaration is hidden.
1028   if (!UseUsingDeclRules && NewTemplate &&
1029       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1030                                        OldTemplate->getTemplateParameters(),
1031                                        false, TPL_TemplateMatch) ||
1032        OldType->getReturnType() != NewType->getReturnType()))
1033     return true;
1034 
1035   // If the function is a class member, its signature includes the
1036   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1037   //
1038   // As part of this, also check whether one of the member functions
1039   // is static, in which case they are not overloads (C++
1040   // 13.1p2). While not part of the definition of the signature,
1041   // this check is important to determine whether these functions
1042   // can be overloaded.
1043   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1044   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1045   if (OldMethod && NewMethod &&
1046       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1047     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1048       if (!UseUsingDeclRules &&
1049           (OldMethod->getRefQualifier() == RQ_None ||
1050            NewMethod->getRefQualifier() == RQ_None)) {
1051         // C++0x [over.load]p2:
1052         //   - Member function declarations with the same name and the same
1053         //     parameter-type-list as well as member function template
1054         //     declarations with the same name, the same parameter-type-list, and
1055         //     the same template parameter lists cannot be overloaded if any of
1056         //     them, but not all, have a ref-qualifier (8.3.5).
1057         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1058           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1059         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1060       }
1061       return true;
1062     }
1063 
1064     // We may not have applied the implicit const for a constexpr member
1065     // function yet (because we haven't yet resolved whether this is a static
1066     // or non-static member function). Add it now, on the assumption that this
1067     // is a redeclaration of OldMethod.
1068     unsigned OldQuals = OldMethod->getTypeQualifiers();
1069     unsigned NewQuals = NewMethod->getTypeQualifiers();
1070     if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
1071         !isa<CXXConstructorDecl>(NewMethod))
1072       NewQuals |= Qualifiers::Const;
1073 
1074     // We do not allow overloading based off of '__restrict'.
1075     OldQuals &= ~Qualifiers::Restrict;
1076     NewQuals &= ~Qualifiers::Restrict;
1077     if (OldQuals != NewQuals)
1078       return true;
1079   }
1080 
1081   // enable_if attributes are an order-sensitive part of the signature.
1082   for (specific_attr_iterator<EnableIfAttr>
1083          NewI = New->specific_attr_begin<EnableIfAttr>(),
1084          NewE = New->specific_attr_end<EnableIfAttr>(),
1085          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1086          OldE = Old->specific_attr_end<EnableIfAttr>();
1087        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1088     if (NewI == NewE || OldI == OldE)
1089       return true;
1090     llvm::FoldingSetNodeID NewID, OldID;
1091     NewI->getCond()->Profile(NewID, Context, true);
1092     OldI->getCond()->Profile(OldID, Context, true);
1093     if (NewID != OldID)
1094       return true;
1095   }
1096 
1097   // The signatures match; this is not an overload.
1098   return false;
1099 }
1100 
1101 /// \brief Checks availability of the function depending on the current
1102 /// function context. Inside an unavailable function, unavailability is ignored.
1103 ///
1104 /// \returns true if \arg FD is unavailable and current context is inside
1105 /// an available function, false otherwise.
isFunctionConsideredUnavailable(FunctionDecl * FD)1106 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1107   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1108 }
1109 
1110 /// \brief Tries a user-defined conversion from From to ToType.
1111 ///
1112 /// Produces an implicit conversion sequence for when a standard conversion
1113 /// is not an option. See TryImplicitConversion for more information.
1114 static ImplicitConversionSequence
TryUserDefinedConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion,bool AllowObjCConversionOnExplicit)1115 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1116                          bool SuppressUserConversions,
1117                          bool AllowExplicit,
1118                          bool InOverloadResolution,
1119                          bool CStyle,
1120                          bool AllowObjCWritebackConversion,
1121                          bool AllowObjCConversionOnExplicit) {
1122   ImplicitConversionSequence ICS;
1123 
1124   if (SuppressUserConversions) {
1125     // We're not in the case above, so there is no conversion that
1126     // we can perform.
1127     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1128     return ICS;
1129   }
1130 
1131   // Attempt user-defined conversion.
1132   OverloadCandidateSet Conversions(From->getExprLoc(),
1133                                    OverloadCandidateSet::CSK_Normal);
1134   OverloadingResult UserDefResult
1135     = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1136                               AllowExplicit, AllowObjCConversionOnExplicit);
1137 
1138   if (UserDefResult == OR_Success) {
1139     ICS.setUserDefined();
1140     ICS.UserDefined.Before.setAsIdentityConversion();
1141     // C++ [over.ics.user]p4:
1142     //   A conversion of an expression of class type to the same class
1143     //   type is given Exact Match rank, and a conversion of an
1144     //   expression of class type to a base class of that type is
1145     //   given Conversion rank, in spite of the fact that a copy
1146     //   constructor (i.e., a user-defined conversion function) is
1147     //   called for those cases.
1148     if (CXXConstructorDecl *Constructor
1149           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1150       QualType FromCanon
1151         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1152       QualType ToCanon
1153         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1154       if (Constructor->isCopyConstructor() &&
1155           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1156         // Turn this into a "standard" conversion sequence, so that it
1157         // gets ranked with standard conversion sequences.
1158         ICS.setStandard();
1159         ICS.Standard.setAsIdentityConversion();
1160         ICS.Standard.setFromType(From->getType());
1161         ICS.Standard.setAllToTypes(ToType);
1162         ICS.Standard.CopyConstructor = Constructor;
1163         if (ToCanon != FromCanon)
1164           ICS.Standard.Second = ICK_Derived_To_Base;
1165       }
1166     }
1167 
1168     // C++ [over.best.ics]p4:
1169     //   However, when considering the argument of a user-defined
1170     //   conversion function that is a candidate by 13.3.1.3 when
1171     //   invoked for the copying of the temporary in the second step
1172     //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1173     //   13.3.1.6 in all cases, only standard conversion sequences and
1174     //   ellipsis conversion sequences are allowed.
1175     if (SuppressUserConversions && ICS.isUserDefined()) {
1176       ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1177     }
1178   } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1179     ICS.setAmbiguous();
1180     ICS.Ambiguous.setFromType(From->getType());
1181     ICS.Ambiguous.setToType(ToType);
1182     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1183          Cand != Conversions.end(); ++Cand)
1184       if (Cand->Viable)
1185         ICS.Ambiguous.addConversion(Cand->Function);
1186   } else {
1187     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1188   }
1189 
1190   return ICS;
1191 }
1192 
1193 /// TryImplicitConversion - Attempt to perform an implicit conversion
1194 /// from the given expression (Expr) to the given type (ToType). This
1195 /// function returns an implicit conversion sequence that can be used
1196 /// to perform the initialization. Given
1197 ///
1198 ///   void f(float f);
1199 ///   void g(int i) { f(i); }
1200 ///
1201 /// this routine would produce an implicit conversion sequence to
1202 /// describe the initialization of f from i, which will be a standard
1203 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1204 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1205 //
1206 /// Note that this routine only determines how the conversion can be
1207 /// performed; it does not actually perform the conversion. As such,
1208 /// it will not produce any diagnostics if no conversion is available,
1209 /// but will instead return an implicit conversion sequence of kind
1210 /// "BadConversion".
1211 ///
1212 /// If @p SuppressUserConversions, then user-defined conversions are
1213 /// not permitted.
1214 /// If @p AllowExplicit, then explicit user-defined conversions are
1215 /// permitted.
1216 ///
1217 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1218 /// writeback conversion, which allows __autoreleasing id* parameters to
1219 /// be initialized with __strong id* or __weak id* arguments.
1220 static ImplicitConversionSequence
TryImplicitConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion,bool AllowObjCConversionOnExplicit)1221 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1222                       bool SuppressUserConversions,
1223                       bool AllowExplicit,
1224                       bool InOverloadResolution,
1225                       bool CStyle,
1226                       bool AllowObjCWritebackConversion,
1227                       bool AllowObjCConversionOnExplicit) {
1228   ImplicitConversionSequence ICS;
1229   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1230                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1231     ICS.setStandard();
1232     return ICS;
1233   }
1234 
1235   if (!S.getLangOpts().CPlusPlus) {
1236     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1237     return ICS;
1238   }
1239 
1240   // C++ [over.ics.user]p4:
1241   //   A conversion of an expression of class type to the same class
1242   //   type is given Exact Match rank, and a conversion of an
1243   //   expression of class type to a base class of that type is
1244   //   given Conversion rank, in spite of the fact that a copy/move
1245   //   constructor (i.e., a user-defined conversion function) is
1246   //   called for those cases.
1247   QualType FromType = From->getType();
1248   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1249       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1250        S.IsDerivedFrom(FromType, ToType))) {
1251     ICS.setStandard();
1252     ICS.Standard.setAsIdentityConversion();
1253     ICS.Standard.setFromType(FromType);
1254     ICS.Standard.setAllToTypes(ToType);
1255 
1256     // We don't actually check at this point whether there is a valid
1257     // copy/move constructor, since overloading just assumes that it
1258     // exists. When we actually perform initialization, we'll find the
1259     // appropriate constructor to copy the returned object, if needed.
1260     ICS.Standard.CopyConstructor = nullptr;
1261 
1262     // Determine whether this is considered a derived-to-base conversion.
1263     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1264       ICS.Standard.Second = ICK_Derived_To_Base;
1265 
1266     return ICS;
1267   }
1268 
1269   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1270                                   AllowExplicit, InOverloadResolution, CStyle,
1271                                   AllowObjCWritebackConversion,
1272                                   AllowObjCConversionOnExplicit);
1273 }
1274 
1275 ImplicitConversionSequence
TryImplicitConversion(Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion)1276 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1277                             bool SuppressUserConversions,
1278                             bool AllowExplicit,
1279                             bool InOverloadResolution,
1280                             bool CStyle,
1281                             bool AllowObjCWritebackConversion) {
1282   return clang::TryImplicitConversion(*this, From, ToType,
1283                                       SuppressUserConversions, AllowExplicit,
1284                                       InOverloadResolution, CStyle,
1285                                       AllowObjCWritebackConversion,
1286                                       /*AllowObjCConversionOnExplicit=*/false);
1287 }
1288 
1289 /// PerformImplicitConversion - Perform an implicit conversion of the
1290 /// expression From to the type ToType. Returns the
1291 /// converted expression. Flavor is the kind of conversion we're
1292 /// performing, used in the error message. If @p AllowExplicit,
1293 /// explicit user-defined conversions are permitted.
1294 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,AssignmentAction Action,bool AllowExplicit)1295 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1296                                 AssignmentAction Action, bool AllowExplicit) {
1297   ImplicitConversionSequence ICS;
1298   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1299 }
1300 
1301 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,AssignmentAction Action,bool AllowExplicit,ImplicitConversionSequence & ICS)1302 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1303                                 AssignmentAction Action, bool AllowExplicit,
1304                                 ImplicitConversionSequence& ICS) {
1305   if (checkPlaceholderForOverload(*this, From))
1306     return ExprError();
1307 
1308   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1309   bool AllowObjCWritebackConversion
1310     = getLangOpts().ObjCAutoRefCount &&
1311       (Action == AA_Passing || Action == AA_Sending);
1312   if (getLangOpts().ObjC1)
1313     CheckObjCBridgeRelatedConversions(From->getLocStart(),
1314                                       ToType, From->getType(), From);
1315   ICS = clang::TryImplicitConversion(*this, From, ToType,
1316                                      /*SuppressUserConversions=*/false,
1317                                      AllowExplicit,
1318                                      /*InOverloadResolution=*/false,
1319                                      /*CStyle=*/false,
1320                                      AllowObjCWritebackConversion,
1321                                      /*AllowObjCConversionOnExplicit=*/false);
1322   return PerformImplicitConversion(From, ToType, ICS, Action);
1323 }
1324 
1325 /// \brief Determine whether the conversion from FromType to ToType is a valid
1326 /// conversion that strips "noreturn" off the nested function type.
IsNoReturnConversion(QualType FromType,QualType ToType,QualType & ResultTy)1327 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1328                                 QualType &ResultTy) {
1329   if (Context.hasSameUnqualifiedType(FromType, ToType))
1330     return false;
1331 
1332   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1333   // where F adds one of the following at most once:
1334   //   - a pointer
1335   //   - a member pointer
1336   //   - a block pointer
1337   CanQualType CanTo = Context.getCanonicalType(ToType);
1338   CanQualType CanFrom = Context.getCanonicalType(FromType);
1339   Type::TypeClass TyClass = CanTo->getTypeClass();
1340   if (TyClass != CanFrom->getTypeClass()) return false;
1341   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1342     if (TyClass == Type::Pointer) {
1343       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1344       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1345     } else if (TyClass == Type::BlockPointer) {
1346       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1347       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1348     } else if (TyClass == Type::MemberPointer) {
1349       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1350       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1351     } else {
1352       return false;
1353     }
1354 
1355     TyClass = CanTo->getTypeClass();
1356     if (TyClass != CanFrom->getTypeClass()) return false;
1357     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1358       return false;
1359   }
1360 
1361   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1362   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1363   if (!EInfo.getNoReturn()) return false;
1364 
1365   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1366   assert(QualType(FromFn, 0).isCanonical());
1367   if (QualType(FromFn, 0) != CanTo) return false;
1368 
1369   ResultTy = ToType;
1370   return true;
1371 }
1372 
1373 /// \brief Determine whether the conversion from FromType to ToType is a valid
1374 /// vector conversion.
1375 ///
1376 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1377 /// conversion.
IsVectorConversion(Sema & S,QualType FromType,QualType ToType,ImplicitConversionKind & ICK)1378 static bool IsVectorConversion(Sema &S, QualType FromType,
1379                                QualType ToType, ImplicitConversionKind &ICK) {
1380   // We need at least one of these types to be a vector type to have a vector
1381   // conversion.
1382   if (!ToType->isVectorType() && !FromType->isVectorType())
1383     return false;
1384 
1385   // Identical types require no conversions.
1386   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1387     return false;
1388 
1389   // There are no conversions between extended vector types, only identity.
1390   if (ToType->isExtVectorType()) {
1391     // There are no conversions between extended vector types other than the
1392     // identity conversion.
1393     if (FromType->isExtVectorType())
1394       return false;
1395 
1396     // Vector splat from any arithmetic type to a vector.
1397     if (FromType->isArithmeticType()) {
1398       ICK = ICK_Vector_Splat;
1399       return true;
1400     }
1401   }
1402 
1403   // We can perform the conversion between vector types in the following cases:
1404   // 1)vector types are equivalent AltiVec and GCC vector types
1405   // 2)lax vector conversions are permitted and the vector types are of the
1406   //   same size
1407   if (ToType->isVectorType() && FromType->isVectorType()) {
1408     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1409         S.isLaxVectorConversion(FromType, ToType)) {
1410       ICK = ICK_Vector_Conversion;
1411       return true;
1412     }
1413   }
1414 
1415   return false;
1416 }
1417 
1418 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1419                                 bool InOverloadResolution,
1420                                 StandardConversionSequence &SCS,
1421                                 bool CStyle);
1422 
1423 /// IsStandardConversion - Determines whether there is a standard
1424 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1425 /// expression From to the type ToType. Standard conversion sequences
1426 /// only consider non-class types; for conversions that involve class
1427 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1428 /// contain the standard conversion sequence required to perform this
1429 /// conversion and this routine will return true. Otherwise, this
1430 /// routine will return false and the value of SCS is unspecified.
IsStandardConversion(Sema & S,Expr * From,QualType ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle,bool AllowObjCWritebackConversion)1431 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1432                                  bool InOverloadResolution,
1433                                  StandardConversionSequence &SCS,
1434                                  bool CStyle,
1435                                  bool AllowObjCWritebackConversion) {
1436   QualType FromType = From->getType();
1437 
1438   // Standard conversions (C++ [conv])
1439   SCS.setAsIdentityConversion();
1440   SCS.IncompatibleObjC = false;
1441   SCS.setFromType(FromType);
1442   SCS.CopyConstructor = nullptr;
1443 
1444   // There are no standard conversions for class types in C++, so
1445   // abort early. When overloading in C, however, we do permit
1446   if (FromType->isRecordType() || ToType->isRecordType()) {
1447     if (S.getLangOpts().CPlusPlus)
1448       return false;
1449 
1450     // When we're overloading in C, we allow, as standard conversions,
1451   }
1452 
1453   // The first conversion can be an lvalue-to-rvalue conversion,
1454   // array-to-pointer conversion, or function-to-pointer conversion
1455   // (C++ 4p1).
1456 
1457   if (FromType == S.Context.OverloadTy) {
1458     DeclAccessPair AccessPair;
1459     if (FunctionDecl *Fn
1460           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1461                                                  AccessPair)) {
1462       // We were able to resolve the address of the overloaded function,
1463       // so we can convert to the type of that function.
1464       FromType = Fn->getType();
1465 
1466       // we can sometimes resolve &foo<int> regardless of ToType, so check
1467       // if the type matches (identity) or we are converting to bool
1468       if (!S.Context.hasSameUnqualifiedType(
1469                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1470         QualType resultTy;
1471         // if the function type matches except for [[noreturn]], it's ok
1472         if (!S.IsNoReturnConversion(FromType,
1473               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1474           // otherwise, only a boolean conversion is standard
1475           if (!ToType->isBooleanType())
1476             return false;
1477       }
1478 
1479       // Check if the "from" expression is taking the address of an overloaded
1480       // function and recompute the FromType accordingly. Take advantage of the
1481       // fact that non-static member functions *must* have such an address-of
1482       // expression.
1483       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1484       if (Method && !Method->isStatic()) {
1485         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1486                "Non-unary operator on non-static member address");
1487         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1488                == UO_AddrOf &&
1489                "Non-address-of operator on non-static member address");
1490         const Type *ClassType
1491           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1492         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1493       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1494         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1495                UO_AddrOf &&
1496                "Non-address-of operator for overloaded function expression");
1497         FromType = S.Context.getPointerType(FromType);
1498       }
1499 
1500       // Check that we've computed the proper type after overload resolution.
1501       assert(S.Context.hasSameType(
1502         FromType,
1503         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1504     } else {
1505       return false;
1506     }
1507   }
1508   // Lvalue-to-rvalue conversion (C++11 4.1):
1509   //   A glvalue (3.10) of a non-function, non-array type T can
1510   //   be converted to a prvalue.
1511   bool argIsLValue = From->isGLValue();
1512   if (argIsLValue &&
1513       !FromType->isFunctionType() && !FromType->isArrayType() &&
1514       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1515     SCS.First = ICK_Lvalue_To_Rvalue;
1516 
1517     // C11 6.3.2.1p2:
1518     //   ... if the lvalue has atomic type, the value has the non-atomic version
1519     //   of the type of the lvalue ...
1520     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1521       FromType = Atomic->getValueType();
1522 
1523     // If T is a non-class type, the type of the rvalue is the
1524     // cv-unqualified version of T. Otherwise, the type of the rvalue
1525     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1526     // just strip the qualifiers because they don't matter.
1527     FromType = FromType.getUnqualifiedType();
1528   } else if (FromType->isArrayType()) {
1529     // Array-to-pointer conversion (C++ 4.2)
1530     SCS.First = ICK_Array_To_Pointer;
1531 
1532     // An lvalue or rvalue of type "array of N T" or "array of unknown
1533     // bound of T" can be converted to an rvalue of type "pointer to
1534     // T" (C++ 4.2p1).
1535     FromType = S.Context.getArrayDecayedType(FromType);
1536 
1537     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1538       // This conversion is deprecated in C++03 (D.4)
1539       SCS.DeprecatedStringLiteralToCharPtr = true;
1540 
1541       // For the purpose of ranking in overload resolution
1542       // (13.3.3.1.1), this conversion is considered an
1543       // array-to-pointer conversion followed by a qualification
1544       // conversion (4.4). (C++ 4.2p2)
1545       SCS.Second = ICK_Identity;
1546       SCS.Third = ICK_Qualification;
1547       SCS.QualificationIncludesObjCLifetime = false;
1548       SCS.setAllToTypes(FromType);
1549       return true;
1550     }
1551   } else if (FromType->isFunctionType() && argIsLValue) {
1552     // Function-to-pointer conversion (C++ 4.3).
1553     SCS.First = ICK_Function_To_Pointer;
1554 
1555     // An lvalue of function type T can be converted to an rvalue of
1556     // type "pointer to T." The result is a pointer to the
1557     // function. (C++ 4.3p1).
1558     FromType = S.Context.getPointerType(FromType);
1559   } else {
1560     // We don't require any conversions for the first step.
1561     SCS.First = ICK_Identity;
1562   }
1563   SCS.setToType(0, FromType);
1564 
1565   // The second conversion can be an integral promotion, floating
1566   // point promotion, integral conversion, floating point conversion,
1567   // floating-integral conversion, pointer conversion,
1568   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1569   // For overloading in C, this can also be a "compatible-type"
1570   // conversion.
1571   bool IncompatibleObjC = false;
1572   ImplicitConversionKind SecondICK = ICK_Identity;
1573   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1574     // The unqualified versions of the types are the same: there's no
1575     // conversion to do.
1576     SCS.Second = ICK_Identity;
1577   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1578     // Integral promotion (C++ 4.5).
1579     SCS.Second = ICK_Integral_Promotion;
1580     FromType = ToType.getUnqualifiedType();
1581   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1582     // Floating point promotion (C++ 4.6).
1583     SCS.Second = ICK_Floating_Promotion;
1584     FromType = ToType.getUnqualifiedType();
1585   } else if (S.IsComplexPromotion(FromType, ToType)) {
1586     // Complex promotion (Clang extension)
1587     SCS.Second = ICK_Complex_Promotion;
1588     FromType = ToType.getUnqualifiedType();
1589   } else if (ToType->isBooleanType() &&
1590              (FromType->isArithmeticType() ||
1591               FromType->isAnyPointerType() ||
1592               FromType->isBlockPointerType() ||
1593               FromType->isMemberPointerType() ||
1594               FromType->isNullPtrType())) {
1595     // Boolean conversions (C++ 4.12).
1596     SCS.Second = ICK_Boolean_Conversion;
1597     FromType = S.Context.BoolTy;
1598   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1599              ToType->isIntegralType(S.Context)) {
1600     // Integral conversions (C++ 4.7).
1601     SCS.Second = ICK_Integral_Conversion;
1602     FromType = ToType.getUnqualifiedType();
1603   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1604     // Complex conversions (C99 6.3.1.6)
1605     SCS.Second = ICK_Complex_Conversion;
1606     FromType = ToType.getUnqualifiedType();
1607   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1608              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1609     // Complex-real conversions (C99 6.3.1.7)
1610     SCS.Second = ICK_Complex_Real;
1611     FromType = ToType.getUnqualifiedType();
1612   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1613     // Floating point conversions (C++ 4.8).
1614     SCS.Second = ICK_Floating_Conversion;
1615     FromType = ToType.getUnqualifiedType();
1616   } else if ((FromType->isRealFloatingType() &&
1617               ToType->isIntegralType(S.Context)) ||
1618              (FromType->isIntegralOrUnscopedEnumerationType() &&
1619               ToType->isRealFloatingType())) {
1620     // Floating-integral conversions (C++ 4.9).
1621     SCS.Second = ICK_Floating_Integral;
1622     FromType = ToType.getUnqualifiedType();
1623   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1624     SCS.Second = ICK_Block_Pointer_Conversion;
1625   } else if (AllowObjCWritebackConversion &&
1626              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1627     SCS.Second = ICK_Writeback_Conversion;
1628   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1629                                    FromType, IncompatibleObjC)) {
1630     // Pointer conversions (C++ 4.10).
1631     SCS.Second = ICK_Pointer_Conversion;
1632     SCS.IncompatibleObjC = IncompatibleObjC;
1633     FromType = FromType.getUnqualifiedType();
1634   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1635                                          InOverloadResolution, FromType)) {
1636     // Pointer to member conversions (4.11).
1637     SCS.Second = ICK_Pointer_Member;
1638   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1639     SCS.Second = SecondICK;
1640     FromType = ToType.getUnqualifiedType();
1641   } else if (!S.getLangOpts().CPlusPlus &&
1642              S.Context.typesAreCompatible(ToType, FromType)) {
1643     // Compatible conversions (Clang extension for C function overloading)
1644     SCS.Second = ICK_Compatible_Conversion;
1645     FromType = ToType.getUnqualifiedType();
1646   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1647     // Treat a conversion that strips "noreturn" as an identity conversion.
1648     SCS.Second = ICK_NoReturn_Adjustment;
1649   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1650                                              InOverloadResolution,
1651                                              SCS, CStyle)) {
1652     SCS.Second = ICK_TransparentUnionConversion;
1653     FromType = ToType;
1654   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1655                                  CStyle)) {
1656     // tryAtomicConversion has updated the standard conversion sequence
1657     // appropriately.
1658     return true;
1659   } else if (ToType->isEventT() &&
1660              From->isIntegerConstantExpr(S.getASTContext()) &&
1661              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1662     SCS.Second = ICK_Zero_Event_Conversion;
1663     FromType = ToType;
1664   } else {
1665     // No second conversion required.
1666     SCS.Second = ICK_Identity;
1667   }
1668   SCS.setToType(1, FromType);
1669 
1670   QualType CanonFrom;
1671   QualType CanonTo;
1672   // The third conversion can be a qualification conversion (C++ 4p1).
1673   bool ObjCLifetimeConversion;
1674   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1675                                   ObjCLifetimeConversion)) {
1676     SCS.Third = ICK_Qualification;
1677     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1678     FromType = ToType;
1679     CanonFrom = S.Context.getCanonicalType(FromType);
1680     CanonTo = S.Context.getCanonicalType(ToType);
1681   } else {
1682     // No conversion required
1683     SCS.Third = ICK_Identity;
1684 
1685     // C++ [over.best.ics]p6:
1686     //   [...] Any difference in top-level cv-qualification is
1687     //   subsumed by the initialization itself and does not constitute
1688     //   a conversion. [...]
1689     CanonFrom = S.Context.getCanonicalType(FromType);
1690     CanonTo = S.Context.getCanonicalType(ToType);
1691     if (CanonFrom.getLocalUnqualifiedType()
1692                                        == CanonTo.getLocalUnqualifiedType() &&
1693         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1694       FromType = ToType;
1695       CanonFrom = CanonTo;
1696     }
1697   }
1698   SCS.setToType(2, FromType);
1699 
1700   // If we have not converted the argument type to the parameter type,
1701   // this is a bad conversion sequence.
1702   if (CanonFrom != CanonTo)
1703     return false;
1704 
1705   return true;
1706 }
1707 
1708 static bool
IsTransparentUnionStandardConversion(Sema & S,Expr * From,QualType & ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)1709 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1710                                      QualType &ToType,
1711                                      bool InOverloadResolution,
1712                                      StandardConversionSequence &SCS,
1713                                      bool CStyle) {
1714 
1715   const RecordType *UT = ToType->getAsUnionType();
1716   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1717     return false;
1718   // The field to initialize within the transparent union.
1719   RecordDecl *UD = UT->getDecl();
1720   // It's compatible if the expression matches any of the fields.
1721   for (const auto *it : UD->fields()) {
1722     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1723                              CStyle, /*ObjCWritebackConversion=*/false)) {
1724       ToType = it->getType();
1725       return true;
1726     }
1727   }
1728   return false;
1729 }
1730 
1731 /// IsIntegralPromotion - Determines whether the conversion from the
1732 /// expression From (whose potentially-adjusted type is FromType) to
1733 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1734 /// sets PromotedType to the promoted type.
IsIntegralPromotion(Expr * From,QualType FromType,QualType ToType)1735 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1736   const BuiltinType *To = ToType->getAs<BuiltinType>();
1737   // All integers are built-in.
1738   if (!To) {
1739     return false;
1740   }
1741 
1742   // An rvalue of type char, signed char, unsigned char, short int, or
1743   // unsigned short int can be converted to an rvalue of type int if
1744   // int can represent all the values of the source type; otherwise,
1745   // the source rvalue can be converted to an rvalue of type unsigned
1746   // int (C++ 4.5p1).
1747   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1748       !FromType->isEnumeralType()) {
1749     if (// We can promote any signed, promotable integer type to an int
1750         (FromType->isSignedIntegerType() ||
1751          // We can promote any unsigned integer type whose size is
1752          // less than int to an int.
1753          (!FromType->isSignedIntegerType() &&
1754           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1755       return To->getKind() == BuiltinType::Int;
1756     }
1757 
1758     return To->getKind() == BuiltinType::UInt;
1759   }
1760 
1761   // C++11 [conv.prom]p3:
1762   //   A prvalue of an unscoped enumeration type whose underlying type is not
1763   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1764   //   following types that can represent all the values of the enumeration
1765   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1766   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1767   //   long long int. If none of the types in that list can represent all the
1768   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1769   //   type can be converted to an rvalue a prvalue of the extended integer type
1770   //   with lowest integer conversion rank (4.13) greater than the rank of long
1771   //   long in which all the values of the enumeration can be represented. If
1772   //   there are two such extended types, the signed one is chosen.
1773   // C++11 [conv.prom]p4:
1774   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1775   //   can be converted to a prvalue of its underlying type. Moreover, if
1776   //   integral promotion can be applied to its underlying type, a prvalue of an
1777   //   unscoped enumeration type whose underlying type is fixed can also be
1778   //   converted to a prvalue of the promoted underlying type.
1779   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1780     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1781     // provided for a scoped enumeration.
1782     if (FromEnumType->getDecl()->isScoped())
1783       return false;
1784 
1785     // We can perform an integral promotion to the underlying type of the enum,
1786     // even if that's not the promoted type.
1787     if (FromEnumType->getDecl()->isFixed()) {
1788       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1789       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1790              IsIntegralPromotion(From, Underlying, ToType);
1791     }
1792 
1793     // We have already pre-calculated the promotion type, so this is trivial.
1794     if (ToType->isIntegerType() &&
1795         !RequireCompleteType(From->getLocStart(), FromType, 0))
1796       return Context.hasSameUnqualifiedType(ToType,
1797                                 FromEnumType->getDecl()->getPromotionType());
1798   }
1799 
1800   // C++0x [conv.prom]p2:
1801   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1802   //   to an rvalue a prvalue of the first of the following types that can
1803   //   represent all the values of its underlying type: int, unsigned int,
1804   //   long int, unsigned long int, long long int, or unsigned long long int.
1805   //   If none of the types in that list can represent all the values of its
1806   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1807   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1808   //   type.
1809   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1810       ToType->isIntegerType()) {
1811     // Determine whether the type we're converting from is signed or
1812     // unsigned.
1813     bool FromIsSigned = FromType->isSignedIntegerType();
1814     uint64_t FromSize = Context.getTypeSize(FromType);
1815 
1816     // The types we'll try to promote to, in the appropriate
1817     // order. Try each of these types.
1818     QualType PromoteTypes[6] = {
1819       Context.IntTy, Context.UnsignedIntTy,
1820       Context.LongTy, Context.UnsignedLongTy ,
1821       Context.LongLongTy, Context.UnsignedLongLongTy
1822     };
1823     for (int Idx = 0; Idx < 6; ++Idx) {
1824       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1825       if (FromSize < ToSize ||
1826           (FromSize == ToSize &&
1827            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1828         // We found the type that we can promote to. If this is the
1829         // type we wanted, we have a promotion. Otherwise, no
1830         // promotion.
1831         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1832       }
1833     }
1834   }
1835 
1836   // An rvalue for an integral bit-field (9.6) can be converted to an
1837   // rvalue of type int if int can represent all the values of the
1838   // bit-field; otherwise, it can be converted to unsigned int if
1839   // unsigned int can represent all the values of the bit-field. If
1840   // the bit-field is larger yet, no integral promotion applies to
1841   // it. If the bit-field has an enumerated type, it is treated as any
1842   // other value of that type for promotion purposes (C++ 4.5p3).
1843   // FIXME: We should delay checking of bit-fields until we actually perform the
1844   // conversion.
1845   using llvm::APSInt;
1846   if (From)
1847     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1848       APSInt BitWidth;
1849       if (FromType->isIntegralType(Context) &&
1850           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1851         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1852         ToSize = Context.getTypeSize(ToType);
1853 
1854         // Are we promoting to an int from a bitfield that fits in an int?
1855         if (BitWidth < ToSize ||
1856             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1857           return To->getKind() == BuiltinType::Int;
1858         }
1859 
1860         // Are we promoting to an unsigned int from an unsigned bitfield
1861         // that fits into an unsigned int?
1862         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1863           return To->getKind() == BuiltinType::UInt;
1864         }
1865 
1866         return false;
1867       }
1868     }
1869 
1870   // An rvalue of type bool can be converted to an rvalue of type int,
1871   // with false becoming zero and true becoming one (C++ 4.5p4).
1872   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1873     return true;
1874   }
1875 
1876   return false;
1877 }
1878 
1879 /// IsFloatingPointPromotion - Determines whether the conversion from
1880 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1881 /// returns true and sets PromotedType to the promoted type.
IsFloatingPointPromotion(QualType FromType,QualType ToType)1882 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1883   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1884     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1885       /// An rvalue of type float can be converted to an rvalue of type
1886       /// double. (C++ 4.6p1).
1887       if (FromBuiltin->getKind() == BuiltinType::Float &&
1888           ToBuiltin->getKind() == BuiltinType::Double)
1889         return true;
1890 
1891       // C99 6.3.1.5p1:
1892       //   When a float is promoted to double or long double, or a
1893       //   double is promoted to long double [...].
1894       if (!getLangOpts().CPlusPlus &&
1895           (FromBuiltin->getKind() == BuiltinType::Float ||
1896            FromBuiltin->getKind() == BuiltinType::Double) &&
1897           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1898         return true;
1899 
1900       // Half can be promoted to float.
1901       if (!getLangOpts().NativeHalfType &&
1902            FromBuiltin->getKind() == BuiltinType::Half &&
1903           ToBuiltin->getKind() == BuiltinType::Float)
1904         return true;
1905     }
1906 
1907   return false;
1908 }
1909 
1910 /// \brief Determine if a conversion is a complex promotion.
1911 ///
1912 /// A complex promotion is defined as a complex -> complex conversion
1913 /// where the conversion between the underlying real types is a
1914 /// floating-point or integral promotion.
IsComplexPromotion(QualType FromType,QualType ToType)1915 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1916   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1917   if (!FromComplex)
1918     return false;
1919 
1920   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1921   if (!ToComplex)
1922     return false;
1923 
1924   return IsFloatingPointPromotion(FromComplex->getElementType(),
1925                                   ToComplex->getElementType()) ||
1926     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
1927                         ToComplex->getElementType());
1928 }
1929 
1930 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1931 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1932 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1933 /// if non-empty, will be a pointer to ToType that may or may not have
1934 /// the right set of qualifiers on its pointee.
1935 ///
1936 static QualType
BuildSimilarlyQualifiedPointerType(const Type * FromPtr,QualType ToPointee,QualType ToType,ASTContext & Context,bool StripObjCLifetime=false)1937 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1938                                    QualType ToPointee, QualType ToType,
1939                                    ASTContext &Context,
1940                                    bool StripObjCLifetime = false) {
1941   assert((FromPtr->getTypeClass() == Type::Pointer ||
1942           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1943          "Invalid similarly-qualified pointer type");
1944 
1945   /// Conversions to 'id' subsume cv-qualifier conversions.
1946   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1947     return ToType.getUnqualifiedType();
1948 
1949   QualType CanonFromPointee
1950     = Context.getCanonicalType(FromPtr->getPointeeType());
1951   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1952   Qualifiers Quals = CanonFromPointee.getQualifiers();
1953 
1954   if (StripObjCLifetime)
1955     Quals.removeObjCLifetime();
1956 
1957   // Exact qualifier match -> return the pointer type we're converting to.
1958   if (CanonToPointee.getLocalQualifiers() == Quals) {
1959     // ToType is exactly what we need. Return it.
1960     if (!ToType.isNull())
1961       return ToType.getUnqualifiedType();
1962 
1963     // Build a pointer to ToPointee. It has the right qualifiers
1964     // already.
1965     if (isa<ObjCObjectPointerType>(ToType))
1966       return Context.getObjCObjectPointerType(ToPointee);
1967     return Context.getPointerType(ToPointee);
1968   }
1969 
1970   // Just build a canonical type that has the right qualifiers.
1971   QualType QualifiedCanonToPointee
1972     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1973 
1974   if (isa<ObjCObjectPointerType>(ToType))
1975     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1976   return Context.getPointerType(QualifiedCanonToPointee);
1977 }
1978 
isNullPointerConstantForConversion(Expr * Expr,bool InOverloadResolution,ASTContext & Context)1979 static bool isNullPointerConstantForConversion(Expr *Expr,
1980                                                bool InOverloadResolution,
1981                                                ASTContext &Context) {
1982   // Handle value-dependent integral null pointer constants correctly.
1983   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1984   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1985       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1986     return !InOverloadResolution;
1987 
1988   return Expr->isNullPointerConstant(Context,
1989                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1990                                         : Expr::NPC_ValueDependentIsNull);
1991 }
1992 
1993 /// IsPointerConversion - Determines whether the conversion of the
1994 /// expression From, which has the (possibly adjusted) type FromType,
1995 /// can be converted to the type ToType via a pointer conversion (C++
1996 /// 4.10). If so, returns true and places the converted type (that
1997 /// might differ from ToType in its cv-qualifiers at some level) into
1998 /// ConvertedType.
1999 ///
2000 /// This routine also supports conversions to and from block pointers
2001 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2002 /// pointers to interfaces. FIXME: Once we've determined the
2003 /// appropriate overloading rules for Objective-C, we may want to
2004 /// split the Objective-C checks into a different routine; however,
2005 /// GCC seems to consider all of these conversions to be pointer
2006 /// conversions, so for now they live here. IncompatibleObjC will be
2007 /// set if the conversion is an allowed Objective-C conversion that
2008 /// should result in a warning.
IsPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType,bool & IncompatibleObjC)2009 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2010                                bool InOverloadResolution,
2011                                QualType& ConvertedType,
2012                                bool &IncompatibleObjC) {
2013   IncompatibleObjC = false;
2014   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2015                               IncompatibleObjC))
2016     return true;
2017 
2018   // Conversion from a null pointer constant to any Objective-C pointer type.
2019   if (ToType->isObjCObjectPointerType() &&
2020       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2021     ConvertedType = ToType;
2022     return true;
2023   }
2024 
2025   // Blocks: Block pointers can be converted to void*.
2026   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2027       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2028     ConvertedType = ToType;
2029     return true;
2030   }
2031   // Blocks: A null pointer constant can be converted to a block
2032   // pointer type.
2033   if (ToType->isBlockPointerType() &&
2034       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2035     ConvertedType = ToType;
2036     return true;
2037   }
2038 
2039   // If the left-hand-side is nullptr_t, the right side can be a null
2040   // pointer constant.
2041   if (ToType->isNullPtrType() &&
2042       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2043     ConvertedType = ToType;
2044     return true;
2045   }
2046 
2047   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2048   if (!ToTypePtr)
2049     return false;
2050 
2051   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2052   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2053     ConvertedType = ToType;
2054     return true;
2055   }
2056 
2057   // Beyond this point, both types need to be pointers
2058   // , including objective-c pointers.
2059   QualType ToPointeeType = ToTypePtr->getPointeeType();
2060   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2061       !getLangOpts().ObjCAutoRefCount) {
2062     ConvertedType = BuildSimilarlyQualifiedPointerType(
2063                                       FromType->getAs<ObjCObjectPointerType>(),
2064                                                        ToPointeeType,
2065                                                        ToType, Context);
2066     return true;
2067   }
2068   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2069   if (!FromTypePtr)
2070     return false;
2071 
2072   QualType FromPointeeType = FromTypePtr->getPointeeType();
2073 
2074   // If the unqualified pointee types are the same, this can't be a
2075   // pointer conversion, so don't do all of the work below.
2076   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2077     return false;
2078 
2079   // An rvalue of type "pointer to cv T," where T is an object type,
2080   // can be converted to an rvalue of type "pointer to cv void" (C++
2081   // 4.10p2).
2082   if (FromPointeeType->isIncompleteOrObjectType() &&
2083       ToPointeeType->isVoidType()) {
2084     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2085                                                        ToPointeeType,
2086                                                        ToType, Context,
2087                                                    /*StripObjCLifetime=*/true);
2088     return true;
2089   }
2090 
2091   // MSVC allows implicit function to void* type conversion.
2092   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2093       ToPointeeType->isVoidType()) {
2094     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2095                                                        ToPointeeType,
2096                                                        ToType, Context);
2097     return true;
2098   }
2099 
2100   // When we're overloading in C, we allow a special kind of pointer
2101   // conversion for compatible-but-not-identical pointee types.
2102   if (!getLangOpts().CPlusPlus &&
2103       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2104     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2105                                                        ToPointeeType,
2106                                                        ToType, Context);
2107     return true;
2108   }
2109 
2110   // C++ [conv.ptr]p3:
2111   //
2112   //   An rvalue of type "pointer to cv D," where D is a class type,
2113   //   can be converted to an rvalue of type "pointer to cv B," where
2114   //   B is a base class (clause 10) of D. If B is an inaccessible
2115   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2116   //   necessitates this conversion is ill-formed. The result of the
2117   //   conversion is a pointer to the base class sub-object of the
2118   //   derived class object. The null pointer value is converted to
2119   //   the null pointer value of the destination type.
2120   //
2121   // Note that we do not check for ambiguity or inaccessibility
2122   // here. That is handled by CheckPointerConversion.
2123   if (getLangOpts().CPlusPlus &&
2124       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2125       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2126       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2127       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2128     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2129                                                        ToPointeeType,
2130                                                        ToType, Context);
2131     return true;
2132   }
2133 
2134   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2135       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2136     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2137                                                        ToPointeeType,
2138                                                        ToType, Context);
2139     return true;
2140   }
2141 
2142   return false;
2143 }
2144 
2145 /// \brief Adopt the given qualifiers for the given type.
AdoptQualifiers(ASTContext & Context,QualType T,Qualifiers Qs)2146 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2147   Qualifiers TQs = T.getQualifiers();
2148 
2149   // Check whether qualifiers already match.
2150   if (TQs == Qs)
2151     return T;
2152 
2153   if (Qs.compatiblyIncludes(TQs))
2154     return Context.getQualifiedType(T, Qs);
2155 
2156   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2157 }
2158 
2159 /// isObjCPointerConversion - Determines whether this is an
2160 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2161 /// with the same arguments and return values.
isObjCPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType,bool & IncompatibleObjC)2162 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2163                                    QualType& ConvertedType,
2164                                    bool &IncompatibleObjC) {
2165   if (!getLangOpts().ObjC1)
2166     return false;
2167 
2168   // The set of qualifiers on the type we're converting from.
2169   Qualifiers FromQualifiers = FromType.getQualifiers();
2170 
2171   // First, we handle all conversions on ObjC object pointer types.
2172   const ObjCObjectPointerType* ToObjCPtr =
2173     ToType->getAs<ObjCObjectPointerType>();
2174   const ObjCObjectPointerType *FromObjCPtr =
2175     FromType->getAs<ObjCObjectPointerType>();
2176 
2177   if (ToObjCPtr && FromObjCPtr) {
2178     // If the pointee types are the same (ignoring qualifications),
2179     // then this is not a pointer conversion.
2180     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2181                                        FromObjCPtr->getPointeeType()))
2182       return false;
2183 
2184     // Check for compatible
2185     // Objective C++: We're able to convert between "id" or "Class" and a
2186     // pointer to any interface (in both directions).
2187     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2188       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2189       return true;
2190     }
2191     // Conversions with Objective-C's id<...>.
2192     if ((FromObjCPtr->isObjCQualifiedIdType() ||
2193          ToObjCPtr->isObjCQualifiedIdType()) &&
2194         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2195                                                   /*compare=*/false)) {
2196       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2197       return true;
2198     }
2199     // Objective C++: We're able to convert from a pointer to an
2200     // interface to a pointer to a different interface.
2201     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2202       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2203       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2204       if (getLangOpts().CPlusPlus && LHS && RHS &&
2205           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2206                                                 FromObjCPtr->getPointeeType()))
2207         return false;
2208       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2209                                                    ToObjCPtr->getPointeeType(),
2210                                                          ToType, Context);
2211       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2212       return true;
2213     }
2214 
2215     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2216       // Okay: this is some kind of implicit downcast of Objective-C
2217       // interfaces, which is permitted. However, we're going to
2218       // complain about it.
2219       IncompatibleObjC = true;
2220       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2221                                                    ToObjCPtr->getPointeeType(),
2222                                                          ToType, Context);
2223       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2224       return true;
2225     }
2226   }
2227   // Beyond this point, both types need to be C pointers or block pointers.
2228   QualType ToPointeeType;
2229   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2230     ToPointeeType = ToCPtr->getPointeeType();
2231   else if (const BlockPointerType *ToBlockPtr =
2232             ToType->getAs<BlockPointerType>()) {
2233     // Objective C++: We're able to convert from a pointer to any object
2234     // to a block pointer type.
2235     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2236       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2237       return true;
2238     }
2239     ToPointeeType = ToBlockPtr->getPointeeType();
2240   }
2241   else if (FromType->getAs<BlockPointerType>() &&
2242            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2243     // Objective C++: We're able to convert from a block pointer type to a
2244     // pointer to any object.
2245     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2246     return true;
2247   }
2248   else
2249     return false;
2250 
2251   QualType FromPointeeType;
2252   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2253     FromPointeeType = FromCPtr->getPointeeType();
2254   else if (const BlockPointerType *FromBlockPtr =
2255            FromType->getAs<BlockPointerType>())
2256     FromPointeeType = FromBlockPtr->getPointeeType();
2257   else
2258     return false;
2259 
2260   // If we have pointers to pointers, recursively check whether this
2261   // is an Objective-C conversion.
2262   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2263       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2264                               IncompatibleObjC)) {
2265     // We always complain about this conversion.
2266     IncompatibleObjC = true;
2267     ConvertedType = Context.getPointerType(ConvertedType);
2268     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2269     return true;
2270   }
2271   // Allow conversion of pointee being objective-c pointer to another one;
2272   // as in I* to id.
2273   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2274       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2275       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2276                               IncompatibleObjC)) {
2277 
2278     ConvertedType = Context.getPointerType(ConvertedType);
2279     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2280     return true;
2281   }
2282 
2283   // If we have pointers to functions or blocks, check whether the only
2284   // differences in the argument and result types are in Objective-C
2285   // pointer conversions. If so, we permit the conversion (but
2286   // complain about it).
2287   const FunctionProtoType *FromFunctionType
2288     = FromPointeeType->getAs<FunctionProtoType>();
2289   const FunctionProtoType *ToFunctionType
2290     = ToPointeeType->getAs<FunctionProtoType>();
2291   if (FromFunctionType && ToFunctionType) {
2292     // If the function types are exactly the same, this isn't an
2293     // Objective-C pointer conversion.
2294     if (Context.getCanonicalType(FromPointeeType)
2295           == Context.getCanonicalType(ToPointeeType))
2296       return false;
2297 
2298     // Perform the quick checks that will tell us whether these
2299     // function types are obviously different.
2300     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2301         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2302         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2303       return false;
2304 
2305     bool HasObjCConversion = false;
2306     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2307         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2308       // Okay, the types match exactly. Nothing to do.
2309     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2310                                        ToFunctionType->getReturnType(),
2311                                        ConvertedType, IncompatibleObjC)) {
2312       // Okay, we have an Objective-C pointer conversion.
2313       HasObjCConversion = true;
2314     } else {
2315       // Function types are too different. Abort.
2316       return false;
2317     }
2318 
2319     // Check argument types.
2320     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2321          ArgIdx != NumArgs; ++ArgIdx) {
2322       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2323       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2324       if (Context.getCanonicalType(FromArgType)
2325             == Context.getCanonicalType(ToArgType)) {
2326         // Okay, the types match exactly. Nothing to do.
2327       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2328                                          ConvertedType, IncompatibleObjC)) {
2329         // Okay, we have an Objective-C pointer conversion.
2330         HasObjCConversion = true;
2331       } else {
2332         // Argument types are too different. Abort.
2333         return false;
2334       }
2335     }
2336 
2337     if (HasObjCConversion) {
2338       // We had an Objective-C conversion. Allow this pointer
2339       // conversion, but complain about it.
2340       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2341       IncompatibleObjC = true;
2342       return true;
2343     }
2344   }
2345 
2346   return false;
2347 }
2348 
2349 /// \brief Determine whether this is an Objective-C writeback conversion,
2350 /// used for parameter passing when performing automatic reference counting.
2351 ///
2352 /// \param FromType The type we're converting form.
2353 ///
2354 /// \param ToType The type we're converting to.
2355 ///
2356 /// \param ConvertedType The type that will be produced after applying
2357 /// this conversion.
isObjCWritebackConversion(QualType FromType,QualType ToType,QualType & ConvertedType)2358 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2359                                      QualType &ConvertedType) {
2360   if (!getLangOpts().ObjCAutoRefCount ||
2361       Context.hasSameUnqualifiedType(FromType, ToType))
2362     return false;
2363 
2364   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2365   QualType ToPointee;
2366   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2367     ToPointee = ToPointer->getPointeeType();
2368   else
2369     return false;
2370 
2371   Qualifiers ToQuals = ToPointee.getQualifiers();
2372   if (!ToPointee->isObjCLifetimeType() ||
2373       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2374       !ToQuals.withoutObjCLifetime().empty())
2375     return false;
2376 
2377   // Argument must be a pointer to __strong to __weak.
2378   QualType FromPointee;
2379   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2380     FromPointee = FromPointer->getPointeeType();
2381   else
2382     return false;
2383 
2384   Qualifiers FromQuals = FromPointee.getQualifiers();
2385   if (!FromPointee->isObjCLifetimeType() ||
2386       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2387        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2388     return false;
2389 
2390   // Make sure that we have compatible qualifiers.
2391   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2392   if (!ToQuals.compatiblyIncludes(FromQuals))
2393     return false;
2394 
2395   // Remove qualifiers from the pointee type we're converting from; they
2396   // aren't used in the compatibility check belong, and we'll be adding back
2397   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2398   FromPointee = FromPointee.getUnqualifiedType();
2399 
2400   // The unqualified form of the pointee types must be compatible.
2401   ToPointee = ToPointee.getUnqualifiedType();
2402   bool IncompatibleObjC;
2403   if (Context.typesAreCompatible(FromPointee, ToPointee))
2404     FromPointee = ToPointee;
2405   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2406                                     IncompatibleObjC))
2407     return false;
2408 
2409   /// \brief Construct the type we're converting to, which is a pointer to
2410   /// __autoreleasing pointee.
2411   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2412   ConvertedType = Context.getPointerType(FromPointee);
2413   return true;
2414 }
2415 
IsBlockPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType)2416 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2417                                     QualType& ConvertedType) {
2418   QualType ToPointeeType;
2419   if (const BlockPointerType *ToBlockPtr =
2420         ToType->getAs<BlockPointerType>())
2421     ToPointeeType = ToBlockPtr->getPointeeType();
2422   else
2423     return false;
2424 
2425   QualType FromPointeeType;
2426   if (const BlockPointerType *FromBlockPtr =
2427       FromType->getAs<BlockPointerType>())
2428     FromPointeeType = FromBlockPtr->getPointeeType();
2429   else
2430     return false;
2431   // We have pointer to blocks, check whether the only
2432   // differences in the argument and result types are in Objective-C
2433   // pointer conversions. If so, we permit the conversion.
2434 
2435   const FunctionProtoType *FromFunctionType
2436     = FromPointeeType->getAs<FunctionProtoType>();
2437   const FunctionProtoType *ToFunctionType
2438     = ToPointeeType->getAs<FunctionProtoType>();
2439 
2440   if (!FromFunctionType || !ToFunctionType)
2441     return false;
2442 
2443   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2444     return true;
2445 
2446   // Perform the quick checks that will tell us whether these
2447   // function types are obviously different.
2448   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2449       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2450     return false;
2451 
2452   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2453   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2454   if (FromEInfo != ToEInfo)
2455     return false;
2456 
2457   bool IncompatibleObjC = false;
2458   if (Context.hasSameType(FromFunctionType->getReturnType(),
2459                           ToFunctionType->getReturnType())) {
2460     // Okay, the types match exactly. Nothing to do.
2461   } else {
2462     QualType RHS = FromFunctionType->getReturnType();
2463     QualType LHS = ToFunctionType->getReturnType();
2464     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2465         !RHS.hasQualifiers() && LHS.hasQualifiers())
2466        LHS = LHS.getUnqualifiedType();
2467 
2468      if (Context.hasSameType(RHS,LHS)) {
2469        // OK exact match.
2470      } else if (isObjCPointerConversion(RHS, LHS,
2471                                         ConvertedType, IncompatibleObjC)) {
2472      if (IncompatibleObjC)
2473        return false;
2474      // Okay, we have an Objective-C pointer conversion.
2475      }
2476      else
2477        return false;
2478    }
2479 
2480    // Check argument types.
2481    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2482         ArgIdx != NumArgs; ++ArgIdx) {
2483      IncompatibleObjC = false;
2484      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2485      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2486      if (Context.hasSameType(FromArgType, ToArgType)) {
2487        // Okay, the types match exactly. Nothing to do.
2488      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2489                                         ConvertedType, IncompatibleObjC)) {
2490        if (IncompatibleObjC)
2491          return false;
2492        // Okay, we have an Objective-C pointer conversion.
2493      } else
2494        // Argument types are too different. Abort.
2495        return false;
2496    }
2497    if (LangOpts.ObjCAutoRefCount &&
2498        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2499                                                     ToFunctionType))
2500      return false;
2501 
2502    ConvertedType = ToType;
2503    return true;
2504 }
2505 
2506 enum {
2507   ft_default,
2508   ft_different_class,
2509   ft_parameter_arity,
2510   ft_parameter_mismatch,
2511   ft_return_type,
2512   ft_qualifer_mismatch
2513 };
2514 
2515 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2516 /// function types.  Catches different number of parameter, mismatch in
2517 /// parameter types, and different return types.
HandleFunctionTypeMismatch(PartialDiagnostic & PDiag,QualType FromType,QualType ToType)2518 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2519                                       QualType FromType, QualType ToType) {
2520   // If either type is not valid, include no extra info.
2521   if (FromType.isNull() || ToType.isNull()) {
2522     PDiag << ft_default;
2523     return;
2524   }
2525 
2526   // Get the function type from the pointers.
2527   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2528     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2529                             *ToMember = ToType->getAs<MemberPointerType>();
2530     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2531       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2532             << QualType(FromMember->getClass(), 0);
2533       return;
2534     }
2535     FromType = FromMember->getPointeeType();
2536     ToType = ToMember->getPointeeType();
2537   }
2538 
2539   if (FromType->isPointerType())
2540     FromType = FromType->getPointeeType();
2541   if (ToType->isPointerType())
2542     ToType = ToType->getPointeeType();
2543 
2544   // Remove references.
2545   FromType = FromType.getNonReferenceType();
2546   ToType = ToType.getNonReferenceType();
2547 
2548   // Don't print extra info for non-specialized template functions.
2549   if (FromType->isInstantiationDependentType() &&
2550       !FromType->getAs<TemplateSpecializationType>()) {
2551     PDiag << ft_default;
2552     return;
2553   }
2554 
2555   // No extra info for same types.
2556   if (Context.hasSameType(FromType, ToType)) {
2557     PDiag << ft_default;
2558     return;
2559   }
2560 
2561   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2562                           *ToFunction = ToType->getAs<FunctionProtoType>();
2563 
2564   // Both types need to be function types.
2565   if (!FromFunction || !ToFunction) {
2566     PDiag << ft_default;
2567     return;
2568   }
2569 
2570   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2571     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2572           << FromFunction->getNumParams();
2573     return;
2574   }
2575 
2576   // Handle different parameter types.
2577   unsigned ArgPos;
2578   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2579     PDiag << ft_parameter_mismatch << ArgPos + 1
2580           << ToFunction->getParamType(ArgPos)
2581           << FromFunction->getParamType(ArgPos);
2582     return;
2583   }
2584 
2585   // Handle different return type.
2586   if (!Context.hasSameType(FromFunction->getReturnType(),
2587                            ToFunction->getReturnType())) {
2588     PDiag << ft_return_type << ToFunction->getReturnType()
2589           << FromFunction->getReturnType();
2590     return;
2591   }
2592 
2593   unsigned FromQuals = FromFunction->getTypeQuals(),
2594            ToQuals = ToFunction->getTypeQuals();
2595   if (FromQuals != ToQuals) {
2596     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2597     return;
2598   }
2599 
2600   // Unable to find a difference, so add no extra info.
2601   PDiag << ft_default;
2602 }
2603 
2604 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2605 /// for equality of their argument types. Caller has already checked that
2606 /// they have same number of arguments.  If the parameters are different,
2607 /// ArgPos will have the parameter index of the first different parameter.
FunctionParamTypesAreEqual(const FunctionProtoType * OldType,const FunctionProtoType * NewType,unsigned * ArgPos)2608 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2609                                       const FunctionProtoType *NewType,
2610                                       unsigned *ArgPos) {
2611   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2612                                               N = NewType->param_type_begin(),
2613                                               E = OldType->param_type_end();
2614        O && (O != E); ++O, ++N) {
2615     if (!Context.hasSameType(O->getUnqualifiedType(),
2616                              N->getUnqualifiedType())) {
2617       if (ArgPos)
2618         *ArgPos = O - OldType->param_type_begin();
2619       return false;
2620     }
2621   }
2622   return true;
2623 }
2624 
2625 /// CheckPointerConversion - Check the pointer conversion from the
2626 /// expression From to the type ToType. This routine checks for
2627 /// ambiguous or inaccessible derived-to-base pointer
2628 /// conversions for which IsPointerConversion has already returned
2629 /// true. It returns true and produces a diagnostic if there was an
2630 /// error, or returns false otherwise.
CheckPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess)2631 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2632                                   CastKind &Kind,
2633                                   CXXCastPath& BasePath,
2634                                   bool IgnoreBaseAccess) {
2635   QualType FromType = From->getType();
2636   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2637 
2638   Kind = CK_BitCast;
2639 
2640   if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2641       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2642       Expr::NPCK_ZeroExpression) {
2643     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2644       DiagRuntimeBehavior(From->getExprLoc(), From,
2645                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2646                             << ToType << From->getSourceRange());
2647     else if (!isUnevaluatedContext())
2648       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2649         << ToType << From->getSourceRange();
2650   }
2651   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2652     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2653       QualType FromPointeeType = FromPtrType->getPointeeType(),
2654                ToPointeeType   = ToPtrType->getPointeeType();
2655 
2656       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2657           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2658         // We must have a derived-to-base conversion. Check an
2659         // ambiguous or inaccessible conversion.
2660         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2661                                          From->getExprLoc(),
2662                                          From->getSourceRange(), &BasePath,
2663                                          IgnoreBaseAccess))
2664           return true;
2665 
2666         // The conversion was successful.
2667         Kind = CK_DerivedToBase;
2668       }
2669     }
2670   } else if (const ObjCObjectPointerType *ToPtrType =
2671                ToType->getAs<ObjCObjectPointerType>()) {
2672     if (const ObjCObjectPointerType *FromPtrType =
2673           FromType->getAs<ObjCObjectPointerType>()) {
2674       // Objective-C++ conversions are always okay.
2675       // FIXME: We should have a different class of conversions for the
2676       // Objective-C++ implicit conversions.
2677       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2678         return false;
2679     } else if (FromType->isBlockPointerType()) {
2680       Kind = CK_BlockPointerToObjCPointerCast;
2681     } else {
2682       Kind = CK_CPointerToObjCPointerCast;
2683     }
2684   } else if (ToType->isBlockPointerType()) {
2685     if (!FromType->isBlockPointerType())
2686       Kind = CK_AnyPointerToBlockPointerCast;
2687   }
2688 
2689   // We shouldn't fall into this case unless it's valid for other
2690   // reasons.
2691   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2692     Kind = CK_NullToPointer;
2693 
2694   return false;
2695 }
2696 
2697 /// IsMemberPointerConversion - Determines whether the conversion of the
2698 /// expression From, which has the (possibly adjusted) type FromType, can be
2699 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2700 /// If so, returns true and places the converted type (that might differ from
2701 /// ToType in its cv-qualifiers at some level) into ConvertedType.
IsMemberPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType)2702 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2703                                      QualType ToType,
2704                                      bool InOverloadResolution,
2705                                      QualType &ConvertedType) {
2706   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2707   if (!ToTypePtr)
2708     return false;
2709 
2710   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2711   if (From->isNullPointerConstant(Context,
2712                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2713                                         : Expr::NPC_ValueDependentIsNull)) {
2714     ConvertedType = ToType;
2715     return true;
2716   }
2717 
2718   // Otherwise, both types have to be member pointers.
2719   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2720   if (!FromTypePtr)
2721     return false;
2722 
2723   // A pointer to member of B can be converted to a pointer to member of D,
2724   // where D is derived from B (C++ 4.11p2).
2725   QualType FromClass(FromTypePtr->getClass(), 0);
2726   QualType ToClass(ToTypePtr->getClass(), 0);
2727 
2728   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2729       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2730       IsDerivedFrom(ToClass, FromClass)) {
2731     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2732                                                  ToClass.getTypePtr());
2733     return true;
2734   }
2735 
2736   return false;
2737 }
2738 
2739 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2740 /// expression From to the type ToType. This routine checks for ambiguous or
2741 /// virtual or inaccessible base-to-derived member pointer conversions
2742 /// for which IsMemberPointerConversion has already returned true. It returns
2743 /// true and produces a diagnostic if there was an error, or returns false
2744 /// otherwise.
CheckMemberPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess)2745 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2746                                         CastKind &Kind,
2747                                         CXXCastPath &BasePath,
2748                                         bool IgnoreBaseAccess) {
2749   QualType FromType = From->getType();
2750   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2751   if (!FromPtrType) {
2752     // This must be a null pointer to member pointer conversion
2753     assert(From->isNullPointerConstant(Context,
2754                                        Expr::NPC_ValueDependentIsNull) &&
2755            "Expr must be null pointer constant!");
2756     Kind = CK_NullToMemberPointer;
2757     return false;
2758   }
2759 
2760   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2761   assert(ToPtrType && "No member pointer cast has a target type "
2762                       "that is not a member pointer.");
2763 
2764   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2765   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2766 
2767   // FIXME: What about dependent types?
2768   assert(FromClass->isRecordType() && "Pointer into non-class.");
2769   assert(ToClass->isRecordType() && "Pointer into non-class.");
2770 
2771   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2772                      /*DetectVirtual=*/true);
2773   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2774   assert(DerivationOkay &&
2775          "Should not have been called if derivation isn't OK.");
2776   (void)DerivationOkay;
2777 
2778   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2779                                   getUnqualifiedType())) {
2780     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2781     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2782       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2783     return true;
2784   }
2785 
2786   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2787     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2788       << FromClass << ToClass << QualType(VBase, 0)
2789       << From->getSourceRange();
2790     return true;
2791   }
2792 
2793   if (!IgnoreBaseAccess)
2794     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2795                          Paths.front(),
2796                          diag::err_downcast_from_inaccessible_base);
2797 
2798   // Must be a base to derived member conversion.
2799   BuildBasePathArray(Paths, BasePath);
2800   Kind = CK_BaseToDerivedMemberPointer;
2801   return false;
2802 }
2803 
2804 /// Determine whether the lifetime conversion between the two given
2805 /// qualifiers sets is nontrivial.
isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,Qualifiers ToQuals)2806 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2807                                                Qualifiers ToQuals) {
2808   // Converting anything to const __unsafe_unretained is trivial.
2809   if (ToQuals.hasConst() &&
2810       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2811     return false;
2812 
2813   return true;
2814 }
2815 
2816 /// IsQualificationConversion - Determines whether the conversion from
2817 /// an rvalue of type FromType to ToType is a qualification conversion
2818 /// (C++ 4.4).
2819 ///
2820 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2821 /// when the qualification conversion involves a change in the Objective-C
2822 /// object lifetime.
2823 bool
IsQualificationConversion(QualType FromType,QualType ToType,bool CStyle,bool & ObjCLifetimeConversion)2824 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2825                                 bool CStyle, bool &ObjCLifetimeConversion) {
2826   FromType = Context.getCanonicalType(FromType);
2827   ToType = Context.getCanonicalType(ToType);
2828   ObjCLifetimeConversion = false;
2829 
2830   // If FromType and ToType are the same type, this is not a
2831   // qualification conversion.
2832   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2833     return false;
2834 
2835   // (C++ 4.4p4):
2836   //   A conversion can add cv-qualifiers at levels other than the first
2837   //   in multi-level pointers, subject to the following rules: [...]
2838   bool PreviousToQualsIncludeConst = true;
2839   bool UnwrappedAnyPointer = false;
2840   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2841     // Within each iteration of the loop, we check the qualifiers to
2842     // determine if this still looks like a qualification
2843     // conversion. Then, if all is well, we unwrap one more level of
2844     // pointers or pointers-to-members and do it all again
2845     // until there are no more pointers or pointers-to-members left to
2846     // unwrap.
2847     UnwrappedAnyPointer = true;
2848 
2849     Qualifiers FromQuals = FromType.getQualifiers();
2850     Qualifiers ToQuals = ToType.getQualifiers();
2851 
2852     // Objective-C ARC:
2853     //   Check Objective-C lifetime conversions.
2854     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2855         UnwrappedAnyPointer) {
2856       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2857         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2858           ObjCLifetimeConversion = true;
2859         FromQuals.removeObjCLifetime();
2860         ToQuals.removeObjCLifetime();
2861       } else {
2862         // Qualification conversions cannot cast between different
2863         // Objective-C lifetime qualifiers.
2864         return false;
2865       }
2866     }
2867 
2868     // Allow addition/removal of GC attributes but not changing GC attributes.
2869     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2870         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2871       FromQuals.removeObjCGCAttr();
2872       ToQuals.removeObjCGCAttr();
2873     }
2874 
2875     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2876     //      2,j, and similarly for volatile.
2877     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2878       return false;
2879 
2880     //   -- if the cv 1,j and cv 2,j are different, then const is in
2881     //      every cv for 0 < k < j.
2882     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2883         && !PreviousToQualsIncludeConst)
2884       return false;
2885 
2886     // Keep track of whether all prior cv-qualifiers in the "to" type
2887     // include const.
2888     PreviousToQualsIncludeConst
2889       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2890   }
2891 
2892   // We are left with FromType and ToType being the pointee types
2893   // after unwrapping the original FromType and ToType the same number
2894   // of types. If we unwrapped any pointers, and if FromType and
2895   // ToType have the same unqualified type (since we checked
2896   // qualifiers above), then this is a qualification conversion.
2897   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2898 }
2899 
2900 /// \brief - Determine whether this is a conversion from a scalar type to an
2901 /// atomic type.
2902 ///
2903 /// If successful, updates \c SCS's second and third steps in the conversion
2904 /// sequence to finish the conversion.
tryAtomicConversion(Sema & S,Expr * From,QualType ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)2905 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2906                                 bool InOverloadResolution,
2907                                 StandardConversionSequence &SCS,
2908                                 bool CStyle) {
2909   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2910   if (!ToAtomic)
2911     return false;
2912 
2913   StandardConversionSequence InnerSCS;
2914   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2915                             InOverloadResolution, InnerSCS,
2916                             CStyle, /*AllowObjCWritebackConversion=*/false))
2917     return false;
2918 
2919   SCS.Second = InnerSCS.Second;
2920   SCS.setToType(1, InnerSCS.getToType(1));
2921   SCS.Third = InnerSCS.Third;
2922   SCS.QualificationIncludesObjCLifetime
2923     = InnerSCS.QualificationIncludesObjCLifetime;
2924   SCS.setToType(2, InnerSCS.getToType(2));
2925   return true;
2926 }
2927 
isFirstArgumentCompatibleWithType(ASTContext & Context,CXXConstructorDecl * Constructor,QualType Type)2928 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2929                                               CXXConstructorDecl *Constructor,
2930                                               QualType Type) {
2931   const FunctionProtoType *CtorType =
2932       Constructor->getType()->getAs<FunctionProtoType>();
2933   if (CtorType->getNumParams() > 0) {
2934     QualType FirstArg = CtorType->getParamType(0);
2935     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2936       return true;
2937   }
2938   return false;
2939 }
2940 
2941 static OverloadingResult
IsInitializerListConstructorConversion(Sema & S,Expr * From,QualType ToType,CXXRecordDecl * To,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,bool AllowExplicit)2942 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2943                                        CXXRecordDecl *To,
2944                                        UserDefinedConversionSequence &User,
2945                                        OverloadCandidateSet &CandidateSet,
2946                                        bool AllowExplicit) {
2947   DeclContext::lookup_result R = S.LookupConstructors(To);
2948   for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2949        Con != ConEnd; ++Con) {
2950     NamedDecl *D = *Con;
2951     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2952 
2953     // Find the constructor (which may be a template).
2954     CXXConstructorDecl *Constructor = nullptr;
2955     FunctionTemplateDecl *ConstructorTmpl
2956       = dyn_cast<FunctionTemplateDecl>(D);
2957     if (ConstructorTmpl)
2958       Constructor
2959         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2960     else
2961       Constructor = cast<CXXConstructorDecl>(D);
2962 
2963     bool Usable = !Constructor->isInvalidDecl() &&
2964                   S.isInitListConstructor(Constructor) &&
2965                   (AllowExplicit || !Constructor->isExplicit());
2966     if (Usable) {
2967       // If the first argument is (a reference to) the target type,
2968       // suppress conversions.
2969       bool SuppressUserConversions =
2970           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2971       if (ConstructorTmpl)
2972         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2973                                        /*ExplicitArgs*/ nullptr,
2974                                        From, CandidateSet,
2975                                        SuppressUserConversions);
2976       else
2977         S.AddOverloadCandidate(Constructor, FoundDecl,
2978                                From, CandidateSet,
2979                                SuppressUserConversions);
2980     }
2981   }
2982 
2983   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2984 
2985   OverloadCandidateSet::iterator Best;
2986   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2987   case OR_Success: {
2988     // Record the standard conversion we used and the conversion function.
2989     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2990     QualType ThisType = Constructor->getThisType(S.Context);
2991     // Initializer lists don't have conversions as such.
2992     User.Before.setAsIdentityConversion();
2993     User.HadMultipleCandidates = HadMultipleCandidates;
2994     User.ConversionFunction = Constructor;
2995     User.FoundConversionFunction = Best->FoundDecl;
2996     User.After.setAsIdentityConversion();
2997     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2998     User.After.setAllToTypes(ToType);
2999     return OR_Success;
3000   }
3001 
3002   case OR_No_Viable_Function:
3003     return OR_No_Viable_Function;
3004   case OR_Deleted:
3005     return OR_Deleted;
3006   case OR_Ambiguous:
3007     return OR_Ambiguous;
3008   }
3009 
3010   llvm_unreachable("Invalid OverloadResult!");
3011 }
3012 
3013 /// Determines whether there is a user-defined conversion sequence
3014 /// (C++ [over.ics.user]) that converts expression From to the type
3015 /// ToType. If such a conversion exists, User will contain the
3016 /// user-defined conversion sequence that performs such a conversion
3017 /// and this routine will return true. Otherwise, this routine returns
3018 /// false and User is unspecified.
3019 ///
3020 /// \param AllowExplicit  true if the conversion should consider C++0x
3021 /// "explicit" conversion functions as well as non-explicit conversion
3022 /// functions (C++0x [class.conv.fct]p2).
3023 ///
3024 /// \param AllowObjCConversionOnExplicit true if the conversion should
3025 /// allow an extra Objective-C pointer conversion on uses of explicit
3026 /// constructors. Requires \c AllowExplicit to also be set.
3027 static OverloadingResult
IsUserDefinedConversion(Sema & S,Expr * From,QualType ToType,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,bool AllowExplicit,bool AllowObjCConversionOnExplicit)3028 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3029                         UserDefinedConversionSequence &User,
3030                         OverloadCandidateSet &CandidateSet,
3031                         bool AllowExplicit,
3032                         bool AllowObjCConversionOnExplicit) {
3033   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3034 
3035   // Whether we will only visit constructors.
3036   bool ConstructorsOnly = false;
3037 
3038   // If the type we are conversion to is a class type, enumerate its
3039   // constructors.
3040   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3041     // C++ [over.match.ctor]p1:
3042     //   When objects of class type are direct-initialized (8.5), or
3043     //   copy-initialized from an expression of the same or a
3044     //   derived class type (8.5), overload resolution selects the
3045     //   constructor. [...] For copy-initialization, the candidate
3046     //   functions are all the converting constructors (12.3.1) of
3047     //   that class. The argument list is the expression-list within
3048     //   the parentheses of the initializer.
3049     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3050         (From->getType()->getAs<RecordType>() &&
3051          S.IsDerivedFrom(From->getType(), ToType)))
3052       ConstructorsOnly = true;
3053 
3054     S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3055     // RequireCompleteType may have returned true due to some invalid decl
3056     // during template instantiation, but ToType may be complete enough now
3057     // to try to recover.
3058     if (ToType->isIncompleteType()) {
3059       // We're not going to find any constructors.
3060     } else if (CXXRecordDecl *ToRecordDecl
3061                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3062 
3063       Expr **Args = &From;
3064       unsigned NumArgs = 1;
3065       bool ListInitializing = false;
3066       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3067         // But first, see if there is an init-list-constructor that will work.
3068         OverloadingResult Result = IsInitializerListConstructorConversion(
3069             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3070         if (Result != OR_No_Viable_Function)
3071           return Result;
3072         // Never mind.
3073         CandidateSet.clear();
3074 
3075         // If we're list-initializing, we pass the individual elements as
3076         // arguments, not the entire list.
3077         Args = InitList->getInits();
3078         NumArgs = InitList->getNumInits();
3079         ListInitializing = true;
3080       }
3081 
3082       DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3083       for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3084            Con != ConEnd; ++Con) {
3085         NamedDecl *D = *Con;
3086         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3087 
3088         // Find the constructor (which may be a template).
3089         CXXConstructorDecl *Constructor = nullptr;
3090         FunctionTemplateDecl *ConstructorTmpl
3091           = dyn_cast<FunctionTemplateDecl>(D);
3092         if (ConstructorTmpl)
3093           Constructor
3094             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3095         else
3096           Constructor = cast<CXXConstructorDecl>(D);
3097 
3098         bool Usable = !Constructor->isInvalidDecl();
3099         if (ListInitializing)
3100           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3101         else
3102           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3103         if (Usable) {
3104           bool SuppressUserConversions = !ConstructorsOnly;
3105           if (SuppressUserConversions && ListInitializing) {
3106             SuppressUserConversions = false;
3107             if (NumArgs == 1) {
3108               // If the first argument is (a reference to) the target type,
3109               // suppress conversions.
3110               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3111                                                 S.Context, Constructor, ToType);
3112             }
3113           }
3114           if (ConstructorTmpl)
3115             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3116                                            /*ExplicitArgs*/ nullptr,
3117                                            llvm::makeArrayRef(Args, NumArgs),
3118                                            CandidateSet, SuppressUserConversions);
3119           else
3120             // Allow one user-defined conversion when user specifies a
3121             // From->ToType conversion via an static cast (c-style, etc).
3122             S.AddOverloadCandidate(Constructor, FoundDecl,
3123                                    llvm::makeArrayRef(Args, NumArgs),
3124                                    CandidateSet, SuppressUserConversions);
3125         }
3126       }
3127     }
3128   }
3129 
3130   // Enumerate conversion functions, if we're allowed to.
3131   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3132   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3133     // No conversion functions from incomplete types.
3134   } else if (const RecordType *FromRecordType
3135                                    = From->getType()->getAs<RecordType>()) {
3136     if (CXXRecordDecl *FromRecordDecl
3137          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3138       // Add all of the conversion functions as candidates.
3139       std::pair<CXXRecordDecl::conversion_iterator,
3140                 CXXRecordDecl::conversion_iterator>
3141         Conversions = FromRecordDecl->getVisibleConversionFunctions();
3142       for (CXXRecordDecl::conversion_iterator
3143              I = Conversions.first, E = Conversions.second; I != E; ++I) {
3144         DeclAccessPair FoundDecl = I.getPair();
3145         NamedDecl *D = FoundDecl.getDecl();
3146         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3147         if (isa<UsingShadowDecl>(D))
3148           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3149 
3150         CXXConversionDecl *Conv;
3151         FunctionTemplateDecl *ConvTemplate;
3152         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3153           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3154         else
3155           Conv = cast<CXXConversionDecl>(D);
3156 
3157         if (AllowExplicit || !Conv->isExplicit()) {
3158           if (ConvTemplate)
3159             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3160                                              ActingContext, From, ToType,
3161                                              CandidateSet,
3162                                              AllowObjCConversionOnExplicit);
3163           else
3164             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3165                                      From, ToType, CandidateSet,
3166                                      AllowObjCConversionOnExplicit);
3167         }
3168       }
3169     }
3170   }
3171 
3172   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3173 
3174   OverloadCandidateSet::iterator Best;
3175   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3176   case OR_Success:
3177     // Record the standard conversion we used and the conversion function.
3178     if (CXXConstructorDecl *Constructor
3179           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3180       // C++ [over.ics.user]p1:
3181       //   If the user-defined conversion is specified by a
3182       //   constructor (12.3.1), the initial standard conversion
3183       //   sequence converts the source type to the type required by
3184       //   the argument of the constructor.
3185       //
3186       QualType ThisType = Constructor->getThisType(S.Context);
3187       if (isa<InitListExpr>(From)) {
3188         // Initializer lists don't have conversions as such.
3189         User.Before.setAsIdentityConversion();
3190       } else {
3191         if (Best->Conversions[0].isEllipsis())
3192           User.EllipsisConversion = true;
3193         else {
3194           User.Before = Best->Conversions[0].Standard;
3195           User.EllipsisConversion = false;
3196         }
3197       }
3198       User.HadMultipleCandidates = HadMultipleCandidates;
3199       User.ConversionFunction = Constructor;
3200       User.FoundConversionFunction = Best->FoundDecl;
3201       User.After.setAsIdentityConversion();
3202       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3203       User.After.setAllToTypes(ToType);
3204       return OR_Success;
3205     }
3206     if (CXXConversionDecl *Conversion
3207                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3208       // C++ [over.ics.user]p1:
3209       //
3210       //   [...] If the user-defined conversion is specified by a
3211       //   conversion function (12.3.2), the initial standard
3212       //   conversion sequence converts the source type to the
3213       //   implicit object parameter of the conversion function.
3214       User.Before = Best->Conversions[0].Standard;
3215       User.HadMultipleCandidates = HadMultipleCandidates;
3216       User.ConversionFunction = Conversion;
3217       User.FoundConversionFunction = Best->FoundDecl;
3218       User.EllipsisConversion = false;
3219 
3220       // C++ [over.ics.user]p2:
3221       //   The second standard conversion sequence converts the
3222       //   result of the user-defined conversion to the target type
3223       //   for the sequence. Since an implicit conversion sequence
3224       //   is an initialization, the special rules for
3225       //   initialization by user-defined conversion apply when
3226       //   selecting the best user-defined conversion for a
3227       //   user-defined conversion sequence (see 13.3.3 and
3228       //   13.3.3.1).
3229       User.After = Best->FinalConversion;
3230       return OR_Success;
3231     }
3232     llvm_unreachable("Not a constructor or conversion function?");
3233 
3234   case OR_No_Viable_Function:
3235     return OR_No_Viable_Function;
3236   case OR_Deleted:
3237     // No conversion here! We're done.
3238     return OR_Deleted;
3239 
3240   case OR_Ambiguous:
3241     return OR_Ambiguous;
3242   }
3243 
3244   llvm_unreachable("Invalid OverloadResult!");
3245 }
3246 
3247 bool
DiagnoseMultipleUserDefinedConversion(Expr * From,QualType ToType)3248 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3249   ImplicitConversionSequence ICS;
3250   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3251                                     OverloadCandidateSet::CSK_Normal);
3252   OverloadingResult OvResult =
3253     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3254                             CandidateSet, false, false);
3255   if (OvResult == OR_Ambiguous)
3256     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3257         << From->getType() << ToType << From->getSourceRange();
3258   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3259     if (!RequireCompleteType(From->getLocStart(), ToType,
3260                              diag::err_typecheck_nonviable_condition_incomplete,
3261                              From->getType(), From->getSourceRange()))
3262       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3263           << From->getType() << From->getSourceRange() << ToType;
3264   } else
3265     return false;
3266   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3267   return true;
3268 }
3269 
3270 /// \brief Compare the user-defined conversion functions or constructors
3271 /// of two user-defined conversion sequences to determine whether any ordering
3272 /// is possible.
3273 static ImplicitConversionSequence::CompareKind
compareConversionFunctions(Sema & S,FunctionDecl * Function1,FunctionDecl * Function2)3274 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3275                            FunctionDecl *Function2) {
3276   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3277     return ImplicitConversionSequence::Indistinguishable;
3278 
3279   // Objective-C++:
3280   //   If both conversion functions are implicitly-declared conversions from
3281   //   a lambda closure type to a function pointer and a block pointer,
3282   //   respectively, always prefer the conversion to a function pointer,
3283   //   because the function pointer is more lightweight and is more likely
3284   //   to keep code working.
3285   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3286   if (!Conv1)
3287     return ImplicitConversionSequence::Indistinguishable;
3288 
3289   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3290   if (!Conv2)
3291     return ImplicitConversionSequence::Indistinguishable;
3292 
3293   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3294     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3295     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3296     if (Block1 != Block2)
3297       return Block1 ? ImplicitConversionSequence::Worse
3298                     : ImplicitConversionSequence::Better;
3299   }
3300 
3301   return ImplicitConversionSequence::Indistinguishable;
3302 }
3303 
hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence & ICS)3304 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3305     const ImplicitConversionSequence &ICS) {
3306   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3307          (ICS.isUserDefined() &&
3308           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3309 }
3310 
3311 /// CompareImplicitConversionSequences - Compare two implicit
3312 /// conversion sequences to determine whether one is better than the
3313 /// other or if they are indistinguishable (C++ 13.3.3.2).
3314 static ImplicitConversionSequence::CompareKind
CompareImplicitConversionSequences(Sema & S,const ImplicitConversionSequence & ICS1,const ImplicitConversionSequence & ICS2)3315 CompareImplicitConversionSequences(Sema &S,
3316                                    const ImplicitConversionSequence& ICS1,
3317                                    const ImplicitConversionSequence& ICS2)
3318 {
3319   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3320   // conversion sequences (as defined in 13.3.3.1)
3321   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3322   //      conversion sequence than a user-defined conversion sequence or
3323   //      an ellipsis conversion sequence, and
3324   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3325   //      conversion sequence than an ellipsis conversion sequence
3326   //      (13.3.3.1.3).
3327   //
3328   // C++0x [over.best.ics]p10:
3329   //   For the purpose of ranking implicit conversion sequences as
3330   //   described in 13.3.3.2, the ambiguous conversion sequence is
3331   //   treated as a user-defined sequence that is indistinguishable
3332   //   from any other user-defined conversion sequence.
3333 
3334   // String literal to 'char *' conversion has been deprecated in C++03. It has
3335   // been removed from C++11. We still accept this conversion, if it happens at
3336   // the best viable function. Otherwise, this conversion is considered worse
3337   // than ellipsis conversion. Consider this as an extension; this is not in the
3338   // standard. For example:
3339   //
3340   // int &f(...);    // #1
3341   // void f(char*);  // #2
3342   // void g() { int &r = f("foo"); }
3343   //
3344   // In C++03, we pick #2 as the best viable function.
3345   // In C++11, we pick #1 as the best viable function, because ellipsis
3346   // conversion is better than string-literal to char* conversion (since there
3347   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3348   // convert arguments, #2 would be the best viable function in C++11.
3349   // If the best viable function has this conversion, a warning will be issued
3350   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3351 
3352   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3353       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3354       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3355     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3356                ? ImplicitConversionSequence::Worse
3357                : ImplicitConversionSequence::Better;
3358 
3359   if (ICS1.getKindRank() < ICS2.getKindRank())
3360     return ImplicitConversionSequence::Better;
3361   if (ICS2.getKindRank() < ICS1.getKindRank())
3362     return ImplicitConversionSequence::Worse;
3363 
3364   // The following checks require both conversion sequences to be of
3365   // the same kind.
3366   if (ICS1.getKind() != ICS2.getKind())
3367     return ImplicitConversionSequence::Indistinguishable;
3368 
3369   ImplicitConversionSequence::CompareKind Result =
3370       ImplicitConversionSequence::Indistinguishable;
3371 
3372   // Two implicit conversion sequences of the same form are
3373   // indistinguishable conversion sequences unless one of the
3374   // following rules apply: (C++ 13.3.3.2p3):
3375   if (ICS1.isStandard())
3376     Result = CompareStandardConversionSequences(S,
3377                                                 ICS1.Standard, ICS2.Standard);
3378   else if (ICS1.isUserDefined()) {
3379     // User-defined conversion sequence U1 is a better conversion
3380     // sequence than another user-defined conversion sequence U2 if
3381     // they contain the same user-defined conversion function or
3382     // constructor and if the second standard conversion sequence of
3383     // U1 is better than the second standard conversion sequence of
3384     // U2 (C++ 13.3.3.2p3).
3385     if (ICS1.UserDefined.ConversionFunction ==
3386           ICS2.UserDefined.ConversionFunction)
3387       Result = CompareStandardConversionSequences(S,
3388                                                   ICS1.UserDefined.After,
3389                                                   ICS2.UserDefined.After);
3390     else
3391       Result = compareConversionFunctions(S,
3392                                           ICS1.UserDefined.ConversionFunction,
3393                                           ICS2.UserDefined.ConversionFunction);
3394   }
3395 
3396   // List-initialization sequence L1 is a better conversion sequence than
3397   // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3398   // for some X and L2 does not.
3399   if (Result == ImplicitConversionSequence::Indistinguishable &&
3400       !ICS1.isBad()) {
3401     if (ICS1.isStdInitializerListElement() &&
3402         !ICS2.isStdInitializerListElement())
3403       return ImplicitConversionSequence::Better;
3404     if (!ICS1.isStdInitializerListElement() &&
3405         ICS2.isStdInitializerListElement())
3406       return ImplicitConversionSequence::Worse;
3407   }
3408 
3409   return Result;
3410 }
3411 
hasSimilarType(ASTContext & Context,QualType T1,QualType T2)3412 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3413   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3414     Qualifiers Quals;
3415     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3416     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3417   }
3418 
3419   return Context.hasSameUnqualifiedType(T1, T2);
3420 }
3421 
3422 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3423 // determine if one is a proper subset of the other.
3424 static ImplicitConversionSequence::CompareKind
compareStandardConversionSubsets(ASTContext & Context,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3425 compareStandardConversionSubsets(ASTContext &Context,
3426                                  const StandardConversionSequence& SCS1,
3427                                  const StandardConversionSequence& SCS2) {
3428   ImplicitConversionSequence::CompareKind Result
3429     = ImplicitConversionSequence::Indistinguishable;
3430 
3431   // the identity conversion sequence is considered to be a subsequence of
3432   // any non-identity conversion sequence
3433   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3434     return ImplicitConversionSequence::Better;
3435   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3436     return ImplicitConversionSequence::Worse;
3437 
3438   if (SCS1.Second != SCS2.Second) {
3439     if (SCS1.Second == ICK_Identity)
3440       Result = ImplicitConversionSequence::Better;
3441     else if (SCS2.Second == ICK_Identity)
3442       Result = ImplicitConversionSequence::Worse;
3443     else
3444       return ImplicitConversionSequence::Indistinguishable;
3445   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3446     return ImplicitConversionSequence::Indistinguishable;
3447 
3448   if (SCS1.Third == SCS2.Third) {
3449     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3450                              : ImplicitConversionSequence::Indistinguishable;
3451   }
3452 
3453   if (SCS1.Third == ICK_Identity)
3454     return Result == ImplicitConversionSequence::Worse
3455              ? ImplicitConversionSequence::Indistinguishable
3456              : ImplicitConversionSequence::Better;
3457 
3458   if (SCS2.Third == ICK_Identity)
3459     return Result == ImplicitConversionSequence::Better
3460              ? ImplicitConversionSequence::Indistinguishable
3461              : ImplicitConversionSequence::Worse;
3462 
3463   return ImplicitConversionSequence::Indistinguishable;
3464 }
3465 
3466 /// \brief Determine whether one of the given reference bindings is better
3467 /// than the other based on what kind of bindings they are.
isBetterReferenceBindingKind(const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3468 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3469                                        const StandardConversionSequence &SCS2) {
3470   // C++0x [over.ics.rank]p3b4:
3471   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3472   //      implicit object parameter of a non-static member function declared
3473   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3474   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3475   //      lvalue reference to a function lvalue and S2 binds an rvalue
3476   //      reference*.
3477   //
3478   // FIXME: Rvalue references. We're going rogue with the above edits,
3479   // because the semantics in the current C++0x working paper (N3225 at the
3480   // time of this writing) break the standard definition of std::forward
3481   // and std::reference_wrapper when dealing with references to functions.
3482   // Proposed wording changes submitted to CWG for consideration.
3483   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3484       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3485     return false;
3486 
3487   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3488           SCS2.IsLvalueReference) ||
3489          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3490           !SCS2.IsLvalueReference);
3491 }
3492 
3493 /// CompareStandardConversionSequences - Compare two standard
3494 /// conversion sequences to determine whether one is better than the
3495 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3496 static ImplicitConversionSequence::CompareKind
CompareStandardConversionSequences(Sema & S,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3497 CompareStandardConversionSequences(Sema &S,
3498                                    const StandardConversionSequence& SCS1,
3499                                    const StandardConversionSequence& SCS2)
3500 {
3501   // Standard conversion sequence S1 is a better conversion sequence
3502   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3503 
3504   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3505   //     sequences in the canonical form defined by 13.3.3.1.1,
3506   //     excluding any Lvalue Transformation; the identity conversion
3507   //     sequence is considered to be a subsequence of any
3508   //     non-identity conversion sequence) or, if not that,
3509   if (ImplicitConversionSequence::CompareKind CK
3510         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3511     return CK;
3512 
3513   //  -- the rank of S1 is better than the rank of S2 (by the rules
3514   //     defined below), or, if not that,
3515   ImplicitConversionRank Rank1 = SCS1.getRank();
3516   ImplicitConversionRank Rank2 = SCS2.getRank();
3517   if (Rank1 < Rank2)
3518     return ImplicitConversionSequence::Better;
3519   else if (Rank2 < Rank1)
3520     return ImplicitConversionSequence::Worse;
3521 
3522   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3523   // are indistinguishable unless one of the following rules
3524   // applies:
3525 
3526   //   A conversion that is not a conversion of a pointer, or
3527   //   pointer to member, to bool is better than another conversion
3528   //   that is such a conversion.
3529   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3530     return SCS2.isPointerConversionToBool()
3531              ? ImplicitConversionSequence::Better
3532              : ImplicitConversionSequence::Worse;
3533 
3534   // C++ [over.ics.rank]p4b2:
3535   //
3536   //   If class B is derived directly or indirectly from class A,
3537   //   conversion of B* to A* is better than conversion of B* to
3538   //   void*, and conversion of A* to void* is better than conversion
3539   //   of B* to void*.
3540   bool SCS1ConvertsToVoid
3541     = SCS1.isPointerConversionToVoidPointer(S.Context);
3542   bool SCS2ConvertsToVoid
3543     = SCS2.isPointerConversionToVoidPointer(S.Context);
3544   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3545     // Exactly one of the conversion sequences is a conversion to
3546     // a void pointer; it's the worse conversion.
3547     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3548                               : ImplicitConversionSequence::Worse;
3549   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3550     // Neither conversion sequence converts to a void pointer; compare
3551     // their derived-to-base conversions.
3552     if (ImplicitConversionSequence::CompareKind DerivedCK
3553           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3554       return DerivedCK;
3555   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3556              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3557     // Both conversion sequences are conversions to void
3558     // pointers. Compare the source types to determine if there's an
3559     // inheritance relationship in their sources.
3560     QualType FromType1 = SCS1.getFromType();
3561     QualType FromType2 = SCS2.getFromType();
3562 
3563     // Adjust the types we're converting from via the array-to-pointer
3564     // conversion, if we need to.
3565     if (SCS1.First == ICK_Array_To_Pointer)
3566       FromType1 = S.Context.getArrayDecayedType(FromType1);
3567     if (SCS2.First == ICK_Array_To_Pointer)
3568       FromType2 = S.Context.getArrayDecayedType(FromType2);
3569 
3570     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3571     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3572 
3573     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3574       return ImplicitConversionSequence::Better;
3575     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3576       return ImplicitConversionSequence::Worse;
3577 
3578     // Objective-C++: If one interface is more specific than the
3579     // other, it is the better one.
3580     const ObjCObjectPointerType* FromObjCPtr1
3581       = FromType1->getAs<ObjCObjectPointerType>();
3582     const ObjCObjectPointerType* FromObjCPtr2
3583       = FromType2->getAs<ObjCObjectPointerType>();
3584     if (FromObjCPtr1 && FromObjCPtr2) {
3585       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3586                                                           FromObjCPtr2);
3587       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3588                                                            FromObjCPtr1);
3589       if (AssignLeft != AssignRight) {
3590         return AssignLeft? ImplicitConversionSequence::Better
3591                          : ImplicitConversionSequence::Worse;
3592       }
3593     }
3594   }
3595 
3596   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3597   // bullet 3).
3598   if (ImplicitConversionSequence::CompareKind QualCK
3599         = CompareQualificationConversions(S, SCS1, SCS2))
3600     return QualCK;
3601 
3602   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3603     // Check for a better reference binding based on the kind of bindings.
3604     if (isBetterReferenceBindingKind(SCS1, SCS2))
3605       return ImplicitConversionSequence::Better;
3606     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3607       return ImplicitConversionSequence::Worse;
3608 
3609     // C++ [over.ics.rank]p3b4:
3610     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3611     //      which the references refer are the same type except for
3612     //      top-level cv-qualifiers, and the type to which the reference
3613     //      initialized by S2 refers is more cv-qualified than the type
3614     //      to which the reference initialized by S1 refers.
3615     QualType T1 = SCS1.getToType(2);
3616     QualType T2 = SCS2.getToType(2);
3617     T1 = S.Context.getCanonicalType(T1);
3618     T2 = S.Context.getCanonicalType(T2);
3619     Qualifiers T1Quals, T2Quals;
3620     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3621     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3622     if (UnqualT1 == UnqualT2) {
3623       // Objective-C++ ARC: If the references refer to objects with different
3624       // lifetimes, prefer bindings that don't change lifetime.
3625       if (SCS1.ObjCLifetimeConversionBinding !=
3626                                           SCS2.ObjCLifetimeConversionBinding) {
3627         return SCS1.ObjCLifetimeConversionBinding
3628                                            ? ImplicitConversionSequence::Worse
3629                                            : ImplicitConversionSequence::Better;
3630       }
3631 
3632       // If the type is an array type, promote the element qualifiers to the
3633       // type for comparison.
3634       if (isa<ArrayType>(T1) && T1Quals)
3635         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3636       if (isa<ArrayType>(T2) && T2Quals)
3637         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3638       if (T2.isMoreQualifiedThan(T1))
3639         return ImplicitConversionSequence::Better;
3640       else if (T1.isMoreQualifiedThan(T2))
3641         return ImplicitConversionSequence::Worse;
3642     }
3643   }
3644 
3645   // In Microsoft mode, prefer an integral conversion to a
3646   // floating-to-integral conversion if the integral conversion
3647   // is between types of the same size.
3648   // For example:
3649   // void f(float);
3650   // void f(int);
3651   // int main {
3652   //    long a;
3653   //    f(a);
3654   // }
3655   // Here, MSVC will call f(int) instead of generating a compile error
3656   // as clang will do in standard mode.
3657   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3658       SCS2.Second == ICK_Floating_Integral &&
3659       S.Context.getTypeSize(SCS1.getFromType()) ==
3660           S.Context.getTypeSize(SCS1.getToType(2)))
3661     return ImplicitConversionSequence::Better;
3662 
3663   return ImplicitConversionSequence::Indistinguishable;
3664 }
3665 
3666 /// CompareQualificationConversions - Compares two standard conversion
3667 /// sequences to determine whether they can be ranked based on their
3668 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3669 ImplicitConversionSequence::CompareKind
CompareQualificationConversions(Sema & S,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3670 CompareQualificationConversions(Sema &S,
3671                                 const StandardConversionSequence& SCS1,
3672                                 const StandardConversionSequence& SCS2) {
3673   // C++ 13.3.3.2p3:
3674   //  -- S1 and S2 differ only in their qualification conversion and
3675   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3676   //     cv-qualification signature of type T1 is a proper subset of
3677   //     the cv-qualification signature of type T2, and S1 is not the
3678   //     deprecated string literal array-to-pointer conversion (4.2).
3679   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3680       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3681     return ImplicitConversionSequence::Indistinguishable;
3682 
3683   // FIXME: the example in the standard doesn't use a qualification
3684   // conversion (!)
3685   QualType T1 = SCS1.getToType(2);
3686   QualType T2 = SCS2.getToType(2);
3687   T1 = S.Context.getCanonicalType(T1);
3688   T2 = S.Context.getCanonicalType(T2);
3689   Qualifiers T1Quals, T2Quals;
3690   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3691   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3692 
3693   // If the types are the same, we won't learn anything by unwrapped
3694   // them.
3695   if (UnqualT1 == UnqualT2)
3696     return ImplicitConversionSequence::Indistinguishable;
3697 
3698   // If the type is an array type, promote the element qualifiers to the type
3699   // for comparison.
3700   if (isa<ArrayType>(T1) && T1Quals)
3701     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3702   if (isa<ArrayType>(T2) && T2Quals)
3703     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3704 
3705   ImplicitConversionSequence::CompareKind Result
3706     = ImplicitConversionSequence::Indistinguishable;
3707 
3708   // Objective-C++ ARC:
3709   //   Prefer qualification conversions not involving a change in lifetime
3710   //   to qualification conversions that do not change lifetime.
3711   if (SCS1.QualificationIncludesObjCLifetime !=
3712                                       SCS2.QualificationIncludesObjCLifetime) {
3713     Result = SCS1.QualificationIncludesObjCLifetime
3714                ? ImplicitConversionSequence::Worse
3715                : ImplicitConversionSequence::Better;
3716   }
3717 
3718   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3719     // Within each iteration of the loop, we check the qualifiers to
3720     // determine if this still looks like a qualification
3721     // conversion. Then, if all is well, we unwrap one more level of
3722     // pointers or pointers-to-members and do it all again
3723     // until there are no more pointers or pointers-to-members left
3724     // to unwrap. This essentially mimics what
3725     // IsQualificationConversion does, but here we're checking for a
3726     // strict subset of qualifiers.
3727     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3728       // The qualifiers are the same, so this doesn't tell us anything
3729       // about how the sequences rank.
3730       ;
3731     else if (T2.isMoreQualifiedThan(T1)) {
3732       // T1 has fewer qualifiers, so it could be the better sequence.
3733       if (Result == ImplicitConversionSequence::Worse)
3734         // Neither has qualifiers that are a subset of the other's
3735         // qualifiers.
3736         return ImplicitConversionSequence::Indistinguishable;
3737 
3738       Result = ImplicitConversionSequence::Better;
3739     } else if (T1.isMoreQualifiedThan(T2)) {
3740       // T2 has fewer qualifiers, so it could be the better sequence.
3741       if (Result == ImplicitConversionSequence::Better)
3742         // Neither has qualifiers that are a subset of the other's
3743         // qualifiers.
3744         return ImplicitConversionSequence::Indistinguishable;
3745 
3746       Result = ImplicitConversionSequence::Worse;
3747     } else {
3748       // Qualifiers are disjoint.
3749       return ImplicitConversionSequence::Indistinguishable;
3750     }
3751 
3752     // If the types after this point are equivalent, we're done.
3753     if (S.Context.hasSameUnqualifiedType(T1, T2))
3754       break;
3755   }
3756 
3757   // Check that the winning standard conversion sequence isn't using
3758   // the deprecated string literal array to pointer conversion.
3759   switch (Result) {
3760   case ImplicitConversionSequence::Better:
3761     if (SCS1.DeprecatedStringLiteralToCharPtr)
3762       Result = ImplicitConversionSequence::Indistinguishable;
3763     break;
3764 
3765   case ImplicitConversionSequence::Indistinguishable:
3766     break;
3767 
3768   case ImplicitConversionSequence::Worse:
3769     if (SCS2.DeprecatedStringLiteralToCharPtr)
3770       Result = ImplicitConversionSequence::Indistinguishable;
3771     break;
3772   }
3773 
3774   return Result;
3775 }
3776 
3777 /// CompareDerivedToBaseConversions - Compares two standard conversion
3778 /// sequences to determine whether they can be ranked based on their
3779 /// various kinds of derived-to-base conversions (C++
3780 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3781 /// conversions between Objective-C interface types.
3782 ImplicitConversionSequence::CompareKind
CompareDerivedToBaseConversions(Sema & S,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3783 CompareDerivedToBaseConversions(Sema &S,
3784                                 const StandardConversionSequence& SCS1,
3785                                 const StandardConversionSequence& SCS2) {
3786   QualType FromType1 = SCS1.getFromType();
3787   QualType ToType1 = SCS1.getToType(1);
3788   QualType FromType2 = SCS2.getFromType();
3789   QualType ToType2 = SCS2.getToType(1);
3790 
3791   // Adjust the types we're converting from via the array-to-pointer
3792   // conversion, if we need to.
3793   if (SCS1.First == ICK_Array_To_Pointer)
3794     FromType1 = S.Context.getArrayDecayedType(FromType1);
3795   if (SCS2.First == ICK_Array_To_Pointer)
3796     FromType2 = S.Context.getArrayDecayedType(FromType2);
3797 
3798   // Canonicalize all of the types.
3799   FromType1 = S.Context.getCanonicalType(FromType1);
3800   ToType1 = S.Context.getCanonicalType(ToType1);
3801   FromType2 = S.Context.getCanonicalType(FromType2);
3802   ToType2 = S.Context.getCanonicalType(ToType2);
3803 
3804   // C++ [over.ics.rank]p4b3:
3805   //
3806   //   If class B is derived directly or indirectly from class A and
3807   //   class C is derived directly or indirectly from B,
3808   //
3809   // Compare based on pointer conversions.
3810   if (SCS1.Second == ICK_Pointer_Conversion &&
3811       SCS2.Second == ICK_Pointer_Conversion &&
3812       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3813       FromType1->isPointerType() && FromType2->isPointerType() &&
3814       ToType1->isPointerType() && ToType2->isPointerType()) {
3815     QualType FromPointee1
3816       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3817     QualType ToPointee1
3818       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3819     QualType FromPointee2
3820       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3821     QualType ToPointee2
3822       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3823 
3824     //   -- conversion of C* to B* is better than conversion of C* to A*,
3825     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3826       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3827         return ImplicitConversionSequence::Better;
3828       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3829         return ImplicitConversionSequence::Worse;
3830     }
3831 
3832     //   -- conversion of B* to A* is better than conversion of C* to A*,
3833     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3834       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3835         return ImplicitConversionSequence::Better;
3836       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3837         return ImplicitConversionSequence::Worse;
3838     }
3839   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3840              SCS2.Second == ICK_Pointer_Conversion) {
3841     const ObjCObjectPointerType *FromPtr1
3842       = FromType1->getAs<ObjCObjectPointerType>();
3843     const ObjCObjectPointerType *FromPtr2
3844       = FromType2->getAs<ObjCObjectPointerType>();
3845     const ObjCObjectPointerType *ToPtr1
3846       = ToType1->getAs<ObjCObjectPointerType>();
3847     const ObjCObjectPointerType *ToPtr2
3848       = ToType2->getAs<ObjCObjectPointerType>();
3849 
3850     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3851       // Apply the same conversion ranking rules for Objective-C pointer types
3852       // that we do for C++ pointers to class types. However, we employ the
3853       // Objective-C pseudo-subtyping relationship used for assignment of
3854       // Objective-C pointer types.
3855       bool FromAssignLeft
3856         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3857       bool FromAssignRight
3858         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3859       bool ToAssignLeft
3860         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3861       bool ToAssignRight
3862         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3863 
3864       // A conversion to an a non-id object pointer type or qualified 'id'
3865       // type is better than a conversion to 'id'.
3866       if (ToPtr1->isObjCIdType() &&
3867           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3868         return ImplicitConversionSequence::Worse;
3869       if (ToPtr2->isObjCIdType() &&
3870           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3871         return ImplicitConversionSequence::Better;
3872 
3873       // A conversion to a non-id object pointer type is better than a
3874       // conversion to a qualified 'id' type
3875       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3876         return ImplicitConversionSequence::Worse;
3877       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3878         return ImplicitConversionSequence::Better;
3879 
3880       // A conversion to an a non-Class object pointer type or qualified 'Class'
3881       // type is better than a conversion to 'Class'.
3882       if (ToPtr1->isObjCClassType() &&
3883           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3884         return ImplicitConversionSequence::Worse;
3885       if (ToPtr2->isObjCClassType() &&
3886           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3887         return ImplicitConversionSequence::Better;
3888 
3889       // A conversion to a non-Class object pointer type is better than a
3890       // conversion to a qualified 'Class' type.
3891       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3892         return ImplicitConversionSequence::Worse;
3893       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3894         return ImplicitConversionSequence::Better;
3895 
3896       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3897       if (S.Context.hasSameType(FromType1, FromType2) &&
3898           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3899           (ToAssignLeft != ToAssignRight))
3900         return ToAssignLeft? ImplicitConversionSequence::Worse
3901                            : ImplicitConversionSequence::Better;
3902 
3903       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3904       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3905           (FromAssignLeft != FromAssignRight))
3906         return FromAssignLeft? ImplicitConversionSequence::Better
3907         : ImplicitConversionSequence::Worse;
3908     }
3909   }
3910 
3911   // Ranking of member-pointer types.
3912   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3913       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3914       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3915     const MemberPointerType * FromMemPointer1 =
3916                                         FromType1->getAs<MemberPointerType>();
3917     const MemberPointerType * ToMemPointer1 =
3918                                           ToType1->getAs<MemberPointerType>();
3919     const MemberPointerType * FromMemPointer2 =
3920                                           FromType2->getAs<MemberPointerType>();
3921     const MemberPointerType * ToMemPointer2 =
3922                                           ToType2->getAs<MemberPointerType>();
3923     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3924     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3925     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3926     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3927     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3928     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3929     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3930     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3931     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3932     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3933       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3934         return ImplicitConversionSequence::Worse;
3935       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3936         return ImplicitConversionSequence::Better;
3937     }
3938     // conversion of B::* to C::* is better than conversion of A::* to C::*
3939     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3940       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3941         return ImplicitConversionSequence::Better;
3942       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3943         return ImplicitConversionSequence::Worse;
3944     }
3945   }
3946 
3947   if (SCS1.Second == ICK_Derived_To_Base) {
3948     //   -- conversion of C to B is better than conversion of C to A,
3949     //   -- binding of an expression of type C to a reference of type
3950     //      B& is better than binding an expression of type C to a
3951     //      reference of type A&,
3952     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3953         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3954       if (S.IsDerivedFrom(ToType1, ToType2))
3955         return ImplicitConversionSequence::Better;
3956       else if (S.IsDerivedFrom(ToType2, ToType1))
3957         return ImplicitConversionSequence::Worse;
3958     }
3959 
3960     //   -- conversion of B to A is better than conversion of C to A.
3961     //   -- binding of an expression of type B to a reference of type
3962     //      A& is better than binding an expression of type C to a
3963     //      reference of type A&,
3964     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3965         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3966       if (S.IsDerivedFrom(FromType2, FromType1))
3967         return ImplicitConversionSequence::Better;
3968       else if (S.IsDerivedFrom(FromType1, FromType2))
3969         return ImplicitConversionSequence::Worse;
3970     }
3971   }
3972 
3973   return ImplicitConversionSequence::Indistinguishable;
3974 }
3975 
3976 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
3977 /// C++ class.
isTypeValid(QualType T)3978 static bool isTypeValid(QualType T) {
3979   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3980     return !Record->isInvalidDecl();
3981 
3982   return true;
3983 }
3984 
3985 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3986 /// determine whether they are reference-related,
3987 /// reference-compatible, reference-compatible with added
3988 /// qualification, or incompatible, for use in C++ initialization by
3989 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3990 /// type, and the first type (T1) is the pointee type of the reference
3991 /// type being initialized.
3992 Sema::ReferenceCompareResult
CompareReferenceRelationship(SourceLocation Loc,QualType OrigT1,QualType OrigT2,bool & DerivedToBase,bool & ObjCConversion,bool & ObjCLifetimeConversion)3993 Sema::CompareReferenceRelationship(SourceLocation Loc,
3994                                    QualType OrigT1, QualType OrigT2,
3995                                    bool &DerivedToBase,
3996                                    bool &ObjCConversion,
3997                                    bool &ObjCLifetimeConversion) {
3998   assert(!OrigT1->isReferenceType() &&
3999     "T1 must be the pointee type of the reference type");
4000   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4001 
4002   QualType T1 = Context.getCanonicalType(OrigT1);
4003   QualType T2 = Context.getCanonicalType(OrigT2);
4004   Qualifiers T1Quals, T2Quals;
4005   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4006   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4007 
4008   // C++ [dcl.init.ref]p4:
4009   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4010   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4011   //   T1 is a base class of T2.
4012   DerivedToBase = false;
4013   ObjCConversion = false;
4014   ObjCLifetimeConversion = false;
4015   if (UnqualT1 == UnqualT2) {
4016     // Nothing to do.
4017   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
4018              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4019              IsDerivedFrom(UnqualT2, UnqualT1))
4020     DerivedToBase = true;
4021   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4022            UnqualT2->isObjCObjectOrInterfaceType() &&
4023            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4024     ObjCConversion = true;
4025   else
4026     return Ref_Incompatible;
4027 
4028   // At this point, we know that T1 and T2 are reference-related (at
4029   // least).
4030 
4031   // If the type is an array type, promote the element qualifiers to the type
4032   // for comparison.
4033   if (isa<ArrayType>(T1) && T1Quals)
4034     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4035   if (isa<ArrayType>(T2) && T2Quals)
4036     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4037 
4038   // C++ [dcl.init.ref]p4:
4039   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4040   //   reference-related to T2 and cv1 is the same cv-qualification
4041   //   as, or greater cv-qualification than, cv2. For purposes of
4042   //   overload resolution, cases for which cv1 is greater
4043   //   cv-qualification than cv2 are identified as
4044   //   reference-compatible with added qualification (see 13.3.3.2).
4045   //
4046   // Note that we also require equivalence of Objective-C GC and address-space
4047   // qualifiers when performing these computations, so that e.g., an int in
4048   // address space 1 is not reference-compatible with an int in address
4049   // space 2.
4050   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4051       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4052     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4053       ObjCLifetimeConversion = true;
4054 
4055     T1Quals.removeObjCLifetime();
4056     T2Quals.removeObjCLifetime();
4057   }
4058 
4059   if (T1Quals == T2Quals)
4060     return Ref_Compatible;
4061   else if (T1Quals.compatiblyIncludes(T2Quals))
4062     return Ref_Compatible_With_Added_Qualification;
4063   else
4064     return Ref_Related;
4065 }
4066 
4067 /// \brief Look for a user-defined conversion to an value reference-compatible
4068 ///        with DeclType. Return true if something definite is found.
4069 static bool
FindConversionForRefInit(Sema & S,ImplicitConversionSequence & ICS,QualType DeclType,SourceLocation DeclLoc,Expr * Init,QualType T2,bool AllowRvalues,bool AllowExplicit)4070 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4071                          QualType DeclType, SourceLocation DeclLoc,
4072                          Expr *Init, QualType T2, bool AllowRvalues,
4073                          bool AllowExplicit) {
4074   assert(T2->isRecordType() && "Can only find conversions of record types.");
4075   CXXRecordDecl *T2RecordDecl
4076     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4077 
4078   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4079   std::pair<CXXRecordDecl::conversion_iterator,
4080             CXXRecordDecl::conversion_iterator>
4081     Conversions = T2RecordDecl->getVisibleConversionFunctions();
4082   for (CXXRecordDecl::conversion_iterator
4083          I = Conversions.first, E = Conversions.second; I != E; ++I) {
4084     NamedDecl *D = *I;
4085     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4086     if (isa<UsingShadowDecl>(D))
4087       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4088 
4089     FunctionTemplateDecl *ConvTemplate
4090       = dyn_cast<FunctionTemplateDecl>(D);
4091     CXXConversionDecl *Conv;
4092     if (ConvTemplate)
4093       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4094     else
4095       Conv = cast<CXXConversionDecl>(D);
4096 
4097     // If this is an explicit conversion, and we're not allowed to consider
4098     // explicit conversions, skip it.
4099     if (!AllowExplicit && Conv->isExplicit())
4100       continue;
4101 
4102     if (AllowRvalues) {
4103       bool DerivedToBase = false;
4104       bool ObjCConversion = false;
4105       bool ObjCLifetimeConversion = false;
4106 
4107       // If we are initializing an rvalue reference, don't permit conversion
4108       // functions that return lvalues.
4109       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4110         const ReferenceType *RefType
4111           = Conv->getConversionType()->getAs<LValueReferenceType>();
4112         if (RefType && !RefType->getPointeeType()->isFunctionType())
4113           continue;
4114       }
4115 
4116       if (!ConvTemplate &&
4117           S.CompareReferenceRelationship(
4118             DeclLoc,
4119             Conv->getConversionType().getNonReferenceType()
4120               .getUnqualifiedType(),
4121             DeclType.getNonReferenceType().getUnqualifiedType(),
4122             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4123           Sema::Ref_Incompatible)
4124         continue;
4125     } else {
4126       // If the conversion function doesn't return a reference type,
4127       // it can't be considered for this conversion. An rvalue reference
4128       // is only acceptable if its referencee is a function type.
4129 
4130       const ReferenceType *RefType =
4131         Conv->getConversionType()->getAs<ReferenceType>();
4132       if (!RefType ||
4133           (!RefType->isLValueReferenceType() &&
4134            !RefType->getPointeeType()->isFunctionType()))
4135         continue;
4136     }
4137 
4138     if (ConvTemplate)
4139       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4140                                        Init, DeclType, CandidateSet,
4141                                        /*AllowObjCConversionOnExplicit=*/false);
4142     else
4143       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4144                                DeclType, CandidateSet,
4145                                /*AllowObjCConversionOnExplicit=*/false);
4146   }
4147 
4148   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4149 
4150   OverloadCandidateSet::iterator Best;
4151   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4152   case OR_Success:
4153     // C++ [over.ics.ref]p1:
4154     //
4155     //   [...] If the parameter binds directly to the result of
4156     //   applying a conversion function to the argument
4157     //   expression, the implicit conversion sequence is a
4158     //   user-defined conversion sequence (13.3.3.1.2), with the
4159     //   second standard conversion sequence either an identity
4160     //   conversion or, if the conversion function returns an
4161     //   entity of a type that is a derived class of the parameter
4162     //   type, a derived-to-base Conversion.
4163     if (!Best->FinalConversion.DirectBinding)
4164       return false;
4165 
4166     ICS.setUserDefined();
4167     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4168     ICS.UserDefined.After = Best->FinalConversion;
4169     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4170     ICS.UserDefined.ConversionFunction = Best->Function;
4171     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4172     ICS.UserDefined.EllipsisConversion = false;
4173     assert(ICS.UserDefined.After.ReferenceBinding &&
4174            ICS.UserDefined.After.DirectBinding &&
4175            "Expected a direct reference binding!");
4176     return true;
4177 
4178   case OR_Ambiguous:
4179     ICS.setAmbiguous();
4180     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4181          Cand != CandidateSet.end(); ++Cand)
4182       if (Cand->Viable)
4183         ICS.Ambiguous.addConversion(Cand->Function);
4184     return true;
4185 
4186   case OR_No_Viable_Function:
4187   case OR_Deleted:
4188     // There was no suitable conversion, or we found a deleted
4189     // conversion; continue with other checks.
4190     return false;
4191   }
4192 
4193   llvm_unreachable("Invalid OverloadResult!");
4194 }
4195 
4196 /// \brief Compute an implicit conversion sequence for reference
4197 /// initialization.
4198 static ImplicitConversionSequence
TryReferenceInit(Sema & S,Expr * Init,QualType DeclType,SourceLocation DeclLoc,bool SuppressUserConversions,bool AllowExplicit)4199 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4200                  SourceLocation DeclLoc,
4201                  bool SuppressUserConversions,
4202                  bool AllowExplicit) {
4203   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4204 
4205   // Most paths end in a failed conversion.
4206   ImplicitConversionSequence ICS;
4207   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4208 
4209   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4210   QualType T2 = Init->getType();
4211 
4212   // If the initializer is the address of an overloaded function, try
4213   // to resolve the overloaded function. If all goes well, T2 is the
4214   // type of the resulting function.
4215   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4216     DeclAccessPair Found;
4217     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4218                                                                 false, Found))
4219       T2 = Fn->getType();
4220   }
4221 
4222   // Compute some basic properties of the types and the initializer.
4223   bool isRValRef = DeclType->isRValueReferenceType();
4224   bool DerivedToBase = false;
4225   bool ObjCConversion = false;
4226   bool ObjCLifetimeConversion = false;
4227   Expr::Classification InitCategory = Init->Classify(S.Context);
4228   Sema::ReferenceCompareResult RefRelationship
4229     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4230                                      ObjCConversion, ObjCLifetimeConversion);
4231 
4232 
4233   // C++0x [dcl.init.ref]p5:
4234   //   A reference to type "cv1 T1" is initialized by an expression
4235   //   of type "cv2 T2" as follows:
4236 
4237   //     -- If reference is an lvalue reference and the initializer expression
4238   if (!isRValRef) {
4239     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4240     //        reference-compatible with "cv2 T2," or
4241     //
4242     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4243     if (InitCategory.isLValue() &&
4244         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4245       // C++ [over.ics.ref]p1:
4246       //   When a parameter of reference type binds directly (8.5.3)
4247       //   to an argument expression, the implicit conversion sequence
4248       //   is the identity conversion, unless the argument expression
4249       //   has a type that is a derived class of the parameter type,
4250       //   in which case the implicit conversion sequence is a
4251       //   derived-to-base Conversion (13.3.3.1).
4252       ICS.setStandard();
4253       ICS.Standard.First = ICK_Identity;
4254       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4255                          : ObjCConversion? ICK_Compatible_Conversion
4256                          : ICK_Identity;
4257       ICS.Standard.Third = ICK_Identity;
4258       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4259       ICS.Standard.setToType(0, T2);
4260       ICS.Standard.setToType(1, T1);
4261       ICS.Standard.setToType(2, T1);
4262       ICS.Standard.ReferenceBinding = true;
4263       ICS.Standard.DirectBinding = true;
4264       ICS.Standard.IsLvalueReference = !isRValRef;
4265       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4266       ICS.Standard.BindsToRvalue = false;
4267       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4268       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4269       ICS.Standard.CopyConstructor = nullptr;
4270       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4271 
4272       // Nothing more to do: the inaccessibility/ambiguity check for
4273       // derived-to-base conversions is suppressed when we're
4274       // computing the implicit conversion sequence (C++
4275       // [over.best.ics]p2).
4276       return ICS;
4277     }
4278 
4279     //       -- has a class type (i.e., T2 is a class type), where T1 is
4280     //          not reference-related to T2, and can be implicitly
4281     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4282     //          is reference-compatible with "cv3 T3" 92) (this
4283     //          conversion is selected by enumerating the applicable
4284     //          conversion functions (13.3.1.6) and choosing the best
4285     //          one through overload resolution (13.3)),
4286     if (!SuppressUserConversions && T2->isRecordType() &&
4287         !S.RequireCompleteType(DeclLoc, T2, 0) &&
4288         RefRelationship == Sema::Ref_Incompatible) {
4289       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4290                                    Init, T2, /*AllowRvalues=*/false,
4291                                    AllowExplicit))
4292         return ICS;
4293     }
4294   }
4295 
4296   //     -- Otherwise, the reference shall be an lvalue reference to a
4297   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4298   //        shall be an rvalue reference.
4299   //
4300   // We actually handle one oddity of C++ [over.ics.ref] at this
4301   // point, which is that, due to p2 (which short-circuits reference
4302   // binding by only attempting a simple conversion for non-direct
4303   // bindings) and p3's strange wording, we allow a const volatile
4304   // reference to bind to an rvalue. Hence the check for the presence
4305   // of "const" rather than checking for "const" being the only
4306   // qualifier.
4307   // This is also the point where rvalue references and lvalue inits no longer
4308   // go together.
4309   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4310     return ICS;
4311 
4312   //       -- If the initializer expression
4313   //
4314   //            -- is an xvalue, class prvalue, array prvalue or function
4315   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4316   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4317       (InitCategory.isXValue() ||
4318       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4319       (InitCategory.isLValue() && T2->isFunctionType()))) {
4320     ICS.setStandard();
4321     ICS.Standard.First = ICK_Identity;
4322     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4323                       : ObjCConversion? ICK_Compatible_Conversion
4324                       : ICK_Identity;
4325     ICS.Standard.Third = ICK_Identity;
4326     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4327     ICS.Standard.setToType(0, T2);
4328     ICS.Standard.setToType(1, T1);
4329     ICS.Standard.setToType(2, T1);
4330     ICS.Standard.ReferenceBinding = true;
4331     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4332     // binding unless we're binding to a class prvalue.
4333     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4334     // allow the use of rvalue references in C++98/03 for the benefit of
4335     // standard library implementors; therefore, we need the xvalue check here.
4336     ICS.Standard.DirectBinding =
4337       S.getLangOpts().CPlusPlus11 ||
4338       (InitCategory.isPRValue() && !T2->isRecordType());
4339     ICS.Standard.IsLvalueReference = !isRValRef;
4340     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4341     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4342     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4343     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4344     ICS.Standard.CopyConstructor = nullptr;
4345     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4346     return ICS;
4347   }
4348 
4349   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4350   //               reference-related to T2, and can be implicitly converted to
4351   //               an xvalue, class prvalue, or function lvalue of type
4352   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4353   //               "cv3 T3",
4354   //
4355   //          then the reference is bound to the value of the initializer
4356   //          expression in the first case and to the result of the conversion
4357   //          in the second case (or, in either case, to an appropriate base
4358   //          class subobject).
4359   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4360       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4361       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4362                                Init, T2, /*AllowRvalues=*/true,
4363                                AllowExplicit)) {
4364     // In the second case, if the reference is an rvalue reference
4365     // and the second standard conversion sequence of the
4366     // user-defined conversion sequence includes an lvalue-to-rvalue
4367     // conversion, the program is ill-formed.
4368     if (ICS.isUserDefined() && isRValRef &&
4369         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4370       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4371 
4372     return ICS;
4373   }
4374 
4375   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4376   //          initialized from the initializer expression using the
4377   //          rules for a non-reference copy initialization (8.5). The
4378   //          reference is then bound to the temporary. If T1 is
4379   //          reference-related to T2, cv1 must be the same
4380   //          cv-qualification as, or greater cv-qualification than,
4381   //          cv2; otherwise, the program is ill-formed.
4382   if (RefRelationship == Sema::Ref_Related) {
4383     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4384     // we would be reference-compatible or reference-compatible with
4385     // added qualification. But that wasn't the case, so the reference
4386     // initialization fails.
4387     //
4388     // Note that we only want to check address spaces and cvr-qualifiers here.
4389     // ObjC GC and lifetime qualifiers aren't important.
4390     Qualifiers T1Quals = T1.getQualifiers();
4391     Qualifiers T2Quals = T2.getQualifiers();
4392     T1Quals.removeObjCGCAttr();
4393     T1Quals.removeObjCLifetime();
4394     T2Quals.removeObjCGCAttr();
4395     T2Quals.removeObjCLifetime();
4396     if (!T1Quals.compatiblyIncludes(T2Quals))
4397       return ICS;
4398   }
4399 
4400   // If at least one of the types is a class type, the types are not
4401   // related, and we aren't allowed any user conversions, the
4402   // reference binding fails. This case is important for breaking
4403   // recursion, since TryImplicitConversion below will attempt to
4404   // create a temporary through the use of a copy constructor.
4405   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4406       (T1->isRecordType() || T2->isRecordType()))
4407     return ICS;
4408 
4409   // If T1 is reference-related to T2 and the reference is an rvalue
4410   // reference, the initializer expression shall not be an lvalue.
4411   if (RefRelationship >= Sema::Ref_Related &&
4412       isRValRef && Init->Classify(S.Context).isLValue())
4413     return ICS;
4414 
4415   // C++ [over.ics.ref]p2:
4416   //   When a parameter of reference type is not bound directly to
4417   //   an argument expression, the conversion sequence is the one
4418   //   required to convert the argument expression to the
4419   //   underlying type of the reference according to
4420   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4421   //   to copy-initializing a temporary of the underlying type with
4422   //   the argument expression. Any difference in top-level
4423   //   cv-qualification is subsumed by the initialization itself
4424   //   and does not constitute a conversion.
4425   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4426                               /*AllowExplicit=*/false,
4427                               /*InOverloadResolution=*/false,
4428                               /*CStyle=*/false,
4429                               /*AllowObjCWritebackConversion=*/false,
4430                               /*AllowObjCConversionOnExplicit=*/false);
4431 
4432   // Of course, that's still a reference binding.
4433   if (ICS.isStandard()) {
4434     ICS.Standard.ReferenceBinding = true;
4435     ICS.Standard.IsLvalueReference = !isRValRef;
4436     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4437     ICS.Standard.BindsToRvalue = true;
4438     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4439     ICS.Standard.ObjCLifetimeConversionBinding = false;
4440   } else if (ICS.isUserDefined()) {
4441     // Don't allow rvalue references to bind to lvalues.
4442     if (DeclType->isRValueReferenceType()) {
4443       if (const ReferenceType *RefType =
4444               ICS.UserDefined.ConversionFunction->getReturnType()
4445                   ->getAs<LValueReferenceType>()) {
4446         if (!RefType->getPointeeType()->isFunctionType()) {
4447           ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4448                      DeclType);
4449           return ICS;
4450         }
4451       }
4452     }
4453     ICS.UserDefined.Before.setAsIdentityConversion();
4454     ICS.UserDefined.After.ReferenceBinding = true;
4455     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4456     ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4457     ICS.UserDefined.After.BindsToRvalue = true;
4458     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4459     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4460   }
4461 
4462   return ICS;
4463 }
4464 
4465 static ImplicitConversionSequence
4466 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4467                       bool SuppressUserConversions,
4468                       bool InOverloadResolution,
4469                       bool AllowObjCWritebackConversion,
4470                       bool AllowExplicit = false);
4471 
4472 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4473 /// initializer list From.
4474 static ImplicitConversionSequence
TryListConversion(Sema & S,InitListExpr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion)4475 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4476                   bool SuppressUserConversions,
4477                   bool InOverloadResolution,
4478                   bool AllowObjCWritebackConversion) {
4479   // C++11 [over.ics.list]p1:
4480   //   When an argument is an initializer list, it is not an expression and
4481   //   special rules apply for converting it to a parameter type.
4482 
4483   ImplicitConversionSequence Result;
4484   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4485 
4486   // We need a complete type for what follows. Incomplete types can never be
4487   // initialized from init lists.
4488   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4489     return Result;
4490 
4491   // C++11 [over.ics.list]p2:
4492   //   If the parameter type is std::initializer_list<X> or "array of X" and
4493   //   all the elements can be implicitly converted to X, the implicit
4494   //   conversion sequence is the worst conversion necessary to convert an
4495   //   element of the list to X.
4496   bool toStdInitializerList = false;
4497   QualType X;
4498   if (ToType->isArrayType())
4499     X = S.Context.getAsArrayType(ToType)->getElementType();
4500   else
4501     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4502   if (!X.isNull()) {
4503     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4504       Expr *Init = From->getInit(i);
4505       ImplicitConversionSequence ICS =
4506           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4507                                 InOverloadResolution,
4508                                 AllowObjCWritebackConversion);
4509       // If a single element isn't convertible, fail.
4510       if (ICS.isBad()) {
4511         Result = ICS;
4512         break;
4513       }
4514       // Otherwise, look for the worst conversion.
4515       if (Result.isBad() ||
4516           CompareImplicitConversionSequences(S, ICS, Result) ==
4517               ImplicitConversionSequence::Worse)
4518         Result = ICS;
4519     }
4520 
4521     // For an empty list, we won't have computed any conversion sequence.
4522     // Introduce the identity conversion sequence.
4523     if (From->getNumInits() == 0) {
4524       Result.setStandard();
4525       Result.Standard.setAsIdentityConversion();
4526       Result.Standard.setFromType(ToType);
4527       Result.Standard.setAllToTypes(ToType);
4528     }
4529 
4530     Result.setStdInitializerListElement(toStdInitializerList);
4531     return Result;
4532   }
4533 
4534   // C++11 [over.ics.list]p3:
4535   //   Otherwise, if the parameter is a non-aggregate class X and overload
4536   //   resolution chooses a single best constructor [...] the implicit
4537   //   conversion sequence is a user-defined conversion sequence. If multiple
4538   //   constructors are viable but none is better than the others, the
4539   //   implicit conversion sequence is a user-defined conversion sequence.
4540   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4541     // This function can deal with initializer lists.
4542     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4543                                     /*AllowExplicit=*/false,
4544                                     InOverloadResolution, /*CStyle=*/false,
4545                                     AllowObjCWritebackConversion,
4546                                     /*AllowObjCConversionOnExplicit=*/false);
4547   }
4548 
4549   // C++11 [over.ics.list]p4:
4550   //   Otherwise, if the parameter has an aggregate type which can be
4551   //   initialized from the initializer list [...] the implicit conversion
4552   //   sequence is a user-defined conversion sequence.
4553   if (ToType->isAggregateType()) {
4554     // Type is an aggregate, argument is an init list. At this point it comes
4555     // down to checking whether the initialization works.
4556     // FIXME: Find out whether this parameter is consumed or not.
4557     InitializedEntity Entity =
4558         InitializedEntity::InitializeParameter(S.Context, ToType,
4559                                                /*Consumed=*/false);
4560     if (S.CanPerformCopyInitialization(Entity, From)) {
4561       Result.setUserDefined();
4562       Result.UserDefined.Before.setAsIdentityConversion();
4563       // Initializer lists don't have a type.
4564       Result.UserDefined.Before.setFromType(QualType());
4565       Result.UserDefined.Before.setAllToTypes(QualType());
4566 
4567       Result.UserDefined.After.setAsIdentityConversion();
4568       Result.UserDefined.After.setFromType(ToType);
4569       Result.UserDefined.After.setAllToTypes(ToType);
4570       Result.UserDefined.ConversionFunction = nullptr;
4571     }
4572     return Result;
4573   }
4574 
4575   // C++11 [over.ics.list]p5:
4576   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4577   if (ToType->isReferenceType()) {
4578     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4579     // mention initializer lists in any way. So we go by what list-
4580     // initialization would do and try to extrapolate from that.
4581 
4582     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4583 
4584     // If the initializer list has a single element that is reference-related
4585     // to the parameter type, we initialize the reference from that.
4586     if (From->getNumInits() == 1) {
4587       Expr *Init = From->getInit(0);
4588 
4589       QualType T2 = Init->getType();
4590 
4591       // If the initializer is the address of an overloaded function, try
4592       // to resolve the overloaded function. If all goes well, T2 is the
4593       // type of the resulting function.
4594       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4595         DeclAccessPair Found;
4596         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4597                                    Init, ToType, false, Found))
4598           T2 = Fn->getType();
4599       }
4600 
4601       // Compute some basic properties of the types and the initializer.
4602       bool dummy1 = false;
4603       bool dummy2 = false;
4604       bool dummy3 = false;
4605       Sema::ReferenceCompareResult RefRelationship
4606         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4607                                          dummy2, dummy3);
4608 
4609       if (RefRelationship >= Sema::Ref_Related) {
4610         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4611                                 SuppressUserConversions,
4612                                 /*AllowExplicit=*/false);
4613       }
4614     }
4615 
4616     // Otherwise, we bind the reference to a temporary created from the
4617     // initializer list.
4618     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4619                                InOverloadResolution,
4620                                AllowObjCWritebackConversion);
4621     if (Result.isFailure())
4622       return Result;
4623     assert(!Result.isEllipsis() &&
4624            "Sub-initialization cannot result in ellipsis conversion.");
4625 
4626     // Can we even bind to a temporary?
4627     if (ToType->isRValueReferenceType() ||
4628         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4629       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4630                                             Result.UserDefined.After;
4631       SCS.ReferenceBinding = true;
4632       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4633       SCS.BindsToRvalue = true;
4634       SCS.BindsToFunctionLvalue = false;
4635       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4636       SCS.ObjCLifetimeConversionBinding = false;
4637     } else
4638       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4639                     From, ToType);
4640     return Result;
4641   }
4642 
4643   // C++11 [over.ics.list]p6:
4644   //   Otherwise, if the parameter type is not a class:
4645   if (!ToType->isRecordType()) {
4646     //    - if the initializer list has one element, the implicit conversion
4647     //      sequence is the one required to convert the element to the
4648     //      parameter type.
4649     unsigned NumInits = From->getNumInits();
4650     if (NumInits == 1)
4651       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4652                                      SuppressUserConversions,
4653                                      InOverloadResolution,
4654                                      AllowObjCWritebackConversion);
4655     //    - if the initializer list has no elements, the implicit conversion
4656     //      sequence is the identity conversion.
4657     else if (NumInits == 0) {
4658       Result.setStandard();
4659       Result.Standard.setAsIdentityConversion();
4660       Result.Standard.setFromType(ToType);
4661       Result.Standard.setAllToTypes(ToType);
4662     }
4663     return Result;
4664   }
4665 
4666   // C++11 [over.ics.list]p7:
4667   //   In all cases other than those enumerated above, no conversion is possible
4668   return Result;
4669 }
4670 
4671 /// TryCopyInitialization - Try to copy-initialize a value of type
4672 /// ToType from the expression From. Return the implicit conversion
4673 /// sequence required to pass this argument, which may be a bad
4674 /// conversion sequence (meaning that the argument cannot be passed to
4675 /// a parameter of this type). If @p SuppressUserConversions, then we
4676 /// do not permit any user-defined conversion sequences.
4677 static ImplicitConversionSequence
TryCopyInitialization(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion,bool AllowExplicit)4678 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4679                       bool SuppressUserConversions,
4680                       bool InOverloadResolution,
4681                       bool AllowObjCWritebackConversion,
4682                       bool AllowExplicit) {
4683   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4684     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4685                              InOverloadResolution,AllowObjCWritebackConversion);
4686 
4687   if (ToType->isReferenceType())
4688     return TryReferenceInit(S, From, ToType,
4689                             /*FIXME:*/From->getLocStart(),
4690                             SuppressUserConversions,
4691                             AllowExplicit);
4692 
4693   return TryImplicitConversion(S, From, ToType,
4694                                SuppressUserConversions,
4695                                /*AllowExplicit=*/false,
4696                                InOverloadResolution,
4697                                /*CStyle=*/false,
4698                                AllowObjCWritebackConversion,
4699                                /*AllowObjCConversionOnExplicit=*/false);
4700 }
4701 
TryCopyInitialization(const CanQualType FromQTy,const CanQualType ToQTy,Sema & S,SourceLocation Loc,ExprValueKind FromVK)4702 static bool TryCopyInitialization(const CanQualType FromQTy,
4703                                   const CanQualType ToQTy,
4704                                   Sema &S,
4705                                   SourceLocation Loc,
4706                                   ExprValueKind FromVK) {
4707   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4708   ImplicitConversionSequence ICS =
4709     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4710 
4711   return !ICS.isBad();
4712 }
4713 
4714 /// TryObjectArgumentInitialization - Try to initialize the object
4715 /// parameter of the given member function (@c Method) from the
4716 /// expression @p From.
4717 static ImplicitConversionSequence
TryObjectArgumentInitialization(Sema & S,QualType FromType,Expr::Classification FromClassification,CXXMethodDecl * Method,CXXRecordDecl * ActingContext)4718 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4719                                 Expr::Classification FromClassification,
4720                                 CXXMethodDecl *Method,
4721                                 CXXRecordDecl *ActingContext) {
4722   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4723   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4724   //                 const volatile object.
4725   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4726     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4727   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4728 
4729   // Set up the conversion sequence as a "bad" conversion, to allow us
4730   // to exit early.
4731   ImplicitConversionSequence ICS;
4732 
4733   // We need to have an object of class type.
4734   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4735     FromType = PT->getPointeeType();
4736 
4737     // When we had a pointer, it's implicitly dereferenced, so we
4738     // better have an lvalue.
4739     assert(FromClassification.isLValue());
4740   }
4741 
4742   assert(FromType->isRecordType());
4743 
4744   // C++0x [over.match.funcs]p4:
4745   //   For non-static member functions, the type of the implicit object
4746   //   parameter is
4747   //
4748   //     - "lvalue reference to cv X" for functions declared without a
4749   //        ref-qualifier or with the & ref-qualifier
4750   //     - "rvalue reference to cv X" for functions declared with the &&
4751   //        ref-qualifier
4752   //
4753   // where X is the class of which the function is a member and cv is the
4754   // cv-qualification on the member function declaration.
4755   //
4756   // However, when finding an implicit conversion sequence for the argument, we
4757   // are not allowed to create temporaries or perform user-defined conversions
4758   // (C++ [over.match.funcs]p5). We perform a simplified version of
4759   // reference binding here, that allows class rvalues to bind to
4760   // non-constant references.
4761 
4762   // First check the qualifiers.
4763   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4764   if (ImplicitParamType.getCVRQualifiers()
4765                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4766       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4767     ICS.setBad(BadConversionSequence::bad_qualifiers,
4768                FromType, ImplicitParamType);
4769     return ICS;
4770   }
4771 
4772   // Check that we have either the same type or a derived type. It
4773   // affects the conversion rank.
4774   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4775   ImplicitConversionKind SecondKind;
4776   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4777     SecondKind = ICK_Identity;
4778   } else if (S.IsDerivedFrom(FromType, ClassType))
4779     SecondKind = ICK_Derived_To_Base;
4780   else {
4781     ICS.setBad(BadConversionSequence::unrelated_class,
4782                FromType, ImplicitParamType);
4783     return ICS;
4784   }
4785 
4786   // Check the ref-qualifier.
4787   switch (Method->getRefQualifier()) {
4788   case RQ_None:
4789     // Do nothing; we don't care about lvalueness or rvalueness.
4790     break;
4791 
4792   case RQ_LValue:
4793     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4794       // non-const lvalue reference cannot bind to an rvalue
4795       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4796                  ImplicitParamType);
4797       return ICS;
4798     }
4799     break;
4800 
4801   case RQ_RValue:
4802     if (!FromClassification.isRValue()) {
4803       // rvalue reference cannot bind to an lvalue
4804       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4805                  ImplicitParamType);
4806       return ICS;
4807     }
4808     break;
4809   }
4810 
4811   // Success. Mark this as a reference binding.
4812   ICS.setStandard();
4813   ICS.Standard.setAsIdentityConversion();
4814   ICS.Standard.Second = SecondKind;
4815   ICS.Standard.setFromType(FromType);
4816   ICS.Standard.setAllToTypes(ImplicitParamType);
4817   ICS.Standard.ReferenceBinding = true;
4818   ICS.Standard.DirectBinding = true;
4819   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4820   ICS.Standard.BindsToFunctionLvalue = false;
4821   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4822   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4823     = (Method->getRefQualifier() == RQ_None);
4824   return ICS;
4825 }
4826 
4827 /// PerformObjectArgumentInitialization - Perform initialization of
4828 /// the implicit object parameter for the given Method with the given
4829 /// expression.
4830 ExprResult
PerformObjectArgumentInitialization(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,CXXMethodDecl * Method)4831 Sema::PerformObjectArgumentInitialization(Expr *From,
4832                                           NestedNameSpecifier *Qualifier,
4833                                           NamedDecl *FoundDecl,
4834                                           CXXMethodDecl *Method) {
4835   QualType FromRecordType, DestType;
4836   QualType ImplicitParamRecordType  =
4837     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4838 
4839   Expr::Classification FromClassification;
4840   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4841     FromRecordType = PT->getPointeeType();
4842     DestType = Method->getThisType(Context);
4843     FromClassification = Expr::Classification::makeSimpleLValue();
4844   } else {
4845     FromRecordType = From->getType();
4846     DestType = ImplicitParamRecordType;
4847     FromClassification = From->Classify(Context);
4848   }
4849 
4850   // Note that we always use the true parent context when performing
4851   // the actual argument initialization.
4852   ImplicitConversionSequence ICS
4853     = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4854                                       Method, Method->getParent());
4855   if (ICS.isBad()) {
4856     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4857       Qualifiers FromQs = FromRecordType.getQualifiers();
4858       Qualifiers ToQs = DestType.getQualifiers();
4859       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4860       if (CVR) {
4861         Diag(From->getLocStart(),
4862              diag::err_member_function_call_bad_cvr)
4863           << Method->getDeclName() << FromRecordType << (CVR - 1)
4864           << From->getSourceRange();
4865         Diag(Method->getLocation(), diag::note_previous_decl)
4866           << Method->getDeclName();
4867         return ExprError();
4868       }
4869     }
4870 
4871     return Diag(From->getLocStart(),
4872                 diag::err_implicit_object_parameter_init)
4873        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4874   }
4875 
4876   if (ICS.Standard.Second == ICK_Derived_To_Base) {
4877     ExprResult FromRes =
4878       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4879     if (FromRes.isInvalid())
4880       return ExprError();
4881     From = FromRes.get();
4882   }
4883 
4884   if (!Context.hasSameType(From->getType(), DestType))
4885     From = ImpCastExprToType(From, DestType, CK_NoOp,
4886                              From->getValueKind()).get();
4887   return From;
4888 }
4889 
4890 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4891 /// expression From to bool (C++0x [conv]p3).
4892 static ImplicitConversionSequence
TryContextuallyConvertToBool(Sema & S,Expr * From)4893 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4894   return TryImplicitConversion(S, From, S.Context.BoolTy,
4895                                /*SuppressUserConversions=*/false,
4896                                /*AllowExplicit=*/true,
4897                                /*InOverloadResolution=*/false,
4898                                /*CStyle=*/false,
4899                                /*AllowObjCWritebackConversion=*/false,
4900                                /*AllowObjCConversionOnExplicit=*/false);
4901 }
4902 
4903 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4904 /// of the expression From to bool (C++0x [conv]p3).
PerformContextuallyConvertToBool(Expr * From)4905 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4906   if (checkPlaceholderForOverload(*this, From))
4907     return ExprError();
4908 
4909   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4910   if (!ICS.isBad())
4911     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4912 
4913   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4914     return Diag(From->getLocStart(),
4915                 diag::err_typecheck_bool_condition)
4916                   << From->getType() << From->getSourceRange();
4917   return ExprError();
4918 }
4919 
4920 /// Check that the specified conversion is permitted in a converted constant
4921 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4922 /// is acceptable.
CheckConvertedConstantConversions(Sema & S,StandardConversionSequence & SCS)4923 static bool CheckConvertedConstantConversions(Sema &S,
4924                                               StandardConversionSequence &SCS) {
4925   // Since we know that the target type is an integral or unscoped enumeration
4926   // type, most conversion kinds are impossible. All possible First and Third
4927   // conversions are fine.
4928   switch (SCS.Second) {
4929   case ICK_Identity:
4930   case ICK_Integral_Promotion:
4931   case ICK_Integral_Conversion:
4932   case ICK_Zero_Event_Conversion:
4933     return true;
4934 
4935   case ICK_Boolean_Conversion:
4936     // Conversion from an integral or unscoped enumeration type to bool is
4937     // classified as ICK_Boolean_Conversion, but it's also an integral
4938     // conversion, so it's permitted in a converted constant expression.
4939     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4940            SCS.getToType(2)->isBooleanType();
4941 
4942   case ICK_Floating_Integral:
4943   case ICK_Complex_Real:
4944     return false;
4945 
4946   case ICK_Lvalue_To_Rvalue:
4947   case ICK_Array_To_Pointer:
4948   case ICK_Function_To_Pointer:
4949   case ICK_NoReturn_Adjustment:
4950   case ICK_Qualification:
4951   case ICK_Compatible_Conversion:
4952   case ICK_Vector_Conversion:
4953   case ICK_Vector_Splat:
4954   case ICK_Derived_To_Base:
4955   case ICK_Pointer_Conversion:
4956   case ICK_Pointer_Member:
4957   case ICK_Block_Pointer_Conversion:
4958   case ICK_Writeback_Conversion:
4959   case ICK_Floating_Promotion:
4960   case ICK_Complex_Promotion:
4961   case ICK_Complex_Conversion:
4962   case ICK_Floating_Conversion:
4963   case ICK_TransparentUnionConversion:
4964     llvm_unreachable("unexpected second conversion kind");
4965 
4966   case ICK_Num_Conversion_Kinds:
4967     break;
4968   }
4969 
4970   llvm_unreachable("unknown conversion kind");
4971 }
4972 
4973 /// CheckConvertedConstantExpression - Check that the expression From is a
4974 /// converted constant expression of type T, perform the conversion and produce
4975 /// the converted expression, per C++11 [expr.const]p3.
CheckConvertedConstantExpression(Expr * From,QualType T,llvm::APSInt & Value,CCEKind CCE)4976 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4977                                                   llvm::APSInt &Value,
4978                                                   CCEKind CCE) {
4979   assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4980   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4981 
4982   if (checkPlaceholderForOverload(*this, From))
4983     return ExprError();
4984 
4985   // C++11 [expr.const]p3 with proposed wording fixes:
4986   //  A converted constant expression of type T is a core constant expression,
4987   //  implicitly converted to a prvalue of type T, where the converted
4988   //  expression is a literal constant expression and the implicit conversion
4989   //  sequence contains only user-defined conversions, lvalue-to-rvalue
4990   //  conversions, integral promotions, and integral conversions other than
4991   //  narrowing conversions.
4992   ImplicitConversionSequence ICS =
4993     TryImplicitConversion(From, T,
4994                           /*SuppressUserConversions=*/false,
4995                           /*AllowExplicit=*/false,
4996                           /*InOverloadResolution=*/false,
4997                           /*CStyle=*/false,
4998                           /*AllowObjcWritebackConversion=*/false);
4999   StandardConversionSequence *SCS = nullptr;
5000   switch (ICS.getKind()) {
5001   case ImplicitConversionSequence::StandardConversion:
5002     if (!CheckConvertedConstantConversions(*this, ICS.Standard))
5003       return Diag(From->getLocStart(),
5004                   diag::err_typecheck_converted_constant_expression_disallowed)
5005                << From->getType() << From->getSourceRange() << T;
5006     SCS = &ICS.Standard;
5007     break;
5008   case ImplicitConversionSequence::UserDefinedConversion:
5009     // We are converting from class type to an integral or enumeration type, so
5010     // the Before sequence must be trivial.
5011     if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
5012       return Diag(From->getLocStart(),
5013                   diag::err_typecheck_converted_constant_expression_disallowed)
5014                << From->getType() << From->getSourceRange() << T;
5015     SCS = &ICS.UserDefined.After;
5016     break;
5017   case ImplicitConversionSequence::AmbiguousConversion:
5018   case ImplicitConversionSequence::BadConversion:
5019     if (!DiagnoseMultipleUserDefinedConversion(From, T))
5020       return Diag(From->getLocStart(),
5021                   diag::err_typecheck_converted_constant_expression)
5022                     << From->getType() << From->getSourceRange() << T;
5023     return ExprError();
5024 
5025   case ImplicitConversionSequence::EllipsisConversion:
5026     llvm_unreachable("ellipsis conversion in converted constant expression");
5027   }
5028 
5029   ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
5030   if (Result.isInvalid())
5031     return Result;
5032 
5033   // Check for a narrowing implicit conversion.
5034   APValue PreNarrowingValue;
5035   QualType PreNarrowingType;
5036   switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5037                                 PreNarrowingType)) {
5038   case NK_Variable_Narrowing:
5039     // Implicit conversion to a narrower type, and the value is not a constant
5040     // expression. We'll diagnose this in a moment.
5041   case NK_Not_Narrowing:
5042     break;
5043 
5044   case NK_Constant_Narrowing:
5045     Diag(From->getLocStart(), diag::ext_cce_narrowing)
5046       << CCE << /*Constant*/1
5047       << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
5048     break;
5049 
5050   case NK_Type_Narrowing:
5051     Diag(From->getLocStart(), diag::ext_cce_narrowing)
5052       << CCE << /*Constant*/0 << From->getType() << T;
5053     break;
5054   }
5055 
5056   // Check the expression is a constant expression.
5057   SmallVector<PartialDiagnosticAt, 8> Notes;
5058   Expr::EvalResult Eval;
5059   Eval.Diag = &Notes;
5060 
5061   if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
5062     // The expression can't be folded, so we can't keep it at this position in
5063     // the AST.
5064     Result = ExprError();
5065   } else {
5066     Value = Eval.Val.getInt();
5067 
5068     if (Notes.empty()) {
5069       // It's a constant expression.
5070       return Result;
5071     }
5072   }
5073 
5074   // It's not a constant expression. Produce an appropriate diagnostic.
5075   if (Notes.size() == 1 &&
5076       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5077     Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5078   else {
5079     Diag(From->getLocStart(), diag::err_expr_not_cce)
5080       << CCE << From->getSourceRange();
5081     for (unsigned I = 0; I < Notes.size(); ++I)
5082       Diag(Notes[I].first, Notes[I].second);
5083   }
5084   return Result;
5085 }
5086 
5087 /// dropPointerConversions - If the given standard conversion sequence
5088 /// involves any pointer conversions, remove them.  This may change
5089 /// the result type of the conversion sequence.
dropPointerConversion(StandardConversionSequence & SCS)5090 static void dropPointerConversion(StandardConversionSequence &SCS) {
5091   if (SCS.Second == ICK_Pointer_Conversion) {
5092     SCS.Second = ICK_Identity;
5093     SCS.Third = ICK_Identity;
5094     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5095   }
5096 }
5097 
5098 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5099 /// convert the expression From to an Objective-C pointer type.
5100 static ImplicitConversionSequence
TryContextuallyConvertToObjCPointer(Sema & S,Expr * From)5101 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5102   // Do an implicit conversion to 'id'.
5103   QualType Ty = S.Context.getObjCIdType();
5104   ImplicitConversionSequence ICS
5105     = TryImplicitConversion(S, From, Ty,
5106                             // FIXME: Are these flags correct?
5107                             /*SuppressUserConversions=*/false,
5108                             /*AllowExplicit=*/true,
5109                             /*InOverloadResolution=*/false,
5110                             /*CStyle=*/false,
5111                             /*AllowObjCWritebackConversion=*/false,
5112                             /*AllowObjCConversionOnExplicit=*/true);
5113 
5114   // Strip off any final conversions to 'id'.
5115   switch (ICS.getKind()) {
5116   case ImplicitConversionSequence::BadConversion:
5117   case ImplicitConversionSequence::AmbiguousConversion:
5118   case ImplicitConversionSequence::EllipsisConversion:
5119     break;
5120 
5121   case ImplicitConversionSequence::UserDefinedConversion:
5122     dropPointerConversion(ICS.UserDefined.After);
5123     break;
5124 
5125   case ImplicitConversionSequence::StandardConversion:
5126     dropPointerConversion(ICS.Standard);
5127     break;
5128   }
5129 
5130   return ICS;
5131 }
5132 
5133 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5134 /// conversion of the expression From to an Objective-C pointer type.
PerformContextuallyConvertToObjCPointer(Expr * From)5135 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5136   if (checkPlaceholderForOverload(*this, From))
5137     return ExprError();
5138 
5139   QualType Ty = Context.getObjCIdType();
5140   ImplicitConversionSequence ICS =
5141     TryContextuallyConvertToObjCPointer(*this, From);
5142   if (!ICS.isBad())
5143     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5144   return ExprError();
5145 }
5146 
5147 /// Determine whether the provided type is an integral type, or an enumeration
5148 /// type of a permitted flavor.
match(QualType T)5149 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5150   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5151                                  : T->isIntegralOrUnscopedEnumerationType();
5152 }
5153 
5154 static ExprResult
diagnoseAmbiguousConversion(Sema & SemaRef,SourceLocation Loc,Expr * From,Sema::ContextualImplicitConverter & Converter,QualType T,UnresolvedSetImpl & ViableConversions)5155 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5156                             Sema::ContextualImplicitConverter &Converter,
5157                             QualType T, UnresolvedSetImpl &ViableConversions) {
5158 
5159   if (Converter.Suppress)
5160     return ExprError();
5161 
5162   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5163   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5164     CXXConversionDecl *Conv =
5165         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5166     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5167     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5168   }
5169   return From;
5170 }
5171 
5172 static bool
diagnoseNoViableConversion(Sema & SemaRef,SourceLocation Loc,Expr * & From,Sema::ContextualImplicitConverter & Converter,QualType T,bool HadMultipleCandidates,UnresolvedSetImpl & ExplicitConversions)5173 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5174                            Sema::ContextualImplicitConverter &Converter,
5175                            QualType T, bool HadMultipleCandidates,
5176                            UnresolvedSetImpl &ExplicitConversions) {
5177   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5178     DeclAccessPair Found = ExplicitConversions[0];
5179     CXXConversionDecl *Conversion =
5180         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5181 
5182     // The user probably meant to invoke the given explicit
5183     // conversion; use it.
5184     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5185     std::string TypeStr;
5186     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5187 
5188     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5189         << FixItHint::CreateInsertion(From->getLocStart(),
5190                                       "static_cast<" + TypeStr + ">(")
5191         << FixItHint::CreateInsertion(
5192                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5193     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5194 
5195     // If we aren't in a SFINAE context, build a call to the
5196     // explicit conversion function.
5197     if (SemaRef.isSFINAEContext())
5198       return true;
5199 
5200     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5201     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5202                                                        HadMultipleCandidates);
5203     if (Result.isInvalid())
5204       return true;
5205     // Record usage of conversion in an implicit cast.
5206     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5207                                     CK_UserDefinedConversion, Result.get(),
5208                                     nullptr, Result.get()->getValueKind());
5209   }
5210   return false;
5211 }
5212 
recordConversion(Sema & SemaRef,SourceLocation Loc,Expr * & From,Sema::ContextualImplicitConverter & Converter,QualType T,bool HadMultipleCandidates,DeclAccessPair & Found)5213 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5214                              Sema::ContextualImplicitConverter &Converter,
5215                              QualType T, bool HadMultipleCandidates,
5216                              DeclAccessPair &Found) {
5217   CXXConversionDecl *Conversion =
5218       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5219   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5220 
5221   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5222   if (!Converter.SuppressConversion) {
5223     if (SemaRef.isSFINAEContext())
5224       return true;
5225 
5226     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5227         << From->getSourceRange();
5228   }
5229 
5230   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5231                                                      HadMultipleCandidates);
5232   if (Result.isInvalid())
5233     return true;
5234   // Record usage of conversion in an implicit cast.
5235   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5236                                   CK_UserDefinedConversion, Result.get(),
5237                                   nullptr, Result.get()->getValueKind());
5238   return false;
5239 }
5240 
finishContextualImplicitConversion(Sema & SemaRef,SourceLocation Loc,Expr * From,Sema::ContextualImplicitConverter & Converter)5241 static ExprResult finishContextualImplicitConversion(
5242     Sema &SemaRef, SourceLocation Loc, Expr *From,
5243     Sema::ContextualImplicitConverter &Converter) {
5244   if (!Converter.match(From->getType()) && !Converter.Suppress)
5245     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5246         << From->getSourceRange();
5247 
5248   return SemaRef.DefaultLvalueConversion(From);
5249 }
5250 
5251 static void
collectViableConversionCandidates(Sema & SemaRef,Expr * From,QualType ToType,UnresolvedSetImpl & ViableConversions,OverloadCandidateSet & CandidateSet)5252 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5253                                   UnresolvedSetImpl &ViableConversions,
5254                                   OverloadCandidateSet &CandidateSet) {
5255   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5256     DeclAccessPair FoundDecl = ViableConversions[I];
5257     NamedDecl *D = FoundDecl.getDecl();
5258     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5259     if (isa<UsingShadowDecl>(D))
5260       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5261 
5262     CXXConversionDecl *Conv;
5263     FunctionTemplateDecl *ConvTemplate;
5264     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5265       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5266     else
5267       Conv = cast<CXXConversionDecl>(D);
5268 
5269     if (ConvTemplate)
5270       SemaRef.AddTemplateConversionCandidate(
5271         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5272         /*AllowObjCConversionOnExplicit=*/false);
5273     else
5274       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5275                                      ToType, CandidateSet,
5276                                      /*AllowObjCConversionOnExplicit=*/false);
5277   }
5278 }
5279 
5280 /// \brief Attempt to convert the given expression to a type which is accepted
5281 /// by the given converter.
5282 ///
5283 /// This routine will attempt to convert an expression of class type to a
5284 /// type accepted by the specified converter. In C++11 and before, the class
5285 /// must have a single non-explicit conversion function converting to a matching
5286 /// type. In C++1y, there can be multiple such conversion functions, but only
5287 /// one target type.
5288 ///
5289 /// \param Loc The source location of the construct that requires the
5290 /// conversion.
5291 ///
5292 /// \param From The expression we're converting from.
5293 ///
5294 /// \param Converter Used to control and diagnose the conversion process.
5295 ///
5296 /// \returns The expression, converted to an integral or enumeration type if
5297 /// successful.
PerformContextualImplicitConversion(SourceLocation Loc,Expr * From,ContextualImplicitConverter & Converter)5298 ExprResult Sema::PerformContextualImplicitConversion(
5299     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5300   // We can't perform any more checking for type-dependent expressions.
5301   if (From->isTypeDependent())
5302     return From;
5303 
5304   // Process placeholders immediately.
5305   if (From->hasPlaceholderType()) {
5306     ExprResult result = CheckPlaceholderExpr(From);
5307     if (result.isInvalid())
5308       return result;
5309     From = result.get();
5310   }
5311 
5312   // If the expression already has a matching type, we're golden.
5313   QualType T = From->getType();
5314   if (Converter.match(T))
5315     return DefaultLvalueConversion(From);
5316 
5317   // FIXME: Check for missing '()' if T is a function type?
5318 
5319   // We can only perform contextual implicit conversions on objects of class
5320   // type.
5321   const RecordType *RecordTy = T->getAs<RecordType>();
5322   if (!RecordTy || !getLangOpts().CPlusPlus) {
5323     if (!Converter.Suppress)
5324       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5325     return From;
5326   }
5327 
5328   // We must have a complete class type.
5329   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5330     ContextualImplicitConverter &Converter;
5331     Expr *From;
5332 
5333     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5334         : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5335 
5336     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5337       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5338     }
5339   } IncompleteDiagnoser(Converter, From);
5340 
5341   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5342     return From;
5343 
5344   // Look for a conversion to an integral or enumeration type.
5345   UnresolvedSet<4>
5346       ViableConversions; // These are *potentially* viable in C++1y.
5347   UnresolvedSet<4> ExplicitConversions;
5348   std::pair<CXXRecordDecl::conversion_iterator,
5349             CXXRecordDecl::conversion_iterator> Conversions =
5350       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5351 
5352   bool HadMultipleCandidates =
5353       (std::distance(Conversions.first, Conversions.second) > 1);
5354 
5355   // To check that there is only one target type, in C++1y:
5356   QualType ToType;
5357   bool HasUniqueTargetType = true;
5358 
5359   // Collect explicit or viable (potentially in C++1y) conversions.
5360   for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5361                                           E = Conversions.second;
5362        I != E; ++I) {
5363     NamedDecl *D = (*I)->getUnderlyingDecl();
5364     CXXConversionDecl *Conversion;
5365     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5366     if (ConvTemplate) {
5367       if (getLangOpts().CPlusPlus1y)
5368         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5369       else
5370         continue; // C++11 does not consider conversion operator templates(?).
5371     } else
5372       Conversion = cast<CXXConversionDecl>(D);
5373 
5374     assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5375            "Conversion operator templates are considered potentially "
5376            "viable in C++1y");
5377 
5378     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5379     if (Converter.match(CurToType) || ConvTemplate) {
5380 
5381       if (Conversion->isExplicit()) {
5382         // FIXME: For C++1y, do we need this restriction?
5383         // cf. diagnoseNoViableConversion()
5384         if (!ConvTemplate)
5385           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5386       } else {
5387         if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5388           if (ToType.isNull())
5389             ToType = CurToType.getUnqualifiedType();
5390           else if (HasUniqueTargetType &&
5391                    (CurToType.getUnqualifiedType() != ToType))
5392             HasUniqueTargetType = false;
5393         }
5394         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5395       }
5396     }
5397   }
5398 
5399   if (getLangOpts().CPlusPlus1y) {
5400     // C++1y [conv]p6:
5401     // ... An expression e of class type E appearing in such a context
5402     // is said to be contextually implicitly converted to a specified
5403     // type T and is well-formed if and only if e can be implicitly
5404     // converted to a type T that is determined as follows: E is searched
5405     // for conversion functions whose return type is cv T or reference to
5406     // cv T such that T is allowed by the context. There shall be
5407     // exactly one such T.
5408 
5409     // If no unique T is found:
5410     if (ToType.isNull()) {
5411       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5412                                      HadMultipleCandidates,
5413                                      ExplicitConversions))
5414         return ExprError();
5415       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5416     }
5417 
5418     // If more than one unique Ts are found:
5419     if (!HasUniqueTargetType)
5420       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5421                                          ViableConversions);
5422 
5423     // If one unique T is found:
5424     // First, build a candidate set from the previously recorded
5425     // potentially viable conversions.
5426     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5427     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5428                                       CandidateSet);
5429 
5430     // Then, perform overload resolution over the candidate set.
5431     OverloadCandidateSet::iterator Best;
5432     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5433     case OR_Success: {
5434       // Apply this conversion.
5435       DeclAccessPair Found =
5436           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5437       if (recordConversion(*this, Loc, From, Converter, T,
5438                            HadMultipleCandidates, Found))
5439         return ExprError();
5440       break;
5441     }
5442     case OR_Ambiguous:
5443       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5444                                          ViableConversions);
5445     case OR_No_Viable_Function:
5446       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5447                                      HadMultipleCandidates,
5448                                      ExplicitConversions))
5449         return ExprError();
5450     // fall through 'OR_Deleted' case.
5451     case OR_Deleted:
5452       // We'll complain below about a non-integral condition type.
5453       break;
5454     }
5455   } else {
5456     switch (ViableConversions.size()) {
5457     case 0: {
5458       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5459                                      HadMultipleCandidates,
5460                                      ExplicitConversions))
5461         return ExprError();
5462 
5463       // We'll complain below about a non-integral condition type.
5464       break;
5465     }
5466     case 1: {
5467       // Apply this conversion.
5468       DeclAccessPair Found = ViableConversions[0];
5469       if (recordConversion(*this, Loc, From, Converter, T,
5470                            HadMultipleCandidates, Found))
5471         return ExprError();
5472       break;
5473     }
5474     default:
5475       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5476                                          ViableConversions);
5477     }
5478   }
5479 
5480   return finishContextualImplicitConversion(*this, Loc, From, Converter);
5481 }
5482 
5483 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5484 /// an acceptable non-member overloaded operator for a call whose
5485 /// arguments have types T1 (and, if non-empty, T2). This routine
5486 /// implements the check in C++ [over.match.oper]p3b2 concerning
5487 /// enumeration types.
IsAcceptableNonMemberOperatorCandidate(ASTContext & Context,FunctionDecl * Fn,ArrayRef<Expr * > Args)5488 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5489                                                    FunctionDecl *Fn,
5490                                                    ArrayRef<Expr *> Args) {
5491   QualType T1 = Args[0]->getType();
5492   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5493 
5494   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5495     return true;
5496 
5497   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5498     return true;
5499 
5500   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5501   if (Proto->getNumParams() < 1)
5502     return false;
5503 
5504   if (T1->isEnumeralType()) {
5505     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5506     if (Context.hasSameUnqualifiedType(T1, ArgType))
5507       return true;
5508   }
5509 
5510   if (Proto->getNumParams() < 2)
5511     return false;
5512 
5513   if (!T2.isNull() && T2->isEnumeralType()) {
5514     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5515     if (Context.hasSameUnqualifiedType(T2, ArgType))
5516       return true;
5517   }
5518 
5519   return false;
5520 }
5521 
5522 /// AddOverloadCandidate - Adds the given function to the set of
5523 /// candidate functions, using the given function call arguments.  If
5524 /// @p SuppressUserConversions, then don't allow user-defined
5525 /// conversions via constructors or conversion operators.
5526 ///
5527 /// \param PartialOverloading true if we are performing "partial" overloading
5528 /// based on an incomplete set of function arguments. This feature is used by
5529 /// code completion.
5530 void
AddOverloadCandidate(FunctionDecl * Function,DeclAccessPair FoundDecl,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading,bool AllowExplicit)5531 Sema::AddOverloadCandidate(FunctionDecl *Function,
5532                            DeclAccessPair FoundDecl,
5533                            ArrayRef<Expr *> Args,
5534                            OverloadCandidateSet &CandidateSet,
5535                            bool SuppressUserConversions,
5536                            bool PartialOverloading,
5537                            bool AllowExplicit) {
5538   const FunctionProtoType *Proto
5539     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5540   assert(Proto && "Functions without a prototype cannot be overloaded");
5541   assert(!Function->getDescribedFunctionTemplate() &&
5542          "Use AddTemplateOverloadCandidate for function templates");
5543 
5544   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5545     if (!isa<CXXConstructorDecl>(Method)) {
5546       // If we get here, it's because we're calling a member function
5547       // that is named without a member access expression (e.g.,
5548       // "this->f") that was either written explicitly or created
5549       // implicitly. This can happen with a qualified call to a member
5550       // function, e.g., X::f(). We use an empty type for the implied
5551       // object argument (C++ [over.call.func]p3), and the acting context
5552       // is irrelevant.
5553       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5554                          QualType(), Expr::Classification::makeSimpleLValue(),
5555                          Args, CandidateSet, SuppressUserConversions);
5556       return;
5557     }
5558     // We treat a constructor like a non-member function, since its object
5559     // argument doesn't participate in overload resolution.
5560   }
5561 
5562   if (!CandidateSet.isNewCandidate(Function))
5563     return;
5564 
5565   // C++ [over.match.oper]p3:
5566   //   if no operand has a class type, only those non-member functions in the
5567   //   lookup set that have a first parameter of type T1 or "reference to
5568   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5569   //   is a right operand) a second parameter of type T2 or "reference to
5570   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
5571   //   candidate functions.
5572   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5573       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5574     return;
5575 
5576   // C++11 [class.copy]p11: [DR1402]
5577   //   A defaulted move constructor that is defined as deleted is ignored by
5578   //   overload resolution.
5579   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5580   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5581       Constructor->isMoveConstructor())
5582     return;
5583 
5584   // Overload resolution is always an unevaluated context.
5585   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5586 
5587   if (Constructor) {
5588     // C++ [class.copy]p3:
5589     //   A member function template is never instantiated to perform the copy
5590     //   of a class object to an object of its class type.
5591     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5592     if (Args.size() == 1 &&
5593         Constructor->isSpecializationCopyingObject() &&
5594         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5595          IsDerivedFrom(Args[0]->getType(), ClassType)))
5596       return;
5597   }
5598 
5599   // Add this candidate
5600   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5601   Candidate.FoundDecl = FoundDecl;
5602   Candidate.Function = Function;
5603   Candidate.Viable = true;
5604   Candidate.IsSurrogate = false;
5605   Candidate.IgnoreObjectArgument = false;
5606   Candidate.ExplicitCallArguments = Args.size();
5607 
5608   unsigned NumParams = Proto->getNumParams();
5609 
5610   // (C++ 13.3.2p2): A candidate function having fewer than m
5611   // parameters is viable only if it has an ellipsis in its parameter
5612   // list (8.3.5).
5613   if ((Args.size() + (PartialOverloading && Args.size())) > NumParams &&
5614       !Proto->isVariadic()) {
5615     Candidate.Viable = false;
5616     Candidate.FailureKind = ovl_fail_too_many_arguments;
5617     return;
5618   }
5619 
5620   // (C++ 13.3.2p2): A candidate function having more than m parameters
5621   // is viable only if the (m+1)st parameter has a default argument
5622   // (8.3.6). For the purposes of overload resolution, the
5623   // parameter list is truncated on the right, so that there are
5624   // exactly m parameters.
5625   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5626   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5627     // Not enough arguments.
5628     Candidate.Viable = false;
5629     Candidate.FailureKind = ovl_fail_too_few_arguments;
5630     return;
5631   }
5632 
5633   // (CUDA B.1): Check for invalid calls between targets.
5634   if (getLangOpts().CUDA)
5635     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5636       if (CheckCUDATarget(Caller, Function)) {
5637         Candidate.Viable = false;
5638         Candidate.FailureKind = ovl_fail_bad_target;
5639         return;
5640       }
5641 
5642   // Determine the implicit conversion sequences for each of the
5643   // arguments.
5644   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5645     if (ArgIdx < NumParams) {
5646       // (C++ 13.3.2p3): for F to be a viable function, there shall
5647       // exist for each argument an implicit conversion sequence
5648       // (13.3.3.1) that converts that argument to the corresponding
5649       // parameter of F.
5650       QualType ParamType = Proto->getParamType(ArgIdx);
5651       Candidate.Conversions[ArgIdx]
5652         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5653                                 SuppressUserConversions,
5654                                 /*InOverloadResolution=*/true,
5655                                 /*AllowObjCWritebackConversion=*/
5656                                   getLangOpts().ObjCAutoRefCount,
5657                                 AllowExplicit);
5658       if (Candidate.Conversions[ArgIdx].isBad()) {
5659         Candidate.Viable = false;
5660         Candidate.FailureKind = ovl_fail_bad_conversion;
5661         return;
5662       }
5663     } else {
5664       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5665       // argument for which there is no corresponding parameter is
5666       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5667       Candidate.Conversions[ArgIdx].setEllipsis();
5668     }
5669   }
5670 
5671   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5672     Candidate.Viable = false;
5673     Candidate.FailureKind = ovl_fail_enable_if;
5674     Candidate.DeductionFailure.Data = FailedAttr;
5675     return;
5676   }
5677 }
5678 
IsNotEnableIfAttr(Attr * A)5679 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5680 
CheckEnableIf(FunctionDecl * Function,ArrayRef<Expr * > Args,bool MissingImplicitThis)5681 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5682                                   bool MissingImplicitThis) {
5683   // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5684   // we need to find the first failing one.
5685   if (!Function->hasAttrs())
5686     return nullptr;
5687   AttrVec Attrs = Function->getAttrs();
5688   AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5689                                        IsNotEnableIfAttr);
5690   if (Attrs.begin() == E)
5691     return nullptr;
5692   std::reverse(Attrs.begin(), E);
5693 
5694   SFINAETrap Trap(*this);
5695 
5696   // Convert the arguments.
5697   SmallVector<Expr *, 16> ConvertedArgs;
5698   bool InitializationFailed = false;
5699   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5700     if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5701         !cast<CXXMethodDecl>(Function)->isStatic() &&
5702         !isa<CXXConstructorDecl>(Function)) {
5703       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5704       ExprResult R =
5705         PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5706                                             Method, Method);
5707       if (R.isInvalid()) {
5708         InitializationFailed = true;
5709         break;
5710       }
5711       ConvertedArgs.push_back(R.get());
5712     } else {
5713       ExprResult R =
5714         PerformCopyInitialization(InitializedEntity::InitializeParameter(
5715                                                 Context,
5716                                                 Function->getParamDecl(i)),
5717                                   SourceLocation(),
5718                                   Args[i]);
5719       if (R.isInvalid()) {
5720         InitializationFailed = true;
5721         break;
5722       }
5723       ConvertedArgs.push_back(R.get());
5724     }
5725   }
5726 
5727   if (InitializationFailed || Trap.hasErrorOccurred())
5728     return cast<EnableIfAttr>(Attrs[0]);
5729 
5730   for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5731     APValue Result;
5732     EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5733     if (!EIA->getCond()->EvaluateWithSubstitution(
5734             Result, Context, Function,
5735             ArrayRef<const Expr*>(ConvertedArgs.data(),
5736                                   ConvertedArgs.size())) ||
5737         !Result.isInt() || !Result.getInt().getBoolValue()) {
5738       return EIA;
5739     }
5740   }
5741   return nullptr;
5742 }
5743 
5744 /// \brief Add all of the function declarations in the given function set to
5745 /// the overload candidate set.
AddFunctionCandidates(const UnresolvedSetImpl & Fns,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,TemplateArgumentListInfo * ExplicitTemplateArgs)5746 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5747                                  ArrayRef<Expr *> Args,
5748                                  OverloadCandidateSet& CandidateSet,
5749                                  bool SuppressUserConversions,
5750                                TemplateArgumentListInfo *ExplicitTemplateArgs) {
5751   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5752     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5753     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5754       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5755         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5756                            cast<CXXMethodDecl>(FD)->getParent(),
5757                            Args[0]->getType(), Args[0]->Classify(Context),
5758                            Args.slice(1), CandidateSet,
5759                            SuppressUserConversions);
5760       else
5761         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5762                              SuppressUserConversions);
5763     } else {
5764       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5765       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5766           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5767         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5768                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5769                                    ExplicitTemplateArgs,
5770                                    Args[0]->getType(),
5771                                    Args[0]->Classify(Context), Args.slice(1),
5772                                    CandidateSet, SuppressUserConversions);
5773       else
5774         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5775                                      ExplicitTemplateArgs, Args,
5776                                      CandidateSet, SuppressUserConversions);
5777     }
5778   }
5779 }
5780 
5781 /// AddMethodCandidate - Adds a named decl (which is some kind of
5782 /// method) as a method candidate to the given overload set.
AddMethodCandidate(DeclAccessPair FoundDecl,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions)5783 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5784                               QualType ObjectType,
5785                               Expr::Classification ObjectClassification,
5786                               ArrayRef<Expr *> Args,
5787                               OverloadCandidateSet& CandidateSet,
5788                               bool SuppressUserConversions) {
5789   NamedDecl *Decl = FoundDecl.getDecl();
5790   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5791 
5792   if (isa<UsingShadowDecl>(Decl))
5793     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5794 
5795   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5796     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5797            "Expected a member function template");
5798     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5799                                /*ExplicitArgs*/ nullptr,
5800                                ObjectType, ObjectClassification,
5801                                Args, CandidateSet,
5802                                SuppressUserConversions);
5803   } else {
5804     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5805                        ObjectType, ObjectClassification,
5806                        Args,
5807                        CandidateSet, SuppressUserConversions);
5808   }
5809 }
5810 
5811 /// AddMethodCandidate - Adds the given C++ member function to the set
5812 /// of candidate functions, using the given function call arguments
5813 /// and the object argument (@c Object). For example, in a call
5814 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5815 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5816 /// allow user-defined conversions via constructors or conversion
5817 /// operators.
5818 void
AddMethodCandidate(CXXMethodDecl * Method,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions)5819 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5820                          CXXRecordDecl *ActingContext, QualType ObjectType,
5821                          Expr::Classification ObjectClassification,
5822                          ArrayRef<Expr *> Args,
5823                          OverloadCandidateSet &CandidateSet,
5824                          bool SuppressUserConversions) {
5825   const FunctionProtoType *Proto
5826     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5827   assert(Proto && "Methods without a prototype cannot be overloaded");
5828   assert(!isa<CXXConstructorDecl>(Method) &&
5829          "Use AddOverloadCandidate for constructors");
5830 
5831   if (!CandidateSet.isNewCandidate(Method))
5832     return;
5833 
5834   // C++11 [class.copy]p23: [DR1402]
5835   //   A defaulted move assignment operator that is defined as deleted is
5836   //   ignored by overload resolution.
5837   if (Method->isDefaulted() && Method->isDeleted() &&
5838       Method->isMoveAssignmentOperator())
5839     return;
5840 
5841   // Overload resolution is always an unevaluated context.
5842   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5843 
5844   // Add this candidate
5845   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5846   Candidate.FoundDecl = FoundDecl;
5847   Candidate.Function = Method;
5848   Candidate.IsSurrogate = false;
5849   Candidate.IgnoreObjectArgument = false;
5850   Candidate.ExplicitCallArguments = Args.size();
5851 
5852   unsigned NumParams = Proto->getNumParams();
5853 
5854   // (C++ 13.3.2p2): A candidate function having fewer than m
5855   // parameters is viable only if it has an ellipsis in its parameter
5856   // list (8.3.5).
5857   if (Args.size() > NumParams && !Proto->isVariadic()) {
5858     Candidate.Viable = false;
5859     Candidate.FailureKind = ovl_fail_too_many_arguments;
5860     return;
5861   }
5862 
5863   // (C++ 13.3.2p2): A candidate function having more than m parameters
5864   // is viable only if the (m+1)st parameter has a default argument
5865   // (8.3.6). For the purposes of overload resolution, the
5866   // parameter list is truncated on the right, so that there are
5867   // exactly m parameters.
5868   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5869   if (Args.size() < MinRequiredArgs) {
5870     // Not enough arguments.
5871     Candidate.Viable = false;
5872     Candidate.FailureKind = ovl_fail_too_few_arguments;
5873     return;
5874   }
5875 
5876   Candidate.Viable = true;
5877 
5878   if (Method->isStatic() || ObjectType.isNull())
5879     // The implicit object argument is ignored.
5880     Candidate.IgnoreObjectArgument = true;
5881   else {
5882     // Determine the implicit conversion sequence for the object
5883     // parameter.
5884     Candidate.Conversions[0]
5885       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5886                                         Method, ActingContext);
5887     if (Candidate.Conversions[0].isBad()) {
5888       Candidate.Viable = false;
5889       Candidate.FailureKind = ovl_fail_bad_conversion;
5890       return;
5891     }
5892   }
5893 
5894   // Determine the implicit conversion sequences for each of the
5895   // arguments.
5896   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5897     if (ArgIdx < NumParams) {
5898       // (C++ 13.3.2p3): for F to be a viable function, there shall
5899       // exist for each argument an implicit conversion sequence
5900       // (13.3.3.1) that converts that argument to the corresponding
5901       // parameter of F.
5902       QualType ParamType = Proto->getParamType(ArgIdx);
5903       Candidate.Conversions[ArgIdx + 1]
5904         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5905                                 SuppressUserConversions,
5906                                 /*InOverloadResolution=*/true,
5907                                 /*AllowObjCWritebackConversion=*/
5908                                   getLangOpts().ObjCAutoRefCount);
5909       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5910         Candidate.Viable = false;
5911         Candidate.FailureKind = ovl_fail_bad_conversion;
5912         return;
5913       }
5914     } else {
5915       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5916       // argument for which there is no corresponding parameter is
5917       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
5918       Candidate.Conversions[ArgIdx + 1].setEllipsis();
5919     }
5920   }
5921 
5922   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
5923     Candidate.Viable = false;
5924     Candidate.FailureKind = ovl_fail_enable_if;
5925     Candidate.DeductionFailure.Data = FailedAttr;
5926     return;
5927   }
5928 }
5929 
5930 /// \brief Add a C++ member function template as a candidate to the candidate
5931 /// set, using template argument deduction to produce an appropriate member
5932 /// function template specialization.
5933 void
AddMethodTemplateCandidate(FunctionTemplateDecl * MethodTmpl,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,TemplateArgumentListInfo * ExplicitTemplateArgs,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions)5934 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5935                                  DeclAccessPair FoundDecl,
5936                                  CXXRecordDecl *ActingContext,
5937                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5938                                  QualType ObjectType,
5939                                  Expr::Classification ObjectClassification,
5940                                  ArrayRef<Expr *> Args,
5941                                  OverloadCandidateSet& CandidateSet,
5942                                  bool SuppressUserConversions) {
5943   if (!CandidateSet.isNewCandidate(MethodTmpl))
5944     return;
5945 
5946   // C++ [over.match.funcs]p7:
5947   //   In each case where a candidate is a function template, candidate
5948   //   function template specializations are generated using template argument
5949   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5950   //   candidate functions in the usual way.113) A given name can refer to one
5951   //   or more function templates and also to a set of overloaded non-template
5952   //   functions. In such a case, the candidate functions generated from each
5953   //   function template are combined with the set of non-template candidate
5954   //   functions.
5955   TemplateDeductionInfo Info(CandidateSet.getLocation());
5956   FunctionDecl *Specialization = nullptr;
5957   if (TemplateDeductionResult Result
5958       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5959                                 Specialization, Info)) {
5960     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5961     Candidate.FoundDecl = FoundDecl;
5962     Candidate.Function = MethodTmpl->getTemplatedDecl();
5963     Candidate.Viable = false;
5964     Candidate.FailureKind = ovl_fail_bad_deduction;
5965     Candidate.IsSurrogate = false;
5966     Candidate.IgnoreObjectArgument = false;
5967     Candidate.ExplicitCallArguments = Args.size();
5968     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5969                                                           Info);
5970     return;
5971   }
5972 
5973   // Add the function template specialization produced by template argument
5974   // deduction as a candidate.
5975   assert(Specialization && "Missing member function template specialization?");
5976   assert(isa<CXXMethodDecl>(Specialization) &&
5977          "Specialization is not a member function?");
5978   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5979                      ActingContext, ObjectType, ObjectClassification, Args,
5980                      CandidateSet, SuppressUserConversions);
5981 }
5982 
5983 /// \brief Add a C++ function template specialization as a candidate
5984 /// in the candidate set, using template argument deduction to produce
5985 /// an appropriate function template specialization.
5986 void
AddTemplateOverloadCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions)5987 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5988                                    DeclAccessPair FoundDecl,
5989                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5990                                    ArrayRef<Expr *> Args,
5991                                    OverloadCandidateSet& CandidateSet,
5992                                    bool SuppressUserConversions) {
5993   if (!CandidateSet.isNewCandidate(FunctionTemplate))
5994     return;
5995 
5996   // C++ [over.match.funcs]p7:
5997   //   In each case where a candidate is a function template, candidate
5998   //   function template specializations are generated using template argument
5999   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6000   //   candidate functions in the usual way.113) A given name can refer to one
6001   //   or more function templates and also to a set of overloaded non-template
6002   //   functions. In such a case, the candidate functions generated from each
6003   //   function template are combined with the set of non-template candidate
6004   //   functions.
6005   TemplateDeductionInfo Info(CandidateSet.getLocation());
6006   FunctionDecl *Specialization = nullptr;
6007   if (TemplateDeductionResult Result
6008         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6009                                   Specialization, Info)) {
6010     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6011     Candidate.FoundDecl = FoundDecl;
6012     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6013     Candidate.Viable = false;
6014     Candidate.FailureKind = ovl_fail_bad_deduction;
6015     Candidate.IsSurrogate = false;
6016     Candidate.IgnoreObjectArgument = false;
6017     Candidate.ExplicitCallArguments = Args.size();
6018     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6019                                                           Info);
6020     return;
6021   }
6022 
6023   // Add the function template specialization produced by template argument
6024   // deduction as a candidate.
6025   assert(Specialization && "Missing function template specialization?");
6026   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6027                        SuppressUserConversions);
6028 }
6029 
6030 /// Determine whether this is an allowable conversion from the result
6031 /// of an explicit conversion operator to the expected type, per C++
6032 /// [over.match.conv]p1 and [over.match.ref]p1.
6033 ///
6034 /// \param ConvType The return type of the conversion function.
6035 ///
6036 /// \param ToType The type we are converting to.
6037 ///
6038 /// \param AllowObjCPointerConversion Allow a conversion from one
6039 /// Objective-C pointer to another.
6040 ///
6041 /// \returns true if the conversion is allowable, false otherwise.
isAllowableExplicitConversion(Sema & S,QualType ConvType,QualType ToType,bool AllowObjCPointerConversion)6042 static bool isAllowableExplicitConversion(Sema &S,
6043                                           QualType ConvType, QualType ToType,
6044                                           bool AllowObjCPointerConversion) {
6045   QualType ToNonRefType = ToType.getNonReferenceType();
6046 
6047   // Easy case: the types are the same.
6048   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6049     return true;
6050 
6051   // Allow qualification conversions.
6052   bool ObjCLifetimeConversion;
6053   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6054                                   ObjCLifetimeConversion))
6055     return true;
6056 
6057   // If we're not allowed to consider Objective-C pointer conversions,
6058   // we're done.
6059   if (!AllowObjCPointerConversion)
6060     return false;
6061 
6062   // Is this an Objective-C pointer conversion?
6063   bool IncompatibleObjC = false;
6064   QualType ConvertedType;
6065   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6066                                    IncompatibleObjC);
6067 }
6068 
6069 /// AddConversionCandidate - Add a C++ conversion function as a
6070 /// candidate in the candidate set (C++ [over.match.conv],
6071 /// C++ [over.match.copy]). From is the expression we're converting from,
6072 /// and ToType is the type that we're eventually trying to convert to
6073 /// (which may or may not be the same type as the type that the
6074 /// conversion function produces).
6075 void
AddConversionCandidate(CXXConversionDecl * Conversion,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet,bool AllowObjCConversionOnExplicit)6076 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6077                              DeclAccessPair FoundDecl,
6078                              CXXRecordDecl *ActingContext,
6079                              Expr *From, QualType ToType,
6080                              OverloadCandidateSet& CandidateSet,
6081                              bool AllowObjCConversionOnExplicit) {
6082   assert(!Conversion->getDescribedFunctionTemplate() &&
6083          "Conversion function templates use AddTemplateConversionCandidate");
6084   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6085   if (!CandidateSet.isNewCandidate(Conversion))
6086     return;
6087 
6088   // If the conversion function has an undeduced return type, trigger its
6089   // deduction now.
6090   if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
6091     if (DeduceReturnType(Conversion, From->getExprLoc()))
6092       return;
6093     ConvType = Conversion->getConversionType().getNonReferenceType();
6094   }
6095 
6096   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6097   // operator is only a candidate if its return type is the target type or
6098   // can be converted to the target type with a qualification conversion.
6099   if (Conversion->isExplicit() &&
6100       !isAllowableExplicitConversion(*this, ConvType, ToType,
6101                                      AllowObjCConversionOnExplicit))
6102     return;
6103 
6104   // Overload resolution is always an unevaluated context.
6105   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6106 
6107   // Add this candidate
6108   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6109   Candidate.FoundDecl = FoundDecl;
6110   Candidate.Function = Conversion;
6111   Candidate.IsSurrogate = false;
6112   Candidate.IgnoreObjectArgument = false;
6113   Candidate.FinalConversion.setAsIdentityConversion();
6114   Candidate.FinalConversion.setFromType(ConvType);
6115   Candidate.FinalConversion.setAllToTypes(ToType);
6116   Candidate.Viable = true;
6117   Candidate.ExplicitCallArguments = 1;
6118 
6119   // C++ [over.match.funcs]p4:
6120   //   For conversion functions, the function is considered to be a member of
6121   //   the class of the implicit implied object argument for the purpose of
6122   //   defining the type of the implicit object parameter.
6123   //
6124   // Determine the implicit conversion sequence for the implicit
6125   // object parameter.
6126   QualType ImplicitParamType = From->getType();
6127   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6128     ImplicitParamType = FromPtrType->getPointeeType();
6129   CXXRecordDecl *ConversionContext
6130     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6131 
6132   Candidate.Conversions[0]
6133     = TryObjectArgumentInitialization(*this, From->getType(),
6134                                       From->Classify(Context),
6135                                       Conversion, ConversionContext);
6136 
6137   if (Candidate.Conversions[0].isBad()) {
6138     Candidate.Viable = false;
6139     Candidate.FailureKind = ovl_fail_bad_conversion;
6140     return;
6141   }
6142 
6143   // We won't go through a user-defined type conversion function to convert a
6144   // derived to base as such conversions are given Conversion Rank. They only
6145   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6146   QualType FromCanon
6147     = Context.getCanonicalType(From->getType().getUnqualifiedType());
6148   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6149   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6150     Candidate.Viable = false;
6151     Candidate.FailureKind = ovl_fail_trivial_conversion;
6152     return;
6153   }
6154 
6155   // To determine what the conversion from the result of calling the
6156   // conversion function to the type we're eventually trying to
6157   // convert to (ToType), we need to synthesize a call to the
6158   // conversion function and attempt copy initialization from it. This
6159   // makes sure that we get the right semantics with respect to
6160   // lvalues/rvalues and the type. Fortunately, we can allocate this
6161   // call on the stack and we don't need its arguments to be
6162   // well-formed.
6163   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6164                             VK_LValue, From->getLocStart());
6165   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6166                                 Context.getPointerType(Conversion->getType()),
6167                                 CK_FunctionToPointerDecay,
6168                                 &ConversionRef, VK_RValue);
6169 
6170   QualType ConversionType = Conversion->getConversionType();
6171   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
6172     Candidate.Viable = false;
6173     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6174     return;
6175   }
6176 
6177   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6178 
6179   // Note that it is safe to allocate CallExpr on the stack here because
6180   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6181   // allocator).
6182   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6183   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6184                 From->getLocStart());
6185   ImplicitConversionSequence ICS =
6186     TryCopyInitialization(*this, &Call, ToType,
6187                           /*SuppressUserConversions=*/true,
6188                           /*InOverloadResolution=*/false,
6189                           /*AllowObjCWritebackConversion=*/false);
6190 
6191   switch (ICS.getKind()) {
6192   case ImplicitConversionSequence::StandardConversion:
6193     Candidate.FinalConversion = ICS.Standard;
6194 
6195     // C++ [over.ics.user]p3:
6196     //   If the user-defined conversion is specified by a specialization of a
6197     //   conversion function template, the second standard conversion sequence
6198     //   shall have exact match rank.
6199     if (Conversion->getPrimaryTemplate() &&
6200         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6201       Candidate.Viable = false;
6202       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6203       return;
6204     }
6205 
6206     // C++0x [dcl.init.ref]p5:
6207     //    In the second case, if the reference is an rvalue reference and
6208     //    the second standard conversion sequence of the user-defined
6209     //    conversion sequence includes an lvalue-to-rvalue conversion, the
6210     //    program is ill-formed.
6211     if (ToType->isRValueReferenceType() &&
6212         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6213       Candidate.Viable = false;
6214       Candidate.FailureKind = ovl_fail_bad_final_conversion;
6215       return;
6216     }
6217     break;
6218 
6219   case ImplicitConversionSequence::BadConversion:
6220     Candidate.Viable = false;
6221     Candidate.FailureKind = ovl_fail_bad_final_conversion;
6222     return;
6223 
6224   default:
6225     llvm_unreachable(
6226            "Can only end up with a standard conversion sequence or failure");
6227   }
6228 
6229   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6230     Candidate.Viable = false;
6231     Candidate.FailureKind = ovl_fail_enable_if;
6232     Candidate.DeductionFailure.Data = FailedAttr;
6233     return;
6234   }
6235 }
6236 
6237 /// \brief Adds a conversion function template specialization
6238 /// candidate to the overload set, using template argument deduction
6239 /// to deduce the template arguments of the conversion function
6240 /// template from the type that we are converting to (C++
6241 /// [temp.deduct.conv]).
6242 void
AddTemplateConversionCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,CXXRecordDecl * ActingDC,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet,bool AllowObjCConversionOnExplicit)6243 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6244                                      DeclAccessPair FoundDecl,
6245                                      CXXRecordDecl *ActingDC,
6246                                      Expr *From, QualType ToType,
6247                                      OverloadCandidateSet &CandidateSet,
6248                                      bool AllowObjCConversionOnExplicit) {
6249   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6250          "Only conversion function templates permitted here");
6251 
6252   if (!CandidateSet.isNewCandidate(FunctionTemplate))
6253     return;
6254 
6255   TemplateDeductionInfo Info(CandidateSet.getLocation());
6256   CXXConversionDecl *Specialization = nullptr;
6257   if (TemplateDeductionResult Result
6258         = DeduceTemplateArguments(FunctionTemplate, ToType,
6259                                   Specialization, Info)) {
6260     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6261     Candidate.FoundDecl = FoundDecl;
6262     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6263     Candidate.Viable = false;
6264     Candidate.FailureKind = ovl_fail_bad_deduction;
6265     Candidate.IsSurrogate = false;
6266     Candidate.IgnoreObjectArgument = false;
6267     Candidate.ExplicitCallArguments = 1;
6268     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6269                                                           Info);
6270     return;
6271   }
6272 
6273   // Add the conversion function template specialization produced by
6274   // template argument deduction as a candidate.
6275   assert(Specialization && "Missing function template specialization?");
6276   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6277                          CandidateSet, AllowObjCConversionOnExplicit);
6278 }
6279 
6280 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6281 /// converts the given @c Object to a function pointer via the
6282 /// conversion function @c Conversion, and then attempts to call it
6283 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6284 /// the type of function that we'll eventually be calling.
AddSurrogateCandidate(CXXConversionDecl * Conversion,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,const FunctionProtoType * Proto,Expr * Object,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)6285 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6286                                  DeclAccessPair FoundDecl,
6287                                  CXXRecordDecl *ActingContext,
6288                                  const FunctionProtoType *Proto,
6289                                  Expr *Object,
6290                                  ArrayRef<Expr *> Args,
6291                                  OverloadCandidateSet& CandidateSet) {
6292   if (!CandidateSet.isNewCandidate(Conversion))
6293     return;
6294 
6295   // Overload resolution is always an unevaluated context.
6296   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6297 
6298   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6299   Candidate.FoundDecl = FoundDecl;
6300   Candidate.Function = nullptr;
6301   Candidate.Surrogate = Conversion;
6302   Candidate.Viable = true;
6303   Candidate.IsSurrogate = true;
6304   Candidate.IgnoreObjectArgument = false;
6305   Candidate.ExplicitCallArguments = Args.size();
6306 
6307   // Determine the implicit conversion sequence for the implicit
6308   // object parameter.
6309   ImplicitConversionSequence ObjectInit
6310     = TryObjectArgumentInitialization(*this, Object->getType(),
6311                                       Object->Classify(Context),
6312                                       Conversion, ActingContext);
6313   if (ObjectInit.isBad()) {
6314     Candidate.Viable = false;
6315     Candidate.FailureKind = ovl_fail_bad_conversion;
6316     Candidate.Conversions[0] = ObjectInit;
6317     return;
6318   }
6319 
6320   // The first conversion is actually a user-defined conversion whose
6321   // first conversion is ObjectInit's standard conversion (which is
6322   // effectively a reference binding). Record it as such.
6323   Candidate.Conversions[0].setUserDefined();
6324   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6325   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6326   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6327   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6328   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6329   Candidate.Conversions[0].UserDefined.After
6330     = Candidate.Conversions[0].UserDefined.Before;
6331   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6332 
6333   // Find the
6334   unsigned NumParams = Proto->getNumParams();
6335 
6336   // (C++ 13.3.2p2): A candidate function having fewer than m
6337   // parameters is viable only if it has an ellipsis in its parameter
6338   // list (8.3.5).
6339   if (Args.size() > NumParams && !Proto->isVariadic()) {
6340     Candidate.Viable = false;
6341     Candidate.FailureKind = ovl_fail_too_many_arguments;
6342     return;
6343   }
6344 
6345   // Function types don't have any default arguments, so just check if
6346   // we have enough arguments.
6347   if (Args.size() < NumParams) {
6348     // Not enough arguments.
6349     Candidate.Viable = false;
6350     Candidate.FailureKind = ovl_fail_too_few_arguments;
6351     return;
6352   }
6353 
6354   // Determine the implicit conversion sequences for each of the
6355   // arguments.
6356   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6357     if (ArgIdx < NumParams) {
6358       // (C++ 13.3.2p3): for F to be a viable function, there shall
6359       // exist for each argument an implicit conversion sequence
6360       // (13.3.3.1) that converts that argument to the corresponding
6361       // parameter of F.
6362       QualType ParamType = Proto->getParamType(ArgIdx);
6363       Candidate.Conversions[ArgIdx + 1]
6364         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6365                                 /*SuppressUserConversions=*/false,
6366                                 /*InOverloadResolution=*/false,
6367                                 /*AllowObjCWritebackConversion=*/
6368                                   getLangOpts().ObjCAutoRefCount);
6369       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6370         Candidate.Viable = false;
6371         Candidate.FailureKind = ovl_fail_bad_conversion;
6372         return;
6373       }
6374     } else {
6375       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6376       // argument for which there is no corresponding parameter is
6377       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6378       Candidate.Conversions[ArgIdx + 1].setEllipsis();
6379     }
6380   }
6381 
6382   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6383     Candidate.Viable = false;
6384     Candidate.FailureKind = ovl_fail_enable_if;
6385     Candidate.DeductionFailure.Data = FailedAttr;
6386     return;
6387   }
6388 }
6389 
6390 /// \brief Add overload candidates for overloaded operators that are
6391 /// member functions.
6392 ///
6393 /// Add the overloaded operator candidates that are member functions
6394 /// for the operator Op that was used in an operator expression such
6395 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6396 /// CandidateSet will store the added overload candidates. (C++
6397 /// [over.match.oper]).
AddMemberOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,SourceRange OpRange)6398 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6399                                        SourceLocation OpLoc,
6400                                        ArrayRef<Expr *> Args,
6401                                        OverloadCandidateSet& CandidateSet,
6402                                        SourceRange OpRange) {
6403   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6404 
6405   // C++ [over.match.oper]p3:
6406   //   For a unary operator @ with an operand of a type whose
6407   //   cv-unqualified version is T1, and for a binary operator @ with
6408   //   a left operand of a type whose cv-unqualified version is T1 and
6409   //   a right operand of a type whose cv-unqualified version is T2,
6410   //   three sets of candidate functions, designated member
6411   //   candidates, non-member candidates and built-in candidates, are
6412   //   constructed as follows:
6413   QualType T1 = Args[0]->getType();
6414 
6415   //     -- If T1 is a complete class type or a class currently being
6416   //        defined, the set of member candidates is the result of the
6417   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6418   //        the set of member candidates is empty.
6419   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6420     // Complete the type if it can be completed.
6421     RequireCompleteType(OpLoc, T1, 0);
6422     // If the type is neither complete nor being defined, bail out now.
6423     if (!T1Rec->getDecl()->getDefinition())
6424       return;
6425 
6426     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6427     LookupQualifiedName(Operators, T1Rec->getDecl());
6428     Operators.suppressDiagnostics();
6429 
6430     for (LookupResult::iterator Oper = Operators.begin(),
6431                              OperEnd = Operators.end();
6432          Oper != OperEnd;
6433          ++Oper)
6434       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6435                          Args[0]->Classify(Context),
6436                          Args.slice(1),
6437                          CandidateSet,
6438                          /* SuppressUserConversions = */ false);
6439   }
6440 }
6441 
6442 /// AddBuiltinCandidate - Add a candidate for a built-in
6443 /// operator. ResultTy and ParamTys are the result and parameter types
6444 /// of the built-in candidate, respectively. Args and NumArgs are the
6445 /// arguments being passed to the candidate. IsAssignmentOperator
6446 /// should be true when this built-in candidate is an assignment
6447 /// operator. NumContextualBoolArguments is the number of arguments
6448 /// (at the beginning of the argument list) that will be contextually
6449 /// converted to bool.
AddBuiltinCandidate(QualType ResultTy,QualType * ParamTys,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool IsAssignmentOperator,unsigned NumContextualBoolArguments)6450 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6451                                ArrayRef<Expr *> Args,
6452                                OverloadCandidateSet& CandidateSet,
6453                                bool IsAssignmentOperator,
6454                                unsigned NumContextualBoolArguments) {
6455   // Overload resolution is always an unevaluated context.
6456   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6457 
6458   // Add this candidate
6459   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6460   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6461   Candidate.Function = nullptr;
6462   Candidate.IsSurrogate = false;
6463   Candidate.IgnoreObjectArgument = false;
6464   Candidate.BuiltinTypes.ResultTy = ResultTy;
6465   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6466     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6467 
6468   // Determine the implicit conversion sequences for each of the
6469   // arguments.
6470   Candidate.Viable = true;
6471   Candidate.ExplicitCallArguments = Args.size();
6472   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6473     // C++ [over.match.oper]p4:
6474     //   For the built-in assignment operators, conversions of the
6475     //   left operand are restricted as follows:
6476     //     -- no temporaries are introduced to hold the left operand, and
6477     //     -- no user-defined conversions are applied to the left
6478     //        operand to achieve a type match with the left-most
6479     //        parameter of a built-in candidate.
6480     //
6481     // We block these conversions by turning off user-defined
6482     // conversions, since that is the only way that initialization of
6483     // a reference to a non-class type can occur from something that
6484     // is not of the same type.
6485     if (ArgIdx < NumContextualBoolArguments) {
6486       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6487              "Contextual conversion to bool requires bool type");
6488       Candidate.Conversions[ArgIdx]
6489         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6490     } else {
6491       Candidate.Conversions[ArgIdx]
6492         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6493                                 ArgIdx == 0 && IsAssignmentOperator,
6494                                 /*InOverloadResolution=*/false,
6495                                 /*AllowObjCWritebackConversion=*/
6496                                   getLangOpts().ObjCAutoRefCount);
6497     }
6498     if (Candidate.Conversions[ArgIdx].isBad()) {
6499       Candidate.Viable = false;
6500       Candidate.FailureKind = ovl_fail_bad_conversion;
6501       break;
6502     }
6503   }
6504 }
6505 
6506 namespace {
6507 
6508 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6509 /// candidate operator functions for built-in operators (C++
6510 /// [over.built]). The types are separated into pointer types and
6511 /// enumeration types.
6512 class BuiltinCandidateTypeSet  {
6513   /// TypeSet - A set of types.
6514   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6515 
6516   /// PointerTypes - The set of pointer types that will be used in the
6517   /// built-in candidates.
6518   TypeSet PointerTypes;
6519 
6520   /// MemberPointerTypes - The set of member pointer types that will be
6521   /// used in the built-in candidates.
6522   TypeSet MemberPointerTypes;
6523 
6524   /// EnumerationTypes - The set of enumeration types that will be
6525   /// used in the built-in candidates.
6526   TypeSet EnumerationTypes;
6527 
6528   /// \brief The set of vector types that will be used in the built-in
6529   /// candidates.
6530   TypeSet VectorTypes;
6531 
6532   /// \brief A flag indicating non-record types are viable candidates
6533   bool HasNonRecordTypes;
6534 
6535   /// \brief A flag indicating whether either arithmetic or enumeration types
6536   /// were present in the candidate set.
6537   bool HasArithmeticOrEnumeralTypes;
6538 
6539   /// \brief A flag indicating whether the nullptr type was present in the
6540   /// candidate set.
6541   bool HasNullPtrType;
6542 
6543   /// Sema - The semantic analysis instance where we are building the
6544   /// candidate type set.
6545   Sema &SemaRef;
6546 
6547   /// Context - The AST context in which we will build the type sets.
6548   ASTContext &Context;
6549 
6550   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6551                                                const Qualifiers &VisibleQuals);
6552   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6553 
6554 public:
6555   /// iterator - Iterates through the types that are part of the set.
6556   typedef TypeSet::iterator iterator;
6557 
BuiltinCandidateTypeSet(Sema & SemaRef)6558   BuiltinCandidateTypeSet(Sema &SemaRef)
6559     : HasNonRecordTypes(false),
6560       HasArithmeticOrEnumeralTypes(false),
6561       HasNullPtrType(false),
6562       SemaRef(SemaRef),
6563       Context(SemaRef.Context) { }
6564 
6565   void AddTypesConvertedFrom(QualType Ty,
6566                              SourceLocation Loc,
6567                              bool AllowUserConversions,
6568                              bool AllowExplicitConversions,
6569                              const Qualifiers &VisibleTypeConversionsQuals);
6570 
6571   /// pointer_begin - First pointer type found;
pointer_begin()6572   iterator pointer_begin() { return PointerTypes.begin(); }
6573 
6574   /// pointer_end - Past the last pointer type found;
pointer_end()6575   iterator pointer_end() { return PointerTypes.end(); }
6576 
6577   /// member_pointer_begin - First member pointer type found;
member_pointer_begin()6578   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6579 
6580   /// member_pointer_end - Past the last member pointer type found;
member_pointer_end()6581   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6582 
6583   /// enumeration_begin - First enumeration type found;
enumeration_begin()6584   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6585 
6586   /// enumeration_end - Past the last enumeration type found;
enumeration_end()6587   iterator enumeration_end() { return EnumerationTypes.end(); }
6588 
vector_begin()6589   iterator vector_begin() { return VectorTypes.begin(); }
vector_end()6590   iterator vector_end() { return VectorTypes.end(); }
6591 
hasNonRecordTypes()6592   bool hasNonRecordTypes() { return HasNonRecordTypes; }
hasArithmeticOrEnumeralTypes()6593   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
hasNullPtrType() const6594   bool hasNullPtrType() const { return HasNullPtrType; }
6595 };
6596 
6597 } // end anonymous namespace
6598 
6599 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6600 /// the set of pointer types along with any more-qualified variants of
6601 /// that type. For example, if @p Ty is "int const *", this routine
6602 /// will add "int const *", "int const volatile *", "int const
6603 /// restrict *", and "int const volatile restrict *" to the set of
6604 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6605 /// false otherwise.
6606 ///
6607 /// FIXME: what to do about extended qualifiers?
6608 bool
AddPointerWithMoreQualifiedTypeVariants(QualType Ty,const Qualifiers & VisibleQuals)6609 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6610                                              const Qualifiers &VisibleQuals) {
6611 
6612   // Insert this type.
6613   if (!PointerTypes.insert(Ty))
6614     return false;
6615 
6616   QualType PointeeTy;
6617   const PointerType *PointerTy = Ty->getAs<PointerType>();
6618   bool buildObjCPtr = false;
6619   if (!PointerTy) {
6620     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6621     PointeeTy = PTy->getPointeeType();
6622     buildObjCPtr = true;
6623   } else {
6624     PointeeTy = PointerTy->getPointeeType();
6625   }
6626 
6627   // Don't add qualified variants of arrays. For one, they're not allowed
6628   // (the qualifier would sink to the element type), and for another, the
6629   // only overload situation where it matters is subscript or pointer +- int,
6630   // and those shouldn't have qualifier variants anyway.
6631   if (PointeeTy->isArrayType())
6632     return true;
6633 
6634   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6635   bool hasVolatile = VisibleQuals.hasVolatile();
6636   bool hasRestrict = VisibleQuals.hasRestrict();
6637 
6638   // Iterate through all strict supersets of BaseCVR.
6639   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6640     if ((CVR | BaseCVR) != CVR) continue;
6641     // Skip over volatile if no volatile found anywhere in the types.
6642     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6643 
6644     // Skip over restrict if no restrict found anywhere in the types, or if
6645     // the type cannot be restrict-qualified.
6646     if ((CVR & Qualifiers::Restrict) &&
6647         (!hasRestrict ||
6648          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6649       continue;
6650 
6651     // Build qualified pointee type.
6652     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6653 
6654     // Build qualified pointer type.
6655     QualType QPointerTy;
6656     if (!buildObjCPtr)
6657       QPointerTy = Context.getPointerType(QPointeeTy);
6658     else
6659       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6660 
6661     // Insert qualified pointer type.
6662     PointerTypes.insert(QPointerTy);
6663   }
6664 
6665   return true;
6666 }
6667 
6668 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6669 /// to the set of pointer types along with any more-qualified variants of
6670 /// that type. For example, if @p Ty is "int const *", this routine
6671 /// will add "int const *", "int const volatile *", "int const
6672 /// restrict *", and "int const volatile restrict *" to the set of
6673 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6674 /// false otherwise.
6675 ///
6676 /// FIXME: what to do about extended qualifiers?
6677 bool
AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty)6678 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6679     QualType Ty) {
6680   // Insert this type.
6681   if (!MemberPointerTypes.insert(Ty))
6682     return false;
6683 
6684   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6685   assert(PointerTy && "type was not a member pointer type!");
6686 
6687   QualType PointeeTy = PointerTy->getPointeeType();
6688   // Don't add qualified variants of arrays. For one, they're not allowed
6689   // (the qualifier would sink to the element type), and for another, the
6690   // only overload situation where it matters is subscript or pointer +- int,
6691   // and those shouldn't have qualifier variants anyway.
6692   if (PointeeTy->isArrayType())
6693     return true;
6694   const Type *ClassTy = PointerTy->getClass();
6695 
6696   // Iterate through all strict supersets of the pointee type's CVR
6697   // qualifiers.
6698   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6699   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6700     if ((CVR | BaseCVR) != CVR) continue;
6701 
6702     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6703     MemberPointerTypes.insert(
6704       Context.getMemberPointerType(QPointeeTy, ClassTy));
6705   }
6706 
6707   return true;
6708 }
6709 
6710 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6711 /// Ty can be implicit converted to the given set of @p Types. We're
6712 /// primarily interested in pointer types and enumeration types. We also
6713 /// take member pointer types, for the conditional operator.
6714 /// AllowUserConversions is true if we should look at the conversion
6715 /// functions of a class type, and AllowExplicitConversions if we
6716 /// should also include the explicit conversion functions of a class
6717 /// type.
6718 void
AddTypesConvertedFrom(QualType Ty,SourceLocation Loc,bool AllowUserConversions,bool AllowExplicitConversions,const Qualifiers & VisibleQuals)6719 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6720                                                SourceLocation Loc,
6721                                                bool AllowUserConversions,
6722                                                bool AllowExplicitConversions,
6723                                                const Qualifiers &VisibleQuals) {
6724   // Only deal with canonical types.
6725   Ty = Context.getCanonicalType(Ty);
6726 
6727   // Look through reference types; they aren't part of the type of an
6728   // expression for the purposes of conversions.
6729   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6730     Ty = RefTy->getPointeeType();
6731 
6732   // If we're dealing with an array type, decay to the pointer.
6733   if (Ty->isArrayType())
6734     Ty = SemaRef.Context.getArrayDecayedType(Ty);
6735 
6736   // Otherwise, we don't care about qualifiers on the type.
6737   Ty = Ty.getLocalUnqualifiedType();
6738 
6739   // Flag if we ever add a non-record type.
6740   const RecordType *TyRec = Ty->getAs<RecordType>();
6741   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6742 
6743   // Flag if we encounter an arithmetic type.
6744   HasArithmeticOrEnumeralTypes =
6745     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6746 
6747   if (Ty->isObjCIdType() || Ty->isObjCClassType())
6748     PointerTypes.insert(Ty);
6749   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6750     // Insert our type, and its more-qualified variants, into the set
6751     // of types.
6752     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6753       return;
6754   } else if (Ty->isMemberPointerType()) {
6755     // Member pointers are far easier, since the pointee can't be converted.
6756     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6757       return;
6758   } else if (Ty->isEnumeralType()) {
6759     HasArithmeticOrEnumeralTypes = true;
6760     EnumerationTypes.insert(Ty);
6761   } else if (Ty->isVectorType()) {
6762     // We treat vector types as arithmetic types in many contexts as an
6763     // extension.
6764     HasArithmeticOrEnumeralTypes = true;
6765     VectorTypes.insert(Ty);
6766   } else if (Ty->isNullPtrType()) {
6767     HasNullPtrType = true;
6768   } else if (AllowUserConversions && TyRec) {
6769     // No conversion functions in incomplete types.
6770     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6771       return;
6772 
6773     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6774     std::pair<CXXRecordDecl::conversion_iterator,
6775               CXXRecordDecl::conversion_iterator>
6776       Conversions = ClassDecl->getVisibleConversionFunctions();
6777     for (CXXRecordDecl::conversion_iterator
6778            I = Conversions.first, E = Conversions.second; I != E; ++I) {
6779       NamedDecl *D = I.getDecl();
6780       if (isa<UsingShadowDecl>(D))
6781         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6782 
6783       // Skip conversion function templates; they don't tell us anything
6784       // about which builtin types we can convert to.
6785       if (isa<FunctionTemplateDecl>(D))
6786         continue;
6787 
6788       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6789       if (AllowExplicitConversions || !Conv->isExplicit()) {
6790         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6791                               VisibleQuals);
6792       }
6793     }
6794   }
6795 }
6796 
6797 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6798 /// the volatile- and non-volatile-qualified assignment operators for the
6799 /// given type to the candidate set.
AddBuiltinAssignmentOperatorCandidates(Sema & S,QualType T,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)6800 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6801                                                    QualType T,
6802                                                    ArrayRef<Expr *> Args,
6803                                     OverloadCandidateSet &CandidateSet) {
6804   QualType ParamTypes[2];
6805 
6806   // T& operator=(T&, T)
6807   ParamTypes[0] = S.Context.getLValueReferenceType(T);
6808   ParamTypes[1] = T;
6809   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6810                         /*IsAssignmentOperator=*/true);
6811 
6812   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6813     // volatile T& operator=(volatile T&, T)
6814     ParamTypes[0]
6815       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6816     ParamTypes[1] = T;
6817     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6818                           /*IsAssignmentOperator=*/true);
6819   }
6820 }
6821 
6822 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6823 /// if any, found in visible type conversion functions found in ArgExpr's type.
CollectVRQualifiers(ASTContext & Context,Expr * ArgExpr)6824 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6825     Qualifiers VRQuals;
6826     const RecordType *TyRec;
6827     if (const MemberPointerType *RHSMPType =
6828         ArgExpr->getType()->getAs<MemberPointerType>())
6829       TyRec = RHSMPType->getClass()->getAs<RecordType>();
6830     else
6831       TyRec = ArgExpr->getType()->getAs<RecordType>();
6832     if (!TyRec) {
6833       // Just to be safe, assume the worst case.
6834       VRQuals.addVolatile();
6835       VRQuals.addRestrict();
6836       return VRQuals;
6837     }
6838 
6839     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6840     if (!ClassDecl->hasDefinition())
6841       return VRQuals;
6842 
6843     std::pair<CXXRecordDecl::conversion_iterator,
6844               CXXRecordDecl::conversion_iterator>
6845       Conversions = ClassDecl->getVisibleConversionFunctions();
6846 
6847     for (CXXRecordDecl::conversion_iterator
6848            I = Conversions.first, E = Conversions.second; I != E; ++I) {
6849       NamedDecl *D = I.getDecl();
6850       if (isa<UsingShadowDecl>(D))
6851         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6852       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6853         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6854         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6855           CanTy = ResTypeRef->getPointeeType();
6856         // Need to go down the pointer/mempointer chain and add qualifiers
6857         // as see them.
6858         bool done = false;
6859         while (!done) {
6860           if (CanTy.isRestrictQualified())
6861             VRQuals.addRestrict();
6862           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6863             CanTy = ResTypePtr->getPointeeType();
6864           else if (const MemberPointerType *ResTypeMPtr =
6865                 CanTy->getAs<MemberPointerType>())
6866             CanTy = ResTypeMPtr->getPointeeType();
6867           else
6868             done = true;
6869           if (CanTy.isVolatileQualified())
6870             VRQuals.addVolatile();
6871           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6872             return VRQuals;
6873         }
6874       }
6875     }
6876     return VRQuals;
6877 }
6878 
6879 namespace {
6880 
6881 /// \brief Helper class to manage the addition of builtin operator overload
6882 /// candidates. It provides shared state and utility methods used throughout
6883 /// the process, as well as a helper method to add each group of builtin
6884 /// operator overloads from the standard to a candidate set.
6885 class BuiltinOperatorOverloadBuilder {
6886   // Common instance state available to all overload candidate addition methods.
6887   Sema &S;
6888   ArrayRef<Expr *> Args;
6889   Qualifiers VisibleTypeConversionsQuals;
6890   bool HasArithmeticOrEnumeralCandidateType;
6891   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6892   OverloadCandidateSet &CandidateSet;
6893 
6894   // Define some constants used to index and iterate over the arithemetic types
6895   // provided via the getArithmeticType() method below.
6896   // The "promoted arithmetic types" are the arithmetic
6897   // types are that preserved by promotion (C++ [over.built]p2).
6898   static const unsigned FirstIntegralType = 3;
6899   static const unsigned LastIntegralType = 20;
6900   static const unsigned FirstPromotedIntegralType = 3,
6901                         LastPromotedIntegralType = 11;
6902   static const unsigned FirstPromotedArithmeticType = 0,
6903                         LastPromotedArithmeticType = 11;
6904   static const unsigned NumArithmeticTypes = 20;
6905 
6906   /// \brief Get the canonical type for a given arithmetic type index.
getArithmeticType(unsigned index)6907   CanQualType getArithmeticType(unsigned index) {
6908     assert(index < NumArithmeticTypes);
6909     static CanQualType ASTContext::* const
6910       ArithmeticTypes[NumArithmeticTypes] = {
6911       // Start of promoted types.
6912       &ASTContext::FloatTy,
6913       &ASTContext::DoubleTy,
6914       &ASTContext::LongDoubleTy,
6915 
6916       // Start of integral types.
6917       &ASTContext::IntTy,
6918       &ASTContext::LongTy,
6919       &ASTContext::LongLongTy,
6920       &ASTContext::Int128Ty,
6921       &ASTContext::UnsignedIntTy,
6922       &ASTContext::UnsignedLongTy,
6923       &ASTContext::UnsignedLongLongTy,
6924       &ASTContext::UnsignedInt128Ty,
6925       // End of promoted types.
6926 
6927       &ASTContext::BoolTy,
6928       &ASTContext::CharTy,
6929       &ASTContext::WCharTy,
6930       &ASTContext::Char16Ty,
6931       &ASTContext::Char32Ty,
6932       &ASTContext::SignedCharTy,
6933       &ASTContext::ShortTy,
6934       &ASTContext::UnsignedCharTy,
6935       &ASTContext::UnsignedShortTy,
6936       // End of integral types.
6937       // FIXME: What about complex? What about half?
6938     };
6939     return S.Context.*ArithmeticTypes[index];
6940   }
6941 
6942   /// \brief Gets the canonical type resulting from the usual arithemetic
6943   /// converions for the given arithmetic types.
getUsualArithmeticConversions(unsigned L,unsigned R)6944   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6945     // Accelerator table for performing the usual arithmetic conversions.
6946     // The rules are basically:
6947     //   - if either is floating-point, use the wider floating-point
6948     //   - if same signedness, use the higher rank
6949     //   - if same size, use unsigned of the higher rank
6950     //   - use the larger type
6951     // These rules, together with the axiom that higher ranks are
6952     // never smaller, are sufficient to precompute all of these results
6953     // *except* when dealing with signed types of higher rank.
6954     // (we could precompute SLL x UI for all known platforms, but it's
6955     // better not to make any assumptions).
6956     // We assume that int128 has a higher rank than long long on all platforms.
6957     enum PromotedType {
6958             Dep=-1,
6959             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6960     };
6961     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6962                                         [LastPromotedArithmeticType] = {
6963 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6964 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6965 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6966 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6967 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6968 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6969 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6970 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6971 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6972 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6973 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6974     };
6975 
6976     assert(L < LastPromotedArithmeticType);
6977     assert(R < LastPromotedArithmeticType);
6978     int Idx = ConversionsTable[L][R];
6979 
6980     // Fast path: the table gives us a concrete answer.
6981     if (Idx != Dep) return getArithmeticType(Idx);
6982 
6983     // Slow path: we need to compare widths.
6984     // An invariant is that the signed type has higher rank.
6985     CanQualType LT = getArithmeticType(L),
6986                 RT = getArithmeticType(R);
6987     unsigned LW = S.Context.getIntWidth(LT),
6988              RW = S.Context.getIntWidth(RT);
6989 
6990     // If they're different widths, use the signed type.
6991     if (LW > RW) return LT;
6992     else if (LW < RW) return RT;
6993 
6994     // Otherwise, use the unsigned type of the signed type's rank.
6995     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6996     assert(L == SLL || R == SLL);
6997     return S.Context.UnsignedLongLongTy;
6998   }
6999 
7000   /// \brief Helper method to factor out the common pattern of adding overloads
7001   /// for '++' and '--' builtin operators.
addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,bool HasVolatile,bool HasRestrict)7002   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7003                                            bool HasVolatile,
7004                                            bool HasRestrict) {
7005     QualType ParamTypes[2] = {
7006       S.Context.getLValueReferenceType(CandidateTy),
7007       S.Context.IntTy
7008     };
7009 
7010     // Non-volatile version.
7011     if (Args.size() == 1)
7012       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7013     else
7014       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7015 
7016     // Use a heuristic to reduce number of builtin candidates in the set:
7017     // add volatile version only if there are conversions to a volatile type.
7018     if (HasVolatile) {
7019       ParamTypes[0] =
7020         S.Context.getLValueReferenceType(
7021           S.Context.getVolatileType(CandidateTy));
7022       if (Args.size() == 1)
7023         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7024       else
7025         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7026     }
7027 
7028     // Add restrict version only if there are conversions to a restrict type
7029     // and our candidate type is a non-restrict-qualified pointer.
7030     if (HasRestrict && CandidateTy->isAnyPointerType() &&
7031         !CandidateTy.isRestrictQualified()) {
7032       ParamTypes[0]
7033         = S.Context.getLValueReferenceType(
7034             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7035       if (Args.size() == 1)
7036         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7037       else
7038         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7039 
7040       if (HasVolatile) {
7041         ParamTypes[0]
7042           = S.Context.getLValueReferenceType(
7043               S.Context.getCVRQualifiedType(CandidateTy,
7044                                             (Qualifiers::Volatile |
7045                                              Qualifiers::Restrict)));
7046         if (Args.size() == 1)
7047           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7048         else
7049           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7050       }
7051     }
7052 
7053   }
7054 
7055 public:
BuiltinOperatorOverloadBuilder(Sema & S,ArrayRef<Expr * > Args,Qualifiers VisibleTypeConversionsQuals,bool HasArithmeticOrEnumeralCandidateType,SmallVectorImpl<BuiltinCandidateTypeSet> & CandidateTypes,OverloadCandidateSet & CandidateSet)7056   BuiltinOperatorOverloadBuilder(
7057     Sema &S, ArrayRef<Expr *> Args,
7058     Qualifiers VisibleTypeConversionsQuals,
7059     bool HasArithmeticOrEnumeralCandidateType,
7060     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7061     OverloadCandidateSet &CandidateSet)
7062     : S(S), Args(Args),
7063       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7064       HasArithmeticOrEnumeralCandidateType(
7065         HasArithmeticOrEnumeralCandidateType),
7066       CandidateTypes(CandidateTypes),
7067       CandidateSet(CandidateSet) {
7068     // Validate some of our static helper constants in debug builds.
7069     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7070            "Invalid first promoted integral type");
7071     assert(getArithmeticType(LastPromotedIntegralType - 1)
7072              == S.Context.UnsignedInt128Ty &&
7073            "Invalid last promoted integral type");
7074     assert(getArithmeticType(FirstPromotedArithmeticType)
7075              == S.Context.FloatTy &&
7076            "Invalid first promoted arithmetic type");
7077     assert(getArithmeticType(LastPromotedArithmeticType - 1)
7078              == S.Context.UnsignedInt128Ty &&
7079            "Invalid last promoted arithmetic type");
7080   }
7081 
7082   // C++ [over.built]p3:
7083   //
7084   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
7085   //   is either volatile or empty, there exist candidate operator
7086   //   functions of the form
7087   //
7088   //       VQ T&      operator++(VQ T&);
7089   //       T          operator++(VQ T&, int);
7090   //
7091   // C++ [over.built]p4:
7092   //
7093   //   For every pair (T, VQ), where T is an arithmetic type other
7094   //   than bool, and VQ is either volatile or empty, there exist
7095   //   candidate operator functions of the form
7096   //
7097   //       VQ T&      operator--(VQ T&);
7098   //       T          operator--(VQ T&, int);
addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op)7099   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7100     if (!HasArithmeticOrEnumeralCandidateType)
7101       return;
7102 
7103     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7104          Arith < NumArithmeticTypes; ++Arith) {
7105       addPlusPlusMinusMinusStyleOverloads(
7106         getArithmeticType(Arith),
7107         VisibleTypeConversionsQuals.hasVolatile(),
7108         VisibleTypeConversionsQuals.hasRestrict());
7109     }
7110   }
7111 
7112   // C++ [over.built]p5:
7113   //
7114   //   For every pair (T, VQ), where T is a cv-qualified or
7115   //   cv-unqualified object type, and VQ is either volatile or
7116   //   empty, there exist candidate operator functions of the form
7117   //
7118   //       T*VQ&      operator++(T*VQ&);
7119   //       T*VQ&      operator--(T*VQ&);
7120   //       T*         operator++(T*VQ&, int);
7121   //       T*         operator--(T*VQ&, int);
addPlusPlusMinusMinusPointerOverloads()7122   void addPlusPlusMinusMinusPointerOverloads() {
7123     for (BuiltinCandidateTypeSet::iterator
7124               Ptr = CandidateTypes[0].pointer_begin(),
7125            PtrEnd = CandidateTypes[0].pointer_end();
7126          Ptr != PtrEnd; ++Ptr) {
7127       // Skip pointer types that aren't pointers to object types.
7128       if (!(*Ptr)->getPointeeType()->isObjectType())
7129         continue;
7130 
7131       addPlusPlusMinusMinusStyleOverloads(*Ptr,
7132         (!(*Ptr).isVolatileQualified() &&
7133          VisibleTypeConversionsQuals.hasVolatile()),
7134         (!(*Ptr).isRestrictQualified() &&
7135          VisibleTypeConversionsQuals.hasRestrict()));
7136     }
7137   }
7138 
7139   // C++ [over.built]p6:
7140   //   For every cv-qualified or cv-unqualified object type T, there
7141   //   exist candidate operator functions of the form
7142   //
7143   //       T&         operator*(T*);
7144   //
7145   // C++ [over.built]p7:
7146   //   For every function type T that does not have cv-qualifiers or a
7147   //   ref-qualifier, there exist candidate operator functions of the form
7148   //       T&         operator*(T*);
addUnaryStarPointerOverloads()7149   void addUnaryStarPointerOverloads() {
7150     for (BuiltinCandidateTypeSet::iterator
7151               Ptr = CandidateTypes[0].pointer_begin(),
7152            PtrEnd = CandidateTypes[0].pointer_end();
7153          Ptr != PtrEnd; ++Ptr) {
7154       QualType ParamTy = *Ptr;
7155       QualType PointeeTy = ParamTy->getPointeeType();
7156       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7157         continue;
7158 
7159       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7160         if (Proto->getTypeQuals() || Proto->getRefQualifier())
7161           continue;
7162 
7163       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7164                             &ParamTy, Args, CandidateSet);
7165     }
7166   }
7167 
7168   // C++ [over.built]p9:
7169   //  For every promoted arithmetic type T, there exist candidate
7170   //  operator functions of the form
7171   //
7172   //       T         operator+(T);
7173   //       T         operator-(T);
addUnaryPlusOrMinusArithmeticOverloads()7174   void addUnaryPlusOrMinusArithmeticOverloads() {
7175     if (!HasArithmeticOrEnumeralCandidateType)
7176       return;
7177 
7178     for (unsigned Arith = FirstPromotedArithmeticType;
7179          Arith < LastPromotedArithmeticType; ++Arith) {
7180       QualType ArithTy = getArithmeticType(Arith);
7181       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7182     }
7183 
7184     // Extension: We also add these operators for vector types.
7185     for (BuiltinCandidateTypeSet::iterator
7186               Vec = CandidateTypes[0].vector_begin(),
7187            VecEnd = CandidateTypes[0].vector_end();
7188          Vec != VecEnd; ++Vec) {
7189       QualType VecTy = *Vec;
7190       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7191     }
7192   }
7193 
7194   // C++ [over.built]p8:
7195   //   For every type T, there exist candidate operator functions of
7196   //   the form
7197   //
7198   //       T*         operator+(T*);
addUnaryPlusPointerOverloads()7199   void addUnaryPlusPointerOverloads() {
7200     for (BuiltinCandidateTypeSet::iterator
7201               Ptr = CandidateTypes[0].pointer_begin(),
7202            PtrEnd = CandidateTypes[0].pointer_end();
7203          Ptr != PtrEnd; ++Ptr) {
7204       QualType ParamTy = *Ptr;
7205       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7206     }
7207   }
7208 
7209   // C++ [over.built]p10:
7210   //   For every promoted integral type T, there exist candidate
7211   //   operator functions of the form
7212   //
7213   //        T         operator~(T);
addUnaryTildePromotedIntegralOverloads()7214   void addUnaryTildePromotedIntegralOverloads() {
7215     if (!HasArithmeticOrEnumeralCandidateType)
7216       return;
7217 
7218     for (unsigned Int = FirstPromotedIntegralType;
7219          Int < LastPromotedIntegralType; ++Int) {
7220       QualType IntTy = getArithmeticType(Int);
7221       S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7222     }
7223 
7224     // Extension: We also add this operator for vector types.
7225     for (BuiltinCandidateTypeSet::iterator
7226               Vec = CandidateTypes[0].vector_begin(),
7227            VecEnd = CandidateTypes[0].vector_end();
7228          Vec != VecEnd; ++Vec) {
7229       QualType VecTy = *Vec;
7230       S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7231     }
7232   }
7233 
7234   // C++ [over.match.oper]p16:
7235   //   For every pointer to member type T, there exist candidate operator
7236   //   functions of the form
7237   //
7238   //        bool operator==(T,T);
7239   //        bool operator!=(T,T);
addEqualEqualOrNotEqualMemberPointerOverloads()7240   void addEqualEqualOrNotEqualMemberPointerOverloads() {
7241     /// Set of (canonical) types that we've already handled.
7242     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7243 
7244     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7245       for (BuiltinCandidateTypeSet::iterator
7246                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7247              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7248            MemPtr != MemPtrEnd;
7249            ++MemPtr) {
7250         // Don't add the same builtin candidate twice.
7251         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7252           continue;
7253 
7254         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7255         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7256       }
7257     }
7258   }
7259 
7260   // C++ [over.built]p15:
7261   //
7262   //   For every T, where T is an enumeration type, a pointer type, or
7263   //   std::nullptr_t, there exist candidate operator functions of the form
7264   //
7265   //        bool       operator<(T, T);
7266   //        bool       operator>(T, T);
7267   //        bool       operator<=(T, T);
7268   //        bool       operator>=(T, T);
7269   //        bool       operator==(T, T);
7270   //        bool       operator!=(T, T);
addRelationalPointerOrEnumeralOverloads()7271   void addRelationalPointerOrEnumeralOverloads() {
7272     // C++ [over.match.oper]p3:
7273     //   [...]the built-in candidates include all of the candidate operator
7274     //   functions defined in 13.6 that, compared to the given operator, [...]
7275     //   do not have the same parameter-type-list as any non-template non-member
7276     //   candidate.
7277     //
7278     // Note that in practice, this only affects enumeration types because there
7279     // aren't any built-in candidates of record type, and a user-defined operator
7280     // must have an operand of record or enumeration type. Also, the only other
7281     // overloaded operator with enumeration arguments, operator=,
7282     // cannot be overloaded for enumeration types, so this is the only place
7283     // where we must suppress candidates like this.
7284     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7285       UserDefinedBinaryOperators;
7286 
7287     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7288       if (CandidateTypes[ArgIdx].enumeration_begin() !=
7289           CandidateTypes[ArgIdx].enumeration_end()) {
7290         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7291                                          CEnd = CandidateSet.end();
7292              C != CEnd; ++C) {
7293           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7294             continue;
7295 
7296           if (C->Function->isFunctionTemplateSpecialization())
7297             continue;
7298 
7299           QualType FirstParamType =
7300             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7301           QualType SecondParamType =
7302             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7303 
7304           // Skip if either parameter isn't of enumeral type.
7305           if (!FirstParamType->isEnumeralType() ||
7306               !SecondParamType->isEnumeralType())
7307             continue;
7308 
7309           // Add this operator to the set of known user-defined operators.
7310           UserDefinedBinaryOperators.insert(
7311             std::make_pair(S.Context.getCanonicalType(FirstParamType),
7312                            S.Context.getCanonicalType(SecondParamType)));
7313         }
7314       }
7315     }
7316 
7317     /// Set of (canonical) types that we've already handled.
7318     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7319 
7320     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7321       for (BuiltinCandidateTypeSet::iterator
7322                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7323              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7324            Ptr != PtrEnd; ++Ptr) {
7325         // Don't add the same builtin candidate twice.
7326         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7327           continue;
7328 
7329         QualType ParamTypes[2] = { *Ptr, *Ptr };
7330         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7331       }
7332       for (BuiltinCandidateTypeSet::iterator
7333                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7334              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7335            Enum != EnumEnd; ++Enum) {
7336         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7337 
7338         // Don't add the same builtin candidate twice, or if a user defined
7339         // candidate exists.
7340         if (!AddedTypes.insert(CanonType) ||
7341             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7342                                                             CanonType)))
7343           continue;
7344 
7345         QualType ParamTypes[2] = { *Enum, *Enum };
7346         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7347       }
7348 
7349       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7350         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7351         if (AddedTypes.insert(NullPtrTy) &&
7352             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7353                                                              NullPtrTy))) {
7354           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7355           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7356                                 CandidateSet);
7357         }
7358       }
7359     }
7360   }
7361 
7362   // C++ [over.built]p13:
7363   //
7364   //   For every cv-qualified or cv-unqualified object type T
7365   //   there exist candidate operator functions of the form
7366   //
7367   //      T*         operator+(T*, ptrdiff_t);
7368   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
7369   //      T*         operator-(T*, ptrdiff_t);
7370   //      T*         operator+(ptrdiff_t, T*);
7371   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
7372   //
7373   // C++ [over.built]p14:
7374   //
7375   //   For every T, where T is a pointer to object type, there
7376   //   exist candidate operator functions of the form
7377   //
7378   //      ptrdiff_t  operator-(T, T);
addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op)7379   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7380     /// Set of (canonical) types that we've already handled.
7381     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7382 
7383     for (int Arg = 0; Arg < 2; ++Arg) {
7384       QualType AsymetricParamTypes[2] = {
7385         S.Context.getPointerDiffType(),
7386         S.Context.getPointerDiffType(),
7387       };
7388       for (BuiltinCandidateTypeSet::iterator
7389                 Ptr = CandidateTypes[Arg].pointer_begin(),
7390              PtrEnd = CandidateTypes[Arg].pointer_end();
7391            Ptr != PtrEnd; ++Ptr) {
7392         QualType PointeeTy = (*Ptr)->getPointeeType();
7393         if (!PointeeTy->isObjectType())
7394           continue;
7395 
7396         AsymetricParamTypes[Arg] = *Ptr;
7397         if (Arg == 0 || Op == OO_Plus) {
7398           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7399           // T* operator+(ptrdiff_t, T*);
7400           S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7401         }
7402         if (Op == OO_Minus) {
7403           // ptrdiff_t operator-(T, T);
7404           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7405             continue;
7406 
7407           QualType ParamTypes[2] = { *Ptr, *Ptr };
7408           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7409                                 Args, CandidateSet);
7410         }
7411       }
7412     }
7413   }
7414 
7415   // C++ [over.built]p12:
7416   //
7417   //   For every pair of promoted arithmetic types L and R, there
7418   //   exist candidate operator functions of the form
7419   //
7420   //        LR         operator*(L, R);
7421   //        LR         operator/(L, R);
7422   //        LR         operator+(L, R);
7423   //        LR         operator-(L, R);
7424   //        bool       operator<(L, R);
7425   //        bool       operator>(L, R);
7426   //        bool       operator<=(L, R);
7427   //        bool       operator>=(L, R);
7428   //        bool       operator==(L, R);
7429   //        bool       operator!=(L, R);
7430   //
7431   //   where LR is the result of the usual arithmetic conversions
7432   //   between types L and R.
7433   //
7434   // C++ [over.built]p24:
7435   //
7436   //   For every pair of promoted arithmetic types L and R, there exist
7437   //   candidate operator functions of the form
7438   //
7439   //        LR       operator?(bool, L, R);
7440   //
7441   //   where LR is the result of the usual arithmetic conversions
7442   //   between types L and R.
7443   // Our candidates ignore the first parameter.
addGenericBinaryArithmeticOverloads(bool isComparison)7444   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7445     if (!HasArithmeticOrEnumeralCandidateType)
7446       return;
7447 
7448     for (unsigned Left = FirstPromotedArithmeticType;
7449          Left < LastPromotedArithmeticType; ++Left) {
7450       for (unsigned Right = FirstPromotedArithmeticType;
7451            Right < LastPromotedArithmeticType; ++Right) {
7452         QualType LandR[2] = { getArithmeticType(Left),
7453                               getArithmeticType(Right) };
7454         QualType Result =
7455           isComparison ? S.Context.BoolTy
7456                        : getUsualArithmeticConversions(Left, Right);
7457         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7458       }
7459     }
7460 
7461     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7462     // conditional operator for vector types.
7463     for (BuiltinCandidateTypeSet::iterator
7464               Vec1 = CandidateTypes[0].vector_begin(),
7465            Vec1End = CandidateTypes[0].vector_end();
7466          Vec1 != Vec1End; ++Vec1) {
7467       for (BuiltinCandidateTypeSet::iterator
7468                 Vec2 = CandidateTypes[1].vector_begin(),
7469              Vec2End = CandidateTypes[1].vector_end();
7470            Vec2 != Vec2End; ++Vec2) {
7471         QualType LandR[2] = { *Vec1, *Vec2 };
7472         QualType Result = S.Context.BoolTy;
7473         if (!isComparison) {
7474           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7475             Result = *Vec1;
7476           else
7477             Result = *Vec2;
7478         }
7479 
7480         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7481       }
7482     }
7483   }
7484 
7485   // C++ [over.built]p17:
7486   //
7487   //   For every pair of promoted integral types L and R, there
7488   //   exist candidate operator functions of the form
7489   //
7490   //      LR         operator%(L, R);
7491   //      LR         operator&(L, R);
7492   //      LR         operator^(L, R);
7493   //      LR         operator|(L, R);
7494   //      L          operator<<(L, R);
7495   //      L          operator>>(L, R);
7496   //
7497   //   where LR is the result of the usual arithmetic conversions
7498   //   between types L and R.
addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op)7499   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7500     if (!HasArithmeticOrEnumeralCandidateType)
7501       return;
7502 
7503     for (unsigned Left = FirstPromotedIntegralType;
7504          Left < LastPromotedIntegralType; ++Left) {
7505       for (unsigned Right = FirstPromotedIntegralType;
7506            Right < LastPromotedIntegralType; ++Right) {
7507         QualType LandR[2] = { getArithmeticType(Left),
7508                               getArithmeticType(Right) };
7509         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7510             ? LandR[0]
7511             : getUsualArithmeticConversions(Left, Right);
7512         S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7513       }
7514     }
7515   }
7516 
7517   // C++ [over.built]p20:
7518   //
7519   //   For every pair (T, VQ), where T is an enumeration or
7520   //   pointer to member type and VQ is either volatile or
7521   //   empty, there exist candidate operator functions of the form
7522   //
7523   //        VQ T&      operator=(VQ T&, T);
addAssignmentMemberPointerOrEnumeralOverloads()7524   void addAssignmentMemberPointerOrEnumeralOverloads() {
7525     /// Set of (canonical) types that we've already handled.
7526     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7527 
7528     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7529       for (BuiltinCandidateTypeSet::iterator
7530                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7531              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7532            Enum != EnumEnd; ++Enum) {
7533         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7534           continue;
7535 
7536         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7537       }
7538 
7539       for (BuiltinCandidateTypeSet::iterator
7540                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7541              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7542            MemPtr != MemPtrEnd; ++MemPtr) {
7543         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7544           continue;
7545 
7546         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7547       }
7548     }
7549   }
7550 
7551   // C++ [over.built]p19:
7552   //
7553   //   For every pair (T, VQ), where T is any type and VQ is either
7554   //   volatile or empty, there exist candidate operator functions
7555   //   of the form
7556   //
7557   //        T*VQ&      operator=(T*VQ&, T*);
7558   //
7559   // C++ [over.built]p21:
7560   //
7561   //   For every pair (T, VQ), where T is a cv-qualified or
7562   //   cv-unqualified object type and VQ is either volatile or
7563   //   empty, there exist candidate operator functions of the form
7564   //
7565   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7566   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
addAssignmentPointerOverloads(bool isEqualOp)7567   void addAssignmentPointerOverloads(bool isEqualOp) {
7568     /// Set of (canonical) types that we've already handled.
7569     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7570 
7571     for (BuiltinCandidateTypeSet::iterator
7572               Ptr = CandidateTypes[0].pointer_begin(),
7573            PtrEnd = CandidateTypes[0].pointer_end();
7574          Ptr != PtrEnd; ++Ptr) {
7575       // If this is operator=, keep track of the builtin candidates we added.
7576       if (isEqualOp)
7577         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7578       else if (!(*Ptr)->getPointeeType()->isObjectType())
7579         continue;
7580 
7581       // non-volatile version
7582       QualType ParamTypes[2] = {
7583         S.Context.getLValueReferenceType(*Ptr),
7584         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7585       };
7586       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7587                             /*IsAssigmentOperator=*/ isEqualOp);
7588 
7589       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7590                           VisibleTypeConversionsQuals.hasVolatile();
7591       if (NeedVolatile) {
7592         // volatile version
7593         ParamTypes[0] =
7594           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7595         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7596                               /*IsAssigmentOperator=*/isEqualOp);
7597       }
7598 
7599       if (!(*Ptr).isRestrictQualified() &&
7600           VisibleTypeConversionsQuals.hasRestrict()) {
7601         // restrict version
7602         ParamTypes[0]
7603           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7604         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7605                               /*IsAssigmentOperator=*/isEqualOp);
7606 
7607         if (NeedVolatile) {
7608           // volatile restrict version
7609           ParamTypes[0]
7610             = S.Context.getLValueReferenceType(
7611                 S.Context.getCVRQualifiedType(*Ptr,
7612                                               (Qualifiers::Volatile |
7613                                                Qualifiers::Restrict)));
7614           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7615                                 /*IsAssigmentOperator=*/isEqualOp);
7616         }
7617       }
7618     }
7619 
7620     if (isEqualOp) {
7621       for (BuiltinCandidateTypeSet::iterator
7622                 Ptr = CandidateTypes[1].pointer_begin(),
7623              PtrEnd = CandidateTypes[1].pointer_end();
7624            Ptr != PtrEnd; ++Ptr) {
7625         // Make sure we don't add the same candidate twice.
7626         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7627           continue;
7628 
7629         QualType ParamTypes[2] = {
7630           S.Context.getLValueReferenceType(*Ptr),
7631           *Ptr,
7632         };
7633 
7634         // non-volatile version
7635         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7636                               /*IsAssigmentOperator=*/true);
7637 
7638         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7639                            VisibleTypeConversionsQuals.hasVolatile();
7640         if (NeedVolatile) {
7641           // volatile version
7642           ParamTypes[0] =
7643             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7644           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7645                                 /*IsAssigmentOperator=*/true);
7646         }
7647 
7648         if (!(*Ptr).isRestrictQualified() &&
7649             VisibleTypeConversionsQuals.hasRestrict()) {
7650           // restrict version
7651           ParamTypes[0]
7652             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7653           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7654                                 /*IsAssigmentOperator=*/true);
7655 
7656           if (NeedVolatile) {
7657             // volatile restrict version
7658             ParamTypes[0]
7659               = S.Context.getLValueReferenceType(
7660                   S.Context.getCVRQualifiedType(*Ptr,
7661                                                 (Qualifiers::Volatile |
7662                                                  Qualifiers::Restrict)));
7663             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7664                                   /*IsAssigmentOperator=*/true);
7665           }
7666         }
7667       }
7668     }
7669   }
7670 
7671   // C++ [over.built]p18:
7672   //
7673   //   For every triple (L, VQ, R), where L is an arithmetic type,
7674   //   VQ is either volatile or empty, and R is a promoted
7675   //   arithmetic type, there exist candidate operator functions of
7676   //   the form
7677   //
7678   //        VQ L&      operator=(VQ L&, R);
7679   //        VQ L&      operator*=(VQ L&, R);
7680   //        VQ L&      operator/=(VQ L&, R);
7681   //        VQ L&      operator+=(VQ L&, R);
7682   //        VQ L&      operator-=(VQ L&, R);
addAssignmentArithmeticOverloads(bool isEqualOp)7683   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7684     if (!HasArithmeticOrEnumeralCandidateType)
7685       return;
7686 
7687     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7688       for (unsigned Right = FirstPromotedArithmeticType;
7689            Right < LastPromotedArithmeticType; ++Right) {
7690         QualType ParamTypes[2];
7691         ParamTypes[1] = getArithmeticType(Right);
7692 
7693         // Add this built-in operator as a candidate (VQ is empty).
7694         ParamTypes[0] =
7695           S.Context.getLValueReferenceType(getArithmeticType(Left));
7696         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7697                               /*IsAssigmentOperator=*/isEqualOp);
7698 
7699         // Add this built-in operator as a candidate (VQ is 'volatile').
7700         if (VisibleTypeConversionsQuals.hasVolatile()) {
7701           ParamTypes[0] =
7702             S.Context.getVolatileType(getArithmeticType(Left));
7703           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7704           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7705                                 /*IsAssigmentOperator=*/isEqualOp);
7706         }
7707       }
7708     }
7709 
7710     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7711     for (BuiltinCandidateTypeSet::iterator
7712               Vec1 = CandidateTypes[0].vector_begin(),
7713            Vec1End = CandidateTypes[0].vector_end();
7714          Vec1 != Vec1End; ++Vec1) {
7715       for (BuiltinCandidateTypeSet::iterator
7716                 Vec2 = CandidateTypes[1].vector_begin(),
7717              Vec2End = CandidateTypes[1].vector_end();
7718            Vec2 != Vec2End; ++Vec2) {
7719         QualType ParamTypes[2];
7720         ParamTypes[1] = *Vec2;
7721         // Add this built-in operator as a candidate (VQ is empty).
7722         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7723         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7724                               /*IsAssigmentOperator=*/isEqualOp);
7725 
7726         // Add this built-in operator as a candidate (VQ is 'volatile').
7727         if (VisibleTypeConversionsQuals.hasVolatile()) {
7728           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7729           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7730           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7731                                 /*IsAssigmentOperator=*/isEqualOp);
7732         }
7733       }
7734     }
7735   }
7736 
7737   // C++ [over.built]p22:
7738   //
7739   //   For every triple (L, VQ, R), where L is an integral type, VQ
7740   //   is either volatile or empty, and R is a promoted integral
7741   //   type, there exist candidate operator functions of the form
7742   //
7743   //        VQ L&       operator%=(VQ L&, R);
7744   //        VQ L&       operator<<=(VQ L&, R);
7745   //        VQ L&       operator>>=(VQ L&, R);
7746   //        VQ L&       operator&=(VQ L&, R);
7747   //        VQ L&       operator^=(VQ L&, R);
7748   //        VQ L&       operator|=(VQ L&, R);
addAssignmentIntegralOverloads()7749   void addAssignmentIntegralOverloads() {
7750     if (!HasArithmeticOrEnumeralCandidateType)
7751       return;
7752 
7753     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7754       for (unsigned Right = FirstPromotedIntegralType;
7755            Right < LastPromotedIntegralType; ++Right) {
7756         QualType ParamTypes[2];
7757         ParamTypes[1] = getArithmeticType(Right);
7758 
7759         // Add this built-in operator as a candidate (VQ is empty).
7760         ParamTypes[0] =
7761           S.Context.getLValueReferenceType(getArithmeticType(Left));
7762         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7763         if (VisibleTypeConversionsQuals.hasVolatile()) {
7764           // Add this built-in operator as a candidate (VQ is 'volatile').
7765           ParamTypes[0] = getArithmeticType(Left);
7766           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7767           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7768           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7769         }
7770       }
7771     }
7772   }
7773 
7774   // C++ [over.operator]p23:
7775   //
7776   //   There also exist candidate operator functions of the form
7777   //
7778   //        bool        operator!(bool);
7779   //        bool        operator&&(bool, bool);
7780   //        bool        operator||(bool, bool);
addExclaimOverload()7781   void addExclaimOverload() {
7782     QualType ParamTy = S.Context.BoolTy;
7783     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7784                           /*IsAssignmentOperator=*/false,
7785                           /*NumContextualBoolArguments=*/1);
7786   }
addAmpAmpOrPipePipeOverload()7787   void addAmpAmpOrPipePipeOverload() {
7788     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7789     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7790                           /*IsAssignmentOperator=*/false,
7791                           /*NumContextualBoolArguments=*/2);
7792   }
7793 
7794   // C++ [over.built]p13:
7795   //
7796   //   For every cv-qualified or cv-unqualified object type T there
7797   //   exist candidate operator functions of the form
7798   //
7799   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7800   //        T&         operator[](T*, ptrdiff_t);
7801   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7802   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7803   //        T&         operator[](ptrdiff_t, T*);
addSubscriptOverloads()7804   void addSubscriptOverloads() {
7805     for (BuiltinCandidateTypeSet::iterator
7806               Ptr = CandidateTypes[0].pointer_begin(),
7807            PtrEnd = CandidateTypes[0].pointer_end();
7808          Ptr != PtrEnd; ++Ptr) {
7809       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7810       QualType PointeeType = (*Ptr)->getPointeeType();
7811       if (!PointeeType->isObjectType())
7812         continue;
7813 
7814       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7815 
7816       // T& operator[](T*, ptrdiff_t)
7817       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7818     }
7819 
7820     for (BuiltinCandidateTypeSet::iterator
7821               Ptr = CandidateTypes[1].pointer_begin(),
7822            PtrEnd = CandidateTypes[1].pointer_end();
7823          Ptr != PtrEnd; ++Ptr) {
7824       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7825       QualType PointeeType = (*Ptr)->getPointeeType();
7826       if (!PointeeType->isObjectType())
7827         continue;
7828 
7829       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7830 
7831       // T& operator[](ptrdiff_t, T*)
7832       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7833     }
7834   }
7835 
7836   // C++ [over.built]p11:
7837   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7838   //    C1 is the same type as C2 or is a derived class of C2, T is an object
7839   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7840   //    there exist candidate operator functions of the form
7841   //
7842   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7843   //
7844   //    where CV12 is the union of CV1 and CV2.
addArrowStarOverloads()7845   void addArrowStarOverloads() {
7846     for (BuiltinCandidateTypeSet::iterator
7847              Ptr = CandidateTypes[0].pointer_begin(),
7848            PtrEnd = CandidateTypes[0].pointer_end();
7849          Ptr != PtrEnd; ++Ptr) {
7850       QualType C1Ty = (*Ptr);
7851       QualType C1;
7852       QualifierCollector Q1;
7853       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7854       if (!isa<RecordType>(C1))
7855         continue;
7856       // heuristic to reduce number of builtin candidates in the set.
7857       // Add volatile/restrict version only if there are conversions to a
7858       // volatile/restrict type.
7859       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7860         continue;
7861       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7862         continue;
7863       for (BuiltinCandidateTypeSet::iterator
7864                 MemPtr = CandidateTypes[1].member_pointer_begin(),
7865              MemPtrEnd = CandidateTypes[1].member_pointer_end();
7866            MemPtr != MemPtrEnd; ++MemPtr) {
7867         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7868         QualType C2 = QualType(mptr->getClass(), 0);
7869         C2 = C2.getUnqualifiedType();
7870         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7871           break;
7872         QualType ParamTypes[2] = { *Ptr, *MemPtr };
7873         // build CV12 T&
7874         QualType T = mptr->getPointeeType();
7875         if (!VisibleTypeConversionsQuals.hasVolatile() &&
7876             T.isVolatileQualified())
7877           continue;
7878         if (!VisibleTypeConversionsQuals.hasRestrict() &&
7879             T.isRestrictQualified())
7880           continue;
7881         T = Q1.apply(S.Context, T);
7882         QualType ResultTy = S.Context.getLValueReferenceType(T);
7883         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7884       }
7885     }
7886   }
7887 
7888   // Note that we don't consider the first argument, since it has been
7889   // contextually converted to bool long ago. The candidates below are
7890   // therefore added as binary.
7891   //
7892   // C++ [over.built]p25:
7893   //   For every type T, where T is a pointer, pointer-to-member, or scoped
7894   //   enumeration type, there exist candidate operator functions of the form
7895   //
7896   //        T        operator?(bool, T, T);
7897   //
addConditionalOperatorOverloads()7898   void addConditionalOperatorOverloads() {
7899     /// Set of (canonical) types that we've already handled.
7900     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7901 
7902     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7903       for (BuiltinCandidateTypeSet::iterator
7904                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7905              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7906            Ptr != PtrEnd; ++Ptr) {
7907         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7908           continue;
7909 
7910         QualType ParamTypes[2] = { *Ptr, *Ptr };
7911         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
7912       }
7913 
7914       for (BuiltinCandidateTypeSet::iterator
7915                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7916              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7917            MemPtr != MemPtrEnd; ++MemPtr) {
7918         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7919           continue;
7920 
7921         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7922         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
7923       }
7924 
7925       if (S.getLangOpts().CPlusPlus11) {
7926         for (BuiltinCandidateTypeSet::iterator
7927                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7928                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7929              Enum != EnumEnd; ++Enum) {
7930           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7931             continue;
7932 
7933           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7934             continue;
7935 
7936           QualType ParamTypes[2] = { *Enum, *Enum };
7937           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
7938         }
7939       }
7940     }
7941   }
7942 };
7943 
7944 } // end anonymous namespace
7945 
7946 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
7947 /// operator overloads to the candidate set (C++ [over.built]), based
7948 /// on the operator @p Op and the arguments given. For example, if the
7949 /// operator is a binary '+', this routine might add "int
7950 /// operator+(int, int)" to cover integer addition.
AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)7951 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7952                                         SourceLocation OpLoc,
7953                                         ArrayRef<Expr *> Args,
7954                                         OverloadCandidateSet &CandidateSet) {
7955   // Find all of the types that the arguments can convert to, but only
7956   // if the operator we're looking at has built-in operator candidates
7957   // that make use of these types. Also record whether we encounter non-record
7958   // candidate types or either arithmetic or enumeral candidate types.
7959   Qualifiers VisibleTypeConversionsQuals;
7960   VisibleTypeConversionsQuals.addConst();
7961   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7962     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7963 
7964   bool HasNonRecordCandidateType = false;
7965   bool HasArithmeticOrEnumeralCandidateType = false;
7966   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7967   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7968     CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7969     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7970                                                  OpLoc,
7971                                                  true,
7972                                                  (Op == OO_Exclaim ||
7973                                                   Op == OO_AmpAmp ||
7974                                                   Op == OO_PipePipe),
7975                                                  VisibleTypeConversionsQuals);
7976     HasNonRecordCandidateType = HasNonRecordCandidateType ||
7977         CandidateTypes[ArgIdx].hasNonRecordTypes();
7978     HasArithmeticOrEnumeralCandidateType =
7979         HasArithmeticOrEnumeralCandidateType ||
7980         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7981   }
7982 
7983   // Exit early when no non-record types have been added to the candidate set
7984   // for any of the arguments to the operator.
7985   //
7986   // We can't exit early for !, ||, or &&, since there we have always have
7987   // 'bool' overloads.
7988   if (!HasNonRecordCandidateType &&
7989       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7990     return;
7991 
7992   // Setup an object to manage the common state for building overloads.
7993   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
7994                                            VisibleTypeConversionsQuals,
7995                                            HasArithmeticOrEnumeralCandidateType,
7996                                            CandidateTypes, CandidateSet);
7997 
7998   // Dispatch over the operation to add in only those overloads which apply.
7999   switch (Op) {
8000   case OO_None:
8001   case NUM_OVERLOADED_OPERATORS:
8002     llvm_unreachable("Expected an overloaded operator");
8003 
8004   case OO_New:
8005   case OO_Delete:
8006   case OO_Array_New:
8007   case OO_Array_Delete:
8008   case OO_Call:
8009     llvm_unreachable(
8010                     "Special operators don't use AddBuiltinOperatorCandidates");
8011 
8012   case OO_Comma:
8013   case OO_Arrow:
8014     // C++ [over.match.oper]p3:
8015     //   -- For the operator ',', the unary operator '&', or the
8016     //      operator '->', the built-in candidates set is empty.
8017     break;
8018 
8019   case OO_Plus: // '+' is either unary or binary
8020     if (Args.size() == 1)
8021       OpBuilder.addUnaryPlusPointerOverloads();
8022     // Fall through.
8023 
8024   case OO_Minus: // '-' is either unary or binary
8025     if (Args.size() == 1) {
8026       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8027     } else {
8028       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8029       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8030     }
8031     break;
8032 
8033   case OO_Star: // '*' is either unary or binary
8034     if (Args.size() == 1)
8035       OpBuilder.addUnaryStarPointerOverloads();
8036     else
8037       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8038     break;
8039 
8040   case OO_Slash:
8041     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8042     break;
8043 
8044   case OO_PlusPlus:
8045   case OO_MinusMinus:
8046     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8047     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8048     break;
8049 
8050   case OO_EqualEqual:
8051   case OO_ExclaimEqual:
8052     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8053     // Fall through.
8054 
8055   case OO_Less:
8056   case OO_Greater:
8057   case OO_LessEqual:
8058   case OO_GreaterEqual:
8059     OpBuilder.addRelationalPointerOrEnumeralOverloads();
8060     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8061     break;
8062 
8063   case OO_Percent:
8064   case OO_Caret:
8065   case OO_Pipe:
8066   case OO_LessLess:
8067   case OO_GreaterGreater:
8068     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8069     break;
8070 
8071   case OO_Amp: // '&' is either unary or binary
8072     if (Args.size() == 1)
8073       // C++ [over.match.oper]p3:
8074       //   -- For the operator ',', the unary operator '&', or the
8075       //      operator '->', the built-in candidates set is empty.
8076       break;
8077 
8078     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8079     break;
8080 
8081   case OO_Tilde:
8082     OpBuilder.addUnaryTildePromotedIntegralOverloads();
8083     break;
8084 
8085   case OO_Equal:
8086     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8087     // Fall through.
8088 
8089   case OO_PlusEqual:
8090   case OO_MinusEqual:
8091     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8092     // Fall through.
8093 
8094   case OO_StarEqual:
8095   case OO_SlashEqual:
8096     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8097     break;
8098 
8099   case OO_PercentEqual:
8100   case OO_LessLessEqual:
8101   case OO_GreaterGreaterEqual:
8102   case OO_AmpEqual:
8103   case OO_CaretEqual:
8104   case OO_PipeEqual:
8105     OpBuilder.addAssignmentIntegralOverloads();
8106     break;
8107 
8108   case OO_Exclaim:
8109     OpBuilder.addExclaimOverload();
8110     break;
8111 
8112   case OO_AmpAmp:
8113   case OO_PipePipe:
8114     OpBuilder.addAmpAmpOrPipePipeOverload();
8115     break;
8116 
8117   case OO_Subscript:
8118     OpBuilder.addSubscriptOverloads();
8119     break;
8120 
8121   case OO_ArrowStar:
8122     OpBuilder.addArrowStarOverloads();
8123     break;
8124 
8125   case OO_Conditional:
8126     OpBuilder.addConditionalOperatorOverloads();
8127     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8128     break;
8129   }
8130 }
8131 
8132 /// \brief Add function candidates found via argument-dependent lookup
8133 /// to the set of overloading candidates.
8134 ///
8135 /// This routine performs argument-dependent name lookup based on the
8136 /// given function name (which may also be an operator name) and adds
8137 /// all of the overload candidates found by ADL to the overload
8138 /// candidate set (C++ [basic.lookup.argdep]).
8139 void
AddArgumentDependentLookupCandidates(DeclarationName Name,SourceLocation Loc,ArrayRef<Expr * > Args,TemplateArgumentListInfo * ExplicitTemplateArgs,OverloadCandidateSet & CandidateSet,bool PartialOverloading)8140 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8141                                            SourceLocation Loc,
8142                                            ArrayRef<Expr *> Args,
8143                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
8144                                            OverloadCandidateSet& CandidateSet,
8145                                            bool PartialOverloading) {
8146   ADLResult Fns;
8147 
8148   // FIXME: This approach for uniquing ADL results (and removing
8149   // redundant candidates from the set) relies on pointer-equality,
8150   // which means we need to key off the canonical decl.  However,
8151   // always going back to the canonical decl might not get us the
8152   // right set of default arguments.  What default arguments are
8153   // we supposed to consider on ADL candidates, anyway?
8154 
8155   // FIXME: Pass in the explicit template arguments?
8156   ArgumentDependentLookup(Name, Loc, Args, Fns);
8157 
8158   // Erase all of the candidates we already knew about.
8159   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8160                                    CandEnd = CandidateSet.end();
8161        Cand != CandEnd; ++Cand)
8162     if (Cand->Function) {
8163       Fns.erase(Cand->Function);
8164       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8165         Fns.erase(FunTmpl);
8166     }
8167 
8168   // For each of the ADL candidates we found, add it to the overload
8169   // set.
8170   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8171     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8172     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8173       if (ExplicitTemplateArgs)
8174         continue;
8175 
8176       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8177                            PartialOverloading);
8178     } else
8179       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8180                                    FoundDecl, ExplicitTemplateArgs,
8181                                    Args, CandidateSet);
8182   }
8183 }
8184 
8185 /// isBetterOverloadCandidate - Determines whether the first overload
8186 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8187 bool
isBetterOverloadCandidate(Sema & S,const OverloadCandidate & Cand1,const OverloadCandidate & Cand2,SourceLocation Loc,bool UserDefinedConversion)8188 isBetterOverloadCandidate(Sema &S,
8189                           const OverloadCandidate &Cand1,
8190                           const OverloadCandidate &Cand2,
8191                           SourceLocation Loc,
8192                           bool UserDefinedConversion) {
8193   // Define viable functions to be better candidates than non-viable
8194   // functions.
8195   if (!Cand2.Viable)
8196     return Cand1.Viable;
8197   else if (!Cand1.Viable)
8198     return false;
8199 
8200   // C++ [over.match.best]p1:
8201   //
8202   //   -- if F is a static member function, ICS1(F) is defined such
8203   //      that ICS1(F) is neither better nor worse than ICS1(G) for
8204   //      any function G, and, symmetrically, ICS1(G) is neither
8205   //      better nor worse than ICS1(F).
8206   unsigned StartArg = 0;
8207   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8208     StartArg = 1;
8209 
8210   // C++ [over.match.best]p1:
8211   //   A viable function F1 is defined to be a better function than another
8212   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
8213   //   conversion sequence than ICSi(F2), and then...
8214   unsigned NumArgs = Cand1.NumConversions;
8215   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8216   bool HasBetterConversion = false;
8217   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8218     switch (CompareImplicitConversionSequences(S,
8219                                                Cand1.Conversions[ArgIdx],
8220                                                Cand2.Conversions[ArgIdx])) {
8221     case ImplicitConversionSequence::Better:
8222       // Cand1 has a better conversion sequence.
8223       HasBetterConversion = true;
8224       break;
8225 
8226     case ImplicitConversionSequence::Worse:
8227       // Cand1 can't be better than Cand2.
8228       return false;
8229 
8230     case ImplicitConversionSequence::Indistinguishable:
8231       // Do nothing.
8232       break;
8233     }
8234   }
8235 
8236   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
8237   //       ICSj(F2), or, if not that,
8238   if (HasBetterConversion)
8239     return true;
8240 
8241   //   -- the context is an initialization by user-defined conversion
8242   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
8243   //      from the return type of F1 to the destination type (i.e.,
8244   //      the type of the entity being initialized) is a better
8245   //      conversion sequence than the standard conversion sequence
8246   //      from the return type of F2 to the destination type.
8247   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8248       isa<CXXConversionDecl>(Cand1.Function) &&
8249       isa<CXXConversionDecl>(Cand2.Function)) {
8250     // First check whether we prefer one of the conversion functions over the
8251     // other. This only distinguishes the results in non-standard, extension
8252     // cases such as the conversion from a lambda closure type to a function
8253     // pointer or block.
8254     ImplicitConversionSequence::CompareKind Result =
8255         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8256     if (Result == ImplicitConversionSequence::Indistinguishable)
8257       Result = CompareStandardConversionSequences(S,
8258                                                   Cand1.FinalConversion,
8259                                                   Cand2.FinalConversion);
8260 
8261     if (Result != ImplicitConversionSequence::Indistinguishable)
8262       return Result == ImplicitConversionSequence::Better;
8263 
8264     // FIXME: Compare kind of reference binding if conversion functions
8265     // convert to a reference type used in direct reference binding, per
8266     // C++14 [over.match.best]p1 section 2 bullet 3.
8267   }
8268 
8269   //    -- F1 is a non-template function and F2 is a function template
8270   //       specialization, or, if not that,
8271   bool Cand1IsSpecialization = Cand1.Function &&
8272                                Cand1.Function->getPrimaryTemplate();
8273   bool Cand2IsSpecialization = Cand2.Function &&
8274                                Cand2.Function->getPrimaryTemplate();
8275   if (Cand1IsSpecialization != Cand2IsSpecialization)
8276     return Cand2IsSpecialization;
8277 
8278   //   -- F1 and F2 are function template specializations, and the function
8279   //      template for F1 is more specialized than the template for F2
8280   //      according to the partial ordering rules described in 14.5.5.2, or,
8281   //      if not that,
8282   if (Cand1IsSpecialization && Cand2IsSpecialization) {
8283     if (FunctionTemplateDecl *BetterTemplate
8284           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8285                                          Cand2.Function->getPrimaryTemplate(),
8286                                          Loc,
8287                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8288                                                              : TPOC_Call,
8289                                          Cand1.ExplicitCallArguments,
8290                                          Cand2.ExplicitCallArguments))
8291       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8292   }
8293 
8294   // Check for enable_if value-based overload resolution.
8295   if (Cand1.Function && Cand2.Function &&
8296       (Cand1.Function->hasAttr<EnableIfAttr>() ||
8297        Cand2.Function->hasAttr<EnableIfAttr>())) {
8298     // FIXME: The next several lines are just
8299     // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8300     // instead of reverse order which is how they're stored in the AST.
8301     AttrVec Cand1Attrs;
8302     if (Cand1.Function->hasAttrs()) {
8303       Cand1Attrs = Cand1.Function->getAttrs();
8304       Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8305                                       IsNotEnableIfAttr),
8306                        Cand1Attrs.end());
8307       std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
8308     }
8309 
8310     AttrVec Cand2Attrs;
8311     if (Cand2.Function->hasAttrs()) {
8312       Cand2Attrs = Cand2.Function->getAttrs();
8313       Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8314                                       IsNotEnableIfAttr),
8315                        Cand2Attrs.end());
8316       std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
8317     }
8318 
8319     // Candidate 1 is better if it has strictly more attributes and
8320     // the common sequence is identical.
8321     if (Cand1Attrs.size() <= Cand2Attrs.size())
8322       return false;
8323 
8324     auto Cand1I = Cand1Attrs.begin();
8325     for (auto &Cand2A : Cand2Attrs) {
8326       auto &Cand1A = *Cand1I++;
8327       llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8328       cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8329                                                      S.getASTContext(), true);
8330       cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8331                                                      S.getASTContext(), true);
8332       if (Cand1ID != Cand2ID)
8333         return false;
8334     }
8335 
8336     return true;
8337   }
8338 
8339   return false;
8340 }
8341 
8342 /// \brief Computes the best viable function (C++ 13.3.3)
8343 /// within an overload candidate set.
8344 ///
8345 /// \param Loc The location of the function name (or operator symbol) for
8346 /// which overload resolution occurs.
8347 ///
8348 /// \param Best If overload resolution was successful or found a deleted
8349 /// function, \p Best points to the candidate function found.
8350 ///
8351 /// \returns The result of overload resolution.
8352 OverloadingResult
BestViableFunction(Sema & S,SourceLocation Loc,iterator & Best,bool UserDefinedConversion)8353 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8354                                          iterator &Best,
8355                                          bool UserDefinedConversion) {
8356   // Find the best viable function.
8357   Best = end();
8358   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8359     if (Cand->Viable)
8360       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8361                                                      UserDefinedConversion))
8362         Best = Cand;
8363   }
8364 
8365   // If we didn't find any viable functions, abort.
8366   if (Best == end())
8367     return OR_No_Viable_Function;
8368 
8369   // Make sure that this function is better than every other viable
8370   // function. If not, we have an ambiguity.
8371   for (iterator Cand = begin(); Cand != end(); ++Cand) {
8372     if (Cand->Viable &&
8373         Cand != Best &&
8374         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8375                                    UserDefinedConversion)) {
8376       Best = end();
8377       return OR_Ambiguous;
8378     }
8379   }
8380 
8381   // Best is the best viable function.
8382   if (Best->Function &&
8383       (Best->Function->isDeleted() ||
8384        S.isFunctionConsideredUnavailable(Best->Function)))
8385     return OR_Deleted;
8386 
8387   return OR_Success;
8388 }
8389 
8390 namespace {
8391 
8392 enum OverloadCandidateKind {
8393   oc_function,
8394   oc_method,
8395   oc_constructor,
8396   oc_function_template,
8397   oc_method_template,
8398   oc_constructor_template,
8399   oc_implicit_default_constructor,
8400   oc_implicit_copy_constructor,
8401   oc_implicit_move_constructor,
8402   oc_implicit_copy_assignment,
8403   oc_implicit_move_assignment,
8404   oc_implicit_inherited_constructor
8405 };
8406 
ClassifyOverloadCandidate(Sema & S,FunctionDecl * Fn,std::string & Description)8407 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8408                                                 FunctionDecl *Fn,
8409                                                 std::string &Description) {
8410   bool isTemplate = false;
8411 
8412   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8413     isTemplate = true;
8414     Description = S.getTemplateArgumentBindingsText(
8415       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8416   }
8417 
8418   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8419     if (!Ctor->isImplicit())
8420       return isTemplate ? oc_constructor_template : oc_constructor;
8421 
8422     if (Ctor->getInheritedConstructor())
8423       return oc_implicit_inherited_constructor;
8424 
8425     if (Ctor->isDefaultConstructor())
8426       return oc_implicit_default_constructor;
8427 
8428     if (Ctor->isMoveConstructor())
8429       return oc_implicit_move_constructor;
8430 
8431     assert(Ctor->isCopyConstructor() &&
8432            "unexpected sort of implicit constructor");
8433     return oc_implicit_copy_constructor;
8434   }
8435 
8436   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8437     // This actually gets spelled 'candidate function' for now, but
8438     // it doesn't hurt to split it out.
8439     if (!Meth->isImplicit())
8440       return isTemplate ? oc_method_template : oc_method;
8441 
8442     if (Meth->isMoveAssignmentOperator())
8443       return oc_implicit_move_assignment;
8444 
8445     if (Meth->isCopyAssignmentOperator())
8446       return oc_implicit_copy_assignment;
8447 
8448     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8449     return oc_method;
8450   }
8451 
8452   return isTemplate ? oc_function_template : oc_function;
8453 }
8454 
MaybeEmitInheritedConstructorNote(Sema & S,Decl * Fn)8455 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8456   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8457   if (!Ctor) return;
8458 
8459   Ctor = Ctor->getInheritedConstructor();
8460   if (!Ctor) return;
8461 
8462   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8463 }
8464 
8465 } // end anonymous namespace
8466 
8467 // Notes the location of an overload candidate.
NoteOverloadCandidate(FunctionDecl * Fn,QualType DestType)8468 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8469   std::string FnDesc;
8470   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8471   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8472                              << (unsigned) K << FnDesc;
8473   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8474   Diag(Fn->getLocation(), PD);
8475   MaybeEmitInheritedConstructorNote(*this, Fn);
8476 }
8477 
8478 // Notes the location of all overload candidates designated through
8479 // OverloadedExpr
NoteAllOverloadCandidates(Expr * OverloadedExpr,QualType DestType)8480 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8481   assert(OverloadedExpr->getType() == Context.OverloadTy);
8482 
8483   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8484   OverloadExpr *OvlExpr = Ovl.Expression;
8485 
8486   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8487                             IEnd = OvlExpr->decls_end();
8488        I != IEnd; ++I) {
8489     if (FunctionTemplateDecl *FunTmpl =
8490                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8491       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8492     } else if (FunctionDecl *Fun
8493                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8494       NoteOverloadCandidate(Fun, DestType);
8495     }
8496   }
8497 }
8498 
8499 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8500 /// "lead" diagnostic; it will be given two arguments, the source and
8501 /// target types of the conversion.
DiagnoseAmbiguousConversion(Sema & S,SourceLocation CaretLoc,const PartialDiagnostic & PDiag) const8502 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8503                                  Sema &S,
8504                                  SourceLocation CaretLoc,
8505                                  const PartialDiagnostic &PDiag) const {
8506   S.Diag(CaretLoc, PDiag)
8507     << Ambiguous.getFromType() << Ambiguous.getToType();
8508   // FIXME: The note limiting machinery is borrowed from
8509   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8510   // refactoring here.
8511   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8512   unsigned CandsShown = 0;
8513   AmbiguousConversionSequence::const_iterator I, E;
8514   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8515     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8516       break;
8517     ++CandsShown;
8518     S.NoteOverloadCandidate(*I);
8519   }
8520   if (I != E)
8521     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8522 }
8523 
8524 namespace {
8525 
DiagnoseBadConversion(Sema & S,OverloadCandidate * Cand,unsigned I)8526 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8527   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8528   assert(Conv.isBad());
8529   assert(Cand->Function && "for now, candidate must be a function");
8530   FunctionDecl *Fn = Cand->Function;
8531 
8532   // There's a conversion slot for the object argument if this is a
8533   // non-constructor method.  Note that 'I' corresponds the
8534   // conversion-slot index.
8535   bool isObjectArgument = false;
8536   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8537     if (I == 0)
8538       isObjectArgument = true;
8539     else
8540       I--;
8541   }
8542 
8543   std::string FnDesc;
8544   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8545 
8546   Expr *FromExpr = Conv.Bad.FromExpr;
8547   QualType FromTy = Conv.Bad.getFromType();
8548   QualType ToTy = Conv.Bad.getToType();
8549 
8550   if (FromTy == S.Context.OverloadTy) {
8551     assert(FromExpr && "overload set argument came from implicit argument?");
8552     Expr *E = FromExpr->IgnoreParens();
8553     if (isa<UnaryOperator>(E))
8554       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8555     DeclarationName Name = cast<OverloadExpr>(E)->getName();
8556 
8557     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8558       << (unsigned) FnKind << FnDesc
8559       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8560       << ToTy << Name << I+1;
8561     MaybeEmitInheritedConstructorNote(S, Fn);
8562     return;
8563   }
8564 
8565   // Do some hand-waving analysis to see if the non-viability is due
8566   // to a qualifier mismatch.
8567   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8568   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8569   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8570     CToTy = RT->getPointeeType();
8571   else {
8572     // TODO: detect and diagnose the full richness of const mismatches.
8573     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8574       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8575         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8576   }
8577 
8578   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8579       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8580     Qualifiers FromQs = CFromTy.getQualifiers();
8581     Qualifiers ToQs = CToTy.getQualifiers();
8582 
8583     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8584       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8585         << (unsigned) FnKind << FnDesc
8586         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8587         << FromTy
8588         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8589         << (unsigned) isObjectArgument << I+1;
8590       MaybeEmitInheritedConstructorNote(S, Fn);
8591       return;
8592     }
8593 
8594     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8595       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8596         << (unsigned) FnKind << FnDesc
8597         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8598         << FromTy
8599         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8600         << (unsigned) isObjectArgument << I+1;
8601       MaybeEmitInheritedConstructorNote(S, Fn);
8602       return;
8603     }
8604 
8605     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8606       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8607       << (unsigned) FnKind << FnDesc
8608       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8609       << FromTy
8610       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8611       << (unsigned) isObjectArgument << I+1;
8612       MaybeEmitInheritedConstructorNote(S, Fn);
8613       return;
8614     }
8615 
8616     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8617     assert(CVR && "unexpected qualifiers mismatch");
8618 
8619     if (isObjectArgument) {
8620       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8621         << (unsigned) FnKind << FnDesc
8622         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8623         << FromTy << (CVR - 1);
8624     } else {
8625       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8626         << (unsigned) FnKind << FnDesc
8627         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8628         << FromTy << (CVR - 1) << I+1;
8629     }
8630     MaybeEmitInheritedConstructorNote(S, Fn);
8631     return;
8632   }
8633 
8634   // Special diagnostic for failure to convert an initializer list, since
8635   // telling the user that it has type void is not useful.
8636   if (FromExpr && isa<InitListExpr>(FromExpr)) {
8637     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8638       << (unsigned) FnKind << FnDesc
8639       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8640       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8641     MaybeEmitInheritedConstructorNote(S, Fn);
8642     return;
8643   }
8644 
8645   // Diagnose references or pointers to incomplete types differently,
8646   // since it's far from impossible that the incompleteness triggered
8647   // the failure.
8648   QualType TempFromTy = FromTy.getNonReferenceType();
8649   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8650     TempFromTy = PTy->getPointeeType();
8651   if (TempFromTy->isIncompleteType()) {
8652     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8653       << (unsigned) FnKind << FnDesc
8654       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8655       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8656     MaybeEmitInheritedConstructorNote(S, Fn);
8657     return;
8658   }
8659 
8660   // Diagnose base -> derived pointer conversions.
8661   unsigned BaseToDerivedConversion = 0;
8662   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8663     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8664       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8665                                                FromPtrTy->getPointeeType()) &&
8666           !FromPtrTy->getPointeeType()->isIncompleteType() &&
8667           !ToPtrTy->getPointeeType()->isIncompleteType() &&
8668           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8669                           FromPtrTy->getPointeeType()))
8670         BaseToDerivedConversion = 1;
8671     }
8672   } else if (const ObjCObjectPointerType *FromPtrTy
8673                                     = FromTy->getAs<ObjCObjectPointerType>()) {
8674     if (const ObjCObjectPointerType *ToPtrTy
8675                                         = ToTy->getAs<ObjCObjectPointerType>())
8676       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8677         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8678           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8679                                                 FromPtrTy->getPointeeType()) &&
8680               FromIface->isSuperClassOf(ToIface))
8681             BaseToDerivedConversion = 2;
8682   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8683     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8684         !FromTy->isIncompleteType() &&
8685         !ToRefTy->getPointeeType()->isIncompleteType() &&
8686         S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8687       BaseToDerivedConversion = 3;
8688     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8689                ToTy.getNonReferenceType().getCanonicalType() ==
8690                FromTy.getNonReferenceType().getCanonicalType()) {
8691       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8692         << (unsigned) FnKind << FnDesc
8693         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8694         << (unsigned) isObjectArgument << I + 1;
8695       MaybeEmitInheritedConstructorNote(S, Fn);
8696       return;
8697     }
8698   }
8699 
8700   if (BaseToDerivedConversion) {
8701     S.Diag(Fn->getLocation(),
8702            diag::note_ovl_candidate_bad_base_to_derived_conv)
8703       << (unsigned) FnKind << FnDesc
8704       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8705       << (BaseToDerivedConversion - 1)
8706       << FromTy << ToTy << I+1;
8707     MaybeEmitInheritedConstructorNote(S, Fn);
8708     return;
8709   }
8710 
8711   if (isa<ObjCObjectPointerType>(CFromTy) &&
8712       isa<PointerType>(CToTy)) {
8713       Qualifiers FromQs = CFromTy.getQualifiers();
8714       Qualifiers ToQs = CToTy.getQualifiers();
8715       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8716         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8717         << (unsigned) FnKind << FnDesc
8718         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8719         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8720         MaybeEmitInheritedConstructorNote(S, Fn);
8721         return;
8722       }
8723   }
8724 
8725   // Emit the generic diagnostic and, optionally, add the hints to it.
8726   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8727   FDiag << (unsigned) FnKind << FnDesc
8728     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8729     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8730     << (unsigned) (Cand->Fix.Kind);
8731 
8732   // If we can fix the conversion, suggest the FixIts.
8733   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8734        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8735     FDiag << *HI;
8736   S.Diag(Fn->getLocation(), FDiag);
8737 
8738   MaybeEmitInheritedConstructorNote(S, Fn);
8739 }
8740 
8741 /// Additional arity mismatch diagnosis specific to a function overload
8742 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
8743 /// over a candidate in any candidate set.
CheckArityMismatch(Sema & S,OverloadCandidate * Cand,unsigned NumArgs)8744 bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8745                         unsigned NumArgs) {
8746   FunctionDecl *Fn = Cand->Function;
8747   unsigned MinParams = Fn->getMinRequiredArguments();
8748 
8749   // With invalid overloaded operators, it's possible that we think we
8750   // have an arity mismatch when in fact it looks like we have the
8751   // right number of arguments, because only overloaded operators have
8752   // the weird behavior of overloading member and non-member functions.
8753   // Just don't report anything.
8754   if (Fn->isInvalidDecl() &&
8755       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8756     return true;
8757 
8758   if (NumArgs < MinParams) {
8759     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8760            (Cand->FailureKind == ovl_fail_bad_deduction &&
8761             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8762   } else {
8763     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8764            (Cand->FailureKind == ovl_fail_bad_deduction &&
8765             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8766   }
8767 
8768   return false;
8769 }
8770 
8771 /// General arity mismatch diagnosis over a candidate in a candidate set.
DiagnoseArityMismatch(Sema & S,Decl * D,unsigned NumFormalArgs)8772 void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8773   assert(isa<FunctionDecl>(D) &&
8774       "The templated declaration should at least be a function"
8775       " when diagnosing bad template argument deduction due to too many"
8776       " or too few arguments");
8777 
8778   FunctionDecl *Fn = cast<FunctionDecl>(D);
8779 
8780   // TODO: treat calls to a missing default constructor as a special case
8781   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8782   unsigned MinParams = Fn->getMinRequiredArguments();
8783 
8784   // at least / at most / exactly
8785   unsigned mode, modeCount;
8786   if (NumFormalArgs < MinParams) {
8787     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8788         FnTy->isTemplateVariadic())
8789       mode = 0; // "at least"
8790     else
8791       mode = 2; // "exactly"
8792     modeCount = MinParams;
8793   } else {
8794     if (MinParams != FnTy->getNumParams())
8795       mode = 1; // "at most"
8796     else
8797       mode = 2; // "exactly"
8798     modeCount = FnTy->getNumParams();
8799   }
8800 
8801   std::string Description;
8802   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8803 
8804   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8805     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8806       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8807       << mode << Fn->getParamDecl(0) << NumFormalArgs;
8808   else
8809     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8810       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8811       << mode << modeCount << NumFormalArgs;
8812   MaybeEmitInheritedConstructorNote(S, Fn);
8813 }
8814 
8815 /// Arity mismatch diagnosis specific to a function overload candidate.
DiagnoseArityMismatch(Sema & S,OverloadCandidate * Cand,unsigned NumFormalArgs)8816 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8817                            unsigned NumFormalArgs) {
8818   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8819     DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8820 }
8821 
getDescribedTemplate(Decl * Templated)8822 TemplateDecl *getDescribedTemplate(Decl *Templated) {
8823   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8824     return FD->getDescribedFunctionTemplate();
8825   else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8826     return RD->getDescribedClassTemplate();
8827 
8828   llvm_unreachable("Unsupported: Getting the described template declaration"
8829                    " for bad deduction diagnosis");
8830 }
8831 
8832 /// Diagnose a failed template-argument deduction.
DiagnoseBadDeduction(Sema & S,Decl * Templated,DeductionFailureInfo & DeductionFailure,unsigned NumArgs)8833 void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8834                           DeductionFailureInfo &DeductionFailure,
8835                           unsigned NumArgs) {
8836   TemplateParameter Param = DeductionFailure.getTemplateParameter();
8837   NamedDecl *ParamD;
8838   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8839   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8840   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8841   switch (DeductionFailure.Result) {
8842   case Sema::TDK_Success:
8843     llvm_unreachable("TDK_success while diagnosing bad deduction");
8844 
8845   case Sema::TDK_Incomplete: {
8846     assert(ParamD && "no parameter found for incomplete deduction result");
8847     S.Diag(Templated->getLocation(),
8848            diag::note_ovl_candidate_incomplete_deduction)
8849         << ParamD->getDeclName();
8850     MaybeEmitInheritedConstructorNote(S, Templated);
8851     return;
8852   }
8853 
8854   case Sema::TDK_Underqualified: {
8855     assert(ParamD && "no parameter found for bad qualifiers deduction result");
8856     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8857 
8858     QualType Param = DeductionFailure.getFirstArg()->getAsType();
8859 
8860     // Param will have been canonicalized, but it should just be a
8861     // qualified version of ParamD, so move the qualifiers to that.
8862     QualifierCollector Qs;
8863     Qs.strip(Param);
8864     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8865     assert(S.Context.hasSameType(Param, NonCanonParam));
8866 
8867     // Arg has also been canonicalized, but there's nothing we can do
8868     // about that.  It also doesn't matter as much, because it won't
8869     // have any template parameters in it (because deduction isn't
8870     // done on dependent types).
8871     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
8872 
8873     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8874         << ParamD->getDeclName() << Arg << NonCanonParam;
8875     MaybeEmitInheritedConstructorNote(S, Templated);
8876     return;
8877   }
8878 
8879   case Sema::TDK_Inconsistent: {
8880     assert(ParamD && "no parameter found for inconsistent deduction result");
8881     int which = 0;
8882     if (isa<TemplateTypeParmDecl>(ParamD))
8883       which = 0;
8884     else if (isa<NonTypeTemplateParmDecl>(ParamD))
8885       which = 1;
8886     else {
8887       which = 2;
8888     }
8889 
8890     S.Diag(Templated->getLocation(),
8891            diag::note_ovl_candidate_inconsistent_deduction)
8892         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8893         << *DeductionFailure.getSecondArg();
8894     MaybeEmitInheritedConstructorNote(S, Templated);
8895     return;
8896   }
8897 
8898   case Sema::TDK_InvalidExplicitArguments:
8899     assert(ParamD && "no parameter found for invalid explicit arguments");
8900     if (ParamD->getDeclName())
8901       S.Diag(Templated->getLocation(),
8902              diag::note_ovl_candidate_explicit_arg_mismatch_named)
8903           << ParamD->getDeclName();
8904     else {
8905       int index = 0;
8906       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8907         index = TTP->getIndex();
8908       else if (NonTypeTemplateParmDecl *NTTP
8909                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8910         index = NTTP->getIndex();
8911       else
8912         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8913       S.Diag(Templated->getLocation(),
8914              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8915           << (index + 1);
8916     }
8917     MaybeEmitInheritedConstructorNote(S, Templated);
8918     return;
8919 
8920   case Sema::TDK_TooManyArguments:
8921   case Sema::TDK_TooFewArguments:
8922     DiagnoseArityMismatch(S, Templated, NumArgs);
8923     return;
8924 
8925   case Sema::TDK_InstantiationDepth:
8926     S.Diag(Templated->getLocation(),
8927            diag::note_ovl_candidate_instantiation_depth);
8928     MaybeEmitInheritedConstructorNote(S, Templated);
8929     return;
8930 
8931   case Sema::TDK_SubstitutionFailure: {
8932     // Format the template argument list into the argument string.
8933     SmallString<128> TemplateArgString;
8934     if (TemplateArgumentList *Args =
8935             DeductionFailure.getTemplateArgumentList()) {
8936       TemplateArgString = " ";
8937       TemplateArgString += S.getTemplateArgumentBindingsText(
8938           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
8939     }
8940 
8941     // If this candidate was disabled by enable_if, say so.
8942     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
8943     if (PDiag && PDiag->second.getDiagID() ==
8944           diag::err_typename_nested_not_found_enable_if) {
8945       // FIXME: Use the source range of the condition, and the fully-qualified
8946       //        name of the enable_if template. These are both present in PDiag.
8947       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8948         << "'enable_if'" << TemplateArgString;
8949       return;
8950     }
8951 
8952     // Format the SFINAE diagnostic into the argument string.
8953     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8954     //        formatted message in another diagnostic.
8955     SmallString<128> SFINAEArgString;
8956     SourceRange R;
8957     if (PDiag) {
8958       SFINAEArgString = ": ";
8959       R = SourceRange(PDiag->first, PDiag->first);
8960       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8961     }
8962 
8963     S.Diag(Templated->getLocation(),
8964            diag::note_ovl_candidate_substitution_failure)
8965         << TemplateArgString << SFINAEArgString << R;
8966     MaybeEmitInheritedConstructorNote(S, Templated);
8967     return;
8968   }
8969 
8970   case Sema::TDK_FailedOverloadResolution: {
8971     OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8972     S.Diag(Templated->getLocation(),
8973            diag::note_ovl_candidate_failed_overload_resolution)
8974         << R.Expression->getName();
8975     return;
8976   }
8977 
8978   case Sema::TDK_NonDeducedMismatch: {
8979     // FIXME: Provide a source location to indicate what we couldn't match.
8980     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8981     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
8982     if (FirstTA.getKind() == TemplateArgument::Template &&
8983         SecondTA.getKind() == TemplateArgument::Template) {
8984       TemplateName FirstTN = FirstTA.getAsTemplate();
8985       TemplateName SecondTN = SecondTA.getAsTemplate();
8986       if (FirstTN.getKind() == TemplateName::Template &&
8987           SecondTN.getKind() == TemplateName::Template) {
8988         if (FirstTN.getAsTemplateDecl()->getName() ==
8989             SecondTN.getAsTemplateDecl()->getName()) {
8990           // FIXME: This fixes a bad diagnostic where both templates are named
8991           // the same.  This particular case is a bit difficult since:
8992           // 1) It is passed as a string to the diagnostic printer.
8993           // 2) The diagnostic printer only attempts to find a better
8994           //    name for types, not decls.
8995           // Ideally, this should folded into the diagnostic printer.
8996           S.Diag(Templated->getLocation(),
8997                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8998               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8999           return;
9000         }
9001       }
9002     }
9003     // FIXME: For generic lambda parameters, check if the function is a lambda
9004     // call operator, and if so, emit a prettier and more informative
9005     // diagnostic that mentions 'auto' and lambda in addition to
9006     // (or instead of?) the canonical template type parameters.
9007     S.Diag(Templated->getLocation(),
9008            diag::note_ovl_candidate_non_deduced_mismatch)
9009         << FirstTA << SecondTA;
9010     return;
9011   }
9012   // TODO: diagnose these individually, then kill off
9013   // note_ovl_candidate_bad_deduction, which is uselessly vague.
9014   case Sema::TDK_MiscellaneousDeductionFailure:
9015     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9016     MaybeEmitInheritedConstructorNote(S, Templated);
9017     return;
9018   }
9019 }
9020 
9021 /// Diagnose a failed template-argument deduction, for function calls.
DiagnoseBadDeduction(Sema & S,OverloadCandidate * Cand,unsigned NumArgs)9022 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
9023   unsigned TDK = Cand->DeductionFailure.Result;
9024   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9025     if (CheckArityMismatch(S, Cand, NumArgs))
9026       return;
9027   }
9028   DiagnoseBadDeduction(S, Cand->Function, // pattern
9029                        Cand->DeductionFailure, NumArgs);
9030 }
9031 
9032 /// CUDA: diagnose an invalid call across targets.
DiagnoseBadTarget(Sema & S,OverloadCandidate * Cand)9033 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9034   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9035   FunctionDecl *Callee = Cand->Function;
9036 
9037   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9038                            CalleeTarget = S.IdentifyCUDATarget(Callee);
9039 
9040   std::string FnDesc;
9041   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9042 
9043   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9044       << (unsigned) FnKind << CalleeTarget << CallerTarget;
9045 }
9046 
DiagnoseFailedEnableIfAttr(Sema & S,OverloadCandidate * Cand)9047 void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9048   FunctionDecl *Callee = Cand->Function;
9049   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9050 
9051   S.Diag(Callee->getLocation(),
9052          diag::note_ovl_candidate_disabled_by_enable_if_attr)
9053       << Attr->getCond()->getSourceRange() << Attr->getMessage();
9054 }
9055 
9056 /// Generates a 'note' diagnostic for an overload candidate.  We've
9057 /// already generated a primary error at the call site.
9058 ///
9059 /// It really does need to be a single diagnostic with its caret
9060 /// pointed at the candidate declaration.  Yes, this creates some
9061 /// major challenges of technical writing.  Yes, this makes pointing
9062 /// out problems with specific arguments quite awkward.  It's still
9063 /// better than generating twenty screens of text for every failed
9064 /// overload.
9065 ///
9066 /// It would be great to be able to express per-candidate problems
9067 /// more richly for those diagnostic clients that cared, but we'd
9068 /// still have to be just as careful with the default diagnostics.
NoteFunctionCandidate(Sema & S,OverloadCandidate * Cand,unsigned NumArgs)9069 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9070                            unsigned NumArgs) {
9071   FunctionDecl *Fn = Cand->Function;
9072 
9073   // Note deleted candidates, but only if they're viable.
9074   if (Cand->Viable && (Fn->isDeleted() ||
9075       S.isFunctionConsideredUnavailable(Fn))) {
9076     std::string FnDesc;
9077     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9078 
9079     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9080       << FnKind << FnDesc
9081       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9082     MaybeEmitInheritedConstructorNote(S, Fn);
9083     return;
9084   }
9085 
9086   // We don't really have anything else to say about viable candidates.
9087   if (Cand->Viable) {
9088     S.NoteOverloadCandidate(Fn);
9089     return;
9090   }
9091 
9092   switch (Cand->FailureKind) {
9093   case ovl_fail_too_many_arguments:
9094   case ovl_fail_too_few_arguments:
9095     return DiagnoseArityMismatch(S, Cand, NumArgs);
9096 
9097   case ovl_fail_bad_deduction:
9098     return DiagnoseBadDeduction(S, Cand, NumArgs);
9099 
9100   case ovl_fail_trivial_conversion:
9101   case ovl_fail_bad_final_conversion:
9102   case ovl_fail_final_conversion_not_exact:
9103     return S.NoteOverloadCandidate(Fn);
9104 
9105   case ovl_fail_bad_conversion: {
9106     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9107     for (unsigned N = Cand->NumConversions; I != N; ++I)
9108       if (Cand->Conversions[I].isBad())
9109         return DiagnoseBadConversion(S, Cand, I);
9110 
9111     // FIXME: this currently happens when we're called from SemaInit
9112     // when user-conversion overload fails.  Figure out how to handle
9113     // those conditions and diagnose them well.
9114     return S.NoteOverloadCandidate(Fn);
9115   }
9116 
9117   case ovl_fail_bad_target:
9118     return DiagnoseBadTarget(S, Cand);
9119 
9120   case ovl_fail_enable_if:
9121     return DiagnoseFailedEnableIfAttr(S, Cand);
9122   }
9123 }
9124 
NoteSurrogateCandidate(Sema & S,OverloadCandidate * Cand)9125 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9126   // Desugar the type of the surrogate down to a function type,
9127   // retaining as many typedefs as possible while still showing
9128   // the function type (and, therefore, its parameter types).
9129   QualType FnType = Cand->Surrogate->getConversionType();
9130   bool isLValueReference = false;
9131   bool isRValueReference = false;
9132   bool isPointer = false;
9133   if (const LValueReferenceType *FnTypeRef =
9134         FnType->getAs<LValueReferenceType>()) {
9135     FnType = FnTypeRef->getPointeeType();
9136     isLValueReference = true;
9137   } else if (const RValueReferenceType *FnTypeRef =
9138                FnType->getAs<RValueReferenceType>()) {
9139     FnType = FnTypeRef->getPointeeType();
9140     isRValueReference = true;
9141   }
9142   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9143     FnType = FnTypePtr->getPointeeType();
9144     isPointer = true;
9145   }
9146   // Desugar down to a function type.
9147   FnType = QualType(FnType->getAs<FunctionType>(), 0);
9148   // Reconstruct the pointer/reference as appropriate.
9149   if (isPointer) FnType = S.Context.getPointerType(FnType);
9150   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9151   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9152 
9153   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9154     << FnType;
9155   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9156 }
9157 
NoteBuiltinOperatorCandidate(Sema & S,StringRef Opc,SourceLocation OpLoc,OverloadCandidate * Cand)9158 void NoteBuiltinOperatorCandidate(Sema &S,
9159                                   StringRef Opc,
9160                                   SourceLocation OpLoc,
9161                                   OverloadCandidate *Cand) {
9162   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9163   std::string TypeStr("operator");
9164   TypeStr += Opc;
9165   TypeStr += "(";
9166   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9167   if (Cand->NumConversions == 1) {
9168     TypeStr += ")";
9169     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9170   } else {
9171     TypeStr += ", ";
9172     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9173     TypeStr += ")";
9174     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9175   }
9176 }
9177 
NoteAmbiguousUserConversions(Sema & S,SourceLocation OpLoc,OverloadCandidate * Cand)9178 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9179                                   OverloadCandidate *Cand) {
9180   unsigned NoOperands = Cand->NumConversions;
9181   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9182     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9183     if (ICS.isBad()) break; // all meaningless after first invalid
9184     if (!ICS.isAmbiguous()) continue;
9185 
9186     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9187                               S.PDiag(diag::note_ambiguous_type_conversion));
9188   }
9189 }
9190 
GetLocationForCandidate(const OverloadCandidate * Cand)9191 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9192   if (Cand->Function)
9193     return Cand->Function->getLocation();
9194   if (Cand->IsSurrogate)
9195     return Cand->Surrogate->getLocation();
9196   return SourceLocation();
9197 }
9198 
RankDeductionFailure(const DeductionFailureInfo & DFI)9199 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9200   switch ((Sema::TemplateDeductionResult)DFI.Result) {
9201   case Sema::TDK_Success:
9202     llvm_unreachable("TDK_success while diagnosing bad deduction");
9203 
9204   case Sema::TDK_Invalid:
9205   case Sema::TDK_Incomplete:
9206     return 1;
9207 
9208   case Sema::TDK_Underqualified:
9209   case Sema::TDK_Inconsistent:
9210     return 2;
9211 
9212   case Sema::TDK_SubstitutionFailure:
9213   case Sema::TDK_NonDeducedMismatch:
9214   case Sema::TDK_MiscellaneousDeductionFailure:
9215     return 3;
9216 
9217   case Sema::TDK_InstantiationDepth:
9218   case Sema::TDK_FailedOverloadResolution:
9219     return 4;
9220 
9221   case Sema::TDK_InvalidExplicitArguments:
9222     return 5;
9223 
9224   case Sema::TDK_TooManyArguments:
9225   case Sema::TDK_TooFewArguments:
9226     return 6;
9227   }
9228   llvm_unreachable("Unhandled deduction result");
9229 }
9230 
9231 struct CompareOverloadCandidatesForDisplay {
9232   Sema &S;
9233   size_t NumArgs;
9234 
CompareOverloadCandidatesForDisplayclang::__anon1b2261b70711::CompareOverloadCandidatesForDisplay9235   CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9236       : S(S), NumArgs(nArgs) {}
9237 
operator ()clang::__anon1b2261b70711::CompareOverloadCandidatesForDisplay9238   bool operator()(const OverloadCandidate *L,
9239                   const OverloadCandidate *R) {
9240     // Fast-path this check.
9241     if (L == R) return false;
9242 
9243     // Order first by viability.
9244     if (L->Viable) {
9245       if (!R->Viable) return true;
9246 
9247       // TODO: introduce a tri-valued comparison for overload
9248       // candidates.  Would be more worthwhile if we had a sort
9249       // that could exploit it.
9250       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9251       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9252     } else if (R->Viable)
9253       return false;
9254 
9255     assert(L->Viable == R->Viable);
9256 
9257     // Criteria by which we can sort non-viable candidates:
9258     if (!L->Viable) {
9259       // 1. Arity mismatches come after other candidates.
9260       if (L->FailureKind == ovl_fail_too_many_arguments ||
9261           L->FailureKind == ovl_fail_too_few_arguments) {
9262         if (R->FailureKind == ovl_fail_too_many_arguments ||
9263             R->FailureKind == ovl_fail_too_few_arguments) {
9264           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9265           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9266           if (LDist == RDist) {
9267             if (L->FailureKind == R->FailureKind)
9268               // Sort non-surrogates before surrogates.
9269               return !L->IsSurrogate && R->IsSurrogate;
9270             // Sort candidates requiring fewer parameters than there were
9271             // arguments given after candidates requiring more parameters
9272             // than there were arguments given.
9273             return L->FailureKind == ovl_fail_too_many_arguments;
9274           }
9275           return LDist < RDist;
9276         }
9277         return false;
9278       }
9279       if (R->FailureKind == ovl_fail_too_many_arguments ||
9280           R->FailureKind == ovl_fail_too_few_arguments)
9281         return true;
9282 
9283       // 2. Bad conversions come first and are ordered by the number
9284       // of bad conversions and quality of good conversions.
9285       if (L->FailureKind == ovl_fail_bad_conversion) {
9286         if (R->FailureKind != ovl_fail_bad_conversion)
9287           return true;
9288 
9289         // The conversion that can be fixed with a smaller number of changes,
9290         // comes first.
9291         unsigned numLFixes = L->Fix.NumConversionsFixed;
9292         unsigned numRFixes = R->Fix.NumConversionsFixed;
9293         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9294         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9295         if (numLFixes != numRFixes) {
9296           if (numLFixes < numRFixes)
9297             return true;
9298           else
9299             return false;
9300         }
9301 
9302         // If there's any ordering between the defined conversions...
9303         // FIXME: this might not be transitive.
9304         assert(L->NumConversions == R->NumConversions);
9305 
9306         int leftBetter = 0;
9307         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9308         for (unsigned E = L->NumConversions; I != E; ++I) {
9309           switch (CompareImplicitConversionSequences(S,
9310                                                      L->Conversions[I],
9311                                                      R->Conversions[I])) {
9312           case ImplicitConversionSequence::Better:
9313             leftBetter++;
9314             break;
9315 
9316           case ImplicitConversionSequence::Worse:
9317             leftBetter--;
9318             break;
9319 
9320           case ImplicitConversionSequence::Indistinguishable:
9321             break;
9322           }
9323         }
9324         if (leftBetter > 0) return true;
9325         if (leftBetter < 0) return false;
9326 
9327       } else if (R->FailureKind == ovl_fail_bad_conversion)
9328         return false;
9329 
9330       if (L->FailureKind == ovl_fail_bad_deduction) {
9331         if (R->FailureKind != ovl_fail_bad_deduction)
9332           return true;
9333 
9334         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9335           return RankDeductionFailure(L->DeductionFailure)
9336                < RankDeductionFailure(R->DeductionFailure);
9337       } else if (R->FailureKind == ovl_fail_bad_deduction)
9338         return false;
9339 
9340       // TODO: others?
9341     }
9342 
9343     // Sort everything else by location.
9344     SourceLocation LLoc = GetLocationForCandidate(L);
9345     SourceLocation RLoc = GetLocationForCandidate(R);
9346 
9347     // Put candidates without locations (e.g. builtins) at the end.
9348     if (LLoc.isInvalid()) return false;
9349     if (RLoc.isInvalid()) return true;
9350 
9351     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9352   }
9353 };
9354 
9355 /// CompleteNonViableCandidate - Normally, overload resolution only
9356 /// computes up to the first. Produces the FixIt set if possible.
CompleteNonViableCandidate(Sema & S,OverloadCandidate * Cand,ArrayRef<Expr * > Args)9357 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9358                                 ArrayRef<Expr *> Args) {
9359   assert(!Cand->Viable);
9360 
9361   // Don't do anything on failures other than bad conversion.
9362   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9363 
9364   // We only want the FixIts if all the arguments can be corrected.
9365   bool Unfixable = false;
9366   // Use a implicit copy initialization to check conversion fixes.
9367   Cand->Fix.setConversionChecker(TryCopyInitialization);
9368 
9369   // Skip forward to the first bad conversion.
9370   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9371   unsigned ConvCount = Cand->NumConversions;
9372   while (true) {
9373     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9374     ConvIdx++;
9375     if (Cand->Conversions[ConvIdx - 1].isBad()) {
9376       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9377       break;
9378     }
9379   }
9380 
9381   if (ConvIdx == ConvCount)
9382     return;
9383 
9384   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9385          "remaining conversion is initialized?");
9386 
9387   // FIXME: this should probably be preserved from the overload
9388   // operation somehow.
9389   bool SuppressUserConversions = false;
9390 
9391   const FunctionProtoType* Proto;
9392   unsigned ArgIdx = ConvIdx;
9393 
9394   if (Cand->IsSurrogate) {
9395     QualType ConvType
9396       = Cand->Surrogate->getConversionType().getNonReferenceType();
9397     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9398       ConvType = ConvPtrType->getPointeeType();
9399     Proto = ConvType->getAs<FunctionProtoType>();
9400     ArgIdx--;
9401   } else if (Cand->Function) {
9402     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9403     if (isa<CXXMethodDecl>(Cand->Function) &&
9404         !isa<CXXConstructorDecl>(Cand->Function))
9405       ArgIdx--;
9406   } else {
9407     // Builtin binary operator with a bad first conversion.
9408     assert(ConvCount <= 3);
9409     for (; ConvIdx != ConvCount; ++ConvIdx)
9410       Cand->Conversions[ConvIdx]
9411         = TryCopyInitialization(S, Args[ConvIdx],
9412                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9413                                 SuppressUserConversions,
9414                                 /*InOverloadResolution*/ true,
9415                                 /*AllowObjCWritebackConversion=*/
9416                                   S.getLangOpts().ObjCAutoRefCount);
9417     return;
9418   }
9419 
9420   // Fill in the rest of the conversions.
9421   unsigned NumParams = Proto->getNumParams();
9422   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9423     if (ArgIdx < NumParams) {
9424       Cand->Conversions[ConvIdx] = TryCopyInitialization(
9425           S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9426           /*InOverloadResolution=*/true,
9427           /*AllowObjCWritebackConversion=*/
9428           S.getLangOpts().ObjCAutoRefCount);
9429       // Store the FixIt in the candidate if it exists.
9430       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9431         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9432     }
9433     else
9434       Cand->Conversions[ConvIdx].setEllipsis();
9435   }
9436 }
9437 
9438 } // end anonymous namespace
9439 
9440 /// PrintOverloadCandidates - When overload resolution fails, prints
9441 /// diagnostic messages containing the candidates in the candidate
9442 /// set.
NoteCandidates(Sema & S,OverloadCandidateDisplayKind OCD,ArrayRef<Expr * > Args,StringRef Opc,SourceLocation OpLoc)9443 void OverloadCandidateSet::NoteCandidates(Sema &S,
9444                                           OverloadCandidateDisplayKind OCD,
9445                                           ArrayRef<Expr *> Args,
9446                                           StringRef Opc,
9447                                           SourceLocation OpLoc) {
9448   // Sort the candidates by viability and position.  Sorting directly would
9449   // be prohibitive, so we make a set of pointers and sort those.
9450   SmallVector<OverloadCandidate*, 32> Cands;
9451   if (OCD == OCD_AllCandidates) Cands.reserve(size());
9452   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9453     if (Cand->Viable)
9454       Cands.push_back(Cand);
9455     else if (OCD == OCD_AllCandidates) {
9456       CompleteNonViableCandidate(S, Cand, Args);
9457       if (Cand->Function || Cand->IsSurrogate)
9458         Cands.push_back(Cand);
9459       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
9460       // want to list every possible builtin candidate.
9461     }
9462   }
9463 
9464   std::sort(Cands.begin(), Cands.end(),
9465             CompareOverloadCandidatesForDisplay(S, Args.size()));
9466 
9467   bool ReportedAmbiguousConversions = false;
9468 
9469   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9470   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9471   unsigned CandsShown = 0;
9472   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9473     OverloadCandidate *Cand = *I;
9474 
9475     // Set an arbitrary limit on the number of candidate functions we'll spam
9476     // the user with.  FIXME: This limit should depend on details of the
9477     // candidate list.
9478     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9479       break;
9480     }
9481     ++CandsShown;
9482 
9483     if (Cand->Function)
9484       NoteFunctionCandidate(S, Cand, Args.size());
9485     else if (Cand->IsSurrogate)
9486       NoteSurrogateCandidate(S, Cand);
9487     else {
9488       assert(Cand->Viable &&
9489              "Non-viable built-in candidates are not added to Cands.");
9490       // Generally we only see ambiguities including viable builtin
9491       // operators if overload resolution got screwed up by an
9492       // ambiguous user-defined conversion.
9493       //
9494       // FIXME: It's quite possible for different conversions to see
9495       // different ambiguities, though.
9496       if (!ReportedAmbiguousConversions) {
9497         NoteAmbiguousUserConversions(S, OpLoc, Cand);
9498         ReportedAmbiguousConversions = true;
9499       }
9500 
9501       // If this is a viable builtin, print it.
9502       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9503     }
9504   }
9505 
9506   if (I != E)
9507     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9508 }
9509 
9510 static SourceLocation
GetLocationForCandidate(const TemplateSpecCandidate * Cand)9511 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9512   return Cand->Specialization ? Cand->Specialization->getLocation()
9513                               : SourceLocation();
9514 }
9515 
9516 struct CompareTemplateSpecCandidatesForDisplay {
9517   Sema &S;
CompareTemplateSpecCandidatesForDisplayclang::CompareTemplateSpecCandidatesForDisplay9518   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9519 
operator ()clang::CompareTemplateSpecCandidatesForDisplay9520   bool operator()(const TemplateSpecCandidate *L,
9521                   const TemplateSpecCandidate *R) {
9522     // Fast-path this check.
9523     if (L == R)
9524       return false;
9525 
9526     // Assuming that both candidates are not matches...
9527 
9528     // Sort by the ranking of deduction failures.
9529     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9530       return RankDeductionFailure(L->DeductionFailure) <
9531              RankDeductionFailure(R->DeductionFailure);
9532 
9533     // Sort everything else by location.
9534     SourceLocation LLoc = GetLocationForCandidate(L);
9535     SourceLocation RLoc = GetLocationForCandidate(R);
9536 
9537     // Put candidates without locations (e.g. builtins) at the end.
9538     if (LLoc.isInvalid())
9539       return false;
9540     if (RLoc.isInvalid())
9541       return true;
9542 
9543     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9544   }
9545 };
9546 
9547 /// Diagnose a template argument deduction failure.
9548 /// We are treating these failures as overload failures due to bad
9549 /// deductions.
NoteDeductionFailure(Sema & S)9550 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9551   DiagnoseBadDeduction(S, Specialization, // pattern
9552                        DeductionFailure, /*NumArgs=*/0);
9553 }
9554 
destroyCandidates()9555 void TemplateSpecCandidateSet::destroyCandidates() {
9556   for (iterator i = begin(), e = end(); i != e; ++i) {
9557     i->DeductionFailure.Destroy();
9558   }
9559 }
9560 
clear()9561 void TemplateSpecCandidateSet::clear() {
9562   destroyCandidates();
9563   Candidates.clear();
9564 }
9565 
9566 /// NoteCandidates - When no template specialization match is found, prints
9567 /// diagnostic messages containing the non-matching specializations that form
9568 /// the candidate set.
9569 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9570 /// OCD == OCD_AllCandidates and Cand->Viable == false.
NoteCandidates(Sema & S,SourceLocation Loc)9571 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9572   // Sort the candidates by position (assuming no candidate is a match).
9573   // Sorting directly would be prohibitive, so we make a set of pointers
9574   // and sort those.
9575   SmallVector<TemplateSpecCandidate *, 32> Cands;
9576   Cands.reserve(size());
9577   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9578     if (Cand->Specialization)
9579       Cands.push_back(Cand);
9580     // Otherwise, this is a non-matching builtin candidate.  We do not,
9581     // in general, want to list every possible builtin candidate.
9582   }
9583 
9584   std::sort(Cands.begin(), Cands.end(),
9585             CompareTemplateSpecCandidatesForDisplay(S));
9586 
9587   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9588   // for generalization purposes (?).
9589   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9590 
9591   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9592   unsigned CandsShown = 0;
9593   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9594     TemplateSpecCandidate *Cand = *I;
9595 
9596     // Set an arbitrary limit on the number of candidates we'll spam
9597     // the user with.  FIXME: This limit should depend on details of the
9598     // candidate list.
9599     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9600       break;
9601     ++CandsShown;
9602 
9603     assert(Cand->Specialization &&
9604            "Non-matching built-in candidates are not added to Cands.");
9605     Cand->NoteDeductionFailure(S);
9606   }
9607 
9608   if (I != E)
9609     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9610 }
9611 
9612 // [PossiblyAFunctionType]  -->   [Return]
9613 // NonFunctionType --> NonFunctionType
9614 // R (A) --> R(A)
9615 // R (*)(A) --> R (A)
9616 // R (&)(A) --> R (A)
9617 // R (S::*)(A) --> R (A)
ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)9618 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9619   QualType Ret = PossiblyAFunctionType;
9620   if (const PointerType *ToTypePtr =
9621     PossiblyAFunctionType->getAs<PointerType>())
9622     Ret = ToTypePtr->getPointeeType();
9623   else if (const ReferenceType *ToTypeRef =
9624     PossiblyAFunctionType->getAs<ReferenceType>())
9625     Ret = ToTypeRef->getPointeeType();
9626   else if (const MemberPointerType *MemTypePtr =
9627     PossiblyAFunctionType->getAs<MemberPointerType>())
9628     Ret = MemTypePtr->getPointeeType();
9629   Ret =
9630     Context.getCanonicalType(Ret).getUnqualifiedType();
9631   return Ret;
9632 }
9633 
9634 // A helper class to help with address of function resolution
9635 // - allows us to avoid passing around all those ugly parameters
9636 class AddressOfFunctionResolver
9637 {
9638   Sema& S;
9639   Expr* SourceExpr;
9640   const QualType& TargetType;
9641   QualType TargetFunctionType; // Extracted function type from target type
9642 
9643   bool Complain;
9644   //DeclAccessPair& ResultFunctionAccessPair;
9645   ASTContext& Context;
9646 
9647   bool TargetTypeIsNonStaticMemberFunction;
9648   bool FoundNonTemplateFunction;
9649   bool StaticMemberFunctionFromBoundPointer;
9650 
9651   OverloadExpr::FindResult OvlExprInfo;
9652   OverloadExpr *OvlExpr;
9653   TemplateArgumentListInfo OvlExplicitTemplateArgs;
9654   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9655   TemplateSpecCandidateSet FailedCandidates;
9656 
9657 public:
AddressOfFunctionResolver(Sema & S,Expr * SourceExpr,const QualType & TargetType,bool Complain)9658   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9659                             const QualType &TargetType, bool Complain)
9660       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9661         Complain(Complain), Context(S.getASTContext()),
9662         TargetTypeIsNonStaticMemberFunction(
9663             !!TargetType->getAs<MemberPointerType>()),
9664         FoundNonTemplateFunction(false),
9665         StaticMemberFunctionFromBoundPointer(false),
9666         OvlExprInfo(OverloadExpr::find(SourceExpr)),
9667         OvlExpr(OvlExprInfo.Expression),
9668         FailedCandidates(OvlExpr->getNameLoc()) {
9669     ExtractUnqualifiedFunctionTypeFromTargetType();
9670 
9671     if (TargetFunctionType->isFunctionType()) {
9672       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9673         if (!UME->isImplicitAccess() &&
9674             !S.ResolveSingleFunctionTemplateSpecialization(UME))
9675           StaticMemberFunctionFromBoundPointer = true;
9676     } else if (OvlExpr->hasExplicitTemplateArgs()) {
9677       DeclAccessPair dap;
9678       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9679               OvlExpr, false, &dap)) {
9680         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9681           if (!Method->isStatic()) {
9682             // If the target type is a non-function type and the function found
9683             // is a non-static member function, pretend as if that was the
9684             // target, it's the only possible type to end up with.
9685             TargetTypeIsNonStaticMemberFunction = true;
9686 
9687             // And skip adding the function if its not in the proper form.
9688             // We'll diagnose this due to an empty set of functions.
9689             if (!OvlExprInfo.HasFormOfMemberPointer)
9690               return;
9691           }
9692 
9693         Matches.push_back(std::make_pair(dap, Fn));
9694       }
9695       return;
9696     }
9697 
9698     if (OvlExpr->hasExplicitTemplateArgs())
9699       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9700 
9701     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9702       // C++ [over.over]p4:
9703       //   If more than one function is selected, [...]
9704       if (Matches.size() > 1) {
9705         if (FoundNonTemplateFunction)
9706           EliminateAllTemplateMatches();
9707         else
9708           EliminateAllExceptMostSpecializedTemplate();
9709       }
9710     }
9711   }
9712 
9713 private:
isTargetTypeAFunction() const9714   bool isTargetTypeAFunction() const {
9715     return TargetFunctionType->isFunctionType();
9716   }
9717 
9718   // [ToType]     [Return]
9719 
9720   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9721   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9722   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
ExtractUnqualifiedFunctionTypeFromTargetType()9723   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9724     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9725   }
9726 
9727   // return true if any matching specializations were found
AddMatchingTemplateFunction(FunctionTemplateDecl * FunctionTemplate,const DeclAccessPair & CurAccessFunPair)9728   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9729                                    const DeclAccessPair& CurAccessFunPair) {
9730     if (CXXMethodDecl *Method
9731               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9732       // Skip non-static function templates when converting to pointer, and
9733       // static when converting to member pointer.
9734       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9735         return false;
9736     }
9737     else if (TargetTypeIsNonStaticMemberFunction)
9738       return false;
9739 
9740     // C++ [over.over]p2:
9741     //   If the name is a function template, template argument deduction is
9742     //   done (14.8.2.2), and if the argument deduction succeeds, the
9743     //   resulting template argument list is used to generate a single
9744     //   function template specialization, which is added to the set of
9745     //   overloaded functions considered.
9746     FunctionDecl *Specialization = nullptr;
9747     TemplateDeductionInfo Info(FailedCandidates.getLocation());
9748     if (Sema::TemplateDeductionResult Result
9749           = S.DeduceTemplateArguments(FunctionTemplate,
9750                                       &OvlExplicitTemplateArgs,
9751                                       TargetFunctionType, Specialization,
9752                                       Info, /*InOverloadResolution=*/true)) {
9753       // Make a note of the failed deduction for diagnostics.
9754       FailedCandidates.addCandidate()
9755           .set(FunctionTemplate->getTemplatedDecl(),
9756                MakeDeductionFailureInfo(Context, Result, Info));
9757       return false;
9758     }
9759 
9760     // Template argument deduction ensures that we have an exact match or
9761     // compatible pointer-to-function arguments that would be adjusted by ICS.
9762     // This function template specicalization works.
9763     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9764     assert(S.isSameOrCompatibleFunctionType(
9765               Context.getCanonicalType(Specialization->getType()),
9766               Context.getCanonicalType(TargetFunctionType)));
9767     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9768     return true;
9769   }
9770 
AddMatchingNonTemplateFunction(NamedDecl * Fn,const DeclAccessPair & CurAccessFunPair)9771   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9772                                       const DeclAccessPair& CurAccessFunPair) {
9773     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9774       // Skip non-static functions when converting to pointer, and static
9775       // when converting to member pointer.
9776       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9777         return false;
9778     }
9779     else if (TargetTypeIsNonStaticMemberFunction)
9780       return false;
9781 
9782     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9783       if (S.getLangOpts().CUDA)
9784         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9785           if (S.CheckCUDATarget(Caller, FunDecl))
9786             return false;
9787 
9788       // If any candidate has a placeholder return type, trigger its deduction
9789       // now.
9790       if (S.getLangOpts().CPlusPlus1y &&
9791           FunDecl->getReturnType()->isUndeducedType() &&
9792           S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9793         return false;
9794 
9795       QualType ResultTy;
9796       if (Context.hasSameUnqualifiedType(TargetFunctionType,
9797                                          FunDecl->getType()) ||
9798           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9799                                  ResultTy)) {
9800         Matches.push_back(std::make_pair(CurAccessFunPair,
9801           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9802         FoundNonTemplateFunction = true;
9803         return true;
9804       }
9805     }
9806 
9807     return false;
9808   }
9809 
FindAllFunctionsThatMatchTargetTypeExactly()9810   bool FindAllFunctionsThatMatchTargetTypeExactly() {
9811     bool Ret = false;
9812 
9813     // If the overload expression doesn't have the form of a pointer to
9814     // member, don't try to convert it to a pointer-to-member type.
9815     if (IsInvalidFormOfPointerToMemberFunction())
9816       return false;
9817 
9818     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9819                                E = OvlExpr->decls_end();
9820          I != E; ++I) {
9821       // Look through any using declarations to find the underlying function.
9822       NamedDecl *Fn = (*I)->getUnderlyingDecl();
9823 
9824       // C++ [over.over]p3:
9825       //   Non-member functions and static member functions match
9826       //   targets of type "pointer-to-function" or "reference-to-function."
9827       //   Nonstatic member functions match targets of
9828       //   type "pointer-to-member-function."
9829       // Note that according to DR 247, the containing class does not matter.
9830       if (FunctionTemplateDecl *FunctionTemplate
9831                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
9832         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9833           Ret = true;
9834       }
9835       // If we have explicit template arguments supplied, skip non-templates.
9836       else if (!OvlExpr->hasExplicitTemplateArgs() &&
9837                AddMatchingNonTemplateFunction(Fn, I.getPair()))
9838         Ret = true;
9839     }
9840     assert(Ret || Matches.empty());
9841     return Ret;
9842   }
9843 
EliminateAllExceptMostSpecializedTemplate()9844   void EliminateAllExceptMostSpecializedTemplate() {
9845     //   [...] and any given function template specialization F1 is
9846     //   eliminated if the set contains a second function template
9847     //   specialization whose function template is more specialized
9848     //   than the function template of F1 according to the partial
9849     //   ordering rules of 14.5.5.2.
9850 
9851     // The algorithm specified above is quadratic. We instead use a
9852     // two-pass algorithm (similar to the one used to identify the
9853     // best viable function in an overload set) that identifies the
9854     // best function template (if it exists).
9855 
9856     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9857     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9858       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9859 
9860     // TODO: It looks like FailedCandidates does not serve much purpose
9861     // here, since the no_viable diagnostic has index 0.
9862     UnresolvedSetIterator Result = S.getMostSpecialized(
9863         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
9864         SourceExpr->getLocStart(), S.PDiag(),
9865         S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9866                                                      .second->getDeclName(),
9867         S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9868         Complain, TargetFunctionType);
9869 
9870     if (Result != MatchesCopy.end()) {
9871       // Make it the first and only element
9872       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9873       Matches[0].second = cast<FunctionDecl>(*Result);
9874       Matches.resize(1);
9875     }
9876   }
9877 
EliminateAllTemplateMatches()9878   void EliminateAllTemplateMatches() {
9879     //   [...] any function template specializations in the set are
9880     //   eliminated if the set also contains a non-template function, [...]
9881     for (unsigned I = 0, N = Matches.size(); I != N; ) {
9882       if (Matches[I].second->getPrimaryTemplate() == nullptr)
9883         ++I;
9884       else {
9885         Matches[I] = Matches[--N];
9886         Matches.set_size(N);
9887       }
9888     }
9889   }
9890 
9891 public:
ComplainNoMatchesFound() const9892   void ComplainNoMatchesFound() const {
9893     assert(Matches.empty());
9894     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9895         << OvlExpr->getName() << TargetFunctionType
9896         << OvlExpr->getSourceRange();
9897     if (FailedCandidates.empty())
9898       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9899     else {
9900       // We have some deduction failure messages. Use them to diagnose
9901       // the function templates, and diagnose the non-template candidates
9902       // normally.
9903       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9904                                  IEnd = OvlExpr->decls_end();
9905            I != IEnd; ++I)
9906         if (FunctionDecl *Fun =
9907                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9908           S.NoteOverloadCandidate(Fun, TargetFunctionType);
9909       FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9910     }
9911   }
9912 
IsInvalidFormOfPointerToMemberFunction() const9913   bool IsInvalidFormOfPointerToMemberFunction() const {
9914     return TargetTypeIsNonStaticMemberFunction &&
9915       !OvlExprInfo.HasFormOfMemberPointer;
9916   }
9917 
ComplainIsInvalidFormOfPointerToMemberFunction() const9918   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9919       // TODO: Should we condition this on whether any functions might
9920       // have matched, or is it more appropriate to do that in callers?
9921       // TODO: a fixit wouldn't hurt.
9922       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9923         << TargetType << OvlExpr->getSourceRange();
9924   }
9925 
IsStaticMemberFunctionFromBoundPointer() const9926   bool IsStaticMemberFunctionFromBoundPointer() const {
9927     return StaticMemberFunctionFromBoundPointer;
9928   }
9929 
ComplainIsStaticMemberFunctionFromBoundPointer() const9930   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9931     S.Diag(OvlExpr->getLocStart(),
9932            diag::err_invalid_form_pointer_member_function)
9933       << OvlExpr->getSourceRange();
9934   }
9935 
ComplainOfInvalidConversion() const9936   void ComplainOfInvalidConversion() const {
9937     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9938       << OvlExpr->getName() << TargetType;
9939   }
9940 
ComplainMultipleMatchesFound() const9941   void ComplainMultipleMatchesFound() const {
9942     assert(Matches.size() > 1);
9943     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9944       << OvlExpr->getName()
9945       << OvlExpr->getSourceRange();
9946     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9947   }
9948 
hadMultipleCandidates() const9949   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9950 
getNumMatches() const9951   int getNumMatches() const { return Matches.size(); }
9952 
getMatchingFunctionDecl() const9953   FunctionDecl* getMatchingFunctionDecl() const {
9954     if (Matches.size() != 1) return nullptr;
9955     return Matches[0].second;
9956   }
9957 
getMatchingFunctionAccessPair() const9958   const DeclAccessPair* getMatchingFunctionAccessPair() const {
9959     if (Matches.size() != 1) return nullptr;
9960     return &Matches[0].first;
9961   }
9962 };
9963 
9964 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9965 /// an overloaded function (C++ [over.over]), where @p From is an
9966 /// expression with overloaded function type and @p ToType is the type
9967 /// we're trying to resolve to. For example:
9968 ///
9969 /// @code
9970 /// int f(double);
9971 /// int f(int);
9972 ///
9973 /// int (*pfd)(double) = f; // selects f(double)
9974 /// @endcode
9975 ///
9976 /// This routine returns the resulting FunctionDecl if it could be
9977 /// resolved, and NULL otherwise. When @p Complain is true, this
9978 /// routine will emit diagnostics if there is an error.
9979 FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr * AddressOfExpr,QualType TargetType,bool Complain,DeclAccessPair & FoundResult,bool * pHadMultipleCandidates)9980 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9981                                          QualType TargetType,
9982                                          bool Complain,
9983                                          DeclAccessPair &FoundResult,
9984                                          bool *pHadMultipleCandidates) {
9985   assert(AddressOfExpr->getType() == Context.OverloadTy);
9986 
9987   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9988                                      Complain);
9989   int NumMatches = Resolver.getNumMatches();
9990   FunctionDecl *Fn = nullptr;
9991   if (NumMatches == 0 && Complain) {
9992     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9993       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9994     else
9995       Resolver.ComplainNoMatchesFound();
9996   }
9997   else if (NumMatches > 1 && Complain)
9998     Resolver.ComplainMultipleMatchesFound();
9999   else if (NumMatches == 1) {
10000     Fn = Resolver.getMatchingFunctionDecl();
10001     assert(Fn);
10002     FoundResult = *Resolver.getMatchingFunctionAccessPair();
10003     if (Complain) {
10004       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10005         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10006       else
10007         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10008     }
10009   }
10010 
10011   if (pHadMultipleCandidates)
10012     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10013   return Fn;
10014 }
10015 
10016 /// \brief Given an expression that refers to an overloaded function, try to
10017 /// resolve that overloaded function expression down to a single function.
10018 ///
10019 /// This routine can only resolve template-ids that refer to a single function
10020 /// template, where that template-id refers to a single template whose template
10021 /// arguments are either provided by the template-id or have defaults,
10022 /// as described in C++0x [temp.arg.explicit]p3.
10023 ///
10024 /// If no template-ids are found, no diagnostics are emitted and NULL is
10025 /// returned.
10026 FunctionDecl *
ResolveSingleFunctionTemplateSpecialization(OverloadExpr * ovl,bool Complain,DeclAccessPair * FoundResult)10027 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10028                                                   bool Complain,
10029                                                   DeclAccessPair *FoundResult) {
10030   // C++ [over.over]p1:
10031   //   [...] [Note: any redundant set of parentheses surrounding the
10032   //   overloaded function name is ignored (5.1). ]
10033   // C++ [over.over]p1:
10034   //   [...] The overloaded function name can be preceded by the &
10035   //   operator.
10036 
10037   // If we didn't actually find any template-ids, we're done.
10038   if (!ovl->hasExplicitTemplateArgs())
10039     return nullptr;
10040 
10041   TemplateArgumentListInfo ExplicitTemplateArgs;
10042   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
10043   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10044 
10045   // Look through all of the overloaded functions, searching for one
10046   // whose type matches exactly.
10047   FunctionDecl *Matched = nullptr;
10048   for (UnresolvedSetIterator I = ovl->decls_begin(),
10049          E = ovl->decls_end(); I != E; ++I) {
10050     // C++0x [temp.arg.explicit]p3:
10051     //   [...] In contexts where deduction is done and fails, or in contexts
10052     //   where deduction is not done, if a template argument list is
10053     //   specified and it, along with any default template arguments,
10054     //   identifies a single function template specialization, then the
10055     //   template-id is an lvalue for the function template specialization.
10056     FunctionTemplateDecl *FunctionTemplate
10057       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10058 
10059     // C++ [over.over]p2:
10060     //   If the name is a function template, template argument deduction is
10061     //   done (14.8.2.2), and if the argument deduction succeeds, the
10062     //   resulting template argument list is used to generate a single
10063     //   function template specialization, which is added to the set of
10064     //   overloaded functions considered.
10065     FunctionDecl *Specialization = nullptr;
10066     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10067     if (TemplateDeductionResult Result
10068           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10069                                     Specialization, Info,
10070                                     /*InOverloadResolution=*/true)) {
10071       // Make a note of the failed deduction for diagnostics.
10072       // TODO: Actually use the failed-deduction info?
10073       FailedCandidates.addCandidate()
10074           .set(FunctionTemplate->getTemplatedDecl(),
10075                MakeDeductionFailureInfo(Context, Result, Info));
10076       continue;
10077     }
10078 
10079     assert(Specialization && "no specialization and no error?");
10080 
10081     // Multiple matches; we can't resolve to a single declaration.
10082     if (Matched) {
10083       if (Complain) {
10084         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10085           << ovl->getName();
10086         NoteAllOverloadCandidates(ovl);
10087       }
10088       return nullptr;
10089     }
10090 
10091     Matched = Specialization;
10092     if (FoundResult) *FoundResult = I.getPair();
10093   }
10094 
10095   if (Matched && getLangOpts().CPlusPlus1y &&
10096       Matched->getReturnType()->isUndeducedType() &&
10097       DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10098     return nullptr;
10099 
10100   return Matched;
10101 }
10102 
10103 
10104 
10105 
10106 // Resolve and fix an overloaded expression that can be resolved
10107 // because it identifies a single function template specialization.
10108 //
10109 // Last three arguments should only be supplied if Complain = true
10110 //
10111 // Return true if it was logically possible to so resolve the
10112 // expression, regardless of whether or not it succeeded.  Always
10113 // returns true if 'complain' is set.
ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult & SrcExpr,bool doFunctionPointerConverion,bool complain,const SourceRange & OpRangeForComplaining,QualType DestTypeForComplaining,unsigned DiagIDForComplaining)10114 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10115                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
10116                    bool complain, const SourceRange& OpRangeForComplaining,
10117                                            QualType DestTypeForComplaining,
10118                                             unsigned DiagIDForComplaining) {
10119   assert(SrcExpr.get()->getType() == Context.OverloadTy);
10120 
10121   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10122 
10123   DeclAccessPair found;
10124   ExprResult SingleFunctionExpression;
10125   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10126                            ovl.Expression, /*complain*/ false, &found)) {
10127     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10128       SrcExpr = ExprError();
10129       return true;
10130     }
10131 
10132     // It is only correct to resolve to an instance method if we're
10133     // resolving a form that's permitted to be a pointer to member.
10134     // Otherwise we'll end up making a bound member expression, which
10135     // is illegal in all the contexts we resolve like this.
10136     if (!ovl.HasFormOfMemberPointer &&
10137         isa<CXXMethodDecl>(fn) &&
10138         cast<CXXMethodDecl>(fn)->isInstance()) {
10139       if (!complain) return false;
10140 
10141       Diag(ovl.Expression->getExprLoc(),
10142            diag::err_bound_member_function)
10143         << 0 << ovl.Expression->getSourceRange();
10144 
10145       // TODO: I believe we only end up here if there's a mix of
10146       // static and non-static candidates (otherwise the expression
10147       // would have 'bound member' type, not 'overload' type).
10148       // Ideally we would note which candidate was chosen and why
10149       // the static candidates were rejected.
10150       SrcExpr = ExprError();
10151       return true;
10152     }
10153 
10154     // Fix the expression to refer to 'fn'.
10155     SingleFunctionExpression =
10156         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10157 
10158     // If desired, do function-to-pointer decay.
10159     if (doFunctionPointerConverion) {
10160       SingleFunctionExpression =
10161         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10162       if (SingleFunctionExpression.isInvalid()) {
10163         SrcExpr = ExprError();
10164         return true;
10165       }
10166     }
10167   }
10168 
10169   if (!SingleFunctionExpression.isUsable()) {
10170     if (complain) {
10171       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10172         << ovl.Expression->getName()
10173         << DestTypeForComplaining
10174         << OpRangeForComplaining
10175         << ovl.Expression->getQualifierLoc().getSourceRange();
10176       NoteAllOverloadCandidates(SrcExpr.get());
10177 
10178       SrcExpr = ExprError();
10179       return true;
10180     }
10181 
10182     return false;
10183   }
10184 
10185   SrcExpr = SingleFunctionExpression;
10186   return true;
10187 }
10188 
10189 /// \brief Add a single candidate to the overload set.
AddOverloadedCallCandidate(Sema & S,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading,bool KnownValid)10190 static void AddOverloadedCallCandidate(Sema &S,
10191                                        DeclAccessPair FoundDecl,
10192                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
10193                                        ArrayRef<Expr *> Args,
10194                                        OverloadCandidateSet &CandidateSet,
10195                                        bool PartialOverloading,
10196                                        bool KnownValid) {
10197   NamedDecl *Callee = FoundDecl.getDecl();
10198   if (isa<UsingShadowDecl>(Callee))
10199     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10200 
10201   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10202     if (ExplicitTemplateArgs) {
10203       assert(!KnownValid && "Explicit template arguments?");
10204       return;
10205     }
10206     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10207                            PartialOverloading);
10208     return;
10209   }
10210 
10211   if (FunctionTemplateDecl *FuncTemplate
10212       = dyn_cast<FunctionTemplateDecl>(Callee)) {
10213     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10214                                    ExplicitTemplateArgs, Args, CandidateSet);
10215     return;
10216   }
10217 
10218   assert(!KnownValid && "unhandled case in overloaded call candidate");
10219 }
10220 
10221 /// \brief Add the overload candidates named by callee and/or found by argument
10222 /// dependent lookup to the given overload set.
AddOverloadedCallCandidates(UnresolvedLookupExpr * ULE,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading)10223 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10224                                        ArrayRef<Expr *> Args,
10225                                        OverloadCandidateSet &CandidateSet,
10226                                        bool PartialOverloading) {
10227 
10228 #ifndef NDEBUG
10229   // Verify that ArgumentDependentLookup is consistent with the rules
10230   // in C++0x [basic.lookup.argdep]p3:
10231   //
10232   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10233   //   and let Y be the lookup set produced by argument dependent
10234   //   lookup (defined as follows). If X contains
10235   //
10236   //     -- a declaration of a class member, or
10237   //
10238   //     -- a block-scope function declaration that is not a
10239   //        using-declaration, or
10240   //
10241   //     -- a declaration that is neither a function or a function
10242   //        template
10243   //
10244   //   then Y is empty.
10245 
10246   if (ULE->requiresADL()) {
10247     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10248            E = ULE->decls_end(); I != E; ++I) {
10249       assert(!(*I)->getDeclContext()->isRecord());
10250       assert(isa<UsingShadowDecl>(*I) ||
10251              !(*I)->getDeclContext()->isFunctionOrMethod());
10252       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
10253     }
10254   }
10255 #endif
10256 
10257   // It would be nice to avoid this copy.
10258   TemplateArgumentListInfo TABuffer;
10259   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10260   if (ULE->hasExplicitTemplateArgs()) {
10261     ULE->copyTemplateArgumentsInto(TABuffer);
10262     ExplicitTemplateArgs = &TABuffer;
10263   }
10264 
10265   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10266          E = ULE->decls_end(); I != E; ++I)
10267     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10268                                CandidateSet, PartialOverloading,
10269                                /*KnownValid*/ true);
10270 
10271   if (ULE->requiresADL())
10272     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10273                                          Args, ExplicitTemplateArgs,
10274                                          CandidateSet, PartialOverloading);
10275 }
10276 
10277 /// Determine whether a declaration with the specified name could be moved into
10278 /// a different namespace.
canBeDeclaredInNamespace(const DeclarationName & Name)10279 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10280   switch (Name.getCXXOverloadedOperator()) {
10281   case OO_New: case OO_Array_New:
10282   case OO_Delete: case OO_Array_Delete:
10283     return false;
10284 
10285   default:
10286     return true;
10287   }
10288 }
10289 
10290 /// Attempt to recover from an ill-formed use of a non-dependent name in a
10291 /// template, where the non-dependent name was declared after the template
10292 /// was defined. This is common in code written for a compilers which do not
10293 /// correctly implement two-stage name lookup.
10294 ///
10295 /// Returns true if a viable candidate was found and a diagnostic was issued.
10296 static bool
DiagnoseTwoPhaseLookup(Sema & SemaRef,SourceLocation FnLoc,const CXXScopeSpec & SS,LookupResult & R,OverloadCandidateSet::CandidateSetKind CSK,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args)10297 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10298                        const CXXScopeSpec &SS, LookupResult &R,
10299                        OverloadCandidateSet::CandidateSetKind CSK,
10300                        TemplateArgumentListInfo *ExplicitTemplateArgs,
10301                        ArrayRef<Expr *> Args) {
10302   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10303     return false;
10304 
10305   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10306     if (DC->isTransparentContext())
10307       continue;
10308 
10309     SemaRef.LookupQualifiedName(R, DC);
10310 
10311     if (!R.empty()) {
10312       R.suppressDiagnostics();
10313 
10314       if (isa<CXXRecordDecl>(DC)) {
10315         // Don't diagnose names we find in classes; we get much better
10316         // diagnostics for these from DiagnoseEmptyLookup.
10317         R.clear();
10318         return false;
10319       }
10320 
10321       OverloadCandidateSet Candidates(FnLoc, CSK);
10322       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10323         AddOverloadedCallCandidate(SemaRef, I.getPair(),
10324                                    ExplicitTemplateArgs, Args,
10325                                    Candidates, false, /*KnownValid*/ false);
10326 
10327       OverloadCandidateSet::iterator Best;
10328       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10329         // No viable functions. Don't bother the user with notes for functions
10330         // which don't work and shouldn't be found anyway.
10331         R.clear();
10332         return false;
10333       }
10334 
10335       // Find the namespaces where ADL would have looked, and suggest
10336       // declaring the function there instead.
10337       Sema::AssociatedNamespaceSet AssociatedNamespaces;
10338       Sema::AssociatedClassSet AssociatedClasses;
10339       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10340                                                  AssociatedNamespaces,
10341                                                  AssociatedClasses);
10342       Sema::AssociatedNamespaceSet SuggestedNamespaces;
10343       if (canBeDeclaredInNamespace(R.getLookupName())) {
10344         DeclContext *Std = SemaRef.getStdNamespace();
10345         for (Sema::AssociatedNamespaceSet::iterator
10346                it = AssociatedNamespaces.begin(),
10347                end = AssociatedNamespaces.end(); it != end; ++it) {
10348           // Never suggest declaring a function within namespace 'std'.
10349           if (Std && Std->Encloses(*it))
10350             continue;
10351 
10352           // Never suggest declaring a function within a namespace with a
10353           // reserved name, like __gnu_cxx.
10354           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10355           if (NS &&
10356               NS->getQualifiedNameAsString().find("__") != std::string::npos)
10357             continue;
10358 
10359           SuggestedNamespaces.insert(*it);
10360         }
10361       }
10362 
10363       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10364         << R.getLookupName();
10365       if (SuggestedNamespaces.empty()) {
10366         SemaRef.Diag(Best->Function->getLocation(),
10367                      diag::note_not_found_by_two_phase_lookup)
10368           << R.getLookupName() << 0;
10369       } else if (SuggestedNamespaces.size() == 1) {
10370         SemaRef.Diag(Best->Function->getLocation(),
10371                      diag::note_not_found_by_two_phase_lookup)
10372           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10373       } else {
10374         // FIXME: It would be useful to list the associated namespaces here,
10375         // but the diagnostics infrastructure doesn't provide a way to produce
10376         // a localized representation of a list of items.
10377         SemaRef.Diag(Best->Function->getLocation(),
10378                      diag::note_not_found_by_two_phase_lookup)
10379           << R.getLookupName() << 2;
10380       }
10381 
10382       // Try to recover by calling this function.
10383       return true;
10384     }
10385 
10386     R.clear();
10387   }
10388 
10389   return false;
10390 }
10391 
10392 /// Attempt to recover from ill-formed use of a non-dependent operator in a
10393 /// template, where the non-dependent operator was declared after the template
10394 /// was defined.
10395 ///
10396 /// Returns true if a viable candidate was found and a diagnostic was issued.
10397 static bool
DiagnoseTwoPhaseOperatorLookup(Sema & SemaRef,OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args)10398 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10399                                SourceLocation OpLoc,
10400                                ArrayRef<Expr *> Args) {
10401   DeclarationName OpName =
10402     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10403   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10404   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10405                                 OverloadCandidateSet::CSK_Operator,
10406                                 /*ExplicitTemplateArgs=*/nullptr, Args);
10407 }
10408 
10409 namespace {
10410 class BuildRecoveryCallExprRAII {
10411   Sema &SemaRef;
10412 public:
BuildRecoveryCallExprRAII(Sema & S)10413   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10414     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10415     SemaRef.IsBuildingRecoveryCallExpr = true;
10416   }
10417 
~BuildRecoveryCallExprRAII()10418   ~BuildRecoveryCallExprRAII() {
10419     SemaRef.IsBuildingRecoveryCallExpr = false;
10420   }
10421 };
10422 
10423 }
10424 
10425 /// Attempts to recover from a call where no functions were found.
10426 ///
10427 /// Returns true if new candidates were found.
10428 static ExprResult
BuildRecoveryCallExpr(Sema & SemaRef,Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MutableArrayRef<Expr * > Args,SourceLocation RParenLoc,bool EmptyLookup,bool AllowTypoCorrection)10429 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10430                       UnresolvedLookupExpr *ULE,
10431                       SourceLocation LParenLoc,
10432                       MutableArrayRef<Expr *> Args,
10433                       SourceLocation RParenLoc,
10434                       bool EmptyLookup, bool AllowTypoCorrection) {
10435   // Do not try to recover if it is already building a recovery call.
10436   // This stops infinite loops for template instantiations like
10437   //
10438   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10439   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10440   //
10441   if (SemaRef.IsBuildingRecoveryCallExpr)
10442     return ExprError();
10443   BuildRecoveryCallExprRAII RCE(SemaRef);
10444 
10445   CXXScopeSpec SS;
10446   SS.Adopt(ULE->getQualifierLoc());
10447   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10448 
10449   TemplateArgumentListInfo TABuffer;
10450   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10451   if (ULE->hasExplicitTemplateArgs()) {
10452     ULE->copyTemplateArgumentsInto(TABuffer);
10453     ExplicitTemplateArgs = &TABuffer;
10454   }
10455 
10456   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10457                  Sema::LookupOrdinaryName);
10458   FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10459                                   ExplicitTemplateArgs != nullptr,
10460                                   dyn_cast<MemberExpr>(Fn));
10461   NoTypoCorrectionCCC RejectAll;
10462   CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10463       (CorrectionCandidateCallback*)&Validator :
10464       (CorrectionCandidateCallback*)&RejectAll;
10465   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10466                               OverloadCandidateSet::CSK_Normal,
10467                               ExplicitTemplateArgs, Args) &&
10468       (!EmptyLookup ||
10469        SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
10470                                    ExplicitTemplateArgs, Args)))
10471     return ExprError();
10472 
10473   assert(!R.empty() && "lookup results empty despite recovery");
10474 
10475   // Build an implicit member call if appropriate.  Just drop the
10476   // casts and such from the call, we don't really care.
10477   ExprResult NewFn = ExprError();
10478   if ((*R.begin())->isCXXClassMember())
10479     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10480                                                     R, ExplicitTemplateArgs);
10481   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10482     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10483                                         ExplicitTemplateArgs);
10484   else
10485     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10486 
10487   if (NewFn.isInvalid())
10488     return ExprError();
10489 
10490   // This shouldn't cause an infinite loop because we're giving it
10491   // an expression with viable lookup results, which should never
10492   // end up here.
10493   return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
10494                                MultiExprArg(Args.data(), Args.size()),
10495                                RParenLoc);
10496 }
10497 
10498 /// \brief Constructs and populates an OverloadedCandidateSet from
10499 /// the given function.
10500 /// \returns true when an the ExprResult output parameter has been set.
buildOverloadedCallSet(Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,MultiExprArg Args,SourceLocation RParenLoc,OverloadCandidateSet * CandidateSet,ExprResult * Result)10501 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10502                                   UnresolvedLookupExpr *ULE,
10503                                   MultiExprArg Args,
10504                                   SourceLocation RParenLoc,
10505                                   OverloadCandidateSet *CandidateSet,
10506                                   ExprResult *Result) {
10507 #ifndef NDEBUG
10508   if (ULE->requiresADL()) {
10509     // To do ADL, we must have found an unqualified name.
10510     assert(!ULE->getQualifier() && "qualified name with ADL");
10511 
10512     // We don't perform ADL for implicit declarations of builtins.
10513     // Verify that this was correctly set up.
10514     FunctionDecl *F;
10515     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10516         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10517         F->getBuiltinID() && F->isImplicit())
10518       llvm_unreachable("performing ADL for builtin");
10519 
10520     // We don't perform ADL in C.
10521     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10522   }
10523 #endif
10524 
10525   UnbridgedCastsSet UnbridgedCasts;
10526   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10527     *Result = ExprError();
10528     return true;
10529   }
10530 
10531   // Add the functions denoted by the callee to the set of candidate
10532   // functions, including those from argument-dependent lookup.
10533   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10534 
10535   // If we found nothing, try to recover.
10536   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10537   // out if it fails.
10538   if (CandidateSet->empty()) {
10539     // In Microsoft mode, if we are inside a template class member function then
10540     // create a type dependent CallExpr. The goal is to postpone name lookup
10541     // to instantiation time to be able to search into type dependent base
10542     // classes.
10543     if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
10544         (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10545       CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10546                                             Context.DependentTy, VK_RValue,
10547                                             RParenLoc);
10548       CE->setTypeDependent(true);
10549       *Result = CE;
10550       return true;
10551     }
10552     return false;
10553   }
10554 
10555   UnbridgedCasts.restore();
10556   return false;
10557 }
10558 
10559 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10560 /// the completed call expression. If overload resolution fails, emits
10561 /// diagnostics and returns ExprError()
FinishOverloadedCallExpr(Sema & SemaRef,Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,Expr * ExecConfig,OverloadCandidateSet * CandidateSet,OverloadCandidateSet::iterator * Best,OverloadingResult OverloadResult,bool AllowTypoCorrection)10562 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10563                                            UnresolvedLookupExpr *ULE,
10564                                            SourceLocation LParenLoc,
10565                                            MultiExprArg Args,
10566                                            SourceLocation RParenLoc,
10567                                            Expr *ExecConfig,
10568                                            OverloadCandidateSet *CandidateSet,
10569                                            OverloadCandidateSet::iterator *Best,
10570                                            OverloadingResult OverloadResult,
10571                                            bool AllowTypoCorrection) {
10572   if (CandidateSet->empty())
10573     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10574                                  RParenLoc, /*EmptyLookup=*/true,
10575                                  AllowTypoCorrection);
10576 
10577   switch (OverloadResult) {
10578   case OR_Success: {
10579     FunctionDecl *FDecl = (*Best)->Function;
10580     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10581     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10582       return ExprError();
10583     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10584     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10585                                          ExecConfig);
10586   }
10587 
10588   case OR_No_Viable_Function: {
10589     // Try to recover by looking for viable functions which the user might
10590     // have meant to call.
10591     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10592                                                 Args, RParenLoc,
10593                                                 /*EmptyLookup=*/false,
10594                                                 AllowTypoCorrection);
10595     if (!Recovery.isInvalid())
10596       return Recovery;
10597 
10598     SemaRef.Diag(Fn->getLocStart(),
10599          diag::err_ovl_no_viable_function_in_call)
10600       << ULE->getName() << Fn->getSourceRange();
10601     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10602     break;
10603   }
10604 
10605   case OR_Ambiguous:
10606     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10607       << ULE->getName() << Fn->getSourceRange();
10608     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10609     break;
10610 
10611   case OR_Deleted: {
10612     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10613       << (*Best)->Function->isDeleted()
10614       << ULE->getName()
10615       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10616       << Fn->getSourceRange();
10617     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10618 
10619     // We emitted an error for the unvailable/deleted function call but keep
10620     // the call in the AST.
10621     FunctionDecl *FDecl = (*Best)->Function;
10622     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10623     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10624                                          ExecConfig);
10625   }
10626   }
10627 
10628   // Overload resolution failed.
10629   return ExprError();
10630 }
10631 
10632 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10633 /// (which eventually refers to the declaration Func) and the call
10634 /// arguments Args/NumArgs, attempt to resolve the function call down
10635 /// to a specific function. If overload resolution succeeds, returns
10636 /// the call expression produced by overload resolution.
10637 /// Otherwise, emits diagnostics and returns ExprError.
BuildOverloadedCallExpr(Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,Expr * ExecConfig,bool AllowTypoCorrection)10638 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10639                                          UnresolvedLookupExpr *ULE,
10640                                          SourceLocation LParenLoc,
10641                                          MultiExprArg Args,
10642                                          SourceLocation RParenLoc,
10643                                          Expr *ExecConfig,
10644                                          bool AllowTypoCorrection) {
10645   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10646                                     OverloadCandidateSet::CSK_Normal);
10647   ExprResult result;
10648 
10649   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10650                              &result))
10651     return result;
10652 
10653   OverloadCandidateSet::iterator Best;
10654   OverloadingResult OverloadResult =
10655       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10656 
10657   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10658                                   RParenLoc, ExecConfig, &CandidateSet,
10659                                   &Best, OverloadResult,
10660                                   AllowTypoCorrection);
10661 }
10662 
IsOverloaded(const UnresolvedSetImpl & Functions)10663 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10664   return Functions.size() > 1 ||
10665     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10666 }
10667 
10668 /// \brief Create a unary operation that may resolve to an overloaded
10669 /// operator.
10670 ///
10671 /// \param OpLoc The location of the operator itself (e.g., '*').
10672 ///
10673 /// \param OpcIn The UnaryOperator::Opcode that describes this
10674 /// operator.
10675 ///
10676 /// \param Fns The set of non-member functions that will be
10677 /// considered by overload resolution. The caller needs to build this
10678 /// set based on the context using, e.g.,
10679 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10680 /// set should not contain any member functions; those will be added
10681 /// by CreateOverloadedUnaryOp().
10682 ///
10683 /// \param Input The input argument.
10684 ExprResult
CreateOverloadedUnaryOp(SourceLocation OpLoc,unsigned OpcIn,const UnresolvedSetImpl & Fns,Expr * Input)10685 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10686                               const UnresolvedSetImpl &Fns,
10687                               Expr *Input) {
10688   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10689 
10690   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10691   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10692   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10693   // TODO: provide better source location info.
10694   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10695 
10696   if (checkPlaceholderForOverload(*this, Input))
10697     return ExprError();
10698 
10699   Expr *Args[2] = { Input, nullptr };
10700   unsigned NumArgs = 1;
10701 
10702   // For post-increment and post-decrement, add the implicit '0' as
10703   // the second argument, so that we know this is a post-increment or
10704   // post-decrement.
10705   if (Opc == UO_PostInc || Opc == UO_PostDec) {
10706     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10707     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10708                                      SourceLocation());
10709     NumArgs = 2;
10710   }
10711 
10712   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10713 
10714   if (Input->isTypeDependent()) {
10715     if (Fns.empty())
10716       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10717                                          VK_RValue, OK_Ordinary, OpLoc);
10718 
10719     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10720     UnresolvedLookupExpr *Fn
10721       = UnresolvedLookupExpr::Create(Context, NamingClass,
10722                                      NestedNameSpecifierLoc(), OpNameInfo,
10723                                      /*ADL*/ true, IsOverloaded(Fns),
10724                                      Fns.begin(), Fns.end());
10725     return new (Context)
10726         CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10727                             VK_RValue, OpLoc, false);
10728   }
10729 
10730   // Build an empty overload set.
10731   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
10732 
10733   // Add the candidates from the given function set.
10734   AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
10735 
10736   // Add operator candidates that are member functions.
10737   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10738 
10739   // Add candidates from ADL.
10740   AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
10741                                        /*ExplicitTemplateArgs*/nullptr,
10742                                        CandidateSet);
10743 
10744   // Add builtin operator candidates.
10745   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10746 
10747   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10748 
10749   // Perform overload resolution.
10750   OverloadCandidateSet::iterator Best;
10751   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10752   case OR_Success: {
10753     // We found a built-in operator or an overloaded operator.
10754     FunctionDecl *FnDecl = Best->Function;
10755 
10756     if (FnDecl) {
10757       // We matched an overloaded operator. Build a call to that
10758       // operator.
10759 
10760       // Convert the arguments.
10761       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10762         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
10763 
10764         ExprResult InputRes =
10765           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
10766                                               Best->FoundDecl, Method);
10767         if (InputRes.isInvalid())
10768           return ExprError();
10769         Input = InputRes.get();
10770       } else {
10771         // Convert the arguments.
10772         ExprResult InputInit
10773           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10774                                                       Context,
10775                                                       FnDecl->getParamDecl(0)),
10776                                       SourceLocation(),
10777                                       Input);
10778         if (InputInit.isInvalid())
10779           return ExprError();
10780         Input = InputInit.get();
10781       }
10782 
10783       // Build the actual expression node.
10784       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10785                                                 HadMultipleCandidates, OpLoc);
10786       if (FnExpr.isInvalid())
10787         return ExprError();
10788 
10789       // Determine the result type.
10790       QualType ResultTy = FnDecl->getReturnType();
10791       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10792       ResultTy = ResultTy.getNonLValueExprType(Context);
10793 
10794       Args[0] = Input;
10795       CallExpr *TheCall =
10796         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
10797                                           ResultTy, VK, OpLoc, false);
10798 
10799       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
10800         return ExprError();
10801 
10802       return MaybeBindToTemporary(TheCall);
10803     } else {
10804       // We matched a built-in operator. Convert the arguments, then
10805       // break out so that we will build the appropriate built-in
10806       // operator node.
10807       ExprResult InputRes =
10808         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10809                                   Best->Conversions[0], AA_Passing);
10810       if (InputRes.isInvalid())
10811         return ExprError();
10812       Input = InputRes.get();
10813       break;
10814     }
10815   }
10816 
10817   case OR_No_Viable_Function:
10818     // This is an erroneous use of an operator which can be overloaded by
10819     // a non-member function. Check for non-member operators which were
10820     // defined too late to be candidates.
10821     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
10822       // FIXME: Recover by calling the found function.
10823       return ExprError();
10824 
10825     // No viable function; fall through to handling this as a
10826     // built-in operator, which will produce an error message for us.
10827     break;
10828 
10829   case OR_Ambiguous:
10830     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10831         << UnaryOperator::getOpcodeStr(Opc)
10832         << Input->getType()
10833         << Input->getSourceRange();
10834     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
10835                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10836     return ExprError();
10837 
10838   case OR_Deleted:
10839     Diag(OpLoc, diag::err_ovl_deleted_oper)
10840       << Best->Function->isDeleted()
10841       << UnaryOperator::getOpcodeStr(Opc)
10842       << getDeletedOrUnavailableSuffix(Best->Function)
10843       << Input->getSourceRange();
10844     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
10845                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10846     return ExprError();
10847   }
10848 
10849   // Either we found no viable overloaded operator or we matched a
10850   // built-in operator. In either case, fall through to trying to
10851   // build a built-in operation.
10852   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10853 }
10854 
10855 /// \brief Create a binary operation that may resolve to an overloaded
10856 /// operator.
10857 ///
10858 /// \param OpLoc The location of the operator itself (e.g., '+').
10859 ///
10860 /// \param OpcIn The BinaryOperator::Opcode that describes this
10861 /// operator.
10862 ///
10863 /// \param Fns The set of non-member functions that will be
10864 /// considered by overload resolution. The caller needs to build this
10865 /// set based on the context using, e.g.,
10866 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10867 /// set should not contain any member functions; those will be added
10868 /// by CreateOverloadedBinOp().
10869 ///
10870 /// \param LHS Left-hand argument.
10871 /// \param RHS Right-hand argument.
10872 ExprResult
CreateOverloadedBinOp(SourceLocation OpLoc,unsigned OpcIn,const UnresolvedSetImpl & Fns,Expr * LHS,Expr * RHS)10873 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10874                             unsigned OpcIn,
10875                             const UnresolvedSetImpl &Fns,
10876                             Expr *LHS, Expr *RHS) {
10877   Expr *Args[2] = { LHS, RHS };
10878   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
10879 
10880   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10881   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10882   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10883 
10884   // If either side is type-dependent, create an appropriate dependent
10885   // expression.
10886   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10887     if (Fns.empty()) {
10888       // If there are no functions to store, just build a dependent
10889       // BinaryOperator or CompoundAssignment.
10890       if (Opc <= BO_Assign || Opc > BO_OrAssign)
10891         return new (Context) BinaryOperator(
10892             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
10893             OpLoc, FPFeatures.fp_contract);
10894 
10895       return new (Context) CompoundAssignOperator(
10896           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
10897           Context.DependentTy, Context.DependentTy, OpLoc,
10898           FPFeatures.fp_contract);
10899     }
10900 
10901     // FIXME: save results of ADL from here?
10902     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10903     // TODO: provide better source location info in DNLoc component.
10904     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10905     UnresolvedLookupExpr *Fn
10906       = UnresolvedLookupExpr::Create(Context, NamingClass,
10907                                      NestedNameSpecifierLoc(), OpNameInfo,
10908                                      /*ADL*/ true, IsOverloaded(Fns),
10909                                      Fns.begin(), Fns.end());
10910     return new (Context)
10911         CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
10912                             VK_RValue, OpLoc, FPFeatures.fp_contract);
10913   }
10914 
10915   // Always do placeholder-like conversions on the RHS.
10916   if (checkPlaceholderForOverload(*this, Args[1]))
10917     return ExprError();
10918 
10919   // Do placeholder-like conversion on the LHS; note that we should
10920   // not get here with a PseudoObject LHS.
10921   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10922   if (checkPlaceholderForOverload(*this, Args[0]))
10923     return ExprError();
10924 
10925   // If this is the assignment operator, we only perform overload resolution
10926   // if the left-hand side is a class or enumeration type. This is actually
10927   // a hack. The standard requires that we do overload resolution between the
10928   // various built-in candidates, but as DR507 points out, this can lead to
10929   // problems. So we do it this way, which pretty much follows what GCC does.
10930   // Note that we go the traditional code path for compound assignment forms.
10931   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10932     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10933 
10934   // If this is the .* operator, which is not overloadable, just
10935   // create a built-in binary operator.
10936   if (Opc == BO_PtrMemD)
10937     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10938 
10939   // Build an empty overload set.
10940   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
10941 
10942   // Add the candidates from the given function set.
10943   AddFunctionCandidates(Fns, Args, CandidateSet, false);
10944 
10945   // Add operator candidates that are member functions.
10946   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10947 
10948   // Add candidates from ADL.
10949   AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
10950                                        /*ExplicitTemplateArgs*/ nullptr,
10951                                        CandidateSet);
10952 
10953   // Add builtin operator candidates.
10954   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10955 
10956   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10957 
10958   // Perform overload resolution.
10959   OverloadCandidateSet::iterator Best;
10960   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10961     case OR_Success: {
10962       // We found a built-in operator or an overloaded operator.
10963       FunctionDecl *FnDecl = Best->Function;
10964 
10965       if (FnDecl) {
10966         // We matched an overloaded operator. Build a call to that
10967         // operator.
10968 
10969         // Convert the arguments.
10970         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10971           // Best->Access is only meaningful for class members.
10972           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10973 
10974           ExprResult Arg1 =
10975             PerformCopyInitialization(
10976               InitializedEntity::InitializeParameter(Context,
10977                                                      FnDecl->getParamDecl(0)),
10978               SourceLocation(), Args[1]);
10979           if (Arg1.isInvalid())
10980             return ExprError();
10981 
10982           ExprResult Arg0 =
10983             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
10984                                                 Best->FoundDecl, Method);
10985           if (Arg0.isInvalid())
10986             return ExprError();
10987           Args[0] = Arg0.getAs<Expr>();
10988           Args[1] = RHS = Arg1.getAs<Expr>();
10989         } else {
10990           // Convert the arguments.
10991           ExprResult Arg0 = PerformCopyInitialization(
10992             InitializedEntity::InitializeParameter(Context,
10993                                                    FnDecl->getParamDecl(0)),
10994             SourceLocation(), Args[0]);
10995           if (Arg0.isInvalid())
10996             return ExprError();
10997 
10998           ExprResult Arg1 =
10999             PerformCopyInitialization(
11000               InitializedEntity::InitializeParameter(Context,
11001                                                      FnDecl->getParamDecl(1)),
11002               SourceLocation(), Args[1]);
11003           if (Arg1.isInvalid())
11004             return ExprError();
11005           Args[0] = LHS = Arg0.getAs<Expr>();
11006           Args[1] = RHS = Arg1.getAs<Expr>();
11007         }
11008 
11009         // Build the actual expression node.
11010         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11011                                                   Best->FoundDecl,
11012                                                   HadMultipleCandidates, OpLoc);
11013         if (FnExpr.isInvalid())
11014           return ExprError();
11015 
11016         // Determine the result type.
11017         QualType ResultTy = FnDecl->getReturnType();
11018         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11019         ResultTy = ResultTy.getNonLValueExprType(Context);
11020 
11021         CXXOperatorCallExpr *TheCall =
11022           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11023                                             Args, ResultTy, VK, OpLoc,
11024                                             FPFeatures.fp_contract);
11025 
11026         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11027                                 FnDecl))
11028           return ExprError();
11029 
11030         ArrayRef<const Expr *> ArgsArray(Args, 2);
11031         // Cut off the implicit 'this'.
11032         if (isa<CXXMethodDecl>(FnDecl))
11033           ArgsArray = ArgsArray.slice(1);
11034         checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
11035                   TheCall->getSourceRange(), VariadicDoesNotApply);
11036 
11037         return MaybeBindToTemporary(TheCall);
11038       } else {
11039         // We matched a built-in operator. Convert the arguments, then
11040         // break out so that we will build the appropriate built-in
11041         // operator node.
11042         ExprResult ArgsRes0 =
11043           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11044                                     Best->Conversions[0], AA_Passing);
11045         if (ArgsRes0.isInvalid())
11046           return ExprError();
11047         Args[0] = ArgsRes0.get();
11048 
11049         ExprResult ArgsRes1 =
11050           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11051                                     Best->Conversions[1], AA_Passing);
11052         if (ArgsRes1.isInvalid())
11053           return ExprError();
11054         Args[1] = ArgsRes1.get();
11055         break;
11056       }
11057     }
11058 
11059     case OR_No_Viable_Function: {
11060       // C++ [over.match.oper]p9:
11061       //   If the operator is the operator , [...] and there are no
11062       //   viable functions, then the operator is assumed to be the
11063       //   built-in operator and interpreted according to clause 5.
11064       if (Opc == BO_Comma)
11065         break;
11066 
11067       // For class as left operand for assignment or compound assigment
11068       // operator do not fall through to handling in built-in, but report that
11069       // no overloaded assignment operator found
11070       ExprResult Result = ExprError();
11071       if (Args[0]->getType()->isRecordType() &&
11072           Opc >= BO_Assign && Opc <= BO_OrAssign) {
11073         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
11074              << BinaryOperator::getOpcodeStr(Opc)
11075              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11076         if (Args[0]->getType()->isIncompleteType()) {
11077           Diag(OpLoc, diag::note_assign_lhs_incomplete)
11078             << Args[0]->getType()
11079             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11080         }
11081       } else {
11082         // This is an erroneous use of an operator which can be overloaded by
11083         // a non-member function. Check for non-member operators which were
11084         // defined too late to be candidates.
11085         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11086           // FIXME: Recover by calling the found function.
11087           return ExprError();
11088 
11089         // No viable function; try to create a built-in operation, which will
11090         // produce an error. Then, show the non-viable candidates.
11091         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11092       }
11093       assert(Result.isInvalid() &&
11094              "C++ binary operator overloading is missing candidates!");
11095       if (Result.isInvalid())
11096         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11097                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
11098       return Result;
11099     }
11100 
11101     case OR_Ambiguous:
11102       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
11103           << BinaryOperator::getOpcodeStr(Opc)
11104           << Args[0]->getType() << Args[1]->getType()
11105           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11106       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11107                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11108       return ExprError();
11109 
11110     case OR_Deleted:
11111       if (isImplicitlyDeleted(Best->Function)) {
11112         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11113         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11114           << Context.getRecordType(Method->getParent())
11115           << getSpecialMember(Method);
11116 
11117         // The user probably meant to call this special member. Just
11118         // explain why it's deleted.
11119         NoteDeletedFunction(Method);
11120         return ExprError();
11121       } else {
11122         Diag(OpLoc, diag::err_ovl_deleted_oper)
11123           << Best->Function->isDeleted()
11124           << BinaryOperator::getOpcodeStr(Opc)
11125           << getDeletedOrUnavailableSuffix(Best->Function)
11126           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11127       }
11128       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11129                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
11130       return ExprError();
11131   }
11132 
11133   // We matched a built-in operator; build it.
11134   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11135 }
11136 
11137 ExprResult
CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,SourceLocation RLoc,Expr * Base,Expr * Idx)11138 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11139                                          SourceLocation RLoc,
11140                                          Expr *Base, Expr *Idx) {
11141   Expr *Args[2] = { Base, Idx };
11142   DeclarationName OpName =
11143       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11144 
11145   // If either side is type-dependent, create an appropriate dependent
11146   // expression.
11147   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11148 
11149     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11150     // CHECKME: no 'operator' keyword?
11151     DeclarationNameInfo OpNameInfo(OpName, LLoc);
11152     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11153     UnresolvedLookupExpr *Fn
11154       = UnresolvedLookupExpr::Create(Context, NamingClass,
11155                                      NestedNameSpecifierLoc(), OpNameInfo,
11156                                      /*ADL*/ true, /*Overloaded*/ false,
11157                                      UnresolvedSetIterator(),
11158                                      UnresolvedSetIterator());
11159     // Can't add any actual overloads yet
11160 
11161     return new (Context)
11162         CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11163                             Context.DependentTy, VK_RValue, RLoc, false);
11164   }
11165 
11166   // Handle placeholders on both operands.
11167   if (checkPlaceholderForOverload(*this, Args[0]))
11168     return ExprError();
11169   if (checkPlaceholderForOverload(*this, Args[1]))
11170     return ExprError();
11171 
11172   // Build an empty overload set.
11173   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11174 
11175   // Subscript can only be overloaded as a member function.
11176 
11177   // Add operator candidates that are member functions.
11178   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11179 
11180   // Add builtin operator candidates.
11181   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11182 
11183   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11184 
11185   // Perform overload resolution.
11186   OverloadCandidateSet::iterator Best;
11187   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11188     case OR_Success: {
11189       // We found a built-in operator or an overloaded operator.
11190       FunctionDecl *FnDecl = Best->Function;
11191 
11192       if (FnDecl) {
11193         // We matched an overloaded operator. Build a call to that
11194         // operator.
11195 
11196         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11197 
11198         // Convert the arguments.
11199         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11200         ExprResult Arg0 =
11201           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11202                                               Best->FoundDecl, Method);
11203         if (Arg0.isInvalid())
11204           return ExprError();
11205         Args[0] = Arg0.get();
11206 
11207         // Convert the arguments.
11208         ExprResult InputInit
11209           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11210                                                       Context,
11211                                                       FnDecl->getParamDecl(0)),
11212                                       SourceLocation(),
11213                                       Args[1]);
11214         if (InputInit.isInvalid())
11215           return ExprError();
11216 
11217         Args[1] = InputInit.getAs<Expr>();
11218 
11219         // Build the actual expression node.
11220         DeclarationNameInfo OpLocInfo(OpName, LLoc);
11221         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11222         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11223                                                   Best->FoundDecl,
11224                                                   HadMultipleCandidates,
11225                                                   OpLocInfo.getLoc(),
11226                                                   OpLocInfo.getInfo());
11227         if (FnExpr.isInvalid())
11228           return ExprError();
11229 
11230         // Determine the result type
11231         QualType ResultTy = FnDecl->getReturnType();
11232         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11233         ResultTy = ResultTy.getNonLValueExprType(Context);
11234 
11235         CXXOperatorCallExpr *TheCall =
11236           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11237                                             FnExpr.get(), Args,
11238                                             ResultTy, VK, RLoc,
11239                                             false);
11240 
11241         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11242           return ExprError();
11243 
11244         return MaybeBindToTemporary(TheCall);
11245       } else {
11246         // We matched a built-in operator. Convert the arguments, then
11247         // break out so that we will build the appropriate built-in
11248         // operator node.
11249         ExprResult ArgsRes0 =
11250           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11251                                     Best->Conversions[0], AA_Passing);
11252         if (ArgsRes0.isInvalid())
11253           return ExprError();
11254         Args[0] = ArgsRes0.get();
11255 
11256         ExprResult ArgsRes1 =
11257           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11258                                     Best->Conversions[1], AA_Passing);
11259         if (ArgsRes1.isInvalid())
11260           return ExprError();
11261         Args[1] = ArgsRes1.get();
11262 
11263         break;
11264       }
11265     }
11266 
11267     case OR_No_Viable_Function: {
11268       if (CandidateSet.empty())
11269         Diag(LLoc, diag::err_ovl_no_oper)
11270           << Args[0]->getType() << /*subscript*/ 0
11271           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11272       else
11273         Diag(LLoc, diag::err_ovl_no_viable_subscript)
11274           << Args[0]->getType()
11275           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11276       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11277                                   "[]", LLoc);
11278       return ExprError();
11279     }
11280 
11281     case OR_Ambiguous:
11282       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
11283           << "[]"
11284           << Args[0]->getType() << Args[1]->getType()
11285           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11286       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11287                                   "[]", LLoc);
11288       return ExprError();
11289 
11290     case OR_Deleted:
11291       Diag(LLoc, diag::err_ovl_deleted_oper)
11292         << Best->Function->isDeleted() << "[]"
11293         << getDeletedOrUnavailableSuffix(Best->Function)
11294         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11295       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11296                                   "[]", LLoc);
11297       return ExprError();
11298     }
11299 
11300   // We matched a built-in operator; build it.
11301   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11302 }
11303 
11304 /// BuildCallToMemberFunction - Build a call to a member
11305 /// function. MemExpr is the expression that refers to the member
11306 /// function (and includes the object parameter), Args/NumArgs are the
11307 /// arguments to the function call (not including the object
11308 /// parameter). The caller needs to validate that the member
11309 /// expression refers to a non-static member function or an overloaded
11310 /// member function.
11311 ExprResult
BuildCallToMemberFunction(Scope * S,Expr * MemExprE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc)11312 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11313                                 SourceLocation LParenLoc,
11314                                 MultiExprArg Args,
11315                                 SourceLocation RParenLoc) {
11316   assert(MemExprE->getType() == Context.BoundMemberTy ||
11317          MemExprE->getType() == Context.OverloadTy);
11318 
11319   // Dig out the member expression. This holds both the object
11320   // argument and the member function we're referring to.
11321   Expr *NakedMemExpr = MemExprE->IgnoreParens();
11322 
11323   // Determine whether this is a call to a pointer-to-member function.
11324   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11325     assert(op->getType() == Context.BoundMemberTy);
11326     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11327 
11328     QualType fnType =
11329       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11330 
11331     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11332     QualType resultType = proto->getCallResultType(Context);
11333     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
11334 
11335     // Check that the object type isn't more qualified than the
11336     // member function we're calling.
11337     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11338 
11339     QualType objectType = op->getLHS()->getType();
11340     if (op->getOpcode() == BO_PtrMemI)
11341       objectType = objectType->castAs<PointerType>()->getPointeeType();
11342     Qualifiers objectQuals = objectType.getQualifiers();
11343 
11344     Qualifiers difference = objectQuals - funcQuals;
11345     difference.removeObjCGCAttr();
11346     difference.removeAddressSpace();
11347     if (difference) {
11348       std::string qualsString = difference.getAsString();
11349       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11350         << fnType.getUnqualifiedType()
11351         << qualsString
11352         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11353     }
11354 
11355     CXXMemberCallExpr *call
11356       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11357                                         resultType, valueKind, RParenLoc);
11358 
11359     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
11360                             call, nullptr))
11361       return ExprError();
11362 
11363     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
11364       return ExprError();
11365 
11366     if (CheckOtherCall(call, proto))
11367       return ExprError();
11368 
11369     return MaybeBindToTemporary(call);
11370   }
11371 
11372   UnbridgedCastsSet UnbridgedCasts;
11373   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11374     return ExprError();
11375 
11376   MemberExpr *MemExpr;
11377   CXXMethodDecl *Method = nullptr;
11378   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11379   NestedNameSpecifier *Qualifier = nullptr;
11380   if (isa<MemberExpr>(NakedMemExpr)) {
11381     MemExpr = cast<MemberExpr>(NakedMemExpr);
11382     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11383     FoundDecl = MemExpr->getFoundDecl();
11384     Qualifier = MemExpr->getQualifier();
11385     UnbridgedCasts.restore();
11386   } else {
11387     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11388     Qualifier = UnresExpr->getQualifier();
11389 
11390     QualType ObjectType = UnresExpr->getBaseType();
11391     Expr::Classification ObjectClassification
11392       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11393                             : UnresExpr->getBase()->Classify(Context);
11394 
11395     // Add overload candidates
11396     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11397                                       OverloadCandidateSet::CSK_Normal);
11398 
11399     // FIXME: avoid copy.
11400     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
11401     if (UnresExpr->hasExplicitTemplateArgs()) {
11402       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11403       TemplateArgs = &TemplateArgsBuffer;
11404     }
11405 
11406     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11407            E = UnresExpr->decls_end(); I != E; ++I) {
11408 
11409       NamedDecl *Func = *I;
11410       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11411       if (isa<UsingShadowDecl>(Func))
11412         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11413 
11414 
11415       // Microsoft supports direct constructor calls.
11416       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11417         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11418                              Args, CandidateSet);
11419       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11420         // If explicit template arguments were provided, we can't call a
11421         // non-template member function.
11422         if (TemplateArgs)
11423           continue;
11424 
11425         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11426                            ObjectClassification, Args, CandidateSet,
11427                            /*SuppressUserConversions=*/false);
11428       } else {
11429         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11430                                    I.getPair(), ActingDC, TemplateArgs,
11431                                    ObjectType,  ObjectClassification,
11432                                    Args, CandidateSet,
11433                                    /*SuppressUsedConversions=*/false);
11434       }
11435     }
11436 
11437     DeclarationName DeclName = UnresExpr->getMemberName();
11438 
11439     UnbridgedCasts.restore();
11440 
11441     OverloadCandidateSet::iterator Best;
11442     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11443                                             Best)) {
11444     case OR_Success:
11445       Method = cast<CXXMethodDecl>(Best->Function);
11446       FoundDecl = Best->FoundDecl;
11447       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11448       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11449         return ExprError();
11450       // If FoundDecl is different from Method (such as if one is a template
11451       // and the other a specialization), make sure DiagnoseUseOfDecl is
11452       // called on both.
11453       // FIXME: This would be more comprehensively addressed by modifying
11454       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11455       // being used.
11456       if (Method != FoundDecl.getDecl() &&
11457                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11458         return ExprError();
11459       break;
11460 
11461     case OR_No_Viable_Function:
11462       Diag(UnresExpr->getMemberLoc(),
11463            diag::err_ovl_no_viable_member_function_in_call)
11464         << DeclName << MemExprE->getSourceRange();
11465       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11466       // FIXME: Leaking incoming expressions!
11467       return ExprError();
11468 
11469     case OR_Ambiguous:
11470       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11471         << DeclName << MemExprE->getSourceRange();
11472       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11473       // FIXME: Leaking incoming expressions!
11474       return ExprError();
11475 
11476     case OR_Deleted:
11477       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11478         << Best->Function->isDeleted()
11479         << DeclName
11480         << getDeletedOrUnavailableSuffix(Best->Function)
11481         << MemExprE->getSourceRange();
11482       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11483       // FIXME: Leaking incoming expressions!
11484       return ExprError();
11485     }
11486 
11487     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11488 
11489     // If overload resolution picked a static member, build a
11490     // non-member call based on that function.
11491     if (Method->isStatic()) {
11492       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11493                                    RParenLoc);
11494     }
11495 
11496     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11497   }
11498 
11499   QualType ResultType = Method->getReturnType();
11500   ExprValueKind VK = Expr::getValueKindForType(ResultType);
11501   ResultType = ResultType.getNonLValueExprType(Context);
11502 
11503   assert(Method && "Member call to something that isn't a method?");
11504   CXXMemberCallExpr *TheCall =
11505     new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11506                                     ResultType, VK, RParenLoc);
11507 
11508   // Check for a valid return type.
11509   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
11510                           TheCall, Method))
11511     return ExprError();
11512 
11513   // Convert the object argument (for a non-static member function call).
11514   // We only need to do this if there was actually an overload; otherwise
11515   // it was done at lookup.
11516   if (!Method->isStatic()) {
11517     ExprResult ObjectArg =
11518       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11519                                           FoundDecl, Method);
11520     if (ObjectArg.isInvalid())
11521       return ExprError();
11522     MemExpr->setBase(ObjectArg.get());
11523   }
11524 
11525   // Convert the rest of the arguments
11526   const FunctionProtoType *Proto =
11527     Method->getType()->getAs<FunctionProtoType>();
11528   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11529                               RParenLoc))
11530     return ExprError();
11531 
11532   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11533 
11534   if (CheckFunctionCall(Method, TheCall, Proto))
11535     return ExprError();
11536 
11537   if ((isa<CXXConstructorDecl>(CurContext) ||
11538        isa<CXXDestructorDecl>(CurContext)) &&
11539       TheCall->getMethodDecl()->isPure()) {
11540     const CXXMethodDecl *MD = TheCall->getMethodDecl();
11541 
11542     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11543       Diag(MemExpr->getLocStart(),
11544            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11545         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11546         << MD->getParent()->getDeclName();
11547 
11548       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11549     }
11550   }
11551   return MaybeBindToTemporary(TheCall);
11552 }
11553 
11554 /// BuildCallToObjectOfClassType - Build a call to an object of class
11555 /// type (C++ [over.call.object]), which can end up invoking an
11556 /// overloaded function call operator (@c operator()) or performing a
11557 /// user-defined conversion on the object argument.
11558 ExprResult
BuildCallToObjectOfClassType(Scope * S,Expr * Obj,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc)11559 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11560                                    SourceLocation LParenLoc,
11561                                    MultiExprArg Args,
11562                                    SourceLocation RParenLoc) {
11563   if (checkPlaceholderForOverload(*this, Obj))
11564     return ExprError();
11565   ExprResult Object = Obj;
11566 
11567   UnbridgedCastsSet UnbridgedCasts;
11568   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11569     return ExprError();
11570 
11571   assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11572   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11573 
11574   // C++ [over.call.object]p1:
11575   //  If the primary-expression E in the function call syntax
11576   //  evaluates to a class object of type "cv T", then the set of
11577   //  candidate functions includes at least the function call
11578   //  operators of T. The function call operators of T are obtained by
11579   //  ordinary lookup of the name operator() in the context of
11580   //  (E).operator().
11581   OverloadCandidateSet CandidateSet(LParenLoc,
11582                                     OverloadCandidateSet::CSK_Operator);
11583   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11584 
11585   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11586                           diag::err_incomplete_object_call, Object.get()))
11587     return true;
11588 
11589   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11590   LookupQualifiedName(R, Record->getDecl());
11591   R.suppressDiagnostics();
11592 
11593   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11594        Oper != OperEnd; ++Oper) {
11595     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11596                        Object.get()->Classify(Context),
11597                        Args, CandidateSet,
11598                        /*SuppressUserConversions=*/ false);
11599   }
11600 
11601   // C++ [over.call.object]p2:
11602   //   In addition, for each (non-explicit in C++0x) conversion function
11603   //   declared in T of the form
11604   //
11605   //        operator conversion-type-id () cv-qualifier;
11606   //
11607   //   where cv-qualifier is the same cv-qualification as, or a
11608   //   greater cv-qualification than, cv, and where conversion-type-id
11609   //   denotes the type "pointer to function of (P1,...,Pn) returning
11610   //   R", or the type "reference to pointer to function of
11611   //   (P1,...,Pn) returning R", or the type "reference to function
11612   //   of (P1,...,Pn) returning R", a surrogate call function [...]
11613   //   is also considered as a candidate function. Similarly,
11614   //   surrogate call functions are added to the set of candidate
11615   //   functions for each conversion function declared in an
11616   //   accessible base class provided the function is not hidden
11617   //   within T by another intervening declaration.
11618   std::pair<CXXRecordDecl::conversion_iterator,
11619             CXXRecordDecl::conversion_iterator> Conversions
11620     = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11621   for (CXXRecordDecl::conversion_iterator
11622          I = Conversions.first, E = Conversions.second; I != E; ++I) {
11623     NamedDecl *D = *I;
11624     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11625     if (isa<UsingShadowDecl>(D))
11626       D = cast<UsingShadowDecl>(D)->getTargetDecl();
11627 
11628     // Skip over templated conversion functions; they aren't
11629     // surrogates.
11630     if (isa<FunctionTemplateDecl>(D))
11631       continue;
11632 
11633     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11634     if (!Conv->isExplicit()) {
11635       // Strip the reference type (if any) and then the pointer type (if
11636       // any) to get down to what might be a function type.
11637       QualType ConvType = Conv->getConversionType().getNonReferenceType();
11638       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11639         ConvType = ConvPtrType->getPointeeType();
11640 
11641       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11642       {
11643         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11644                               Object.get(), Args, CandidateSet);
11645       }
11646     }
11647   }
11648 
11649   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11650 
11651   // Perform overload resolution.
11652   OverloadCandidateSet::iterator Best;
11653   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11654                              Best)) {
11655   case OR_Success:
11656     // Overload resolution succeeded; we'll build the appropriate call
11657     // below.
11658     break;
11659 
11660   case OR_No_Viable_Function:
11661     if (CandidateSet.empty())
11662       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11663         << Object.get()->getType() << /*call*/ 1
11664         << Object.get()->getSourceRange();
11665     else
11666       Diag(Object.get()->getLocStart(),
11667            diag::err_ovl_no_viable_object_call)
11668         << Object.get()->getType() << Object.get()->getSourceRange();
11669     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11670     break;
11671 
11672   case OR_Ambiguous:
11673     Diag(Object.get()->getLocStart(),
11674          diag::err_ovl_ambiguous_object_call)
11675       << Object.get()->getType() << Object.get()->getSourceRange();
11676     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11677     break;
11678 
11679   case OR_Deleted:
11680     Diag(Object.get()->getLocStart(),
11681          diag::err_ovl_deleted_object_call)
11682       << Best->Function->isDeleted()
11683       << Object.get()->getType()
11684       << getDeletedOrUnavailableSuffix(Best->Function)
11685       << Object.get()->getSourceRange();
11686     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11687     break;
11688   }
11689 
11690   if (Best == CandidateSet.end())
11691     return true;
11692 
11693   UnbridgedCasts.restore();
11694 
11695   if (Best->Function == nullptr) {
11696     // Since there is no function declaration, this is one of the
11697     // surrogate candidates. Dig out the conversion function.
11698     CXXConversionDecl *Conv
11699       = cast<CXXConversionDecl>(
11700                          Best->Conversions[0].UserDefined.ConversionFunction);
11701 
11702     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11703                               Best->FoundDecl);
11704     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11705       return ExprError();
11706     assert(Conv == Best->FoundDecl.getDecl() &&
11707              "Found Decl & conversion-to-functionptr should be same, right?!");
11708     // We selected one of the surrogate functions that converts the
11709     // object parameter to a function pointer. Perform the conversion
11710     // on the object argument, then let ActOnCallExpr finish the job.
11711 
11712     // Create an implicit member expr to refer to the conversion operator.
11713     // and then call it.
11714     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11715                                              Conv, HadMultipleCandidates);
11716     if (Call.isInvalid())
11717       return ExprError();
11718     // Record usage of conversion in an implicit cast.
11719     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11720                                     CK_UserDefinedConversion, Call.get(),
11721                                     nullptr, VK_RValue);
11722 
11723     return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11724   }
11725 
11726   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
11727 
11728   // We found an overloaded operator(). Build a CXXOperatorCallExpr
11729   // that calls this method, using Object for the implicit object
11730   // parameter and passing along the remaining arguments.
11731   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11732 
11733   // An error diagnostic has already been printed when parsing the declaration.
11734   if (Method->isInvalidDecl())
11735     return ExprError();
11736 
11737   const FunctionProtoType *Proto =
11738     Method->getType()->getAs<FunctionProtoType>();
11739 
11740   unsigned NumParams = Proto->getNumParams();
11741 
11742   DeclarationNameInfo OpLocInfo(
11743                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11744   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11745   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11746                                            HadMultipleCandidates,
11747                                            OpLocInfo.getLoc(),
11748                                            OpLocInfo.getInfo());
11749   if (NewFn.isInvalid())
11750     return true;
11751 
11752   // Build the full argument list for the method call (the implicit object
11753   // parameter is placed at the beginning of the list).
11754   std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
11755   MethodArgs[0] = Object.get();
11756   std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11757 
11758   // Once we've built TheCall, all of the expressions are properly
11759   // owned.
11760   QualType ResultTy = Method->getReturnType();
11761   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11762   ResultTy = ResultTy.getNonLValueExprType(Context);
11763 
11764   CXXOperatorCallExpr *TheCall = new (Context)
11765       CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
11766                           llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11767                           ResultTy, VK, RParenLoc, false);
11768   MethodArgs.reset();
11769 
11770   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
11771     return true;
11772 
11773   // We may have default arguments. If so, we need to allocate more
11774   // slots in the call for them.
11775   if (Args.size() < NumParams)
11776     TheCall->setNumArgs(Context, NumParams + 1);
11777 
11778   bool IsError = false;
11779 
11780   // Initialize the implicit object parameter.
11781   ExprResult ObjRes =
11782     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
11783                                         Best->FoundDecl, Method);
11784   if (ObjRes.isInvalid())
11785     IsError = true;
11786   else
11787     Object = ObjRes;
11788   TheCall->setArg(0, Object.get());
11789 
11790   // Check the argument types.
11791   for (unsigned i = 0; i != NumParams; i++) {
11792     Expr *Arg;
11793     if (i < Args.size()) {
11794       Arg = Args[i];
11795 
11796       // Pass the argument.
11797 
11798       ExprResult InputInit
11799         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11800                                                     Context,
11801                                                     Method->getParamDecl(i)),
11802                                     SourceLocation(), Arg);
11803 
11804       IsError |= InputInit.isInvalid();
11805       Arg = InputInit.getAs<Expr>();
11806     } else {
11807       ExprResult DefArg
11808         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11809       if (DefArg.isInvalid()) {
11810         IsError = true;
11811         break;
11812       }
11813 
11814       Arg = DefArg.getAs<Expr>();
11815     }
11816 
11817     TheCall->setArg(i + 1, Arg);
11818   }
11819 
11820   // If this is a variadic call, handle args passed through "...".
11821   if (Proto->isVariadic()) {
11822     // Promote the arguments (C99 6.5.2.2p7).
11823     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
11824       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
11825                                                         nullptr);
11826       IsError |= Arg.isInvalid();
11827       TheCall->setArg(i + 1, Arg.get());
11828     }
11829   }
11830 
11831   if (IsError) return true;
11832 
11833   DiagnoseSentinelCalls(Method, LParenLoc, Args);
11834 
11835   if (CheckFunctionCall(Method, TheCall, Proto))
11836     return true;
11837 
11838   return MaybeBindToTemporary(TheCall);
11839 }
11840 
11841 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11842 ///  (if one exists), where @c Base is an expression of class type and
11843 /// @c Member is the name of the member we're trying to find.
11844 ExprResult
BuildOverloadedArrowExpr(Scope * S,Expr * Base,SourceLocation OpLoc,bool * NoArrowOperatorFound)11845 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11846                                bool *NoArrowOperatorFound) {
11847   assert(Base->getType()->isRecordType() &&
11848          "left-hand side must have class type");
11849 
11850   if (checkPlaceholderForOverload(*this, Base))
11851     return ExprError();
11852 
11853   SourceLocation Loc = Base->getExprLoc();
11854 
11855   // C++ [over.ref]p1:
11856   //
11857   //   [...] An expression x->m is interpreted as (x.operator->())->m
11858   //   for a class object x of type T if T::operator->() exists and if
11859   //   the operator is selected as the best match function by the
11860   //   overload resolution mechanism (13.3).
11861   DeclarationName OpName =
11862     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11863   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
11864   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11865 
11866   if (RequireCompleteType(Loc, Base->getType(),
11867                           diag::err_typecheck_incomplete_tag, Base))
11868     return ExprError();
11869 
11870   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11871   LookupQualifiedName(R, BaseRecord->getDecl());
11872   R.suppressDiagnostics();
11873 
11874   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11875        Oper != OperEnd; ++Oper) {
11876     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11877                        None, CandidateSet, /*SuppressUserConversions=*/false);
11878   }
11879 
11880   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11881 
11882   // Perform overload resolution.
11883   OverloadCandidateSet::iterator Best;
11884   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11885   case OR_Success:
11886     // Overload resolution succeeded; we'll build the call below.
11887     break;
11888 
11889   case OR_No_Viable_Function:
11890     if (CandidateSet.empty()) {
11891       QualType BaseType = Base->getType();
11892       if (NoArrowOperatorFound) {
11893         // Report this specific error to the caller instead of emitting a
11894         // diagnostic, as requested.
11895         *NoArrowOperatorFound = true;
11896         return ExprError();
11897       }
11898       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11899         << BaseType << Base->getSourceRange();
11900       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
11901         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
11902           << FixItHint::CreateReplacement(OpLoc, ".");
11903       }
11904     } else
11905       Diag(OpLoc, diag::err_ovl_no_viable_oper)
11906         << "operator->" << Base->getSourceRange();
11907     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11908     return ExprError();
11909 
11910   case OR_Ambiguous:
11911     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11912       << "->" << Base->getType() << Base->getSourceRange();
11913     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11914     return ExprError();
11915 
11916   case OR_Deleted:
11917     Diag(OpLoc,  diag::err_ovl_deleted_oper)
11918       << Best->Function->isDeleted()
11919       << "->"
11920       << getDeletedOrUnavailableSuffix(Best->Function)
11921       << Base->getSourceRange();
11922     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11923     return ExprError();
11924   }
11925 
11926   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
11927 
11928   // Convert the object parameter.
11929   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11930   ExprResult BaseResult =
11931     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
11932                                         Best->FoundDecl, Method);
11933   if (BaseResult.isInvalid())
11934     return ExprError();
11935   Base = BaseResult.get();
11936 
11937   // Build the operator call.
11938   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11939                                             HadMultipleCandidates, OpLoc);
11940   if (FnExpr.isInvalid())
11941     return ExprError();
11942 
11943   QualType ResultTy = Method->getReturnType();
11944   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11945   ResultTy = ResultTy.getNonLValueExprType(Context);
11946   CXXOperatorCallExpr *TheCall =
11947     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
11948                                       Base, ResultTy, VK, OpLoc, false);
11949 
11950   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
11951           return ExprError();
11952 
11953   return MaybeBindToTemporary(TheCall);
11954 }
11955 
11956 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11957 /// a literal operator described by the provided lookup results.
BuildLiteralOperatorCall(LookupResult & R,DeclarationNameInfo & SuffixInfo,ArrayRef<Expr * > Args,SourceLocation LitEndLoc,TemplateArgumentListInfo * TemplateArgs)11958 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11959                                           DeclarationNameInfo &SuffixInfo,
11960                                           ArrayRef<Expr*> Args,
11961                                           SourceLocation LitEndLoc,
11962                                        TemplateArgumentListInfo *TemplateArgs) {
11963   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11964 
11965   OverloadCandidateSet CandidateSet(UDSuffixLoc,
11966                                     OverloadCandidateSet::CSK_Normal);
11967   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11968                         TemplateArgs);
11969 
11970   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11971 
11972   // Perform overload resolution. This will usually be trivial, but might need
11973   // to perform substitutions for a literal operator template.
11974   OverloadCandidateSet::iterator Best;
11975   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11976   case OR_Success:
11977   case OR_Deleted:
11978     break;
11979 
11980   case OR_No_Viable_Function:
11981     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11982       << R.getLookupName();
11983     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11984     return ExprError();
11985 
11986   case OR_Ambiguous:
11987     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11988     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11989     return ExprError();
11990   }
11991 
11992   FunctionDecl *FD = Best->Function;
11993   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11994                                         HadMultipleCandidates,
11995                                         SuffixInfo.getLoc(),
11996                                         SuffixInfo.getInfo());
11997   if (Fn.isInvalid())
11998     return true;
11999 
12000   // Check the argument types. This should almost always be a no-op, except
12001   // that array-to-pointer decay is applied to string literals.
12002   Expr *ConvArgs[2];
12003   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12004     ExprResult InputInit = PerformCopyInitialization(
12005       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12006       SourceLocation(), Args[ArgIdx]);
12007     if (InputInit.isInvalid())
12008       return true;
12009     ConvArgs[ArgIdx] = InputInit.get();
12010   }
12011 
12012   QualType ResultTy = FD->getReturnType();
12013   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12014   ResultTy = ResultTy.getNonLValueExprType(Context);
12015 
12016   UserDefinedLiteral *UDL =
12017     new (Context) UserDefinedLiteral(Context, Fn.get(),
12018                                      llvm::makeArrayRef(ConvArgs, Args.size()),
12019                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
12020 
12021   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12022     return ExprError();
12023 
12024   if (CheckFunctionCall(FD, UDL, nullptr))
12025     return ExprError();
12026 
12027   return MaybeBindToTemporary(UDL);
12028 }
12029 
12030 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12031 /// given LookupResult is non-empty, it is assumed to describe a member which
12032 /// will be invoked. Otherwise, the function will be found via argument
12033 /// dependent lookup.
12034 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12035 /// otherwise CallExpr is set to ExprError() and some non-success value
12036 /// is returned.
12037 Sema::ForRangeStatus
BuildForRangeBeginEndCall(Scope * S,SourceLocation Loc,SourceLocation RangeLoc,VarDecl * Decl,BeginEndFunction BEF,const DeclarationNameInfo & NameInfo,LookupResult & MemberLookup,OverloadCandidateSet * CandidateSet,Expr * Range,ExprResult * CallExpr)12038 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12039                                 SourceLocation RangeLoc, VarDecl *Decl,
12040                                 BeginEndFunction BEF,
12041                                 const DeclarationNameInfo &NameInfo,
12042                                 LookupResult &MemberLookup,
12043                                 OverloadCandidateSet *CandidateSet,
12044                                 Expr *Range, ExprResult *CallExpr) {
12045   CandidateSet->clear();
12046   if (!MemberLookup.empty()) {
12047     ExprResult MemberRef =
12048         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12049                                  /*IsPtr=*/false, CXXScopeSpec(),
12050                                  /*TemplateKWLoc=*/SourceLocation(),
12051                                  /*FirstQualifierInScope=*/nullptr,
12052                                  MemberLookup,
12053                                  /*TemplateArgs=*/nullptr);
12054     if (MemberRef.isInvalid()) {
12055       *CallExpr = ExprError();
12056       Diag(Range->getLocStart(), diag::note_in_for_range)
12057           << RangeLoc << BEF << Range->getType();
12058       return FRS_DiagnosticIssued;
12059     }
12060     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12061     if (CallExpr->isInvalid()) {
12062       *CallExpr = ExprError();
12063       Diag(Range->getLocStart(), diag::note_in_for_range)
12064           << RangeLoc << BEF << Range->getType();
12065       return FRS_DiagnosticIssued;
12066     }
12067   } else {
12068     UnresolvedSet<0> FoundNames;
12069     UnresolvedLookupExpr *Fn =
12070       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12071                                    NestedNameSpecifierLoc(), NameInfo,
12072                                    /*NeedsADL=*/true, /*Overloaded=*/false,
12073                                    FoundNames.begin(), FoundNames.end());
12074 
12075     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12076                                                     CandidateSet, CallExpr);
12077     if (CandidateSet->empty() || CandidateSetError) {
12078       *CallExpr = ExprError();
12079       return FRS_NoViableFunction;
12080     }
12081     OverloadCandidateSet::iterator Best;
12082     OverloadingResult OverloadResult =
12083         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12084 
12085     if (OverloadResult == OR_No_Viable_Function) {
12086       *CallExpr = ExprError();
12087       return FRS_NoViableFunction;
12088     }
12089     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12090                                          Loc, nullptr, CandidateSet, &Best,
12091                                          OverloadResult,
12092                                          /*AllowTypoCorrection=*/false);
12093     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12094       *CallExpr = ExprError();
12095       Diag(Range->getLocStart(), diag::note_in_for_range)
12096           << RangeLoc << BEF << Range->getType();
12097       return FRS_DiagnosticIssued;
12098     }
12099   }
12100   return FRS_Success;
12101 }
12102 
12103 
12104 /// FixOverloadedFunctionReference - E is an expression that refers to
12105 /// a C++ overloaded function (possibly with some parentheses and
12106 /// perhaps a '&' around it). We have resolved the overloaded function
12107 /// to the function declaration Fn, so patch up the expression E to
12108 /// refer (possibly indirectly) to Fn. Returns the new expr.
FixOverloadedFunctionReference(Expr * E,DeclAccessPair Found,FunctionDecl * Fn)12109 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12110                                            FunctionDecl *Fn) {
12111   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12112     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12113                                                    Found, Fn);
12114     if (SubExpr == PE->getSubExpr())
12115       return PE;
12116 
12117     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12118   }
12119 
12120   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12121     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12122                                                    Found, Fn);
12123     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12124                                SubExpr->getType()) &&
12125            "Implicit cast type cannot be determined from overload");
12126     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12127     if (SubExpr == ICE->getSubExpr())
12128       return ICE;
12129 
12130     return ImplicitCastExpr::Create(Context, ICE->getType(),
12131                                     ICE->getCastKind(),
12132                                     SubExpr, nullptr,
12133                                     ICE->getValueKind());
12134   }
12135 
12136   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12137     assert(UnOp->getOpcode() == UO_AddrOf &&
12138            "Can only take the address of an overloaded function");
12139     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12140       if (Method->isStatic()) {
12141         // Do nothing: static member functions aren't any different
12142         // from non-member functions.
12143       } else {
12144         // Fix the subexpression, which really has to be an
12145         // UnresolvedLookupExpr holding an overloaded member function
12146         // or template.
12147         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12148                                                        Found, Fn);
12149         if (SubExpr == UnOp->getSubExpr())
12150           return UnOp;
12151 
12152         assert(isa<DeclRefExpr>(SubExpr)
12153                && "fixed to something other than a decl ref");
12154         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12155                && "fixed to a member ref with no nested name qualifier");
12156 
12157         // We have taken the address of a pointer to member
12158         // function. Perform the computation here so that we get the
12159         // appropriate pointer to member type.
12160         QualType ClassType
12161           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12162         QualType MemPtrType
12163           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12164 
12165         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12166                                            VK_RValue, OK_Ordinary,
12167                                            UnOp->getOperatorLoc());
12168       }
12169     }
12170     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12171                                                    Found, Fn);
12172     if (SubExpr == UnOp->getSubExpr())
12173       return UnOp;
12174 
12175     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12176                                      Context.getPointerType(SubExpr->getType()),
12177                                        VK_RValue, OK_Ordinary,
12178                                        UnOp->getOperatorLoc());
12179   }
12180 
12181   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12182     // FIXME: avoid copy.
12183     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12184     if (ULE->hasExplicitTemplateArgs()) {
12185       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12186       TemplateArgs = &TemplateArgsBuffer;
12187     }
12188 
12189     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12190                                            ULE->getQualifierLoc(),
12191                                            ULE->getTemplateKeywordLoc(),
12192                                            Fn,
12193                                            /*enclosing*/ false, // FIXME?
12194                                            ULE->getNameLoc(),
12195                                            Fn->getType(),
12196                                            VK_LValue,
12197                                            Found.getDecl(),
12198                                            TemplateArgs);
12199     MarkDeclRefReferenced(DRE);
12200     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12201     return DRE;
12202   }
12203 
12204   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12205     // FIXME: avoid copy.
12206     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12207     if (MemExpr->hasExplicitTemplateArgs()) {
12208       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12209       TemplateArgs = &TemplateArgsBuffer;
12210     }
12211 
12212     Expr *Base;
12213 
12214     // If we're filling in a static method where we used to have an
12215     // implicit member access, rewrite to a simple decl ref.
12216     if (MemExpr->isImplicitAccess()) {
12217       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12218         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12219                                                MemExpr->getQualifierLoc(),
12220                                                MemExpr->getTemplateKeywordLoc(),
12221                                                Fn,
12222                                                /*enclosing*/ false,
12223                                                MemExpr->getMemberLoc(),
12224                                                Fn->getType(),
12225                                                VK_LValue,
12226                                                Found.getDecl(),
12227                                                TemplateArgs);
12228         MarkDeclRefReferenced(DRE);
12229         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12230         return DRE;
12231       } else {
12232         SourceLocation Loc = MemExpr->getMemberLoc();
12233         if (MemExpr->getQualifier())
12234           Loc = MemExpr->getQualifierLoc().getBeginLoc();
12235         CheckCXXThisCapture(Loc);
12236         Base = new (Context) CXXThisExpr(Loc,
12237                                          MemExpr->getBaseType(),
12238                                          /*isImplicit=*/true);
12239       }
12240     } else
12241       Base = MemExpr->getBase();
12242 
12243     ExprValueKind valueKind;
12244     QualType type;
12245     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12246       valueKind = VK_LValue;
12247       type = Fn->getType();
12248     } else {
12249       valueKind = VK_RValue;
12250       type = Context.BoundMemberTy;
12251     }
12252 
12253     MemberExpr *ME = MemberExpr::Create(Context, Base,
12254                                         MemExpr->isArrow(),
12255                                         MemExpr->getQualifierLoc(),
12256                                         MemExpr->getTemplateKeywordLoc(),
12257                                         Fn,
12258                                         Found,
12259                                         MemExpr->getMemberNameInfo(),
12260                                         TemplateArgs,
12261                                         type, valueKind, OK_Ordinary);
12262     ME->setHadMultipleCandidates(true);
12263     MarkMemberReferenced(ME);
12264     return ME;
12265   }
12266 
12267   llvm_unreachable("Invalid reference to overloaded function");
12268 }
12269 
FixOverloadedFunctionReference(ExprResult E,DeclAccessPair Found,FunctionDecl * Fn)12270 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12271                                                 DeclAccessPair Found,
12272                                                 FunctionDecl *Fn) {
12273   return FixOverloadedFunctionReference(E.get(), Found, Fn);
12274 }
12275 
12276 } // end namespace clang
12277