• 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/PartialDiagnostic.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "clang/Sema/Template.h"
29 #include "clang/Sema/TemplateDeduction.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallString.h"
34 #include <algorithm>
35 
36 namespace clang {
37 using namespace sema;
38 
39 /// A convenience routine for creating a decayed reference to a function.
40 static ExprResult
CreateFunctionRefExpr(Sema & S,FunctionDecl * Fn,NamedDecl * FoundDecl,bool HadMultipleCandidates,SourceLocation Loc=SourceLocation (),const DeclarationNameLoc & LocInfo=DeclarationNameLoc ())41 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
42                       bool HadMultipleCandidates,
43                       SourceLocation Loc = SourceLocation(),
44                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
45   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
46                                                  VK_LValue, Loc, LocInfo);
47   if (HadMultipleCandidates)
48     DRE->setHadMultipleCandidates(true);
49 
50   S.MarkDeclRefReferenced(DRE);
51   S.DiagnoseUseOfDecl(FoundDecl, Loc);
52 
53   ExprResult E = S.Owned(DRE);
54   E = S.DefaultFunctionArrayConversion(E.take());
55   if (E.isInvalid())
56     return ExprError();
57   return E;
58 }
59 
60 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
61                                  bool InOverloadResolution,
62                                  StandardConversionSequence &SCS,
63                                  bool CStyle,
64                                  bool AllowObjCWritebackConversion);
65 
66 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
67                                                  QualType &ToType,
68                                                  bool InOverloadResolution,
69                                                  StandardConversionSequence &SCS,
70                                                  bool CStyle);
71 static OverloadingResult
72 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
73                         UserDefinedConversionSequence& User,
74                         OverloadCandidateSet& Conversions,
75                         bool AllowExplicit);
76 
77 
78 static ImplicitConversionSequence::CompareKind
79 CompareStandardConversionSequences(Sema &S,
80                                    const StandardConversionSequence& SCS1,
81                                    const StandardConversionSequence& SCS2);
82 
83 static ImplicitConversionSequence::CompareKind
84 CompareQualificationConversions(Sema &S,
85                                 const StandardConversionSequence& SCS1,
86                                 const StandardConversionSequence& SCS2);
87 
88 static ImplicitConversionSequence::CompareKind
89 CompareDerivedToBaseConversions(Sema &S,
90                                 const StandardConversionSequence& SCS1,
91                                 const StandardConversionSequence& SCS2);
92 
93 
94 
95 /// GetConversionCategory - Retrieve the implicit conversion
96 /// category corresponding to the given implicit conversion kind.
97 ImplicitConversionCategory
GetConversionCategory(ImplicitConversionKind Kind)98 GetConversionCategory(ImplicitConversionKind Kind) {
99   static const ImplicitConversionCategory
100     Category[(int)ICK_Num_Conversion_Kinds] = {
101     ICC_Identity,
102     ICC_Lvalue_Transformation,
103     ICC_Lvalue_Transformation,
104     ICC_Lvalue_Transformation,
105     ICC_Identity,
106     ICC_Qualification_Adjustment,
107     ICC_Promotion,
108     ICC_Promotion,
109     ICC_Promotion,
110     ICC_Conversion,
111     ICC_Conversion,
112     ICC_Conversion,
113     ICC_Conversion,
114     ICC_Conversion,
115     ICC_Conversion,
116     ICC_Conversion,
117     ICC_Conversion,
118     ICC_Conversion,
119     ICC_Conversion,
120     ICC_Conversion,
121     ICC_Conversion,
122     ICC_Conversion
123   };
124   return Category[(int)Kind];
125 }
126 
127 /// GetConversionRank - Retrieve the implicit conversion rank
128 /// corresponding to the given implicit conversion kind.
GetConversionRank(ImplicitConversionKind Kind)129 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
130   static const ImplicitConversionRank
131     Rank[(int)ICK_Num_Conversion_Kinds] = {
132     ICR_Exact_Match,
133     ICR_Exact_Match,
134     ICR_Exact_Match,
135     ICR_Exact_Match,
136     ICR_Exact_Match,
137     ICR_Exact_Match,
138     ICR_Promotion,
139     ICR_Promotion,
140     ICR_Promotion,
141     ICR_Conversion,
142     ICR_Conversion,
143     ICR_Conversion,
144     ICR_Conversion,
145     ICR_Conversion,
146     ICR_Conversion,
147     ICR_Conversion,
148     ICR_Conversion,
149     ICR_Conversion,
150     ICR_Conversion,
151     ICR_Conversion,
152     ICR_Complex_Real_Conversion,
153     ICR_Conversion,
154     ICR_Conversion,
155     ICR_Writeback_Conversion
156   };
157   return Rank[(int)Kind];
158 }
159 
160 /// GetImplicitConversionName - Return the name of this kind of
161 /// implicit conversion.
GetImplicitConversionName(ImplicitConversionKind Kind)162 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
163   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
164     "No conversion",
165     "Lvalue-to-rvalue",
166     "Array-to-pointer",
167     "Function-to-pointer",
168     "Noreturn adjustment",
169     "Qualification",
170     "Integral promotion",
171     "Floating point promotion",
172     "Complex promotion",
173     "Integral conversion",
174     "Floating conversion",
175     "Complex conversion",
176     "Floating-integral conversion",
177     "Pointer conversion",
178     "Pointer-to-member conversion",
179     "Boolean conversion",
180     "Compatible-types conversion",
181     "Derived-to-base conversion",
182     "Vector conversion",
183     "Vector splat",
184     "Complex-real conversion",
185     "Block Pointer conversion",
186     "Transparent Union Conversion"
187     "Writeback conversion"
188   };
189   return Name[Kind];
190 }
191 
192 /// StandardConversionSequence - Set the standard conversion
193 /// sequence to the identity conversion.
setAsIdentityConversion()194 void StandardConversionSequence::setAsIdentityConversion() {
195   First = ICK_Identity;
196   Second = ICK_Identity;
197   Third = ICK_Identity;
198   DeprecatedStringLiteralToCharPtr = false;
199   QualificationIncludesObjCLifetime = false;
200   ReferenceBinding = false;
201   DirectBinding = false;
202   IsLvalueReference = true;
203   BindsToFunctionLvalue = false;
204   BindsToRvalue = false;
205   BindsImplicitObjectArgumentWithoutRefQualifier = false;
206   ObjCLifetimeConversionBinding = false;
207   CopyConstructor = 0;
208 }
209 
210 /// getRank - Retrieve the rank of this standard conversion sequence
211 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
212 /// implicit conversions.
getRank() const213 ImplicitConversionRank StandardConversionSequence::getRank() const {
214   ImplicitConversionRank Rank = ICR_Exact_Match;
215   if  (GetConversionRank(First) > Rank)
216     Rank = GetConversionRank(First);
217   if  (GetConversionRank(Second) > Rank)
218     Rank = GetConversionRank(Second);
219   if  (GetConversionRank(Third) > Rank)
220     Rank = GetConversionRank(Third);
221   return Rank;
222 }
223 
224 /// isPointerConversionToBool - Determines whether this conversion is
225 /// a conversion of a pointer or pointer-to-member to bool. This is
226 /// used as part of the ranking of standard conversion sequences
227 /// (C++ 13.3.3.2p4).
isPointerConversionToBool() const228 bool StandardConversionSequence::isPointerConversionToBool() const {
229   // Note that FromType has not necessarily been transformed by the
230   // array-to-pointer or function-to-pointer implicit conversions, so
231   // check for their presence as well as checking whether FromType is
232   // a pointer.
233   if (getToType(1)->isBooleanType() &&
234       (getFromType()->isPointerType() ||
235        getFromType()->isObjCObjectPointerType() ||
236        getFromType()->isBlockPointerType() ||
237        getFromType()->isNullPtrType() ||
238        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
239     return true;
240 
241   return false;
242 }
243 
244 /// isPointerConversionToVoidPointer - Determines whether this
245 /// conversion is a conversion of a pointer to a void pointer. This is
246 /// used as part of the ranking of standard conversion sequences (C++
247 /// 13.3.3.2p4).
248 bool
249 StandardConversionSequence::
isPointerConversionToVoidPointer(ASTContext & Context) const250 isPointerConversionToVoidPointer(ASTContext& Context) const {
251   QualType FromType = getFromType();
252   QualType ToType = getToType(1);
253 
254   // Note that FromType has not necessarily been transformed by the
255   // array-to-pointer implicit conversion, so check for its presence
256   // and redo the conversion to get a pointer.
257   if (First == ICK_Array_To_Pointer)
258     FromType = Context.getArrayDecayedType(FromType);
259 
260   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
261     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
262       return ToPtrType->getPointeeType()->isVoidType();
263 
264   return false;
265 }
266 
267 /// Skip any implicit casts which could be either part of a narrowing conversion
268 /// or after one in an implicit conversion.
IgnoreNarrowingConversion(const Expr * Converted)269 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
270   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
271     switch (ICE->getCastKind()) {
272     case CK_NoOp:
273     case CK_IntegralCast:
274     case CK_IntegralToBoolean:
275     case CK_IntegralToFloating:
276     case CK_FloatingToIntegral:
277     case CK_FloatingToBoolean:
278     case CK_FloatingCast:
279       Converted = ICE->getSubExpr();
280       continue;
281 
282     default:
283       return Converted;
284     }
285   }
286 
287   return Converted;
288 }
289 
290 /// Check if this standard conversion sequence represents a narrowing
291 /// conversion, according to C++11 [dcl.init.list]p7.
292 ///
293 /// \param Ctx  The AST context.
294 /// \param Converted  The result of applying this standard conversion sequence.
295 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
296 ///        value of the expression prior to the narrowing conversion.
297 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
298 ///        type of the expression prior to the narrowing conversion.
299 NarrowingKind
getNarrowingKind(ASTContext & Ctx,const Expr * Converted,APValue & ConstantValue,QualType & ConstantType) const300 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
301                                              const Expr *Converted,
302                                              APValue &ConstantValue,
303                                              QualType &ConstantType) const {
304   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
305 
306   // C++11 [dcl.init.list]p7:
307   //   A narrowing conversion is an implicit conversion ...
308   QualType FromType = getToType(0);
309   QualType ToType = getToType(1);
310   switch (Second) {
311   // -- from a floating-point type to an integer type, or
312   //
313   // -- from an integer type or unscoped enumeration type to a floating-point
314   //    type, except where the source is a constant expression and the actual
315   //    value after conversion will fit into the target type and will produce
316   //    the original value when converted back to the original type, or
317   case ICK_Floating_Integral:
318     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
319       return NK_Type_Narrowing;
320     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
321       llvm::APSInt IntConstantValue;
322       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
323       if (Initializer &&
324           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
325         // Convert the integer to the floating type.
326         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
327         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
328                                 llvm::APFloat::rmNearestTiesToEven);
329         // And back.
330         llvm::APSInt ConvertedValue = IntConstantValue;
331         bool ignored;
332         Result.convertToInteger(ConvertedValue,
333                                 llvm::APFloat::rmTowardZero, &ignored);
334         // If the resulting value is different, this was a narrowing conversion.
335         if (IntConstantValue != ConvertedValue) {
336           ConstantValue = APValue(IntConstantValue);
337           ConstantType = Initializer->getType();
338           return NK_Constant_Narrowing;
339         }
340       } else {
341         // Variables are always narrowings.
342         return NK_Variable_Narrowing;
343       }
344     }
345     return NK_Not_Narrowing;
346 
347   // -- from long double to double or float, or from double to float, except
348   //    where the source is a constant expression and the actual value after
349   //    conversion is within the range of values that can be represented (even
350   //    if it cannot be represented exactly), or
351   case ICK_Floating_Conversion:
352     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
353         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
354       // FromType is larger than ToType.
355       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
356       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
357         // Constant!
358         assert(ConstantValue.isFloat());
359         llvm::APFloat FloatVal = ConstantValue.getFloat();
360         // Convert the source value into the target type.
361         bool ignored;
362         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
363           Ctx.getFloatTypeSemantics(ToType),
364           llvm::APFloat::rmNearestTiesToEven, &ignored);
365         // If there was no overflow, the source value is within the range of
366         // values that can be represented.
367         if (ConvertStatus & llvm::APFloat::opOverflow) {
368           ConstantType = Initializer->getType();
369           return NK_Constant_Narrowing;
370         }
371       } else {
372         return NK_Variable_Narrowing;
373       }
374     }
375     return NK_Not_Narrowing;
376 
377   // -- from an integer type or unscoped enumeration type to an integer type
378   //    that cannot represent all the values of the original type, except where
379   //    the source is a constant expression and the actual value after
380   //    conversion will fit into the target type and will produce the original
381   //    value when converted back to the original type.
382   case ICK_Boolean_Conversion:  // Bools are integers too.
383     if (!FromType->isIntegralOrUnscopedEnumerationType()) {
384       // Boolean conversions can be from pointers and pointers to members
385       // [conv.bool], and those aren't considered narrowing conversions.
386       return NK_Not_Narrowing;
387     }  // Otherwise, fall through to the integral case.
388   case ICK_Integral_Conversion: {
389     assert(FromType->isIntegralOrUnscopedEnumerationType());
390     assert(ToType->isIntegralOrUnscopedEnumerationType());
391     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
392     const unsigned FromWidth = Ctx.getIntWidth(FromType);
393     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
394     const unsigned ToWidth = Ctx.getIntWidth(ToType);
395 
396     if (FromWidth > ToWidth ||
397         (FromWidth == ToWidth && FromSigned != ToSigned) ||
398         (FromSigned && !ToSigned)) {
399       // Not all values of FromType can be represented in ToType.
400       llvm::APSInt InitializerValue;
401       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
402       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
403         // Such conversions on variables are always narrowing.
404         return NK_Variable_Narrowing;
405       }
406       bool Narrowing = false;
407       if (FromWidth < ToWidth) {
408         // Negative -> unsigned is narrowing. Otherwise, more bits is never
409         // narrowing.
410         if (InitializerValue.isSigned() && InitializerValue.isNegative())
411           Narrowing = true;
412       } else {
413         // Add a bit to the InitializerValue so we don't have to worry about
414         // signed vs. unsigned comparisons.
415         InitializerValue = InitializerValue.extend(
416           InitializerValue.getBitWidth() + 1);
417         // Convert the initializer to and from the target width and signed-ness.
418         llvm::APSInt ConvertedValue = InitializerValue;
419         ConvertedValue = ConvertedValue.trunc(ToWidth);
420         ConvertedValue.setIsSigned(ToSigned);
421         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
422         ConvertedValue.setIsSigned(InitializerValue.isSigned());
423         // If the result is different, this was a narrowing conversion.
424         if (ConvertedValue != InitializerValue)
425           Narrowing = true;
426       }
427       if (Narrowing) {
428         ConstantType = Initializer->getType();
429         ConstantValue = APValue(InitializerValue);
430         return NK_Constant_Narrowing;
431       }
432     }
433     return NK_Not_Narrowing;
434   }
435 
436   default:
437     // Other kinds of conversions are not narrowings.
438     return NK_Not_Narrowing;
439   }
440 }
441 
442 /// DebugPrint - Print this standard conversion sequence to standard
443 /// error. Useful for debugging overloading issues.
DebugPrint() const444 void StandardConversionSequence::DebugPrint() const {
445   raw_ostream &OS = llvm::errs();
446   bool PrintedSomething = false;
447   if (First != ICK_Identity) {
448     OS << GetImplicitConversionName(First);
449     PrintedSomething = true;
450   }
451 
452   if (Second != ICK_Identity) {
453     if (PrintedSomething) {
454       OS << " -> ";
455     }
456     OS << GetImplicitConversionName(Second);
457 
458     if (CopyConstructor) {
459       OS << " (by copy constructor)";
460     } else if (DirectBinding) {
461       OS << " (direct reference binding)";
462     } else if (ReferenceBinding) {
463       OS << " (reference binding)";
464     }
465     PrintedSomething = true;
466   }
467 
468   if (Third != ICK_Identity) {
469     if (PrintedSomething) {
470       OS << " -> ";
471     }
472     OS << GetImplicitConversionName(Third);
473     PrintedSomething = true;
474   }
475 
476   if (!PrintedSomething) {
477     OS << "No conversions required";
478   }
479 }
480 
481 /// DebugPrint - Print this user-defined conversion sequence to standard
482 /// error. Useful for debugging overloading issues.
DebugPrint() const483 void UserDefinedConversionSequence::DebugPrint() const {
484   raw_ostream &OS = llvm::errs();
485   if (Before.First || Before.Second || Before.Third) {
486     Before.DebugPrint();
487     OS << " -> ";
488   }
489   if (ConversionFunction)
490     OS << '\'' << *ConversionFunction << '\'';
491   else
492     OS << "aggregate initialization";
493   if (After.First || After.Second || After.Third) {
494     OS << " -> ";
495     After.DebugPrint();
496   }
497 }
498 
499 /// DebugPrint - Print this implicit conversion sequence to standard
500 /// error. Useful for debugging overloading issues.
DebugPrint() const501 void ImplicitConversionSequence::DebugPrint() const {
502   raw_ostream &OS = llvm::errs();
503   switch (ConversionKind) {
504   case StandardConversion:
505     OS << "Standard conversion: ";
506     Standard.DebugPrint();
507     break;
508   case UserDefinedConversion:
509     OS << "User-defined conversion: ";
510     UserDefined.DebugPrint();
511     break;
512   case EllipsisConversion:
513     OS << "Ellipsis conversion";
514     break;
515   case AmbiguousConversion:
516     OS << "Ambiguous conversion";
517     break;
518   case BadConversion:
519     OS << "Bad conversion";
520     break;
521   }
522 
523   OS << "\n";
524 }
525 
construct()526 void AmbiguousConversionSequence::construct() {
527   new (&conversions()) ConversionSet();
528 }
529 
destruct()530 void AmbiguousConversionSequence::destruct() {
531   conversions().~ConversionSet();
532 }
533 
534 void
copyFrom(const AmbiguousConversionSequence & O)535 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
536   FromTypePtr = O.FromTypePtr;
537   ToTypePtr = O.ToTypePtr;
538   new (&conversions()) ConversionSet(O.conversions());
539 }
540 
541 namespace {
542   // Structure used by OverloadCandidate::DeductionFailureInfo to store
543   // template argument information.
544   struct DFIArguments {
545     TemplateArgument FirstArg;
546     TemplateArgument SecondArg;
547   };
548   // Structure used by OverloadCandidate::DeductionFailureInfo to store
549   // template parameter and template argument information.
550   struct DFIParamWithArguments : DFIArguments {
551     TemplateParameter Param;
552   };
553 }
554 
555 /// \brief Convert from Sema's representation of template deduction information
556 /// to the form used in overload-candidate information.
557 OverloadCandidate::DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext & Context,Sema::TemplateDeductionResult TDK,TemplateDeductionInfo & Info)558 static MakeDeductionFailureInfo(ASTContext &Context,
559                                 Sema::TemplateDeductionResult TDK,
560                                 TemplateDeductionInfo &Info) {
561   OverloadCandidate::DeductionFailureInfo Result;
562   Result.Result = static_cast<unsigned>(TDK);
563   Result.HasDiagnostic = false;
564   Result.Data = 0;
565   switch (TDK) {
566   case Sema::TDK_Success:
567   case Sema::TDK_Invalid:
568   case Sema::TDK_InstantiationDepth:
569   case Sema::TDK_TooManyArguments:
570   case Sema::TDK_TooFewArguments:
571     break;
572 
573   case Sema::TDK_Incomplete:
574   case Sema::TDK_InvalidExplicitArguments:
575     Result.Data = Info.Param.getOpaqueValue();
576     break;
577 
578   case Sema::TDK_NonDeducedMismatch: {
579     // FIXME: Should allocate from normal heap so that we can free this later.
580     DFIArguments *Saved = new (Context) DFIArguments;
581     Saved->FirstArg = Info.FirstArg;
582     Saved->SecondArg = Info.SecondArg;
583     Result.Data = Saved;
584     break;
585   }
586 
587   case Sema::TDK_Inconsistent:
588   case Sema::TDK_Underqualified: {
589     // FIXME: Should allocate from normal heap so that we can free this later.
590     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
591     Saved->Param = Info.Param;
592     Saved->FirstArg = Info.FirstArg;
593     Saved->SecondArg = Info.SecondArg;
594     Result.Data = Saved;
595     break;
596   }
597 
598   case Sema::TDK_SubstitutionFailure:
599     Result.Data = Info.take();
600     if (Info.hasSFINAEDiagnostic()) {
601       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
602           SourceLocation(), PartialDiagnostic::NullDiagnostic());
603       Info.takeSFINAEDiagnostic(*Diag);
604       Result.HasDiagnostic = true;
605     }
606     break;
607 
608   case Sema::TDK_FailedOverloadResolution:
609     Result.Data = Info.Expression;
610     break;
611 
612   case Sema::TDK_MiscellaneousDeductionFailure:
613     break;
614   }
615 
616   return Result;
617 }
618 
Destroy()619 void OverloadCandidate::DeductionFailureInfo::Destroy() {
620   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
621   case Sema::TDK_Success:
622   case Sema::TDK_Invalid:
623   case Sema::TDK_InstantiationDepth:
624   case Sema::TDK_Incomplete:
625   case Sema::TDK_TooManyArguments:
626   case Sema::TDK_TooFewArguments:
627   case Sema::TDK_InvalidExplicitArguments:
628   case Sema::TDK_FailedOverloadResolution:
629     break;
630 
631   case Sema::TDK_Inconsistent:
632   case Sema::TDK_Underqualified:
633   case Sema::TDK_NonDeducedMismatch:
634     // FIXME: Destroy the data?
635     Data = 0;
636     break;
637 
638   case Sema::TDK_SubstitutionFailure:
639     // FIXME: Destroy the template argument list?
640     Data = 0;
641     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
642       Diag->~PartialDiagnosticAt();
643       HasDiagnostic = false;
644     }
645     break;
646 
647   // Unhandled
648   case Sema::TDK_MiscellaneousDeductionFailure:
649     break;
650   }
651 }
652 
653 PartialDiagnosticAt *
getSFINAEDiagnostic()654 OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
655   if (HasDiagnostic)
656     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
657   return 0;
658 }
659 
660 TemplateParameter
getTemplateParameter()661 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
662   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
663   case Sema::TDK_Success:
664   case Sema::TDK_Invalid:
665   case Sema::TDK_InstantiationDepth:
666   case Sema::TDK_TooManyArguments:
667   case Sema::TDK_TooFewArguments:
668   case Sema::TDK_SubstitutionFailure:
669   case Sema::TDK_NonDeducedMismatch:
670   case Sema::TDK_FailedOverloadResolution:
671     return TemplateParameter();
672 
673   case Sema::TDK_Incomplete:
674   case Sema::TDK_InvalidExplicitArguments:
675     return TemplateParameter::getFromOpaqueValue(Data);
676 
677   case Sema::TDK_Inconsistent:
678   case Sema::TDK_Underqualified:
679     return static_cast<DFIParamWithArguments*>(Data)->Param;
680 
681   // Unhandled
682   case Sema::TDK_MiscellaneousDeductionFailure:
683     break;
684   }
685 
686   return TemplateParameter();
687 }
688 
689 TemplateArgumentList *
getTemplateArgumentList()690 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
691   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
692   case Sema::TDK_Success:
693   case Sema::TDK_Invalid:
694   case Sema::TDK_InstantiationDepth:
695   case Sema::TDK_TooManyArguments:
696   case Sema::TDK_TooFewArguments:
697   case Sema::TDK_Incomplete:
698   case Sema::TDK_InvalidExplicitArguments:
699   case Sema::TDK_Inconsistent:
700   case Sema::TDK_Underqualified:
701   case Sema::TDK_NonDeducedMismatch:
702   case Sema::TDK_FailedOverloadResolution:
703     return 0;
704 
705   case Sema::TDK_SubstitutionFailure:
706     return static_cast<TemplateArgumentList*>(Data);
707 
708   // Unhandled
709   case Sema::TDK_MiscellaneousDeductionFailure:
710     break;
711   }
712 
713   return 0;
714 }
715 
getFirstArg()716 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
717   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
718   case Sema::TDK_Success:
719   case Sema::TDK_Invalid:
720   case Sema::TDK_InstantiationDepth:
721   case Sema::TDK_Incomplete:
722   case Sema::TDK_TooManyArguments:
723   case Sema::TDK_TooFewArguments:
724   case Sema::TDK_InvalidExplicitArguments:
725   case Sema::TDK_SubstitutionFailure:
726   case Sema::TDK_FailedOverloadResolution:
727     return 0;
728 
729   case Sema::TDK_Inconsistent:
730   case Sema::TDK_Underqualified:
731   case Sema::TDK_NonDeducedMismatch:
732     return &static_cast<DFIArguments*>(Data)->FirstArg;
733 
734   // Unhandled
735   case Sema::TDK_MiscellaneousDeductionFailure:
736     break;
737   }
738 
739   return 0;
740 }
741 
742 const TemplateArgument *
getSecondArg()743 OverloadCandidate::DeductionFailureInfo::getSecondArg() {
744   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745   case Sema::TDK_Success:
746   case Sema::TDK_Invalid:
747   case Sema::TDK_InstantiationDepth:
748   case Sema::TDK_Incomplete:
749   case Sema::TDK_TooManyArguments:
750   case Sema::TDK_TooFewArguments:
751   case Sema::TDK_InvalidExplicitArguments:
752   case Sema::TDK_SubstitutionFailure:
753   case Sema::TDK_FailedOverloadResolution:
754     return 0;
755 
756   case Sema::TDK_Inconsistent:
757   case Sema::TDK_Underqualified:
758   case Sema::TDK_NonDeducedMismatch:
759     return &static_cast<DFIArguments*>(Data)->SecondArg;
760 
761   // Unhandled
762   case Sema::TDK_MiscellaneousDeductionFailure:
763     break;
764   }
765 
766   return 0;
767 }
768 
769 Expr *
getExpr()770 OverloadCandidate::DeductionFailureInfo::getExpr() {
771   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
772         Sema::TDK_FailedOverloadResolution)
773     return static_cast<Expr*>(Data);
774 
775   return 0;
776 }
777 
destroyCandidates()778 void OverloadCandidateSet::destroyCandidates() {
779   for (iterator i = begin(), e = end(); i != e; ++i) {
780     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
781       i->Conversions[ii].~ImplicitConversionSequence();
782     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
783       i->DeductionFailure.Destroy();
784   }
785 }
786 
clear()787 void OverloadCandidateSet::clear() {
788   destroyCandidates();
789   NumInlineSequences = 0;
790   Candidates.clear();
791   Functions.clear();
792 }
793 
794 namespace {
795   class UnbridgedCastsSet {
796     struct Entry {
797       Expr **Addr;
798       Expr *Saved;
799     };
800     SmallVector<Entry, 2> Entries;
801 
802   public:
save(Sema & S,Expr * & E)803     void save(Sema &S, Expr *&E) {
804       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
805       Entry entry = { &E, E };
806       Entries.push_back(entry);
807       E = S.stripARCUnbridgedCast(E);
808     }
809 
restore()810     void restore() {
811       for (SmallVectorImpl<Entry>::iterator
812              i = Entries.begin(), e = Entries.end(); i != e; ++i)
813         *i->Addr = i->Saved;
814     }
815   };
816 }
817 
818 /// checkPlaceholderForOverload - Do any interesting placeholder-like
819 /// preprocessing on the given expression.
820 ///
821 /// \param unbridgedCasts a collection to which to add unbridged casts;
822 ///   without this, they will be immediately diagnosed as errors
823 ///
824 /// Return true on unrecoverable error.
checkPlaceholderForOverload(Sema & S,Expr * & E,UnbridgedCastsSet * unbridgedCasts=0)825 static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
826                                         UnbridgedCastsSet *unbridgedCasts = 0) {
827   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
828     // We can't handle overloaded expressions here because overload
829     // resolution might reasonably tweak them.
830     if (placeholder->getKind() == BuiltinType::Overload) return false;
831 
832     // If the context potentially accepts unbridged ARC casts, strip
833     // the unbridged cast and add it to the collection for later restoration.
834     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
835         unbridgedCasts) {
836       unbridgedCasts->save(S, E);
837       return false;
838     }
839 
840     // Go ahead and check everything else.
841     ExprResult result = S.CheckPlaceholderExpr(E);
842     if (result.isInvalid())
843       return true;
844 
845     E = result.take();
846     return false;
847   }
848 
849   // Nothing to do.
850   return false;
851 }
852 
853 /// checkArgPlaceholdersForOverload - Check a set of call operands for
854 /// placeholders.
checkArgPlaceholdersForOverload(Sema & S,Expr ** args,unsigned numArgs,UnbridgedCastsSet & unbridged)855 static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
856                                             unsigned numArgs,
857                                             UnbridgedCastsSet &unbridged) {
858   for (unsigned i = 0; i != numArgs; ++i)
859     if (checkPlaceholderForOverload(S, args[i], &unbridged))
860       return true;
861 
862   return false;
863 }
864 
865 // IsOverload - Determine whether the given New declaration is an
866 // overload of the declarations in Old. This routine returns false if
867 // New and Old cannot be overloaded, e.g., if New has the same
868 // signature as some function in Old (C++ 1.3.10) or if the Old
869 // declarations aren't functions (or function templates) at all. When
870 // it does return false, MatchedDecl will point to the decl that New
871 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
872 // top of the underlying declaration.
873 //
874 // Example: Given the following input:
875 //
876 //   void f(int, float); // #1
877 //   void f(int, int); // #2
878 //   int f(int, int); // #3
879 //
880 // When we process #1, there is no previous declaration of "f",
881 // so IsOverload will not be used.
882 //
883 // When we process #2, Old contains only the FunctionDecl for #1.  By
884 // comparing the parameter types, we see that #1 and #2 are overloaded
885 // (since they have different signatures), so this routine returns
886 // false; MatchedDecl is unchanged.
887 //
888 // When we process #3, Old is an overload set containing #1 and #2. We
889 // compare the signatures of #3 to #1 (they're overloaded, so we do
890 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
891 // identical (return types of functions are not part of the
892 // signature), IsOverload returns false and MatchedDecl will be set to
893 // point to the FunctionDecl for #2.
894 //
895 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
896 // into a class by a using declaration.  The rules for whether to hide
897 // shadow declarations ignore some properties which otherwise figure
898 // into a function template's signature.
899 Sema::OverloadKind
CheckOverload(Scope * S,FunctionDecl * New,const LookupResult & Old,NamedDecl * & Match,bool NewIsUsingDecl)900 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
901                     NamedDecl *&Match, bool NewIsUsingDecl) {
902   for (LookupResult::iterator I = Old.begin(), E = Old.end();
903          I != E; ++I) {
904     NamedDecl *OldD = *I;
905 
906     bool OldIsUsingDecl = false;
907     if (isa<UsingShadowDecl>(OldD)) {
908       OldIsUsingDecl = true;
909 
910       // We can always introduce two using declarations into the same
911       // context, even if they have identical signatures.
912       if (NewIsUsingDecl) continue;
913 
914       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
915     }
916 
917     // If either declaration was introduced by a using declaration,
918     // we'll need to use slightly different rules for matching.
919     // Essentially, these rules are the normal rules, except that
920     // function templates hide function templates with different
921     // return types or template parameter lists.
922     bool UseMemberUsingDeclRules =
923       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
924 
925     if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
926       if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
927         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
928           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
929           continue;
930         }
931 
932         Match = *I;
933         return Ovl_Match;
934       }
935     } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
936       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
937         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
938           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
939           continue;
940         }
941 
942         Match = *I;
943         return Ovl_Match;
944       }
945     } else if (isa<UsingDecl>(OldD)) {
946       // We can overload with these, which can show up when doing
947       // redeclaration checks for UsingDecls.
948       assert(Old.getLookupKind() == LookupUsingDeclName);
949     } else if (isa<TagDecl>(OldD)) {
950       // We can always overload with tags by hiding them.
951     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
952       // Optimistically assume that an unresolved using decl will
953       // overload; if it doesn't, we'll have to diagnose during
954       // template instantiation.
955     } else {
956       // (C++ 13p1):
957       //   Only function declarations can be overloaded; object and type
958       //   declarations cannot be overloaded.
959       Match = *I;
960       return Ovl_NonFunction;
961     }
962   }
963 
964   return Ovl_Overload;
965 }
966 
canBeOverloaded(const FunctionDecl & D)967 static bool canBeOverloaded(const FunctionDecl &D) {
968   if (D.getAttr<OverloadableAttr>())
969     return true;
970   if (D.isExternC())
971     return false;
972 
973   // Main cannot be overloaded (basic.start.main).
974   if (D.isMain())
975     return false;
976 
977   return true;
978 }
979 
shouldTryToOverload(Sema & S,FunctionDecl * New,FunctionDecl * Old,bool UseUsingDeclRules)980 static bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old,
981                                 bool UseUsingDeclRules) {
982   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
983   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
984 
985   // C++ [temp.fct]p2:
986   //   A function template can be overloaded with other function templates
987   //   and with normal (non-template) functions.
988   if ((OldTemplate == 0) != (NewTemplate == 0))
989     return true;
990 
991   // Is the function New an overload of the function Old?
992   QualType OldQType = S.Context.getCanonicalType(Old->getType());
993   QualType NewQType = S.Context.getCanonicalType(New->getType());
994 
995   // Compare the signatures (C++ 1.3.10) of the two functions to
996   // determine whether they are overloads. If we find any mismatch
997   // in the signature, they are overloads.
998 
999   // If either of these functions is a K&R-style function (no
1000   // prototype), then we consider them to have matching signatures.
1001   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1002       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1003     return false;
1004 
1005   const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1006   const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
1007 
1008   // The signature of a function includes the types of its
1009   // parameters (C++ 1.3.10), which includes the presence or absence
1010   // of the ellipsis; see C++ DR 357).
1011   if (OldQType != NewQType &&
1012       (OldType->getNumArgs() != NewType->getNumArgs() ||
1013        OldType->isVariadic() != NewType->isVariadic() ||
1014        !S.FunctionArgTypesAreEqual(OldType, NewType)))
1015     return true;
1016 
1017   // C++ [temp.over.link]p4:
1018   //   The signature of a function template consists of its function
1019   //   signature, its return type and its template parameter list. The names
1020   //   of the template parameters are significant only for establishing the
1021   //   relationship between the template parameters and the rest of the
1022   //   signature.
1023   //
1024   // We check the return type and template parameter lists for function
1025   // templates first; the remaining checks follow.
1026   //
1027   // However, we don't consider either of these when deciding whether
1028   // a member introduced by a shadow declaration is hidden.
1029   if (!UseUsingDeclRules && NewTemplate &&
1030       (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1031                                          OldTemplate->getTemplateParameters(),
1032                                          false, S.TPL_TemplateMatch) ||
1033        OldType->getResultType() != NewType->getResultType()))
1034     return true;
1035 
1036   // If the function is a class member, its signature includes the
1037   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1038   //
1039   // As part of this, also check whether one of the member functions
1040   // is static, in which case they are not overloads (C++
1041   // 13.1p2). While not part of the definition of the signature,
1042   // this check is important to determine whether these functions
1043   // can be overloaded.
1044   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1045   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1046   if (OldMethod && NewMethod &&
1047       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1048     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1049       if (!UseUsingDeclRules &&
1050           (OldMethod->getRefQualifier() == RQ_None ||
1051            NewMethod->getRefQualifier() == RQ_None)) {
1052         // C++0x [over.load]p2:
1053         //   - Member function declarations with the same name and the same
1054         //     parameter-type-list as well as member function template
1055         //     declarations with the same name, the same parameter-type-list, and
1056         //     the same template parameter lists cannot be overloaded if any of
1057         //     them, but not all, have a ref-qualifier (8.3.5).
1058         S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1059           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1060         S.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1061       }
1062       return true;
1063     }
1064 
1065     // We may not have applied the implicit const for a constexpr member
1066     // function yet (because we haven't yet resolved whether this is a static
1067     // or non-static member function). Add it now, on the assumption that this
1068     // is a redeclaration of OldMethod.
1069     unsigned NewQuals = NewMethod->getTypeQualifiers();
1070     if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod))
1071       NewQuals |= Qualifiers::Const;
1072     if (OldMethod->getTypeQualifiers() != NewQuals)
1073       return true;
1074   }
1075 
1076   // The signatures match; this is not an overload.
1077   return false;
1078 }
1079 
IsOverload(FunctionDecl * New,FunctionDecl * Old,bool UseUsingDeclRules)1080 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1081                       bool UseUsingDeclRules) {
1082   if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules))
1083     return false;
1084 
1085   // If both of the functions are extern "C", then they are not
1086   // overloads.
1087   if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
1088     return false;
1089 
1090   return true;
1091 }
1092 
1093 /// \brief Checks availability of the function depending on the current
1094 /// function context. Inside an unavailable function, unavailability is ignored.
1095 ///
1096 /// \returns true if \arg FD is unavailable and current context is inside
1097 /// an available function, false otherwise.
isFunctionConsideredUnavailable(FunctionDecl * FD)1098 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1099   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1100 }
1101 
1102 /// \brief Tries a user-defined conversion from From to ToType.
1103 ///
1104 /// Produces an implicit conversion sequence for when a standard conversion
1105 /// is not an option. See TryImplicitConversion for more information.
1106 static ImplicitConversionSequence
TryUserDefinedConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion)1107 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1108                          bool SuppressUserConversions,
1109                          bool AllowExplicit,
1110                          bool InOverloadResolution,
1111                          bool CStyle,
1112                          bool AllowObjCWritebackConversion) {
1113   ImplicitConversionSequence ICS;
1114 
1115   if (SuppressUserConversions) {
1116     // We're not in the case above, so there is no conversion that
1117     // we can perform.
1118     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1119     return ICS;
1120   }
1121 
1122   // Attempt user-defined conversion.
1123   OverloadCandidateSet Conversions(From->getExprLoc());
1124   OverloadingResult UserDefResult
1125     = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1126                               AllowExplicit);
1127 
1128   if (UserDefResult == OR_Success) {
1129     ICS.setUserDefined();
1130     // C++ [over.ics.user]p4:
1131     //   A conversion of an expression of class type to the same class
1132     //   type is given Exact Match rank, and a conversion of an
1133     //   expression of class type to a base class of that type is
1134     //   given Conversion rank, in spite of the fact that a copy
1135     //   constructor (i.e., a user-defined conversion function) is
1136     //   called for those cases.
1137     if (CXXConstructorDecl *Constructor
1138           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1139       QualType FromCanon
1140         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1141       QualType ToCanon
1142         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1143       if (Constructor->isCopyConstructor() &&
1144           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1145         // Turn this into a "standard" conversion sequence, so that it
1146         // gets ranked with standard conversion sequences.
1147         ICS.setStandard();
1148         ICS.Standard.setAsIdentityConversion();
1149         ICS.Standard.setFromType(From->getType());
1150         ICS.Standard.setAllToTypes(ToType);
1151         ICS.Standard.CopyConstructor = Constructor;
1152         if (ToCanon != FromCanon)
1153           ICS.Standard.Second = ICK_Derived_To_Base;
1154       }
1155     }
1156 
1157     // C++ [over.best.ics]p4:
1158     //   However, when considering the argument of a user-defined
1159     //   conversion function that is a candidate by 13.3.1.3 when
1160     //   invoked for the copying of the temporary in the second step
1161     //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1162     //   13.3.1.6 in all cases, only standard conversion sequences and
1163     //   ellipsis conversion sequences are allowed.
1164     if (SuppressUserConversions && ICS.isUserDefined()) {
1165       ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1166     }
1167   } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1168     ICS.setAmbiguous();
1169     ICS.Ambiguous.setFromType(From->getType());
1170     ICS.Ambiguous.setToType(ToType);
1171     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1172          Cand != Conversions.end(); ++Cand)
1173       if (Cand->Viable)
1174         ICS.Ambiguous.addConversion(Cand->Function);
1175   } else {
1176     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1177   }
1178 
1179   return ICS;
1180 }
1181 
1182 /// TryImplicitConversion - Attempt to perform an implicit conversion
1183 /// from the given expression (Expr) to the given type (ToType). This
1184 /// function returns an implicit conversion sequence that can be used
1185 /// to perform the initialization. Given
1186 ///
1187 ///   void f(float f);
1188 ///   void g(int i) { f(i); }
1189 ///
1190 /// this routine would produce an implicit conversion sequence to
1191 /// describe the initialization of f from i, which will be a standard
1192 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1193 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1194 //
1195 /// Note that this routine only determines how the conversion can be
1196 /// performed; it does not actually perform the conversion. As such,
1197 /// it will not produce any diagnostics if no conversion is available,
1198 /// but will instead return an implicit conversion sequence of kind
1199 /// "BadConversion".
1200 ///
1201 /// If @p SuppressUserConversions, then user-defined conversions are
1202 /// not permitted.
1203 /// If @p AllowExplicit, then explicit user-defined conversions are
1204 /// permitted.
1205 ///
1206 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1207 /// writeback conversion, which allows __autoreleasing id* parameters to
1208 /// be initialized with __strong id* or __weak id* arguments.
1209 static ImplicitConversionSequence
TryImplicitConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion)1210 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1211                       bool SuppressUserConversions,
1212                       bool AllowExplicit,
1213                       bool InOverloadResolution,
1214                       bool CStyle,
1215                       bool AllowObjCWritebackConversion) {
1216   ImplicitConversionSequence ICS;
1217   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1218                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1219     ICS.setStandard();
1220     return ICS;
1221   }
1222 
1223   if (!S.getLangOpts().CPlusPlus) {
1224     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1225     return ICS;
1226   }
1227 
1228   // C++ [over.ics.user]p4:
1229   //   A conversion of an expression of class type to the same class
1230   //   type is given Exact Match rank, and a conversion of an
1231   //   expression of class type to a base class of that type is
1232   //   given Conversion rank, in spite of the fact that a copy/move
1233   //   constructor (i.e., a user-defined conversion function) is
1234   //   called for those cases.
1235   QualType FromType = From->getType();
1236   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1237       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1238        S.IsDerivedFrom(FromType, ToType))) {
1239     ICS.setStandard();
1240     ICS.Standard.setAsIdentityConversion();
1241     ICS.Standard.setFromType(FromType);
1242     ICS.Standard.setAllToTypes(ToType);
1243 
1244     // We don't actually check at this point whether there is a valid
1245     // copy/move constructor, since overloading just assumes that it
1246     // exists. When we actually perform initialization, we'll find the
1247     // appropriate constructor to copy the returned object, if needed.
1248     ICS.Standard.CopyConstructor = 0;
1249 
1250     // Determine whether this is considered a derived-to-base conversion.
1251     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1252       ICS.Standard.Second = ICK_Derived_To_Base;
1253 
1254     return ICS;
1255   }
1256 
1257   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1258                                   AllowExplicit, InOverloadResolution, CStyle,
1259                                   AllowObjCWritebackConversion);
1260 }
1261 
1262 ImplicitConversionSequence
TryImplicitConversion(Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion)1263 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1264                             bool SuppressUserConversions,
1265                             bool AllowExplicit,
1266                             bool InOverloadResolution,
1267                             bool CStyle,
1268                             bool AllowObjCWritebackConversion) {
1269   return clang::TryImplicitConversion(*this, From, ToType,
1270                                       SuppressUserConversions, AllowExplicit,
1271                                       InOverloadResolution, CStyle,
1272                                       AllowObjCWritebackConversion);
1273 }
1274 
1275 /// PerformImplicitConversion - Perform an implicit conversion of the
1276 /// expression From to the type ToType. Returns the
1277 /// converted expression. Flavor is the kind of conversion we're
1278 /// performing, used in the error message. If @p AllowExplicit,
1279 /// explicit user-defined conversions are permitted.
1280 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,AssignmentAction Action,bool AllowExplicit)1281 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1282                                 AssignmentAction Action, bool AllowExplicit) {
1283   ImplicitConversionSequence ICS;
1284   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1285 }
1286 
1287 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,AssignmentAction Action,bool AllowExplicit,ImplicitConversionSequence & ICS)1288 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1289                                 AssignmentAction Action, bool AllowExplicit,
1290                                 ImplicitConversionSequence& ICS) {
1291   if (checkPlaceholderForOverload(*this, From))
1292     return ExprError();
1293 
1294   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1295   bool AllowObjCWritebackConversion
1296     = getLangOpts().ObjCAutoRefCount &&
1297       (Action == AA_Passing || Action == AA_Sending);
1298 
1299   ICS = clang::TryImplicitConversion(*this, From, ToType,
1300                                      /*SuppressUserConversions=*/false,
1301                                      AllowExplicit,
1302                                      /*InOverloadResolution=*/false,
1303                                      /*CStyle=*/false,
1304                                      AllowObjCWritebackConversion);
1305   return PerformImplicitConversion(From, ToType, ICS, Action);
1306 }
1307 
1308 /// \brief Determine whether the conversion from FromType to ToType is a valid
1309 /// conversion that strips "noreturn" off the nested function type.
IsNoReturnConversion(QualType FromType,QualType ToType,QualType & ResultTy)1310 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1311                                 QualType &ResultTy) {
1312   if (Context.hasSameUnqualifiedType(FromType, ToType))
1313     return false;
1314 
1315   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1316   // where F adds one of the following at most once:
1317   //   - a pointer
1318   //   - a member pointer
1319   //   - a block pointer
1320   CanQualType CanTo = Context.getCanonicalType(ToType);
1321   CanQualType CanFrom = Context.getCanonicalType(FromType);
1322   Type::TypeClass TyClass = CanTo->getTypeClass();
1323   if (TyClass != CanFrom->getTypeClass()) return false;
1324   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1325     if (TyClass == Type::Pointer) {
1326       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1327       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1328     } else if (TyClass == Type::BlockPointer) {
1329       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1330       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1331     } else if (TyClass == Type::MemberPointer) {
1332       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1333       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1334     } else {
1335       return false;
1336     }
1337 
1338     TyClass = CanTo->getTypeClass();
1339     if (TyClass != CanFrom->getTypeClass()) return false;
1340     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1341       return false;
1342   }
1343 
1344   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1345   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1346   if (!EInfo.getNoReturn()) return false;
1347 
1348   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1349   assert(QualType(FromFn, 0).isCanonical());
1350   if (QualType(FromFn, 0) != CanTo) return false;
1351 
1352   ResultTy = ToType;
1353   return true;
1354 }
1355 
1356 /// \brief Determine whether the conversion from FromType to ToType is a valid
1357 /// vector conversion.
1358 ///
1359 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1360 /// conversion.
IsVectorConversion(ASTContext & Context,QualType FromType,QualType ToType,ImplicitConversionKind & ICK)1361 static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1362                                QualType ToType, ImplicitConversionKind &ICK) {
1363   // We need at least one of these types to be a vector type to have a vector
1364   // conversion.
1365   if (!ToType->isVectorType() && !FromType->isVectorType())
1366     return false;
1367 
1368   // Identical types require no conversions.
1369   if (Context.hasSameUnqualifiedType(FromType, ToType))
1370     return false;
1371 
1372   // There are no conversions between extended vector types, only identity.
1373   if (ToType->isExtVectorType()) {
1374     // There are no conversions between extended vector types other than the
1375     // identity conversion.
1376     if (FromType->isExtVectorType())
1377       return false;
1378 
1379     // Vector splat from any arithmetic type to a vector.
1380     if (FromType->isArithmeticType()) {
1381       ICK = ICK_Vector_Splat;
1382       return true;
1383     }
1384   }
1385 
1386   // We can perform the conversion between vector types in the following cases:
1387   // 1)vector types are equivalent AltiVec and GCC vector types
1388   // 2)lax vector conversions are permitted and the vector types are of the
1389   //   same size
1390   if (ToType->isVectorType() && FromType->isVectorType()) {
1391     if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1392         (Context.getLangOpts().LaxVectorConversions &&
1393          (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1394       ICK = ICK_Vector_Conversion;
1395       return true;
1396     }
1397   }
1398 
1399   return false;
1400 }
1401 
1402 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1403                                 bool InOverloadResolution,
1404                                 StandardConversionSequence &SCS,
1405                                 bool CStyle);
1406 
1407 /// IsStandardConversion - Determines whether there is a standard
1408 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1409 /// expression From to the type ToType. Standard conversion sequences
1410 /// only consider non-class types; for conversions that involve class
1411 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1412 /// contain the standard conversion sequence required to perform this
1413 /// conversion and this routine will return true. Otherwise, this
1414 /// 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)1415 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1416                                  bool InOverloadResolution,
1417                                  StandardConversionSequence &SCS,
1418                                  bool CStyle,
1419                                  bool AllowObjCWritebackConversion) {
1420   QualType FromType = From->getType();
1421 
1422   // Standard conversions (C++ [conv])
1423   SCS.setAsIdentityConversion();
1424   SCS.DeprecatedStringLiteralToCharPtr = false;
1425   SCS.IncompatibleObjC = false;
1426   SCS.setFromType(FromType);
1427   SCS.CopyConstructor = 0;
1428 
1429   // There are no standard conversions for class types in C++, so
1430   // abort early. When overloading in C, however, we do permit
1431   if (FromType->isRecordType() || ToType->isRecordType()) {
1432     if (S.getLangOpts().CPlusPlus)
1433       return false;
1434 
1435     // When we're overloading in C, we allow, as standard conversions,
1436   }
1437 
1438   // The first conversion can be an lvalue-to-rvalue conversion,
1439   // array-to-pointer conversion, or function-to-pointer conversion
1440   // (C++ 4p1).
1441 
1442   if (FromType == S.Context.OverloadTy) {
1443     DeclAccessPair AccessPair;
1444     if (FunctionDecl *Fn
1445           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1446                                                  AccessPair)) {
1447       // We were able to resolve the address of the overloaded function,
1448       // so we can convert to the type of that function.
1449       FromType = Fn->getType();
1450 
1451       // we can sometimes resolve &foo<int> regardless of ToType, so check
1452       // if the type matches (identity) or we are converting to bool
1453       if (!S.Context.hasSameUnqualifiedType(
1454                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1455         QualType resultTy;
1456         // if the function type matches except for [[noreturn]], it's ok
1457         if (!S.IsNoReturnConversion(FromType,
1458               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1459           // otherwise, only a boolean conversion is standard
1460           if (!ToType->isBooleanType())
1461             return false;
1462       }
1463 
1464       // Check if the "from" expression is taking the address of an overloaded
1465       // function and recompute the FromType accordingly. Take advantage of the
1466       // fact that non-static member functions *must* have such an address-of
1467       // expression.
1468       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1469       if (Method && !Method->isStatic()) {
1470         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1471                "Non-unary operator on non-static member address");
1472         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1473                == UO_AddrOf &&
1474                "Non-address-of operator on non-static member address");
1475         const Type *ClassType
1476           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1477         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1478       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1479         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1480                UO_AddrOf &&
1481                "Non-address-of operator for overloaded function expression");
1482         FromType = S.Context.getPointerType(FromType);
1483       }
1484 
1485       // Check that we've computed the proper type after overload resolution.
1486       assert(S.Context.hasSameType(
1487         FromType,
1488         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1489     } else {
1490       return false;
1491     }
1492   }
1493   // Lvalue-to-rvalue conversion (C++11 4.1):
1494   //   A glvalue (3.10) of a non-function, non-array type T can
1495   //   be converted to a prvalue.
1496   bool argIsLValue = From->isGLValue();
1497   if (argIsLValue &&
1498       !FromType->isFunctionType() && !FromType->isArrayType() &&
1499       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1500     SCS.First = ICK_Lvalue_To_Rvalue;
1501 
1502     // C11 6.3.2.1p2:
1503     //   ... if the lvalue has atomic type, the value has the non-atomic version
1504     //   of the type of the lvalue ...
1505     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1506       FromType = Atomic->getValueType();
1507 
1508     // If T is a non-class type, the type of the rvalue is the
1509     // cv-unqualified version of T. Otherwise, the type of the rvalue
1510     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1511     // just strip the qualifiers because they don't matter.
1512     FromType = FromType.getUnqualifiedType();
1513   } else if (FromType->isArrayType()) {
1514     // Array-to-pointer conversion (C++ 4.2)
1515     SCS.First = ICK_Array_To_Pointer;
1516 
1517     // An lvalue or rvalue of type "array of N T" or "array of unknown
1518     // bound of T" can be converted to an rvalue of type "pointer to
1519     // T" (C++ 4.2p1).
1520     FromType = S.Context.getArrayDecayedType(FromType);
1521 
1522     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1523       // This conversion is deprecated. (C++ D.4).
1524       SCS.DeprecatedStringLiteralToCharPtr = true;
1525 
1526       // For the purpose of ranking in overload resolution
1527       // (13.3.3.1.1), this conversion is considered an
1528       // array-to-pointer conversion followed by a qualification
1529       // conversion (4.4). (C++ 4.2p2)
1530       SCS.Second = ICK_Identity;
1531       SCS.Third = ICK_Qualification;
1532       SCS.QualificationIncludesObjCLifetime = false;
1533       SCS.setAllToTypes(FromType);
1534       return true;
1535     }
1536   } else if (FromType->isFunctionType() && argIsLValue) {
1537     // Function-to-pointer conversion (C++ 4.3).
1538     SCS.First = ICK_Function_To_Pointer;
1539 
1540     // An lvalue of function type T can be converted to an rvalue of
1541     // type "pointer to T." The result is a pointer to the
1542     // function. (C++ 4.3p1).
1543     FromType = S.Context.getPointerType(FromType);
1544   } else {
1545     // We don't require any conversions for the first step.
1546     SCS.First = ICK_Identity;
1547   }
1548   SCS.setToType(0, FromType);
1549 
1550   // The second conversion can be an integral promotion, floating
1551   // point promotion, integral conversion, floating point conversion,
1552   // floating-integral conversion, pointer conversion,
1553   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1554   // For overloading in C, this can also be a "compatible-type"
1555   // conversion.
1556   bool IncompatibleObjC = false;
1557   ImplicitConversionKind SecondICK = ICK_Identity;
1558   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1559     // The unqualified versions of the types are the same: there's no
1560     // conversion to do.
1561     SCS.Second = ICK_Identity;
1562   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1563     // Integral promotion (C++ 4.5).
1564     SCS.Second = ICK_Integral_Promotion;
1565     FromType = ToType.getUnqualifiedType();
1566   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1567     // Floating point promotion (C++ 4.6).
1568     SCS.Second = ICK_Floating_Promotion;
1569     FromType = ToType.getUnqualifiedType();
1570   } else if (S.IsComplexPromotion(FromType, ToType)) {
1571     // Complex promotion (Clang extension)
1572     SCS.Second = ICK_Complex_Promotion;
1573     FromType = ToType.getUnqualifiedType();
1574   } else if (ToType->isBooleanType() &&
1575              (FromType->isArithmeticType() ||
1576               FromType->isAnyPointerType() ||
1577               FromType->isBlockPointerType() ||
1578               FromType->isMemberPointerType() ||
1579               FromType->isNullPtrType())) {
1580     // Boolean conversions (C++ 4.12).
1581     SCS.Second = ICK_Boolean_Conversion;
1582     FromType = S.Context.BoolTy;
1583   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1584              ToType->isIntegralType(S.Context)) {
1585     // Integral conversions (C++ 4.7).
1586     SCS.Second = ICK_Integral_Conversion;
1587     FromType = ToType.getUnqualifiedType();
1588   } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1589     // Complex conversions (C99 6.3.1.6)
1590     SCS.Second = ICK_Complex_Conversion;
1591     FromType = ToType.getUnqualifiedType();
1592   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1593              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1594     // Complex-real conversions (C99 6.3.1.7)
1595     SCS.Second = ICK_Complex_Real;
1596     FromType = ToType.getUnqualifiedType();
1597   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1598     // Floating point conversions (C++ 4.8).
1599     SCS.Second = ICK_Floating_Conversion;
1600     FromType = ToType.getUnqualifiedType();
1601   } else if ((FromType->isRealFloatingType() &&
1602               ToType->isIntegralType(S.Context)) ||
1603              (FromType->isIntegralOrUnscopedEnumerationType() &&
1604               ToType->isRealFloatingType())) {
1605     // Floating-integral conversions (C++ 4.9).
1606     SCS.Second = ICK_Floating_Integral;
1607     FromType = ToType.getUnqualifiedType();
1608   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1609     SCS.Second = ICK_Block_Pointer_Conversion;
1610   } else if (AllowObjCWritebackConversion &&
1611              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1612     SCS.Second = ICK_Writeback_Conversion;
1613   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1614                                    FromType, IncompatibleObjC)) {
1615     // Pointer conversions (C++ 4.10).
1616     SCS.Second = ICK_Pointer_Conversion;
1617     SCS.IncompatibleObjC = IncompatibleObjC;
1618     FromType = FromType.getUnqualifiedType();
1619   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1620                                          InOverloadResolution, FromType)) {
1621     // Pointer to member conversions (4.11).
1622     SCS.Second = ICK_Pointer_Member;
1623   } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1624     SCS.Second = SecondICK;
1625     FromType = ToType.getUnqualifiedType();
1626   } else if (!S.getLangOpts().CPlusPlus &&
1627              S.Context.typesAreCompatible(ToType, FromType)) {
1628     // Compatible conversions (Clang extension for C function overloading)
1629     SCS.Second = ICK_Compatible_Conversion;
1630     FromType = ToType.getUnqualifiedType();
1631   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1632     // Treat a conversion that strips "noreturn" as an identity conversion.
1633     SCS.Second = ICK_NoReturn_Adjustment;
1634   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1635                                              InOverloadResolution,
1636                                              SCS, CStyle)) {
1637     SCS.Second = ICK_TransparentUnionConversion;
1638     FromType = ToType;
1639   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1640                                  CStyle)) {
1641     // tryAtomicConversion has updated the standard conversion sequence
1642     // appropriately.
1643     return true;
1644   } else if (ToType->isEventT() &&
1645              From->isIntegerConstantExpr(S.getASTContext()) &&
1646              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1647     SCS.Second = ICK_Zero_Event_Conversion;
1648     FromType = ToType;
1649   } else {
1650     // No second conversion required.
1651     SCS.Second = ICK_Identity;
1652   }
1653   SCS.setToType(1, FromType);
1654 
1655   QualType CanonFrom;
1656   QualType CanonTo;
1657   // The third conversion can be a qualification conversion (C++ 4p1).
1658   bool ObjCLifetimeConversion;
1659   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1660                                   ObjCLifetimeConversion)) {
1661     SCS.Third = ICK_Qualification;
1662     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1663     FromType = ToType;
1664     CanonFrom = S.Context.getCanonicalType(FromType);
1665     CanonTo = S.Context.getCanonicalType(ToType);
1666   } else {
1667     // No conversion required
1668     SCS.Third = ICK_Identity;
1669 
1670     // C++ [over.best.ics]p6:
1671     //   [...] Any difference in top-level cv-qualification is
1672     //   subsumed by the initialization itself and does not constitute
1673     //   a conversion. [...]
1674     CanonFrom = S.Context.getCanonicalType(FromType);
1675     CanonTo = S.Context.getCanonicalType(ToType);
1676     if (CanonFrom.getLocalUnqualifiedType()
1677                                        == CanonTo.getLocalUnqualifiedType() &&
1678         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1679       FromType = ToType;
1680       CanonFrom = CanonTo;
1681     }
1682   }
1683   SCS.setToType(2, FromType);
1684 
1685   // If we have not converted the argument type to the parameter type,
1686   // this is a bad conversion sequence.
1687   if (CanonFrom != CanonTo)
1688     return false;
1689 
1690   return true;
1691 }
1692 
1693 static bool
IsTransparentUnionStandardConversion(Sema & S,Expr * From,QualType & ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)1694 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1695                                      QualType &ToType,
1696                                      bool InOverloadResolution,
1697                                      StandardConversionSequence &SCS,
1698                                      bool CStyle) {
1699 
1700   const RecordType *UT = ToType->getAsUnionType();
1701   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1702     return false;
1703   // The field to initialize within the transparent union.
1704   RecordDecl *UD = UT->getDecl();
1705   // It's compatible if the expression matches any of the fields.
1706   for (RecordDecl::field_iterator it = UD->field_begin(),
1707        itend = UD->field_end();
1708        it != itend; ++it) {
1709     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1710                              CStyle, /*ObjCWritebackConversion=*/false)) {
1711       ToType = it->getType();
1712       return true;
1713     }
1714   }
1715   return false;
1716 }
1717 
1718 /// IsIntegralPromotion - Determines whether the conversion from the
1719 /// expression From (whose potentially-adjusted type is FromType) to
1720 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1721 /// sets PromotedType to the promoted type.
IsIntegralPromotion(Expr * From,QualType FromType,QualType ToType)1722 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1723   const BuiltinType *To = ToType->getAs<BuiltinType>();
1724   // All integers are built-in.
1725   if (!To) {
1726     return false;
1727   }
1728 
1729   // An rvalue of type char, signed char, unsigned char, short int, or
1730   // unsigned short int can be converted to an rvalue of type int if
1731   // int can represent all the values of the source type; otherwise,
1732   // the source rvalue can be converted to an rvalue of type unsigned
1733   // int (C++ 4.5p1).
1734   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1735       !FromType->isEnumeralType()) {
1736     if (// We can promote any signed, promotable integer type to an int
1737         (FromType->isSignedIntegerType() ||
1738          // We can promote any unsigned integer type whose size is
1739          // less than int to an int.
1740          (!FromType->isSignedIntegerType() &&
1741           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1742       return To->getKind() == BuiltinType::Int;
1743     }
1744 
1745     return To->getKind() == BuiltinType::UInt;
1746   }
1747 
1748   // C++11 [conv.prom]p3:
1749   //   A prvalue of an unscoped enumeration type whose underlying type is not
1750   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1751   //   following types that can represent all the values of the enumeration
1752   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1753   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1754   //   long long int. If none of the types in that list can represent all the
1755   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1756   //   type can be converted to an rvalue a prvalue of the extended integer type
1757   //   with lowest integer conversion rank (4.13) greater than the rank of long
1758   //   long in which all the values of the enumeration can be represented. If
1759   //   there are two such extended types, the signed one is chosen.
1760   // C++11 [conv.prom]p4:
1761   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
1762   //   can be converted to a prvalue of its underlying type. Moreover, if
1763   //   integral promotion can be applied to its underlying type, a prvalue of an
1764   //   unscoped enumeration type whose underlying type is fixed can also be
1765   //   converted to a prvalue of the promoted underlying type.
1766   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1767     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1768     // provided for a scoped enumeration.
1769     if (FromEnumType->getDecl()->isScoped())
1770       return false;
1771 
1772     // We can perform an integral promotion to the underlying type of the enum,
1773     // even if that's not the promoted type.
1774     if (FromEnumType->getDecl()->isFixed()) {
1775       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1776       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1777              IsIntegralPromotion(From, Underlying, ToType);
1778     }
1779 
1780     // We have already pre-calculated the promotion type, so this is trivial.
1781     if (ToType->isIntegerType() &&
1782         !RequireCompleteType(From->getLocStart(), FromType, 0))
1783       return Context.hasSameUnqualifiedType(ToType,
1784                                 FromEnumType->getDecl()->getPromotionType());
1785   }
1786 
1787   // C++0x [conv.prom]p2:
1788   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1789   //   to an rvalue a prvalue of the first of the following types that can
1790   //   represent all the values of its underlying type: int, unsigned int,
1791   //   long int, unsigned long int, long long int, or unsigned long long int.
1792   //   If none of the types in that list can represent all the values of its
1793   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1794   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1795   //   type.
1796   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1797       ToType->isIntegerType()) {
1798     // Determine whether the type we're converting from is signed or
1799     // unsigned.
1800     bool FromIsSigned = FromType->isSignedIntegerType();
1801     uint64_t FromSize = Context.getTypeSize(FromType);
1802 
1803     // The types we'll try to promote to, in the appropriate
1804     // order. Try each of these types.
1805     QualType PromoteTypes[6] = {
1806       Context.IntTy, Context.UnsignedIntTy,
1807       Context.LongTy, Context.UnsignedLongTy ,
1808       Context.LongLongTy, Context.UnsignedLongLongTy
1809     };
1810     for (int Idx = 0; Idx < 6; ++Idx) {
1811       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1812       if (FromSize < ToSize ||
1813           (FromSize == ToSize &&
1814            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1815         // We found the type that we can promote to. If this is the
1816         // type we wanted, we have a promotion. Otherwise, no
1817         // promotion.
1818         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1819       }
1820     }
1821   }
1822 
1823   // An rvalue for an integral bit-field (9.6) can be converted to an
1824   // rvalue of type int if int can represent all the values of the
1825   // bit-field; otherwise, it can be converted to unsigned int if
1826   // unsigned int can represent all the values of the bit-field. If
1827   // the bit-field is larger yet, no integral promotion applies to
1828   // it. If the bit-field has an enumerated type, it is treated as any
1829   // other value of that type for promotion purposes (C++ 4.5p3).
1830   // FIXME: We should delay checking of bit-fields until we actually perform the
1831   // conversion.
1832   using llvm::APSInt;
1833   if (From)
1834     if (FieldDecl *MemberDecl = From->getBitField()) {
1835       APSInt BitWidth;
1836       if (FromType->isIntegralType(Context) &&
1837           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1838         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1839         ToSize = Context.getTypeSize(ToType);
1840 
1841         // Are we promoting to an int from a bitfield that fits in an int?
1842         if (BitWidth < ToSize ||
1843             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1844           return To->getKind() == BuiltinType::Int;
1845         }
1846 
1847         // Are we promoting to an unsigned int from an unsigned bitfield
1848         // that fits into an unsigned int?
1849         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1850           return To->getKind() == BuiltinType::UInt;
1851         }
1852 
1853         return false;
1854       }
1855     }
1856 
1857   // An rvalue of type bool can be converted to an rvalue of type int,
1858   // with false becoming zero and true becoming one (C++ 4.5p4).
1859   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1860     return true;
1861   }
1862 
1863   return false;
1864 }
1865 
1866 /// IsFloatingPointPromotion - Determines whether the conversion from
1867 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1868 /// returns true and sets PromotedType to the promoted type.
IsFloatingPointPromotion(QualType FromType,QualType ToType)1869 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1870   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1871     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1872       /// An rvalue of type float can be converted to an rvalue of type
1873       /// double. (C++ 4.6p1).
1874       if (FromBuiltin->getKind() == BuiltinType::Float &&
1875           ToBuiltin->getKind() == BuiltinType::Double)
1876         return true;
1877 
1878       // C99 6.3.1.5p1:
1879       //   When a float is promoted to double or long double, or a
1880       //   double is promoted to long double [...].
1881       if (!getLangOpts().CPlusPlus &&
1882           (FromBuiltin->getKind() == BuiltinType::Float ||
1883            FromBuiltin->getKind() == BuiltinType::Double) &&
1884           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1885         return true;
1886 
1887       // Half can be promoted to float.
1888       if (!getLangOpts().NativeHalfType &&
1889            FromBuiltin->getKind() == BuiltinType::Half &&
1890           ToBuiltin->getKind() == BuiltinType::Float)
1891         return true;
1892     }
1893 
1894   return false;
1895 }
1896 
1897 /// \brief Determine if a conversion is a complex promotion.
1898 ///
1899 /// A complex promotion is defined as a complex -> complex conversion
1900 /// where the conversion between the underlying real types is a
1901 /// floating-point or integral promotion.
IsComplexPromotion(QualType FromType,QualType ToType)1902 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1903   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1904   if (!FromComplex)
1905     return false;
1906 
1907   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1908   if (!ToComplex)
1909     return false;
1910 
1911   return IsFloatingPointPromotion(FromComplex->getElementType(),
1912                                   ToComplex->getElementType()) ||
1913     IsIntegralPromotion(0, FromComplex->getElementType(),
1914                         ToComplex->getElementType());
1915 }
1916 
1917 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1918 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1919 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1920 /// if non-empty, will be a pointer to ToType that may or may not have
1921 /// the right set of qualifiers on its pointee.
1922 ///
1923 static QualType
BuildSimilarlyQualifiedPointerType(const Type * FromPtr,QualType ToPointee,QualType ToType,ASTContext & Context,bool StripObjCLifetime=false)1924 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1925                                    QualType ToPointee, QualType ToType,
1926                                    ASTContext &Context,
1927                                    bool StripObjCLifetime = false) {
1928   assert((FromPtr->getTypeClass() == Type::Pointer ||
1929           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1930          "Invalid similarly-qualified pointer type");
1931 
1932   /// Conversions to 'id' subsume cv-qualifier conversions.
1933   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1934     return ToType.getUnqualifiedType();
1935 
1936   QualType CanonFromPointee
1937     = Context.getCanonicalType(FromPtr->getPointeeType());
1938   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1939   Qualifiers Quals = CanonFromPointee.getQualifiers();
1940 
1941   if (StripObjCLifetime)
1942     Quals.removeObjCLifetime();
1943 
1944   // Exact qualifier match -> return the pointer type we're converting to.
1945   if (CanonToPointee.getLocalQualifiers() == Quals) {
1946     // ToType is exactly what we need. Return it.
1947     if (!ToType.isNull())
1948       return ToType.getUnqualifiedType();
1949 
1950     // Build a pointer to ToPointee. It has the right qualifiers
1951     // already.
1952     if (isa<ObjCObjectPointerType>(ToType))
1953       return Context.getObjCObjectPointerType(ToPointee);
1954     return Context.getPointerType(ToPointee);
1955   }
1956 
1957   // Just build a canonical type that has the right qualifiers.
1958   QualType QualifiedCanonToPointee
1959     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1960 
1961   if (isa<ObjCObjectPointerType>(ToType))
1962     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1963   return Context.getPointerType(QualifiedCanonToPointee);
1964 }
1965 
isNullPointerConstantForConversion(Expr * Expr,bool InOverloadResolution,ASTContext & Context)1966 static bool isNullPointerConstantForConversion(Expr *Expr,
1967                                                bool InOverloadResolution,
1968                                                ASTContext &Context) {
1969   // Handle value-dependent integral null pointer constants correctly.
1970   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1971   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1972       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1973     return !InOverloadResolution;
1974 
1975   return Expr->isNullPointerConstant(Context,
1976                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1977                                         : Expr::NPC_ValueDependentIsNull);
1978 }
1979 
1980 /// IsPointerConversion - Determines whether the conversion of the
1981 /// expression From, which has the (possibly adjusted) type FromType,
1982 /// can be converted to the type ToType via a pointer conversion (C++
1983 /// 4.10). If so, returns true and places the converted type (that
1984 /// might differ from ToType in its cv-qualifiers at some level) into
1985 /// ConvertedType.
1986 ///
1987 /// This routine also supports conversions to and from block pointers
1988 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1989 /// pointers to interfaces. FIXME: Once we've determined the
1990 /// appropriate overloading rules for Objective-C, we may want to
1991 /// split the Objective-C checks into a different routine; however,
1992 /// GCC seems to consider all of these conversions to be pointer
1993 /// conversions, so for now they live here. IncompatibleObjC will be
1994 /// set if the conversion is an allowed Objective-C conversion that
1995 /// should result in a warning.
IsPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType,bool & IncompatibleObjC)1996 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1997                                bool InOverloadResolution,
1998                                QualType& ConvertedType,
1999                                bool &IncompatibleObjC) {
2000   IncompatibleObjC = false;
2001   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2002                               IncompatibleObjC))
2003     return true;
2004 
2005   // Conversion from a null pointer constant to any Objective-C pointer type.
2006   if (ToType->isObjCObjectPointerType() &&
2007       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2008     ConvertedType = ToType;
2009     return true;
2010   }
2011 
2012   // Blocks: Block pointers can be converted to void*.
2013   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2014       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2015     ConvertedType = ToType;
2016     return true;
2017   }
2018   // Blocks: A null pointer constant can be converted to a block
2019   // pointer type.
2020   if (ToType->isBlockPointerType() &&
2021       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2022     ConvertedType = ToType;
2023     return true;
2024   }
2025 
2026   // If the left-hand-side is nullptr_t, the right side can be a null
2027   // pointer constant.
2028   if (ToType->isNullPtrType() &&
2029       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2030     ConvertedType = ToType;
2031     return true;
2032   }
2033 
2034   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2035   if (!ToTypePtr)
2036     return false;
2037 
2038   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2039   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2040     ConvertedType = ToType;
2041     return true;
2042   }
2043 
2044   // Beyond this point, both types need to be pointers
2045   // , including objective-c pointers.
2046   QualType ToPointeeType = ToTypePtr->getPointeeType();
2047   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2048       !getLangOpts().ObjCAutoRefCount) {
2049     ConvertedType = BuildSimilarlyQualifiedPointerType(
2050                                       FromType->getAs<ObjCObjectPointerType>(),
2051                                                        ToPointeeType,
2052                                                        ToType, Context);
2053     return true;
2054   }
2055   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2056   if (!FromTypePtr)
2057     return false;
2058 
2059   QualType FromPointeeType = FromTypePtr->getPointeeType();
2060 
2061   // If the unqualified pointee types are the same, this can't be a
2062   // pointer conversion, so don't do all of the work below.
2063   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2064     return false;
2065 
2066   // An rvalue of type "pointer to cv T," where T is an object type,
2067   // can be converted to an rvalue of type "pointer to cv void" (C++
2068   // 4.10p2).
2069   if (FromPointeeType->isIncompleteOrObjectType() &&
2070       ToPointeeType->isVoidType()) {
2071     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2072                                                        ToPointeeType,
2073                                                        ToType, Context,
2074                                                    /*StripObjCLifetime=*/true);
2075     return true;
2076   }
2077 
2078   // MSVC allows implicit function to void* type conversion.
2079   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2080       ToPointeeType->isVoidType()) {
2081     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2082                                                        ToPointeeType,
2083                                                        ToType, Context);
2084     return true;
2085   }
2086 
2087   // When we're overloading in C, we allow a special kind of pointer
2088   // conversion for compatible-but-not-identical pointee types.
2089   if (!getLangOpts().CPlusPlus &&
2090       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2091     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2092                                                        ToPointeeType,
2093                                                        ToType, Context);
2094     return true;
2095   }
2096 
2097   // C++ [conv.ptr]p3:
2098   //
2099   //   An rvalue of type "pointer to cv D," where D is a class type,
2100   //   can be converted to an rvalue of type "pointer to cv B," where
2101   //   B is a base class (clause 10) of D. If B is an inaccessible
2102   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2103   //   necessitates this conversion is ill-formed. The result of the
2104   //   conversion is a pointer to the base class sub-object of the
2105   //   derived class object. The null pointer value is converted to
2106   //   the null pointer value of the destination type.
2107   //
2108   // Note that we do not check for ambiguity or inaccessibility
2109   // here. That is handled by CheckPointerConversion.
2110   if (getLangOpts().CPlusPlus &&
2111       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2112       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2113       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2114       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2115     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2116                                                        ToPointeeType,
2117                                                        ToType, Context);
2118     return true;
2119   }
2120 
2121   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2122       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2123     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2124                                                        ToPointeeType,
2125                                                        ToType, Context);
2126     return true;
2127   }
2128 
2129   return false;
2130 }
2131 
2132 /// \brief Adopt the given qualifiers for the given type.
AdoptQualifiers(ASTContext & Context,QualType T,Qualifiers Qs)2133 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2134   Qualifiers TQs = T.getQualifiers();
2135 
2136   // Check whether qualifiers already match.
2137   if (TQs == Qs)
2138     return T;
2139 
2140   if (Qs.compatiblyIncludes(TQs))
2141     return Context.getQualifiedType(T, Qs);
2142 
2143   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2144 }
2145 
2146 /// isObjCPointerConversion - Determines whether this is an
2147 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2148 /// with the same arguments and return values.
isObjCPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType,bool & IncompatibleObjC)2149 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2150                                    QualType& ConvertedType,
2151                                    bool &IncompatibleObjC) {
2152   if (!getLangOpts().ObjC1)
2153     return false;
2154 
2155   // The set of qualifiers on the type we're converting from.
2156   Qualifiers FromQualifiers = FromType.getQualifiers();
2157 
2158   // First, we handle all conversions on ObjC object pointer types.
2159   const ObjCObjectPointerType* ToObjCPtr =
2160     ToType->getAs<ObjCObjectPointerType>();
2161   const ObjCObjectPointerType *FromObjCPtr =
2162     FromType->getAs<ObjCObjectPointerType>();
2163 
2164   if (ToObjCPtr && FromObjCPtr) {
2165     // If the pointee types are the same (ignoring qualifications),
2166     // then this is not a pointer conversion.
2167     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2168                                        FromObjCPtr->getPointeeType()))
2169       return false;
2170 
2171     // Check for compatible
2172     // Objective C++: We're able to convert between "id" or "Class" and a
2173     // pointer to any interface (in both directions).
2174     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2175       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2176       return true;
2177     }
2178     // Conversions with Objective-C's id<...>.
2179     if ((FromObjCPtr->isObjCQualifiedIdType() ||
2180          ToObjCPtr->isObjCQualifiedIdType()) &&
2181         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2182                                                   /*compare=*/false)) {
2183       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2184       return true;
2185     }
2186     // Objective C++: We're able to convert from a pointer to an
2187     // interface to a pointer to a different interface.
2188     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2189       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2190       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2191       if (getLangOpts().CPlusPlus && LHS && RHS &&
2192           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2193                                                 FromObjCPtr->getPointeeType()))
2194         return false;
2195       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2196                                                    ToObjCPtr->getPointeeType(),
2197                                                          ToType, Context);
2198       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2199       return true;
2200     }
2201 
2202     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2203       // Okay: this is some kind of implicit downcast of Objective-C
2204       // interfaces, which is permitted. However, we're going to
2205       // complain about it.
2206       IncompatibleObjC = true;
2207       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2208                                                    ToObjCPtr->getPointeeType(),
2209                                                          ToType, Context);
2210       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2211       return true;
2212     }
2213   }
2214   // Beyond this point, both types need to be C pointers or block pointers.
2215   QualType ToPointeeType;
2216   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2217     ToPointeeType = ToCPtr->getPointeeType();
2218   else if (const BlockPointerType *ToBlockPtr =
2219             ToType->getAs<BlockPointerType>()) {
2220     // Objective C++: We're able to convert from a pointer to any object
2221     // to a block pointer type.
2222     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2223       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2224       return true;
2225     }
2226     ToPointeeType = ToBlockPtr->getPointeeType();
2227   }
2228   else if (FromType->getAs<BlockPointerType>() &&
2229            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2230     // Objective C++: We're able to convert from a block pointer type to a
2231     // pointer to any object.
2232     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2233     return true;
2234   }
2235   else
2236     return false;
2237 
2238   QualType FromPointeeType;
2239   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2240     FromPointeeType = FromCPtr->getPointeeType();
2241   else if (const BlockPointerType *FromBlockPtr =
2242            FromType->getAs<BlockPointerType>())
2243     FromPointeeType = FromBlockPtr->getPointeeType();
2244   else
2245     return false;
2246 
2247   // If we have pointers to pointers, recursively check whether this
2248   // is an Objective-C conversion.
2249   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2250       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2251                               IncompatibleObjC)) {
2252     // We always complain about this conversion.
2253     IncompatibleObjC = true;
2254     ConvertedType = Context.getPointerType(ConvertedType);
2255     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2256     return true;
2257   }
2258   // Allow conversion of pointee being objective-c pointer to another one;
2259   // as in I* to id.
2260   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2261       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2262       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2263                               IncompatibleObjC)) {
2264 
2265     ConvertedType = Context.getPointerType(ConvertedType);
2266     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2267     return true;
2268   }
2269 
2270   // If we have pointers to functions or blocks, check whether the only
2271   // differences in the argument and result types are in Objective-C
2272   // pointer conversions. If so, we permit the conversion (but
2273   // complain about it).
2274   const FunctionProtoType *FromFunctionType
2275     = FromPointeeType->getAs<FunctionProtoType>();
2276   const FunctionProtoType *ToFunctionType
2277     = ToPointeeType->getAs<FunctionProtoType>();
2278   if (FromFunctionType && ToFunctionType) {
2279     // If the function types are exactly the same, this isn't an
2280     // Objective-C pointer conversion.
2281     if (Context.getCanonicalType(FromPointeeType)
2282           == Context.getCanonicalType(ToPointeeType))
2283       return false;
2284 
2285     // Perform the quick checks that will tell us whether these
2286     // function types are obviously different.
2287     if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2288         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2289         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2290       return false;
2291 
2292     bool HasObjCConversion = false;
2293     if (Context.getCanonicalType(FromFunctionType->getResultType())
2294           == Context.getCanonicalType(ToFunctionType->getResultType())) {
2295       // Okay, the types match exactly. Nothing to do.
2296     } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2297                                        ToFunctionType->getResultType(),
2298                                        ConvertedType, IncompatibleObjC)) {
2299       // Okay, we have an Objective-C pointer conversion.
2300       HasObjCConversion = true;
2301     } else {
2302       // Function types are too different. Abort.
2303       return false;
2304     }
2305 
2306     // Check argument types.
2307     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2308          ArgIdx != NumArgs; ++ArgIdx) {
2309       QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2310       QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2311       if (Context.getCanonicalType(FromArgType)
2312             == Context.getCanonicalType(ToArgType)) {
2313         // Okay, the types match exactly. Nothing to do.
2314       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2315                                          ConvertedType, IncompatibleObjC)) {
2316         // Okay, we have an Objective-C pointer conversion.
2317         HasObjCConversion = true;
2318       } else {
2319         // Argument types are too different. Abort.
2320         return false;
2321       }
2322     }
2323 
2324     if (HasObjCConversion) {
2325       // We had an Objective-C conversion. Allow this pointer
2326       // conversion, but complain about it.
2327       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2328       IncompatibleObjC = true;
2329       return true;
2330     }
2331   }
2332 
2333   return false;
2334 }
2335 
2336 /// \brief Determine whether this is an Objective-C writeback conversion,
2337 /// used for parameter passing when performing automatic reference counting.
2338 ///
2339 /// \param FromType The type we're converting form.
2340 ///
2341 /// \param ToType The type we're converting to.
2342 ///
2343 /// \param ConvertedType The type that will be produced after applying
2344 /// this conversion.
isObjCWritebackConversion(QualType FromType,QualType ToType,QualType & ConvertedType)2345 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2346                                      QualType &ConvertedType) {
2347   if (!getLangOpts().ObjCAutoRefCount ||
2348       Context.hasSameUnqualifiedType(FromType, ToType))
2349     return false;
2350 
2351   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2352   QualType ToPointee;
2353   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2354     ToPointee = ToPointer->getPointeeType();
2355   else
2356     return false;
2357 
2358   Qualifiers ToQuals = ToPointee.getQualifiers();
2359   if (!ToPointee->isObjCLifetimeType() ||
2360       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2361       !ToQuals.withoutObjCLifetime().empty())
2362     return false;
2363 
2364   // Argument must be a pointer to __strong to __weak.
2365   QualType FromPointee;
2366   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2367     FromPointee = FromPointer->getPointeeType();
2368   else
2369     return false;
2370 
2371   Qualifiers FromQuals = FromPointee.getQualifiers();
2372   if (!FromPointee->isObjCLifetimeType() ||
2373       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2374        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2375     return false;
2376 
2377   // Make sure that we have compatible qualifiers.
2378   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2379   if (!ToQuals.compatiblyIncludes(FromQuals))
2380     return false;
2381 
2382   // Remove qualifiers from the pointee type we're converting from; they
2383   // aren't used in the compatibility check belong, and we'll be adding back
2384   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2385   FromPointee = FromPointee.getUnqualifiedType();
2386 
2387   // The unqualified form of the pointee types must be compatible.
2388   ToPointee = ToPointee.getUnqualifiedType();
2389   bool IncompatibleObjC;
2390   if (Context.typesAreCompatible(FromPointee, ToPointee))
2391     FromPointee = ToPointee;
2392   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2393                                     IncompatibleObjC))
2394     return false;
2395 
2396   /// \brief Construct the type we're converting to, which is a pointer to
2397   /// __autoreleasing pointee.
2398   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2399   ConvertedType = Context.getPointerType(FromPointee);
2400   return true;
2401 }
2402 
IsBlockPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType)2403 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2404                                     QualType& ConvertedType) {
2405   QualType ToPointeeType;
2406   if (const BlockPointerType *ToBlockPtr =
2407         ToType->getAs<BlockPointerType>())
2408     ToPointeeType = ToBlockPtr->getPointeeType();
2409   else
2410     return false;
2411 
2412   QualType FromPointeeType;
2413   if (const BlockPointerType *FromBlockPtr =
2414       FromType->getAs<BlockPointerType>())
2415     FromPointeeType = FromBlockPtr->getPointeeType();
2416   else
2417     return false;
2418   // We have pointer to blocks, check whether the only
2419   // differences in the argument and result types are in Objective-C
2420   // pointer conversions. If so, we permit the conversion.
2421 
2422   const FunctionProtoType *FromFunctionType
2423     = FromPointeeType->getAs<FunctionProtoType>();
2424   const FunctionProtoType *ToFunctionType
2425     = ToPointeeType->getAs<FunctionProtoType>();
2426 
2427   if (!FromFunctionType || !ToFunctionType)
2428     return false;
2429 
2430   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2431     return true;
2432 
2433   // Perform the quick checks that will tell us whether these
2434   // function types are obviously different.
2435   if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2436       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2437     return false;
2438 
2439   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2440   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2441   if (FromEInfo != ToEInfo)
2442     return false;
2443 
2444   bool IncompatibleObjC = false;
2445   if (Context.hasSameType(FromFunctionType->getResultType(),
2446                           ToFunctionType->getResultType())) {
2447     // Okay, the types match exactly. Nothing to do.
2448   } else {
2449     QualType RHS = FromFunctionType->getResultType();
2450     QualType LHS = ToFunctionType->getResultType();
2451     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2452         !RHS.hasQualifiers() && LHS.hasQualifiers())
2453        LHS = LHS.getUnqualifiedType();
2454 
2455      if (Context.hasSameType(RHS,LHS)) {
2456        // OK exact match.
2457      } else if (isObjCPointerConversion(RHS, LHS,
2458                                         ConvertedType, IncompatibleObjC)) {
2459      if (IncompatibleObjC)
2460        return false;
2461      // Okay, we have an Objective-C pointer conversion.
2462      }
2463      else
2464        return false;
2465    }
2466 
2467    // Check argument types.
2468    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2469         ArgIdx != NumArgs; ++ArgIdx) {
2470      IncompatibleObjC = false;
2471      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2472      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2473      if (Context.hasSameType(FromArgType, ToArgType)) {
2474        // Okay, the types match exactly. Nothing to do.
2475      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2476                                         ConvertedType, IncompatibleObjC)) {
2477        if (IncompatibleObjC)
2478          return false;
2479        // Okay, we have an Objective-C pointer conversion.
2480      } else
2481        // Argument types are too different. Abort.
2482        return false;
2483    }
2484    if (LangOpts.ObjCAutoRefCount &&
2485        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2486                                                     ToFunctionType))
2487      return false;
2488 
2489    ConvertedType = ToType;
2490    return true;
2491 }
2492 
2493 enum {
2494   ft_default,
2495   ft_different_class,
2496   ft_parameter_arity,
2497   ft_parameter_mismatch,
2498   ft_return_type,
2499   ft_qualifer_mismatch
2500 };
2501 
2502 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2503 /// function types.  Catches different number of parameter, mismatch in
2504 /// parameter types, and different return types.
HandleFunctionTypeMismatch(PartialDiagnostic & PDiag,QualType FromType,QualType ToType)2505 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2506                                       QualType FromType, QualType ToType) {
2507   // If either type is not valid, include no extra info.
2508   if (FromType.isNull() || ToType.isNull()) {
2509     PDiag << ft_default;
2510     return;
2511   }
2512 
2513   // Get the function type from the pointers.
2514   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2515     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2516                             *ToMember = ToType->getAs<MemberPointerType>();
2517     if (FromMember->getClass() != ToMember->getClass()) {
2518       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2519             << QualType(FromMember->getClass(), 0);
2520       return;
2521     }
2522     FromType = FromMember->getPointeeType();
2523     ToType = ToMember->getPointeeType();
2524   }
2525 
2526   if (FromType->isPointerType())
2527     FromType = FromType->getPointeeType();
2528   if (ToType->isPointerType())
2529     ToType = ToType->getPointeeType();
2530 
2531   // Remove references.
2532   FromType = FromType.getNonReferenceType();
2533   ToType = ToType.getNonReferenceType();
2534 
2535   // Don't print extra info for non-specialized template functions.
2536   if (FromType->isInstantiationDependentType() &&
2537       !FromType->getAs<TemplateSpecializationType>()) {
2538     PDiag << ft_default;
2539     return;
2540   }
2541 
2542   // No extra info for same types.
2543   if (Context.hasSameType(FromType, ToType)) {
2544     PDiag << ft_default;
2545     return;
2546   }
2547 
2548   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2549                           *ToFunction = ToType->getAs<FunctionProtoType>();
2550 
2551   // Both types need to be function types.
2552   if (!FromFunction || !ToFunction) {
2553     PDiag << ft_default;
2554     return;
2555   }
2556 
2557   if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2558     PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2559           << FromFunction->getNumArgs();
2560     return;
2561   }
2562 
2563   // Handle different parameter types.
2564   unsigned ArgPos;
2565   if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2566     PDiag << ft_parameter_mismatch << ArgPos + 1
2567           << ToFunction->getArgType(ArgPos)
2568           << FromFunction->getArgType(ArgPos);
2569     return;
2570   }
2571 
2572   // Handle different return type.
2573   if (!Context.hasSameType(FromFunction->getResultType(),
2574                            ToFunction->getResultType())) {
2575     PDiag << ft_return_type << ToFunction->getResultType()
2576           << FromFunction->getResultType();
2577     return;
2578   }
2579 
2580   unsigned FromQuals = FromFunction->getTypeQuals(),
2581            ToQuals = ToFunction->getTypeQuals();
2582   if (FromQuals != ToQuals) {
2583     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2584     return;
2585   }
2586 
2587   // Unable to find a difference, so add no extra info.
2588   PDiag << ft_default;
2589 }
2590 
2591 /// FunctionArgTypesAreEqual - This routine checks two function proto types
2592 /// for equality of their argument types. Caller has already checked that
2593 /// they have same number of arguments. This routine assumes that Objective-C
2594 /// pointer types which only differ in their protocol qualifiers are equal.
2595 /// If the parameters are different, ArgPos will have the parameter index
2596 /// of the first different parameter.
FunctionArgTypesAreEqual(const FunctionProtoType * OldType,const FunctionProtoType * NewType,unsigned * ArgPos)2597 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2598                                     const FunctionProtoType *NewType,
2599                                     unsigned *ArgPos) {
2600   if (!getLangOpts().ObjC1) {
2601     for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2602          N = NewType->arg_type_begin(),
2603          E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2604       if (!Context.hasSameType(*O, *N)) {
2605         if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2606         return false;
2607       }
2608     }
2609     return true;
2610   }
2611 
2612   for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2613        N = NewType->arg_type_begin(),
2614        E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2615     QualType ToType = (*O);
2616     QualType FromType = (*N);
2617     if (!Context.hasSameType(ToType, FromType)) {
2618       if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2619         if (const PointerType *PTFr = FromType->getAs<PointerType>())
2620           if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2621                PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2622               (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2623                PTFr->getPointeeType()->isObjCQualifiedClassType()))
2624             continue;
2625       }
2626       else if (const ObjCObjectPointerType *PTTo =
2627                  ToType->getAs<ObjCObjectPointerType>()) {
2628         if (const ObjCObjectPointerType *PTFr =
2629               FromType->getAs<ObjCObjectPointerType>())
2630           if (Context.hasSameUnqualifiedType(
2631                 PTTo->getObjectType()->getBaseType(),
2632                 PTFr->getObjectType()->getBaseType()))
2633             continue;
2634       }
2635       if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2636       return false;
2637     }
2638   }
2639   return true;
2640 }
2641 
2642 /// CheckPointerConversion - Check the pointer conversion from the
2643 /// expression From to the type ToType. This routine checks for
2644 /// ambiguous or inaccessible derived-to-base pointer
2645 /// conversions for which IsPointerConversion has already returned
2646 /// true. It returns true and produces a diagnostic if there was an
2647 /// error, or returns false otherwise.
CheckPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess)2648 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2649                                   CastKind &Kind,
2650                                   CXXCastPath& BasePath,
2651                                   bool IgnoreBaseAccess) {
2652   QualType FromType = From->getType();
2653   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2654 
2655   Kind = CK_BitCast;
2656 
2657   if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2658       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2659       Expr::NPCK_ZeroExpression) {
2660     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2661       DiagRuntimeBehavior(From->getExprLoc(), From,
2662                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2663                             << ToType << From->getSourceRange());
2664     else if (!isUnevaluatedContext())
2665       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2666         << ToType << From->getSourceRange();
2667   }
2668   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2669     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2670       QualType FromPointeeType = FromPtrType->getPointeeType(),
2671                ToPointeeType   = ToPtrType->getPointeeType();
2672 
2673       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2674           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2675         // We must have a derived-to-base conversion. Check an
2676         // ambiguous or inaccessible conversion.
2677         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2678                                          From->getExprLoc(),
2679                                          From->getSourceRange(), &BasePath,
2680                                          IgnoreBaseAccess))
2681           return true;
2682 
2683         // The conversion was successful.
2684         Kind = CK_DerivedToBase;
2685       }
2686     }
2687   } else if (const ObjCObjectPointerType *ToPtrType =
2688                ToType->getAs<ObjCObjectPointerType>()) {
2689     if (const ObjCObjectPointerType *FromPtrType =
2690           FromType->getAs<ObjCObjectPointerType>()) {
2691       // Objective-C++ conversions are always okay.
2692       // FIXME: We should have a different class of conversions for the
2693       // Objective-C++ implicit conversions.
2694       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2695         return false;
2696     } else if (FromType->isBlockPointerType()) {
2697       Kind = CK_BlockPointerToObjCPointerCast;
2698     } else {
2699       Kind = CK_CPointerToObjCPointerCast;
2700     }
2701   } else if (ToType->isBlockPointerType()) {
2702     if (!FromType->isBlockPointerType())
2703       Kind = CK_AnyPointerToBlockPointerCast;
2704   }
2705 
2706   // We shouldn't fall into this case unless it's valid for other
2707   // reasons.
2708   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2709     Kind = CK_NullToPointer;
2710 
2711   return false;
2712 }
2713 
2714 /// IsMemberPointerConversion - Determines whether the conversion of the
2715 /// expression From, which has the (possibly adjusted) type FromType, can be
2716 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2717 /// If so, returns true and places the converted type (that might differ from
2718 /// ToType in its cv-qualifiers at some level) into ConvertedType.
IsMemberPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType)2719 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2720                                      QualType ToType,
2721                                      bool InOverloadResolution,
2722                                      QualType &ConvertedType) {
2723   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2724   if (!ToTypePtr)
2725     return false;
2726 
2727   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2728   if (From->isNullPointerConstant(Context,
2729                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2730                                         : Expr::NPC_ValueDependentIsNull)) {
2731     ConvertedType = ToType;
2732     return true;
2733   }
2734 
2735   // Otherwise, both types have to be member pointers.
2736   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2737   if (!FromTypePtr)
2738     return false;
2739 
2740   // A pointer to member of B can be converted to a pointer to member of D,
2741   // where D is derived from B (C++ 4.11p2).
2742   QualType FromClass(FromTypePtr->getClass(), 0);
2743   QualType ToClass(ToTypePtr->getClass(), 0);
2744 
2745   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2746       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2747       IsDerivedFrom(ToClass, FromClass)) {
2748     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2749                                                  ToClass.getTypePtr());
2750     return true;
2751   }
2752 
2753   return false;
2754 }
2755 
2756 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2757 /// expression From to the type ToType. This routine checks for ambiguous or
2758 /// virtual or inaccessible base-to-derived member pointer conversions
2759 /// for which IsMemberPointerConversion has already returned true. It returns
2760 /// true and produces a diagnostic if there was an error, or returns false
2761 /// otherwise.
CheckMemberPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess)2762 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2763                                         CastKind &Kind,
2764                                         CXXCastPath &BasePath,
2765                                         bool IgnoreBaseAccess) {
2766   QualType FromType = From->getType();
2767   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2768   if (!FromPtrType) {
2769     // This must be a null pointer to member pointer conversion
2770     assert(From->isNullPointerConstant(Context,
2771                                        Expr::NPC_ValueDependentIsNull) &&
2772            "Expr must be null pointer constant!");
2773     Kind = CK_NullToMemberPointer;
2774     return false;
2775   }
2776 
2777   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2778   assert(ToPtrType && "No member pointer cast has a target type "
2779                       "that is not a member pointer.");
2780 
2781   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2782   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2783 
2784   // FIXME: What about dependent types?
2785   assert(FromClass->isRecordType() && "Pointer into non-class.");
2786   assert(ToClass->isRecordType() && "Pointer into non-class.");
2787 
2788   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2789                      /*DetectVirtual=*/true);
2790   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2791   assert(DerivationOkay &&
2792          "Should not have been called if derivation isn't OK.");
2793   (void)DerivationOkay;
2794 
2795   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2796                                   getUnqualifiedType())) {
2797     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2798     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2799       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2800     return true;
2801   }
2802 
2803   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2804     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2805       << FromClass << ToClass << QualType(VBase, 0)
2806       << From->getSourceRange();
2807     return true;
2808   }
2809 
2810   if (!IgnoreBaseAccess)
2811     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2812                          Paths.front(),
2813                          diag::err_downcast_from_inaccessible_base);
2814 
2815   // Must be a base to derived member conversion.
2816   BuildBasePathArray(Paths, BasePath);
2817   Kind = CK_BaseToDerivedMemberPointer;
2818   return false;
2819 }
2820 
2821 /// IsQualificationConversion - Determines whether the conversion from
2822 /// an rvalue of type FromType to ToType is a qualification conversion
2823 /// (C++ 4.4).
2824 ///
2825 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2826 /// when the qualification conversion involves a change in the Objective-C
2827 /// object lifetime.
2828 bool
IsQualificationConversion(QualType FromType,QualType ToType,bool CStyle,bool & ObjCLifetimeConversion)2829 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2830                                 bool CStyle, bool &ObjCLifetimeConversion) {
2831   FromType = Context.getCanonicalType(FromType);
2832   ToType = Context.getCanonicalType(ToType);
2833   ObjCLifetimeConversion = false;
2834 
2835   // If FromType and ToType are the same type, this is not a
2836   // qualification conversion.
2837   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2838     return false;
2839 
2840   // (C++ 4.4p4):
2841   //   A conversion can add cv-qualifiers at levels other than the first
2842   //   in multi-level pointers, subject to the following rules: [...]
2843   bool PreviousToQualsIncludeConst = true;
2844   bool UnwrappedAnyPointer = false;
2845   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2846     // Within each iteration of the loop, we check the qualifiers to
2847     // determine if this still looks like a qualification
2848     // conversion. Then, if all is well, we unwrap one more level of
2849     // pointers or pointers-to-members and do it all again
2850     // until there are no more pointers or pointers-to-members left to
2851     // unwrap.
2852     UnwrappedAnyPointer = true;
2853 
2854     Qualifiers FromQuals = FromType.getQualifiers();
2855     Qualifiers ToQuals = ToType.getQualifiers();
2856 
2857     // Objective-C ARC:
2858     //   Check Objective-C lifetime conversions.
2859     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2860         UnwrappedAnyPointer) {
2861       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2862         ObjCLifetimeConversion = true;
2863         FromQuals.removeObjCLifetime();
2864         ToQuals.removeObjCLifetime();
2865       } else {
2866         // Qualification conversions cannot cast between different
2867         // Objective-C lifetime qualifiers.
2868         return false;
2869       }
2870     }
2871 
2872     // Allow addition/removal of GC attributes but not changing GC attributes.
2873     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2874         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2875       FromQuals.removeObjCGCAttr();
2876       ToQuals.removeObjCGCAttr();
2877     }
2878 
2879     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2880     //      2,j, and similarly for volatile.
2881     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2882       return false;
2883 
2884     //   -- if the cv 1,j and cv 2,j are different, then const is in
2885     //      every cv for 0 < k < j.
2886     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2887         && !PreviousToQualsIncludeConst)
2888       return false;
2889 
2890     // Keep track of whether all prior cv-qualifiers in the "to" type
2891     // include const.
2892     PreviousToQualsIncludeConst
2893       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2894   }
2895 
2896   // We are left with FromType and ToType being the pointee types
2897   // after unwrapping the original FromType and ToType the same number
2898   // of types. If we unwrapped any pointers, and if FromType and
2899   // ToType have the same unqualified type (since we checked
2900   // qualifiers above), then this is a qualification conversion.
2901   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2902 }
2903 
2904 /// \brief - Determine whether this is a conversion from a scalar type to an
2905 /// atomic type.
2906 ///
2907 /// If successful, updates \c SCS's second and third steps in the conversion
2908 /// sequence to finish the conversion.
tryAtomicConversion(Sema & S,Expr * From,QualType ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)2909 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2910                                 bool InOverloadResolution,
2911                                 StandardConversionSequence &SCS,
2912                                 bool CStyle) {
2913   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2914   if (!ToAtomic)
2915     return false;
2916 
2917   StandardConversionSequence InnerSCS;
2918   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2919                             InOverloadResolution, InnerSCS,
2920                             CStyle, /*AllowObjCWritebackConversion=*/false))
2921     return false;
2922 
2923   SCS.Second = InnerSCS.Second;
2924   SCS.setToType(1, InnerSCS.getToType(1));
2925   SCS.Third = InnerSCS.Third;
2926   SCS.QualificationIncludesObjCLifetime
2927     = InnerSCS.QualificationIncludesObjCLifetime;
2928   SCS.setToType(2, InnerSCS.getToType(2));
2929   return true;
2930 }
2931 
isFirstArgumentCompatibleWithType(ASTContext & Context,CXXConstructorDecl * Constructor,QualType Type)2932 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2933                                               CXXConstructorDecl *Constructor,
2934                                               QualType Type) {
2935   const FunctionProtoType *CtorType =
2936       Constructor->getType()->getAs<FunctionProtoType>();
2937   if (CtorType->getNumArgs() > 0) {
2938     QualType FirstArg = CtorType->getArgType(0);
2939     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2940       return true;
2941   }
2942   return false;
2943 }
2944 
2945 static OverloadingResult
IsInitializerListConstructorConversion(Sema & S,Expr * From,QualType ToType,CXXRecordDecl * To,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,bool AllowExplicit)2946 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2947                                        CXXRecordDecl *To,
2948                                        UserDefinedConversionSequence &User,
2949                                        OverloadCandidateSet &CandidateSet,
2950                                        bool AllowExplicit) {
2951   DeclContext::lookup_result R = S.LookupConstructors(To);
2952   for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2953        Con != ConEnd; ++Con) {
2954     NamedDecl *D = *Con;
2955     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2956 
2957     // Find the constructor (which may be a template).
2958     CXXConstructorDecl *Constructor = 0;
2959     FunctionTemplateDecl *ConstructorTmpl
2960       = dyn_cast<FunctionTemplateDecl>(D);
2961     if (ConstructorTmpl)
2962       Constructor
2963         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2964     else
2965       Constructor = cast<CXXConstructorDecl>(D);
2966 
2967     bool Usable = !Constructor->isInvalidDecl() &&
2968                   S.isInitListConstructor(Constructor) &&
2969                   (AllowExplicit || !Constructor->isExplicit());
2970     if (Usable) {
2971       // If the first argument is (a reference to) the target type,
2972       // suppress conversions.
2973       bool SuppressUserConversions =
2974           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2975       if (ConstructorTmpl)
2976         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2977                                        /*ExplicitArgs*/ 0,
2978                                        From, CandidateSet,
2979                                        SuppressUserConversions);
2980       else
2981         S.AddOverloadCandidate(Constructor, FoundDecl,
2982                                From, CandidateSet,
2983                                SuppressUserConversions);
2984     }
2985   }
2986 
2987   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2988 
2989   OverloadCandidateSet::iterator Best;
2990   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2991   case OR_Success: {
2992     // Record the standard conversion we used and the conversion function.
2993     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2994     QualType ThisType = Constructor->getThisType(S.Context);
2995     // Initializer lists don't have conversions as such.
2996     User.Before.setAsIdentityConversion();
2997     User.HadMultipleCandidates = HadMultipleCandidates;
2998     User.ConversionFunction = Constructor;
2999     User.FoundConversionFunction = Best->FoundDecl;
3000     User.After.setAsIdentityConversion();
3001     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3002     User.After.setAllToTypes(ToType);
3003     return OR_Success;
3004   }
3005 
3006   case OR_No_Viable_Function:
3007     return OR_No_Viable_Function;
3008   case OR_Deleted:
3009     return OR_Deleted;
3010   case OR_Ambiguous:
3011     return OR_Ambiguous;
3012   }
3013 
3014   llvm_unreachable("Invalid OverloadResult!");
3015 }
3016 
3017 /// Determines whether there is a user-defined conversion sequence
3018 /// (C++ [over.ics.user]) that converts expression From to the type
3019 /// ToType. If such a conversion exists, User will contain the
3020 /// user-defined conversion sequence that performs such a conversion
3021 /// and this routine will return true. Otherwise, this routine returns
3022 /// false and User is unspecified.
3023 ///
3024 /// \param AllowExplicit  true if the conversion should consider C++0x
3025 /// "explicit" conversion functions as well as non-explicit conversion
3026 /// functions (C++0x [class.conv.fct]p2).
3027 static OverloadingResult
IsUserDefinedConversion(Sema & S,Expr * From,QualType ToType,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,bool AllowExplicit)3028 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3029                         UserDefinedConversionSequence &User,
3030                         OverloadCandidateSet &CandidateSet,
3031                         bool AllowExplicit) {
3032   // Whether we will only visit constructors.
3033   bool ConstructorsOnly = false;
3034 
3035   // If the type we are conversion to is a class type, enumerate its
3036   // constructors.
3037   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3038     // C++ [over.match.ctor]p1:
3039     //   When objects of class type are direct-initialized (8.5), or
3040     //   copy-initialized from an expression of the same or a
3041     //   derived class type (8.5), overload resolution selects the
3042     //   constructor. [...] For copy-initialization, the candidate
3043     //   functions are all the converting constructors (12.3.1) of
3044     //   that class. The argument list is the expression-list within
3045     //   the parentheses of the initializer.
3046     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3047         (From->getType()->getAs<RecordType>() &&
3048          S.IsDerivedFrom(From->getType(), ToType)))
3049       ConstructorsOnly = true;
3050 
3051     S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3052     // RequireCompleteType may have returned true due to some invalid decl
3053     // during template instantiation, but ToType may be complete enough now
3054     // to try to recover.
3055     if (ToType->isIncompleteType()) {
3056       // We're not going to find any constructors.
3057     } else if (CXXRecordDecl *ToRecordDecl
3058                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3059 
3060       Expr **Args = &From;
3061       unsigned NumArgs = 1;
3062       bool ListInitializing = false;
3063       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3064         // But first, see if there is an init-list-contructor that will work.
3065         OverloadingResult Result = IsInitializerListConstructorConversion(
3066             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3067         if (Result != OR_No_Viable_Function)
3068           return Result;
3069         // Never mind.
3070         CandidateSet.clear();
3071 
3072         // If we're list-initializing, we pass the individual elements as
3073         // arguments, not the entire list.
3074         Args = InitList->getInits();
3075         NumArgs = InitList->getNumInits();
3076         ListInitializing = true;
3077       }
3078 
3079       DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3080       for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3081            Con != ConEnd; ++Con) {
3082         NamedDecl *D = *Con;
3083         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3084 
3085         // Find the constructor (which may be a template).
3086         CXXConstructorDecl *Constructor = 0;
3087         FunctionTemplateDecl *ConstructorTmpl
3088           = dyn_cast<FunctionTemplateDecl>(D);
3089         if (ConstructorTmpl)
3090           Constructor
3091             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3092         else
3093           Constructor = cast<CXXConstructorDecl>(D);
3094 
3095         bool Usable = !Constructor->isInvalidDecl();
3096         if (ListInitializing)
3097           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3098         else
3099           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3100         if (Usable) {
3101           bool SuppressUserConversions = !ConstructorsOnly;
3102           if (SuppressUserConversions && ListInitializing) {
3103             SuppressUserConversions = false;
3104             if (NumArgs == 1) {
3105               // If the first argument is (a reference to) the target type,
3106               // suppress conversions.
3107               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3108                                                 S.Context, Constructor, ToType);
3109             }
3110           }
3111           if (ConstructorTmpl)
3112             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3113                                            /*ExplicitArgs*/ 0,
3114                                            llvm::makeArrayRef(Args, NumArgs),
3115                                            CandidateSet, SuppressUserConversions);
3116           else
3117             // Allow one user-defined conversion when user specifies a
3118             // From->ToType conversion via an static cast (c-style, etc).
3119             S.AddOverloadCandidate(Constructor, FoundDecl,
3120                                    llvm::makeArrayRef(Args, NumArgs),
3121                                    CandidateSet, SuppressUserConversions);
3122         }
3123       }
3124     }
3125   }
3126 
3127   // Enumerate conversion functions, if we're allowed to.
3128   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3129   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3130     // No conversion functions from incomplete types.
3131   } else if (const RecordType *FromRecordType
3132                                    = From->getType()->getAs<RecordType>()) {
3133     if (CXXRecordDecl *FromRecordDecl
3134          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3135       // Add all of the conversion functions as candidates.
3136       std::pair<CXXRecordDecl::conversion_iterator,
3137                 CXXRecordDecl::conversion_iterator>
3138         Conversions = FromRecordDecl->getVisibleConversionFunctions();
3139       for (CXXRecordDecl::conversion_iterator
3140              I = Conversions.first, E = Conversions.second; I != E; ++I) {
3141         DeclAccessPair FoundDecl = I.getPair();
3142         NamedDecl *D = FoundDecl.getDecl();
3143         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3144         if (isa<UsingShadowDecl>(D))
3145           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3146 
3147         CXXConversionDecl *Conv;
3148         FunctionTemplateDecl *ConvTemplate;
3149         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3150           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3151         else
3152           Conv = cast<CXXConversionDecl>(D);
3153 
3154         if (AllowExplicit || !Conv->isExplicit()) {
3155           if (ConvTemplate)
3156             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3157                                              ActingContext, From, ToType,
3158                                              CandidateSet);
3159           else
3160             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3161                                      From, ToType, CandidateSet);
3162         }
3163       }
3164     }
3165   }
3166 
3167   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3168 
3169   OverloadCandidateSet::iterator Best;
3170   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3171   case OR_Success:
3172     // Record the standard conversion we used and the conversion function.
3173     if (CXXConstructorDecl *Constructor
3174           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3175       // C++ [over.ics.user]p1:
3176       //   If the user-defined conversion is specified by a
3177       //   constructor (12.3.1), the initial standard conversion
3178       //   sequence converts the source type to the type required by
3179       //   the argument of the constructor.
3180       //
3181       QualType ThisType = Constructor->getThisType(S.Context);
3182       if (isa<InitListExpr>(From)) {
3183         // Initializer lists don't have conversions as such.
3184         User.Before.setAsIdentityConversion();
3185       } else {
3186         if (Best->Conversions[0].isEllipsis())
3187           User.EllipsisConversion = true;
3188         else {
3189           User.Before = Best->Conversions[0].Standard;
3190           User.EllipsisConversion = false;
3191         }
3192       }
3193       User.HadMultipleCandidates = HadMultipleCandidates;
3194       User.ConversionFunction = Constructor;
3195       User.FoundConversionFunction = Best->FoundDecl;
3196       User.After.setAsIdentityConversion();
3197       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3198       User.After.setAllToTypes(ToType);
3199       return OR_Success;
3200     }
3201     if (CXXConversionDecl *Conversion
3202                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3203       // C++ [over.ics.user]p1:
3204       //
3205       //   [...] If the user-defined conversion is specified by a
3206       //   conversion function (12.3.2), the initial standard
3207       //   conversion sequence converts the source type to the
3208       //   implicit object parameter of the conversion function.
3209       User.Before = Best->Conversions[0].Standard;
3210       User.HadMultipleCandidates = HadMultipleCandidates;
3211       User.ConversionFunction = Conversion;
3212       User.FoundConversionFunction = Best->FoundDecl;
3213       User.EllipsisConversion = false;
3214 
3215       // C++ [over.ics.user]p2:
3216       //   The second standard conversion sequence converts the
3217       //   result of the user-defined conversion to the target type
3218       //   for the sequence. Since an implicit conversion sequence
3219       //   is an initialization, the special rules for
3220       //   initialization by user-defined conversion apply when
3221       //   selecting the best user-defined conversion for a
3222       //   user-defined conversion sequence (see 13.3.3 and
3223       //   13.3.3.1).
3224       User.After = Best->FinalConversion;
3225       return OR_Success;
3226     }
3227     llvm_unreachable("Not a constructor or conversion function?");
3228 
3229   case OR_No_Viable_Function:
3230     return OR_No_Viable_Function;
3231   case OR_Deleted:
3232     // No conversion here! We're done.
3233     return OR_Deleted;
3234 
3235   case OR_Ambiguous:
3236     return OR_Ambiguous;
3237   }
3238 
3239   llvm_unreachable("Invalid OverloadResult!");
3240 }
3241 
3242 bool
DiagnoseMultipleUserDefinedConversion(Expr * From,QualType ToType)3243 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3244   ImplicitConversionSequence ICS;
3245   OverloadCandidateSet CandidateSet(From->getExprLoc());
3246   OverloadingResult OvResult =
3247     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3248                             CandidateSet, false);
3249   if (OvResult == OR_Ambiguous)
3250     Diag(From->getLocStart(),
3251          diag::err_typecheck_ambiguous_condition)
3252           << From->getType() << ToType << From->getSourceRange();
3253   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3254     Diag(From->getLocStart(),
3255          diag::err_typecheck_nonviable_condition)
3256     << From->getType() << ToType << From->getSourceRange();
3257   else
3258     return false;
3259   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3260   return true;
3261 }
3262 
3263 /// \brief Compare the user-defined conversion functions or constructors
3264 /// of two user-defined conversion sequences to determine whether any ordering
3265 /// is possible.
3266 static ImplicitConversionSequence::CompareKind
compareConversionFunctions(Sema & S,FunctionDecl * Function1,FunctionDecl * Function2)3267 compareConversionFunctions(Sema &S,
3268                            FunctionDecl *Function1,
3269                            FunctionDecl *Function2) {
3270   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3271     return ImplicitConversionSequence::Indistinguishable;
3272 
3273   // Objective-C++:
3274   //   If both conversion functions are implicitly-declared conversions from
3275   //   a lambda closure type to a function pointer and a block pointer,
3276   //   respectively, always prefer the conversion to a function pointer,
3277   //   because the function pointer is more lightweight and is more likely
3278   //   to keep code working.
3279   CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3280   if (!Conv1)
3281     return ImplicitConversionSequence::Indistinguishable;
3282 
3283   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3284   if (!Conv2)
3285     return ImplicitConversionSequence::Indistinguishable;
3286 
3287   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3288     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3289     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3290     if (Block1 != Block2)
3291       return Block1? ImplicitConversionSequence::Worse
3292                    : ImplicitConversionSequence::Better;
3293   }
3294 
3295   return ImplicitConversionSequence::Indistinguishable;
3296 }
3297 
3298 /// CompareImplicitConversionSequences - Compare two implicit
3299 /// conversion sequences to determine whether one is better than the
3300 /// other or if they are indistinguishable (C++ 13.3.3.2).
3301 static ImplicitConversionSequence::CompareKind
CompareImplicitConversionSequences(Sema & S,const ImplicitConversionSequence & ICS1,const ImplicitConversionSequence & ICS2)3302 CompareImplicitConversionSequences(Sema &S,
3303                                    const ImplicitConversionSequence& ICS1,
3304                                    const ImplicitConversionSequence& ICS2)
3305 {
3306   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3307   // conversion sequences (as defined in 13.3.3.1)
3308   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3309   //      conversion sequence than a user-defined conversion sequence or
3310   //      an ellipsis conversion sequence, and
3311   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3312   //      conversion sequence than an ellipsis conversion sequence
3313   //      (13.3.3.1.3).
3314   //
3315   // C++0x [over.best.ics]p10:
3316   //   For the purpose of ranking implicit conversion sequences as
3317   //   described in 13.3.3.2, the ambiguous conversion sequence is
3318   //   treated as a user-defined sequence that is indistinguishable
3319   //   from any other user-defined conversion sequence.
3320   if (ICS1.getKindRank() < ICS2.getKindRank())
3321     return ImplicitConversionSequence::Better;
3322   if (ICS2.getKindRank() < ICS1.getKindRank())
3323     return ImplicitConversionSequence::Worse;
3324 
3325   // The following checks require both conversion sequences to be of
3326   // the same kind.
3327   if (ICS1.getKind() != ICS2.getKind())
3328     return ImplicitConversionSequence::Indistinguishable;
3329 
3330   ImplicitConversionSequence::CompareKind Result =
3331       ImplicitConversionSequence::Indistinguishable;
3332 
3333   // Two implicit conversion sequences of the same form are
3334   // indistinguishable conversion sequences unless one of the
3335   // following rules apply: (C++ 13.3.3.2p3):
3336   if (ICS1.isStandard())
3337     Result = CompareStandardConversionSequences(S,
3338                                                 ICS1.Standard, ICS2.Standard);
3339   else if (ICS1.isUserDefined()) {
3340     // User-defined conversion sequence U1 is a better conversion
3341     // sequence than another user-defined conversion sequence U2 if
3342     // they contain the same user-defined conversion function or
3343     // constructor and if the second standard conversion sequence of
3344     // U1 is better than the second standard conversion sequence of
3345     // U2 (C++ 13.3.3.2p3).
3346     if (ICS1.UserDefined.ConversionFunction ==
3347           ICS2.UserDefined.ConversionFunction)
3348       Result = CompareStandardConversionSequences(S,
3349                                                   ICS1.UserDefined.After,
3350                                                   ICS2.UserDefined.After);
3351     else
3352       Result = compareConversionFunctions(S,
3353                                           ICS1.UserDefined.ConversionFunction,
3354                                           ICS2.UserDefined.ConversionFunction);
3355   }
3356 
3357   // List-initialization sequence L1 is a better conversion sequence than
3358   // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3359   // for some X and L2 does not.
3360   if (Result == ImplicitConversionSequence::Indistinguishable &&
3361       !ICS1.isBad() &&
3362       ICS1.isListInitializationSequence() &&
3363       ICS2.isListInitializationSequence()) {
3364     if (ICS1.isStdInitializerListElement() &&
3365         !ICS2.isStdInitializerListElement())
3366       return ImplicitConversionSequence::Better;
3367     if (!ICS1.isStdInitializerListElement() &&
3368         ICS2.isStdInitializerListElement())
3369       return ImplicitConversionSequence::Worse;
3370   }
3371 
3372   return Result;
3373 }
3374 
hasSimilarType(ASTContext & Context,QualType T1,QualType T2)3375 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3376   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3377     Qualifiers Quals;
3378     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3379     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3380   }
3381 
3382   return Context.hasSameUnqualifiedType(T1, T2);
3383 }
3384 
3385 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3386 // determine if one is a proper subset of the other.
3387 static ImplicitConversionSequence::CompareKind
compareStandardConversionSubsets(ASTContext & Context,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3388 compareStandardConversionSubsets(ASTContext &Context,
3389                                  const StandardConversionSequence& SCS1,
3390                                  const StandardConversionSequence& SCS2) {
3391   ImplicitConversionSequence::CompareKind Result
3392     = ImplicitConversionSequence::Indistinguishable;
3393 
3394   // the identity conversion sequence is considered to be a subsequence of
3395   // any non-identity conversion sequence
3396   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3397     return ImplicitConversionSequence::Better;
3398   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3399     return ImplicitConversionSequence::Worse;
3400 
3401   if (SCS1.Second != SCS2.Second) {
3402     if (SCS1.Second == ICK_Identity)
3403       Result = ImplicitConversionSequence::Better;
3404     else if (SCS2.Second == ICK_Identity)
3405       Result = ImplicitConversionSequence::Worse;
3406     else
3407       return ImplicitConversionSequence::Indistinguishable;
3408   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3409     return ImplicitConversionSequence::Indistinguishable;
3410 
3411   if (SCS1.Third == SCS2.Third) {
3412     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3413                              : ImplicitConversionSequence::Indistinguishable;
3414   }
3415 
3416   if (SCS1.Third == ICK_Identity)
3417     return Result == ImplicitConversionSequence::Worse
3418              ? ImplicitConversionSequence::Indistinguishable
3419              : ImplicitConversionSequence::Better;
3420 
3421   if (SCS2.Third == ICK_Identity)
3422     return Result == ImplicitConversionSequence::Better
3423              ? ImplicitConversionSequence::Indistinguishable
3424              : ImplicitConversionSequence::Worse;
3425 
3426   return ImplicitConversionSequence::Indistinguishable;
3427 }
3428 
3429 /// \brief Determine whether one of the given reference bindings is better
3430 /// than the other based on what kind of bindings they are.
isBetterReferenceBindingKind(const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3431 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3432                                        const StandardConversionSequence &SCS2) {
3433   // C++0x [over.ics.rank]p3b4:
3434   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3435   //      implicit object parameter of a non-static member function declared
3436   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3437   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3438   //      lvalue reference to a function lvalue and S2 binds an rvalue
3439   //      reference*.
3440   //
3441   // FIXME: Rvalue references. We're going rogue with the above edits,
3442   // because the semantics in the current C++0x working paper (N3225 at the
3443   // time of this writing) break the standard definition of std::forward
3444   // and std::reference_wrapper when dealing with references to functions.
3445   // Proposed wording changes submitted to CWG for consideration.
3446   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3447       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3448     return false;
3449 
3450   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3451           SCS2.IsLvalueReference) ||
3452          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3453           !SCS2.IsLvalueReference);
3454 }
3455 
3456 /// CompareStandardConversionSequences - Compare two standard
3457 /// conversion sequences to determine whether one is better than the
3458 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3459 static ImplicitConversionSequence::CompareKind
CompareStandardConversionSequences(Sema & S,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3460 CompareStandardConversionSequences(Sema &S,
3461                                    const StandardConversionSequence& SCS1,
3462                                    const StandardConversionSequence& SCS2)
3463 {
3464   // Standard conversion sequence S1 is a better conversion sequence
3465   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3466 
3467   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3468   //     sequences in the canonical form defined by 13.3.3.1.1,
3469   //     excluding any Lvalue Transformation; the identity conversion
3470   //     sequence is considered to be a subsequence of any
3471   //     non-identity conversion sequence) or, if not that,
3472   if (ImplicitConversionSequence::CompareKind CK
3473         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3474     return CK;
3475 
3476   //  -- the rank of S1 is better than the rank of S2 (by the rules
3477   //     defined below), or, if not that,
3478   ImplicitConversionRank Rank1 = SCS1.getRank();
3479   ImplicitConversionRank Rank2 = SCS2.getRank();
3480   if (Rank1 < Rank2)
3481     return ImplicitConversionSequence::Better;
3482   else if (Rank2 < Rank1)
3483     return ImplicitConversionSequence::Worse;
3484 
3485   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3486   // are indistinguishable unless one of the following rules
3487   // applies:
3488 
3489   //   A conversion that is not a conversion of a pointer, or
3490   //   pointer to member, to bool is better than another conversion
3491   //   that is such a conversion.
3492   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3493     return SCS2.isPointerConversionToBool()
3494              ? ImplicitConversionSequence::Better
3495              : ImplicitConversionSequence::Worse;
3496 
3497   // C++ [over.ics.rank]p4b2:
3498   //
3499   //   If class B is derived directly or indirectly from class A,
3500   //   conversion of B* to A* is better than conversion of B* to
3501   //   void*, and conversion of A* to void* is better than conversion
3502   //   of B* to void*.
3503   bool SCS1ConvertsToVoid
3504     = SCS1.isPointerConversionToVoidPointer(S.Context);
3505   bool SCS2ConvertsToVoid
3506     = SCS2.isPointerConversionToVoidPointer(S.Context);
3507   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3508     // Exactly one of the conversion sequences is a conversion to
3509     // a void pointer; it's the worse conversion.
3510     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3511                               : ImplicitConversionSequence::Worse;
3512   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3513     // Neither conversion sequence converts to a void pointer; compare
3514     // their derived-to-base conversions.
3515     if (ImplicitConversionSequence::CompareKind DerivedCK
3516           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3517       return DerivedCK;
3518   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3519              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3520     // Both conversion sequences are conversions to void
3521     // pointers. Compare the source types to determine if there's an
3522     // inheritance relationship in their sources.
3523     QualType FromType1 = SCS1.getFromType();
3524     QualType FromType2 = SCS2.getFromType();
3525 
3526     // Adjust the types we're converting from via the array-to-pointer
3527     // conversion, if we need to.
3528     if (SCS1.First == ICK_Array_To_Pointer)
3529       FromType1 = S.Context.getArrayDecayedType(FromType1);
3530     if (SCS2.First == ICK_Array_To_Pointer)
3531       FromType2 = S.Context.getArrayDecayedType(FromType2);
3532 
3533     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3534     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3535 
3536     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3537       return ImplicitConversionSequence::Better;
3538     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3539       return ImplicitConversionSequence::Worse;
3540 
3541     // Objective-C++: If one interface is more specific than the
3542     // other, it is the better one.
3543     const ObjCObjectPointerType* FromObjCPtr1
3544       = FromType1->getAs<ObjCObjectPointerType>();
3545     const ObjCObjectPointerType* FromObjCPtr2
3546       = FromType2->getAs<ObjCObjectPointerType>();
3547     if (FromObjCPtr1 && FromObjCPtr2) {
3548       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3549                                                           FromObjCPtr2);
3550       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3551                                                            FromObjCPtr1);
3552       if (AssignLeft != AssignRight) {
3553         return AssignLeft? ImplicitConversionSequence::Better
3554                          : ImplicitConversionSequence::Worse;
3555       }
3556     }
3557   }
3558 
3559   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3560   // bullet 3).
3561   if (ImplicitConversionSequence::CompareKind QualCK
3562         = CompareQualificationConversions(S, SCS1, SCS2))
3563     return QualCK;
3564 
3565   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3566     // Check for a better reference binding based on the kind of bindings.
3567     if (isBetterReferenceBindingKind(SCS1, SCS2))
3568       return ImplicitConversionSequence::Better;
3569     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3570       return ImplicitConversionSequence::Worse;
3571 
3572     // C++ [over.ics.rank]p3b4:
3573     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3574     //      which the references refer are the same type except for
3575     //      top-level cv-qualifiers, and the type to which the reference
3576     //      initialized by S2 refers is more cv-qualified than the type
3577     //      to which the reference initialized by S1 refers.
3578     QualType T1 = SCS1.getToType(2);
3579     QualType T2 = SCS2.getToType(2);
3580     T1 = S.Context.getCanonicalType(T1);
3581     T2 = S.Context.getCanonicalType(T2);
3582     Qualifiers T1Quals, T2Quals;
3583     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3584     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3585     if (UnqualT1 == UnqualT2) {
3586       // Objective-C++ ARC: If the references refer to objects with different
3587       // lifetimes, prefer bindings that don't change lifetime.
3588       if (SCS1.ObjCLifetimeConversionBinding !=
3589                                           SCS2.ObjCLifetimeConversionBinding) {
3590         return SCS1.ObjCLifetimeConversionBinding
3591                                            ? ImplicitConversionSequence::Worse
3592                                            : ImplicitConversionSequence::Better;
3593       }
3594 
3595       // If the type is an array type, promote the element qualifiers to the
3596       // type for comparison.
3597       if (isa<ArrayType>(T1) && T1Quals)
3598         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3599       if (isa<ArrayType>(T2) && T2Quals)
3600         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3601       if (T2.isMoreQualifiedThan(T1))
3602         return ImplicitConversionSequence::Better;
3603       else if (T1.isMoreQualifiedThan(T2))
3604         return ImplicitConversionSequence::Worse;
3605     }
3606   }
3607 
3608   // In Microsoft mode, prefer an integral conversion to a
3609   // floating-to-integral conversion if the integral conversion
3610   // is between types of the same size.
3611   // For example:
3612   // void f(float);
3613   // void f(int);
3614   // int main {
3615   //    long a;
3616   //    f(a);
3617   // }
3618   // Here, MSVC will call f(int) instead of generating a compile error
3619   // as clang will do in standard mode.
3620   if (S.getLangOpts().MicrosoftMode &&
3621       SCS1.Second == ICK_Integral_Conversion &&
3622       SCS2.Second == ICK_Floating_Integral &&
3623       S.Context.getTypeSize(SCS1.getFromType()) ==
3624       S.Context.getTypeSize(SCS1.getToType(2)))
3625     return ImplicitConversionSequence::Better;
3626 
3627   return ImplicitConversionSequence::Indistinguishable;
3628 }
3629 
3630 /// CompareQualificationConversions - Compares two standard conversion
3631 /// sequences to determine whether they can be ranked based on their
3632 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3633 ImplicitConversionSequence::CompareKind
CompareQualificationConversions(Sema & S,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3634 CompareQualificationConversions(Sema &S,
3635                                 const StandardConversionSequence& SCS1,
3636                                 const StandardConversionSequence& SCS2) {
3637   // C++ 13.3.3.2p3:
3638   //  -- S1 and S2 differ only in their qualification conversion and
3639   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3640   //     cv-qualification signature of type T1 is a proper subset of
3641   //     the cv-qualification signature of type T2, and S1 is not the
3642   //     deprecated string literal array-to-pointer conversion (4.2).
3643   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3644       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3645     return ImplicitConversionSequence::Indistinguishable;
3646 
3647   // FIXME: the example in the standard doesn't use a qualification
3648   // conversion (!)
3649   QualType T1 = SCS1.getToType(2);
3650   QualType T2 = SCS2.getToType(2);
3651   T1 = S.Context.getCanonicalType(T1);
3652   T2 = S.Context.getCanonicalType(T2);
3653   Qualifiers T1Quals, T2Quals;
3654   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3655   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3656 
3657   // If the types are the same, we won't learn anything by unwrapped
3658   // them.
3659   if (UnqualT1 == UnqualT2)
3660     return ImplicitConversionSequence::Indistinguishable;
3661 
3662   // If the type is an array type, promote the element qualifiers to the type
3663   // for comparison.
3664   if (isa<ArrayType>(T1) && T1Quals)
3665     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3666   if (isa<ArrayType>(T2) && T2Quals)
3667     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3668 
3669   ImplicitConversionSequence::CompareKind Result
3670     = ImplicitConversionSequence::Indistinguishable;
3671 
3672   // Objective-C++ ARC:
3673   //   Prefer qualification conversions not involving a change in lifetime
3674   //   to qualification conversions that do not change lifetime.
3675   if (SCS1.QualificationIncludesObjCLifetime !=
3676                                       SCS2.QualificationIncludesObjCLifetime) {
3677     Result = SCS1.QualificationIncludesObjCLifetime
3678                ? ImplicitConversionSequence::Worse
3679                : ImplicitConversionSequence::Better;
3680   }
3681 
3682   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3683     // Within each iteration of the loop, we check the qualifiers to
3684     // determine if this still looks like a qualification
3685     // conversion. Then, if all is well, we unwrap one more level of
3686     // pointers or pointers-to-members and do it all again
3687     // until there are no more pointers or pointers-to-members left
3688     // to unwrap. This essentially mimics what
3689     // IsQualificationConversion does, but here we're checking for a
3690     // strict subset of qualifiers.
3691     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3692       // The qualifiers are the same, so this doesn't tell us anything
3693       // about how the sequences rank.
3694       ;
3695     else if (T2.isMoreQualifiedThan(T1)) {
3696       // T1 has fewer qualifiers, so it could be the better sequence.
3697       if (Result == ImplicitConversionSequence::Worse)
3698         // Neither has qualifiers that are a subset of the other's
3699         // qualifiers.
3700         return ImplicitConversionSequence::Indistinguishable;
3701 
3702       Result = ImplicitConversionSequence::Better;
3703     } else if (T1.isMoreQualifiedThan(T2)) {
3704       // T2 has fewer qualifiers, so it could be the better sequence.
3705       if (Result == ImplicitConversionSequence::Better)
3706         // Neither has qualifiers that are a subset of the other's
3707         // qualifiers.
3708         return ImplicitConversionSequence::Indistinguishable;
3709 
3710       Result = ImplicitConversionSequence::Worse;
3711     } else {
3712       // Qualifiers are disjoint.
3713       return ImplicitConversionSequence::Indistinguishable;
3714     }
3715 
3716     // If the types after this point are equivalent, we're done.
3717     if (S.Context.hasSameUnqualifiedType(T1, T2))
3718       break;
3719   }
3720 
3721   // Check that the winning standard conversion sequence isn't using
3722   // the deprecated string literal array to pointer conversion.
3723   switch (Result) {
3724   case ImplicitConversionSequence::Better:
3725     if (SCS1.DeprecatedStringLiteralToCharPtr)
3726       Result = ImplicitConversionSequence::Indistinguishable;
3727     break;
3728 
3729   case ImplicitConversionSequence::Indistinguishable:
3730     break;
3731 
3732   case ImplicitConversionSequence::Worse:
3733     if (SCS2.DeprecatedStringLiteralToCharPtr)
3734       Result = ImplicitConversionSequence::Indistinguishable;
3735     break;
3736   }
3737 
3738   return Result;
3739 }
3740 
3741 /// CompareDerivedToBaseConversions - Compares two standard conversion
3742 /// sequences to determine whether they can be ranked based on their
3743 /// various kinds of derived-to-base conversions (C++
3744 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3745 /// conversions between Objective-C interface types.
3746 ImplicitConversionSequence::CompareKind
CompareDerivedToBaseConversions(Sema & S,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3747 CompareDerivedToBaseConversions(Sema &S,
3748                                 const StandardConversionSequence& SCS1,
3749                                 const StandardConversionSequence& SCS2) {
3750   QualType FromType1 = SCS1.getFromType();
3751   QualType ToType1 = SCS1.getToType(1);
3752   QualType FromType2 = SCS2.getFromType();
3753   QualType ToType2 = SCS2.getToType(1);
3754 
3755   // Adjust the types we're converting from via the array-to-pointer
3756   // conversion, if we need to.
3757   if (SCS1.First == ICK_Array_To_Pointer)
3758     FromType1 = S.Context.getArrayDecayedType(FromType1);
3759   if (SCS2.First == ICK_Array_To_Pointer)
3760     FromType2 = S.Context.getArrayDecayedType(FromType2);
3761 
3762   // Canonicalize all of the types.
3763   FromType1 = S.Context.getCanonicalType(FromType1);
3764   ToType1 = S.Context.getCanonicalType(ToType1);
3765   FromType2 = S.Context.getCanonicalType(FromType2);
3766   ToType2 = S.Context.getCanonicalType(ToType2);
3767 
3768   // C++ [over.ics.rank]p4b3:
3769   //
3770   //   If class B is derived directly or indirectly from class A and
3771   //   class C is derived directly or indirectly from B,
3772   //
3773   // Compare based on pointer conversions.
3774   if (SCS1.Second == ICK_Pointer_Conversion &&
3775       SCS2.Second == ICK_Pointer_Conversion &&
3776       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3777       FromType1->isPointerType() && FromType2->isPointerType() &&
3778       ToType1->isPointerType() && ToType2->isPointerType()) {
3779     QualType FromPointee1
3780       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3781     QualType ToPointee1
3782       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3783     QualType FromPointee2
3784       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3785     QualType ToPointee2
3786       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3787 
3788     //   -- conversion of C* to B* is better than conversion of C* to A*,
3789     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3790       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3791         return ImplicitConversionSequence::Better;
3792       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3793         return ImplicitConversionSequence::Worse;
3794     }
3795 
3796     //   -- conversion of B* to A* is better than conversion of C* to A*,
3797     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3798       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3799         return ImplicitConversionSequence::Better;
3800       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3801         return ImplicitConversionSequence::Worse;
3802     }
3803   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3804              SCS2.Second == ICK_Pointer_Conversion) {
3805     const ObjCObjectPointerType *FromPtr1
3806       = FromType1->getAs<ObjCObjectPointerType>();
3807     const ObjCObjectPointerType *FromPtr2
3808       = FromType2->getAs<ObjCObjectPointerType>();
3809     const ObjCObjectPointerType *ToPtr1
3810       = ToType1->getAs<ObjCObjectPointerType>();
3811     const ObjCObjectPointerType *ToPtr2
3812       = ToType2->getAs<ObjCObjectPointerType>();
3813 
3814     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3815       // Apply the same conversion ranking rules for Objective-C pointer types
3816       // that we do for C++ pointers to class types. However, we employ the
3817       // Objective-C pseudo-subtyping relationship used for assignment of
3818       // Objective-C pointer types.
3819       bool FromAssignLeft
3820         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3821       bool FromAssignRight
3822         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3823       bool ToAssignLeft
3824         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3825       bool ToAssignRight
3826         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3827 
3828       // A conversion to an a non-id object pointer type or qualified 'id'
3829       // type is better than a conversion to 'id'.
3830       if (ToPtr1->isObjCIdType() &&
3831           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3832         return ImplicitConversionSequence::Worse;
3833       if (ToPtr2->isObjCIdType() &&
3834           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3835         return ImplicitConversionSequence::Better;
3836 
3837       // A conversion to a non-id object pointer type is better than a
3838       // conversion to a qualified 'id' type
3839       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3840         return ImplicitConversionSequence::Worse;
3841       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3842         return ImplicitConversionSequence::Better;
3843 
3844       // A conversion to an a non-Class object pointer type or qualified 'Class'
3845       // type is better than a conversion to 'Class'.
3846       if (ToPtr1->isObjCClassType() &&
3847           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3848         return ImplicitConversionSequence::Worse;
3849       if (ToPtr2->isObjCClassType() &&
3850           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3851         return ImplicitConversionSequence::Better;
3852 
3853       // A conversion to a non-Class object pointer type is better than a
3854       // conversion to a qualified 'Class' type.
3855       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3856         return ImplicitConversionSequence::Worse;
3857       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3858         return ImplicitConversionSequence::Better;
3859 
3860       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3861       if (S.Context.hasSameType(FromType1, FromType2) &&
3862           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3863           (ToAssignLeft != ToAssignRight))
3864         return ToAssignLeft? ImplicitConversionSequence::Worse
3865                            : ImplicitConversionSequence::Better;
3866 
3867       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3868       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3869           (FromAssignLeft != FromAssignRight))
3870         return FromAssignLeft? ImplicitConversionSequence::Better
3871         : ImplicitConversionSequence::Worse;
3872     }
3873   }
3874 
3875   // Ranking of member-pointer types.
3876   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3877       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3878       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3879     const MemberPointerType * FromMemPointer1 =
3880                                         FromType1->getAs<MemberPointerType>();
3881     const MemberPointerType * ToMemPointer1 =
3882                                           ToType1->getAs<MemberPointerType>();
3883     const MemberPointerType * FromMemPointer2 =
3884                                           FromType2->getAs<MemberPointerType>();
3885     const MemberPointerType * ToMemPointer2 =
3886                                           ToType2->getAs<MemberPointerType>();
3887     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3888     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3889     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3890     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3891     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3892     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3893     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3894     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3895     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3896     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3897       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3898         return ImplicitConversionSequence::Worse;
3899       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3900         return ImplicitConversionSequence::Better;
3901     }
3902     // conversion of B::* to C::* is better than conversion of A::* to C::*
3903     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3904       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3905         return ImplicitConversionSequence::Better;
3906       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3907         return ImplicitConversionSequence::Worse;
3908     }
3909   }
3910 
3911   if (SCS1.Second == ICK_Derived_To_Base) {
3912     //   -- conversion of C to B is better than conversion of C to A,
3913     //   -- binding of an expression of type C to a reference of type
3914     //      B& is better than binding an expression of type C to a
3915     //      reference of type A&,
3916     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3917         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3918       if (S.IsDerivedFrom(ToType1, ToType2))
3919         return ImplicitConversionSequence::Better;
3920       else if (S.IsDerivedFrom(ToType2, ToType1))
3921         return ImplicitConversionSequence::Worse;
3922     }
3923 
3924     //   -- conversion of B to A is better than conversion of C to A.
3925     //   -- binding of an expression of type B to a reference of type
3926     //      A& is better than binding an expression of type C to a
3927     //      reference of type A&,
3928     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3929         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3930       if (S.IsDerivedFrom(FromType2, FromType1))
3931         return ImplicitConversionSequence::Better;
3932       else if (S.IsDerivedFrom(FromType1, FromType2))
3933         return ImplicitConversionSequence::Worse;
3934     }
3935   }
3936 
3937   return ImplicitConversionSequence::Indistinguishable;
3938 }
3939 
3940 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3941 /// determine whether they are reference-related,
3942 /// reference-compatible, reference-compatible with added
3943 /// qualification, or incompatible, for use in C++ initialization by
3944 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3945 /// type, and the first type (T1) is the pointee type of the reference
3946 /// type being initialized.
3947 Sema::ReferenceCompareResult
CompareReferenceRelationship(SourceLocation Loc,QualType OrigT1,QualType OrigT2,bool & DerivedToBase,bool & ObjCConversion,bool & ObjCLifetimeConversion)3948 Sema::CompareReferenceRelationship(SourceLocation Loc,
3949                                    QualType OrigT1, QualType OrigT2,
3950                                    bool &DerivedToBase,
3951                                    bool &ObjCConversion,
3952                                    bool &ObjCLifetimeConversion) {
3953   assert(!OrigT1->isReferenceType() &&
3954     "T1 must be the pointee type of the reference type");
3955   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3956 
3957   QualType T1 = Context.getCanonicalType(OrigT1);
3958   QualType T2 = Context.getCanonicalType(OrigT2);
3959   Qualifiers T1Quals, T2Quals;
3960   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3961   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3962 
3963   // C++ [dcl.init.ref]p4:
3964   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3965   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3966   //   T1 is a base class of T2.
3967   DerivedToBase = false;
3968   ObjCConversion = false;
3969   ObjCLifetimeConversion = false;
3970   if (UnqualT1 == UnqualT2) {
3971     // Nothing to do.
3972   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3973            IsDerivedFrom(UnqualT2, UnqualT1))
3974     DerivedToBase = true;
3975   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3976            UnqualT2->isObjCObjectOrInterfaceType() &&
3977            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3978     ObjCConversion = true;
3979   else
3980     return Ref_Incompatible;
3981 
3982   // At this point, we know that T1 and T2 are reference-related (at
3983   // least).
3984 
3985   // If the type is an array type, promote the element qualifiers to the type
3986   // for comparison.
3987   if (isa<ArrayType>(T1) && T1Quals)
3988     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3989   if (isa<ArrayType>(T2) && T2Quals)
3990     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3991 
3992   // C++ [dcl.init.ref]p4:
3993   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3994   //   reference-related to T2 and cv1 is the same cv-qualification
3995   //   as, or greater cv-qualification than, cv2. For purposes of
3996   //   overload resolution, cases for which cv1 is greater
3997   //   cv-qualification than cv2 are identified as
3998   //   reference-compatible with added qualification (see 13.3.3.2).
3999   //
4000   // Note that we also require equivalence of Objective-C GC and address-space
4001   // qualifiers when performing these computations, so that e.g., an int in
4002   // address space 1 is not reference-compatible with an int in address
4003   // space 2.
4004   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4005       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4006     T1Quals.removeObjCLifetime();
4007     T2Quals.removeObjCLifetime();
4008     ObjCLifetimeConversion = true;
4009   }
4010 
4011   if (T1Quals == T2Quals)
4012     return Ref_Compatible;
4013   else if (T1Quals.compatiblyIncludes(T2Quals))
4014     return Ref_Compatible_With_Added_Qualification;
4015   else
4016     return Ref_Related;
4017 }
4018 
4019 /// \brief Look for a user-defined conversion to an value reference-compatible
4020 ///        with DeclType. Return true if something definite is found.
4021 static bool
FindConversionForRefInit(Sema & S,ImplicitConversionSequence & ICS,QualType DeclType,SourceLocation DeclLoc,Expr * Init,QualType T2,bool AllowRvalues,bool AllowExplicit)4022 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4023                          QualType DeclType, SourceLocation DeclLoc,
4024                          Expr *Init, QualType T2, bool AllowRvalues,
4025                          bool AllowExplicit) {
4026   assert(T2->isRecordType() && "Can only find conversions of record types.");
4027   CXXRecordDecl *T2RecordDecl
4028     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4029 
4030   OverloadCandidateSet CandidateSet(DeclLoc);
4031   std::pair<CXXRecordDecl::conversion_iterator,
4032             CXXRecordDecl::conversion_iterator>
4033     Conversions = T2RecordDecl->getVisibleConversionFunctions();
4034   for (CXXRecordDecl::conversion_iterator
4035          I = Conversions.first, E = Conversions.second; I != E; ++I) {
4036     NamedDecl *D = *I;
4037     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4038     if (isa<UsingShadowDecl>(D))
4039       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4040 
4041     FunctionTemplateDecl *ConvTemplate
4042       = dyn_cast<FunctionTemplateDecl>(D);
4043     CXXConversionDecl *Conv;
4044     if (ConvTemplate)
4045       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4046     else
4047       Conv = cast<CXXConversionDecl>(D);
4048 
4049     // If this is an explicit conversion, and we're not allowed to consider
4050     // explicit conversions, skip it.
4051     if (!AllowExplicit && Conv->isExplicit())
4052       continue;
4053 
4054     if (AllowRvalues) {
4055       bool DerivedToBase = false;
4056       bool ObjCConversion = false;
4057       bool ObjCLifetimeConversion = false;
4058 
4059       // If we are initializing an rvalue reference, don't permit conversion
4060       // functions that return lvalues.
4061       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4062         const ReferenceType *RefType
4063           = Conv->getConversionType()->getAs<LValueReferenceType>();
4064         if (RefType && !RefType->getPointeeType()->isFunctionType())
4065           continue;
4066       }
4067 
4068       if (!ConvTemplate &&
4069           S.CompareReferenceRelationship(
4070             DeclLoc,
4071             Conv->getConversionType().getNonReferenceType()
4072               .getUnqualifiedType(),
4073             DeclType.getNonReferenceType().getUnqualifiedType(),
4074             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4075           Sema::Ref_Incompatible)
4076         continue;
4077     } else {
4078       // If the conversion function doesn't return a reference type,
4079       // it can't be considered for this conversion. An rvalue reference
4080       // is only acceptable if its referencee is a function type.
4081 
4082       const ReferenceType *RefType =
4083         Conv->getConversionType()->getAs<ReferenceType>();
4084       if (!RefType ||
4085           (!RefType->isLValueReferenceType() &&
4086            !RefType->getPointeeType()->isFunctionType()))
4087         continue;
4088     }
4089 
4090     if (ConvTemplate)
4091       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4092                                        Init, DeclType, CandidateSet);
4093     else
4094       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4095                                DeclType, CandidateSet);
4096   }
4097 
4098   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4099 
4100   OverloadCandidateSet::iterator Best;
4101   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4102   case OR_Success:
4103     // C++ [over.ics.ref]p1:
4104     //
4105     //   [...] If the parameter binds directly to the result of
4106     //   applying a conversion function to the argument
4107     //   expression, the implicit conversion sequence is a
4108     //   user-defined conversion sequence (13.3.3.1.2), with the
4109     //   second standard conversion sequence either an identity
4110     //   conversion or, if the conversion function returns an
4111     //   entity of a type that is a derived class of the parameter
4112     //   type, a derived-to-base Conversion.
4113     if (!Best->FinalConversion.DirectBinding)
4114       return false;
4115 
4116     ICS.setUserDefined();
4117     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4118     ICS.UserDefined.After = Best->FinalConversion;
4119     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4120     ICS.UserDefined.ConversionFunction = Best->Function;
4121     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4122     ICS.UserDefined.EllipsisConversion = false;
4123     assert(ICS.UserDefined.After.ReferenceBinding &&
4124            ICS.UserDefined.After.DirectBinding &&
4125            "Expected a direct reference binding!");
4126     return true;
4127 
4128   case OR_Ambiguous:
4129     ICS.setAmbiguous();
4130     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4131          Cand != CandidateSet.end(); ++Cand)
4132       if (Cand->Viable)
4133         ICS.Ambiguous.addConversion(Cand->Function);
4134     return true;
4135 
4136   case OR_No_Viable_Function:
4137   case OR_Deleted:
4138     // There was no suitable conversion, or we found a deleted
4139     // conversion; continue with other checks.
4140     return false;
4141   }
4142 
4143   llvm_unreachable("Invalid OverloadResult!");
4144 }
4145 
4146 /// \brief Compute an implicit conversion sequence for reference
4147 /// initialization.
4148 static ImplicitConversionSequence
TryReferenceInit(Sema & S,Expr * Init,QualType DeclType,SourceLocation DeclLoc,bool SuppressUserConversions,bool AllowExplicit)4149 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4150                  SourceLocation DeclLoc,
4151                  bool SuppressUserConversions,
4152                  bool AllowExplicit) {
4153   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4154 
4155   // Most paths end in a failed conversion.
4156   ImplicitConversionSequence ICS;
4157   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4158 
4159   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4160   QualType T2 = Init->getType();
4161 
4162   // If the initializer is the address of an overloaded function, try
4163   // to resolve the overloaded function. If all goes well, T2 is the
4164   // type of the resulting function.
4165   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4166     DeclAccessPair Found;
4167     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4168                                                                 false, Found))
4169       T2 = Fn->getType();
4170   }
4171 
4172   // Compute some basic properties of the types and the initializer.
4173   bool isRValRef = DeclType->isRValueReferenceType();
4174   bool DerivedToBase = false;
4175   bool ObjCConversion = false;
4176   bool ObjCLifetimeConversion = false;
4177   Expr::Classification InitCategory = Init->Classify(S.Context);
4178   Sema::ReferenceCompareResult RefRelationship
4179     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4180                                      ObjCConversion, ObjCLifetimeConversion);
4181 
4182 
4183   // C++0x [dcl.init.ref]p5:
4184   //   A reference to type "cv1 T1" is initialized by an expression
4185   //   of type "cv2 T2" as follows:
4186 
4187   //     -- If reference is an lvalue reference and the initializer expression
4188   if (!isRValRef) {
4189     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4190     //        reference-compatible with "cv2 T2," or
4191     //
4192     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4193     if (InitCategory.isLValue() &&
4194         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4195       // C++ [over.ics.ref]p1:
4196       //   When a parameter of reference type binds directly (8.5.3)
4197       //   to an argument expression, the implicit conversion sequence
4198       //   is the identity conversion, unless the argument expression
4199       //   has a type that is a derived class of the parameter type,
4200       //   in which case the implicit conversion sequence is a
4201       //   derived-to-base Conversion (13.3.3.1).
4202       ICS.setStandard();
4203       ICS.Standard.First = ICK_Identity;
4204       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4205                          : ObjCConversion? ICK_Compatible_Conversion
4206                          : ICK_Identity;
4207       ICS.Standard.Third = ICK_Identity;
4208       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4209       ICS.Standard.setToType(0, T2);
4210       ICS.Standard.setToType(1, T1);
4211       ICS.Standard.setToType(2, T1);
4212       ICS.Standard.ReferenceBinding = true;
4213       ICS.Standard.DirectBinding = true;
4214       ICS.Standard.IsLvalueReference = !isRValRef;
4215       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4216       ICS.Standard.BindsToRvalue = false;
4217       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4218       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4219       ICS.Standard.CopyConstructor = 0;
4220 
4221       // Nothing more to do: the inaccessibility/ambiguity check for
4222       // derived-to-base conversions is suppressed when we're
4223       // computing the implicit conversion sequence (C++
4224       // [over.best.ics]p2).
4225       return ICS;
4226     }
4227 
4228     //       -- has a class type (i.e., T2 is a class type), where T1 is
4229     //          not reference-related to T2, and can be implicitly
4230     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4231     //          is reference-compatible with "cv3 T3" 92) (this
4232     //          conversion is selected by enumerating the applicable
4233     //          conversion functions (13.3.1.6) and choosing the best
4234     //          one through overload resolution (13.3)),
4235     if (!SuppressUserConversions && T2->isRecordType() &&
4236         !S.RequireCompleteType(DeclLoc, T2, 0) &&
4237         RefRelationship == Sema::Ref_Incompatible) {
4238       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4239                                    Init, T2, /*AllowRvalues=*/false,
4240                                    AllowExplicit))
4241         return ICS;
4242     }
4243   }
4244 
4245   //     -- Otherwise, the reference shall be an lvalue reference to a
4246   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4247   //        shall be an rvalue reference.
4248   //
4249   // We actually handle one oddity of C++ [over.ics.ref] at this
4250   // point, which is that, due to p2 (which short-circuits reference
4251   // binding by only attempting a simple conversion for non-direct
4252   // bindings) and p3's strange wording, we allow a const volatile
4253   // reference to bind to an rvalue. Hence the check for the presence
4254   // of "const" rather than checking for "const" being the only
4255   // qualifier.
4256   // This is also the point where rvalue references and lvalue inits no longer
4257   // go together.
4258   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4259     return ICS;
4260 
4261   //       -- If the initializer expression
4262   //
4263   //            -- is an xvalue, class prvalue, array prvalue or function
4264   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4265   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4266       (InitCategory.isXValue() ||
4267       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4268       (InitCategory.isLValue() && T2->isFunctionType()))) {
4269     ICS.setStandard();
4270     ICS.Standard.First = ICK_Identity;
4271     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4272                       : ObjCConversion? ICK_Compatible_Conversion
4273                       : ICK_Identity;
4274     ICS.Standard.Third = ICK_Identity;
4275     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4276     ICS.Standard.setToType(0, T2);
4277     ICS.Standard.setToType(1, T1);
4278     ICS.Standard.setToType(2, T1);
4279     ICS.Standard.ReferenceBinding = true;
4280     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4281     // binding unless we're binding to a class prvalue.
4282     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4283     // allow the use of rvalue references in C++98/03 for the benefit of
4284     // standard library implementors; therefore, we need the xvalue check here.
4285     ICS.Standard.DirectBinding =
4286       S.getLangOpts().CPlusPlus11 ||
4287       (InitCategory.isPRValue() && !T2->isRecordType());
4288     ICS.Standard.IsLvalueReference = !isRValRef;
4289     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4290     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4291     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4292     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4293     ICS.Standard.CopyConstructor = 0;
4294     return ICS;
4295   }
4296 
4297   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4298   //               reference-related to T2, and can be implicitly converted to
4299   //               an xvalue, class prvalue, or function lvalue of type
4300   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4301   //               "cv3 T3",
4302   //
4303   //          then the reference is bound to the value of the initializer
4304   //          expression in the first case and to the result of the conversion
4305   //          in the second case (or, in either case, to an appropriate base
4306   //          class subobject).
4307   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4308       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4309       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4310                                Init, T2, /*AllowRvalues=*/true,
4311                                AllowExplicit)) {
4312     // In the second case, if the reference is an rvalue reference
4313     // and the second standard conversion sequence of the
4314     // user-defined conversion sequence includes an lvalue-to-rvalue
4315     // conversion, the program is ill-formed.
4316     if (ICS.isUserDefined() && isRValRef &&
4317         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4318       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4319 
4320     return ICS;
4321   }
4322 
4323   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4324   //          initialized from the initializer expression using the
4325   //          rules for a non-reference copy initialization (8.5). The
4326   //          reference is then bound to the temporary. If T1 is
4327   //          reference-related to T2, cv1 must be the same
4328   //          cv-qualification as, or greater cv-qualification than,
4329   //          cv2; otherwise, the program is ill-formed.
4330   if (RefRelationship == Sema::Ref_Related) {
4331     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4332     // we would be reference-compatible or reference-compatible with
4333     // added qualification. But that wasn't the case, so the reference
4334     // initialization fails.
4335     //
4336     // Note that we only want to check address spaces and cvr-qualifiers here.
4337     // ObjC GC and lifetime qualifiers aren't important.
4338     Qualifiers T1Quals = T1.getQualifiers();
4339     Qualifiers T2Quals = T2.getQualifiers();
4340     T1Quals.removeObjCGCAttr();
4341     T1Quals.removeObjCLifetime();
4342     T2Quals.removeObjCGCAttr();
4343     T2Quals.removeObjCLifetime();
4344     if (!T1Quals.compatiblyIncludes(T2Quals))
4345       return ICS;
4346   }
4347 
4348   // If at least one of the types is a class type, the types are not
4349   // related, and we aren't allowed any user conversions, the
4350   // reference binding fails. This case is important for breaking
4351   // recursion, since TryImplicitConversion below will attempt to
4352   // create a temporary through the use of a copy constructor.
4353   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4354       (T1->isRecordType() || T2->isRecordType()))
4355     return ICS;
4356 
4357   // If T1 is reference-related to T2 and the reference is an rvalue
4358   // reference, the initializer expression shall not be an lvalue.
4359   if (RefRelationship >= Sema::Ref_Related &&
4360       isRValRef && Init->Classify(S.Context).isLValue())
4361     return ICS;
4362 
4363   // C++ [over.ics.ref]p2:
4364   //   When a parameter of reference type is not bound directly to
4365   //   an argument expression, the conversion sequence is the one
4366   //   required to convert the argument expression to the
4367   //   underlying type of the reference according to
4368   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4369   //   to copy-initializing a temporary of the underlying type with
4370   //   the argument expression. Any difference in top-level
4371   //   cv-qualification is subsumed by the initialization itself
4372   //   and does not constitute a conversion.
4373   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4374                               /*AllowExplicit=*/false,
4375                               /*InOverloadResolution=*/false,
4376                               /*CStyle=*/false,
4377                               /*AllowObjCWritebackConversion=*/false);
4378 
4379   // Of course, that's still a reference binding.
4380   if (ICS.isStandard()) {
4381     ICS.Standard.ReferenceBinding = true;
4382     ICS.Standard.IsLvalueReference = !isRValRef;
4383     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4384     ICS.Standard.BindsToRvalue = true;
4385     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4386     ICS.Standard.ObjCLifetimeConversionBinding = false;
4387   } else if (ICS.isUserDefined()) {
4388     // Don't allow rvalue references to bind to lvalues.
4389     if (DeclType->isRValueReferenceType()) {
4390       if (const ReferenceType *RefType
4391             = ICS.UserDefined.ConversionFunction->getResultType()
4392                 ->getAs<LValueReferenceType>()) {
4393         if (!RefType->getPointeeType()->isFunctionType()) {
4394           ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4395                      DeclType);
4396           return ICS;
4397         }
4398       }
4399     }
4400 
4401     ICS.UserDefined.After.ReferenceBinding = true;
4402     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4403     ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4404     ICS.UserDefined.After.BindsToRvalue = true;
4405     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4406     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4407   }
4408 
4409   return ICS;
4410 }
4411 
4412 static ImplicitConversionSequence
4413 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4414                       bool SuppressUserConversions,
4415                       bool InOverloadResolution,
4416                       bool AllowObjCWritebackConversion,
4417                       bool AllowExplicit = false);
4418 
4419 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4420 /// initializer list From.
4421 static ImplicitConversionSequence
TryListConversion(Sema & S,InitListExpr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion)4422 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4423                   bool SuppressUserConversions,
4424                   bool InOverloadResolution,
4425                   bool AllowObjCWritebackConversion) {
4426   // C++11 [over.ics.list]p1:
4427   //   When an argument is an initializer list, it is not an expression and
4428   //   special rules apply for converting it to a parameter type.
4429 
4430   ImplicitConversionSequence Result;
4431   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4432   Result.setListInitializationSequence();
4433 
4434   // We need a complete type for what follows. Incomplete types can never be
4435   // initialized from init lists.
4436   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4437     return Result;
4438 
4439   // C++11 [over.ics.list]p2:
4440   //   If the parameter type is std::initializer_list<X> or "array of X" and
4441   //   all the elements can be implicitly converted to X, the implicit
4442   //   conversion sequence is the worst conversion necessary to convert an
4443   //   element of the list to X.
4444   bool toStdInitializerList = false;
4445   QualType X;
4446   if (ToType->isArrayType())
4447     X = S.Context.getAsArrayType(ToType)->getElementType();
4448   else
4449     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4450   if (!X.isNull()) {
4451     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4452       Expr *Init = From->getInit(i);
4453       ImplicitConversionSequence ICS =
4454           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4455                                 InOverloadResolution,
4456                                 AllowObjCWritebackConversion);
4457       // If a single element isn't convertible, fail.
4458       if (ICS.isBad()) {
4459         Result = ICS;
4460         break;
4461       }
4462       // Otherwise, look for the worst conversion.
4463       if (Result.isBad() ||
4464           CompareImplicitConversionSequences(S, ICS, Result) ==
4465               ImplicitConversionSequence::Worse)
4466         Result = ICS;
4467     }
4468 
4469     // For an empty list, we won't have computed any conversion sequence.
4470     // Introduce the identity conversion sequence.
4471     if (From->getNumInits() == 0) {
4472       Result.setStandard();
4473       Result.Standard.setAsIdentityConversion();
4474       Result.Standard.setFromType(ToType);
4475       Result.Standard.setAllToTypes(ToType);
4476     }
4477 
4478     Result.setListInitializationSequence();
4479     Result.setStdInitializerListElement(toStdInitializerList);
4480     return Result;
4481   }
4482 
4483   // C++11 [over.ics.list]p3:
4484   //   Otherwise, if the parameter is a non-aggregate class X and overload
4485   //   resolution chooses a single best constructor [...] the implicit
4486   //   conversion sequence is a user-defined conversion sequence. If multiple
4487   //   constructors are viable but none is better than the others, the
4488   //   implicit conversion sequence is a user-defined conversion sequence.
4489   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4490     // This function can deal with initializer lists.
4491     Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4492                                       /*AllowExplicit=*/false,
4493                                       InOverloadResolution, /*CStyle=*/false,
4494                                       AllowObjCWritebackConversion);
4495     Result.setListInitializationSequence();
4496     return Result;
4497   }
4498 
4499   // C++11 [over.ics.list]p4:
4500   //   Otherwise, if the parameter has an aggregate type which can be
4501   //   initialized from the initializer list [...] the implicit conversion
4502   //   sequence is a user-defined conversion sequence.
4503   if (ToType->isAggregateType()) {
4504     // Type is an aggregate, argument is an init list. At this point it comes
4505     // down to checking whether the initialization works.
4506     // FIXME: Find out whether this parameter is consumed or not.
4507     InitializedEntity Entity =
4508         InitializedEntity::InitializeParameter(S.Context, ToType,
4509                                                /*Consumed=*/false);
4510     if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4511       Result.setUserDefined();
4512       Result.UserDefined.Before.setAsIdentityConversion();
4513       // Initializer lists don't have a type.
4514       Result.UserDefined.Before.setFromType(QualType());
4515       Result.UserDefined.Before.setAllToTypes(QualType());
4516 
4517       Result.UserDefined.After.setAsIdentityConversion();
4518       Result.UserDefined.After.setFromType(ToType);
4519       Result.UserDefined.After.setAllToTypes(ToType);
4520       Result.UserDefined.ConversionFunction = 0;
4521     }
4522     return Result;
4523   }
4524 
4525   // C++11 [over.ics.list]p5:
4526   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4527   if (ToType->isReferenceType()) {
4528     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4529     // mention initializer lists in any way. So we go by what list-
4530     // initialization would do and try to extrapolate from that.
4531 
4532     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4533 
4534     // If the initializer list has a single element that is reference-related
4535     // to the parameter type, we initialize the reference from that.
4536     if (From->getNumInits() == 1) {
4537       Expr *Init = From->getInit(0);
4538 
4539       QualType T2 = Init->getType();
4540 
4541       // If the initializer is the address of an overloaded function, try
4542       // to resolve the overloaded function. If all goes well, T2 is the
4543       // type of the resulting function.
4544       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4545         DeclAccessPair Found;
4546         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4547                                    Init, ToType, false, Found))
4548           T2 = Fn->getType();
4549       }
4550 
4551       // Compute some basic properties of the types and the initializer.
4552       bool dummy1 = false;
4553       bool dummy2 = false;
4554       bool dummy3 = false;
4555       Sema::ReferenceCompareResult RefRelationship
4556         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4557                                          dummy2, dummy3);
4558 
4559       if (RefRelationship >= Sema::Ref_Related)
4560         return TryReferenceInit(S, Init, ToType,
4561                                 /*FIXME:*/From->getLocStart(),
4562                                 SuppressUserConversions,
4563                                 /*AllowExplicit=*/false);
4564     }
4565 
4566     // Otherwise, we bind the reference to a temporary created from the
4567     // initializer list.
4568     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4569                                InOverloadResolution,
4570                                AllowObjCWritebackConversion);
4571     if (Result.isFailure())
4572       return Result;
4573     assert(!Result.isEllipsis() &&
4574            "Sub-initialization cannot result in ellipsis conversion.");
4575 
4576     // Can we even bind to a temporary?
4577     if (ToType->isRValueReferenceType() ||
4578         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4579       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4580                                             Result.UserDefined.After;
4581       SCS.ReferenceBinding = true;
4582       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4583       SCS.BindsToRvalue = true;
4584       SCS.BindsToFunctionLvalue = false;
4585       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4586       SCS.ObjCLifetimeConversionBinding = false;
4587     } else
4588       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4589                     From, ToType);
4590     return Result;
4591   }
4592 
4593   // C++11 [over.ics.list]p6:
4594   //   Otherwise, if the parameter type is not a class:
4595   if (!ToType->isRecordType()) {
4596     //    - if the initializer list has one element, the implicit conversion
4597     //      sequence is the one required to convert the element to the
4598     //      parameter type.
4599     unsigned NumInits = From->getNumInits();
4600     if (NumInits == 1)
4601       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4602                                      SuppressUserConversions,
4603                                      InOverloadResolution,
4604                                      AllowObjCWritebackConversion);
4605     //    - if the initializer list has no elements, the implicit conversion
4606     //      sequence is the identity conversion.
4607     else if (NumInits == 0) {
4608       Result.setStandard();
4609       Result.Standard.setAsIdentityConversion();
4610       Result.Standard.setFromType(ToType);
4611       Result.Standard.setAllToTypes(ToType);
4612     }
4613     Result.setListInitializationSequence();
4614     return Result;
4615   }
4616 
4617   // C++11 [over.ics.list]p7:
4618   //   In all cases other than those enumerated above, no conversion is possible
4619   return Result;
4620 }
4621 
4622 /// TryCopyInitialization - Try to copy-initialize a value of type
4623 /// ToType from the expression From. Return the implicit conversion
4624 /// sequence required to pass this argument, which may be a bad
4625 /// conversion sequence (meaning that the argument cannot be passed to
4626 /// a parameter of this type). If @p SuppressUserConversions, then we
4627 /// do not permit any user-defined conversion sequences.
4628 static ImplicitConversionSequence
TryCopyInitialization(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion,bool AllowExplicit)4629 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4630                       bool SuppressUserConversions,
4631                       bool InOverloadResolution,
4632                       bool AllowObjCWritebackConversion,
4633                       bool AllowExplicit) {
4634   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4635     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4636                              InOverloadResolution,AllowObjCWritebackConversion);
4637 
4638   if (ToType->isReferenceType())
4639     return TryReferenceInit(S, From, ToType,
4640                             /*FIXME:*/From->getLocStart(),
4641                             SuppressUserConversions,
4642                             AllowExplicit);
4643 
4644   return TryImplicitConversion(S, From, ToType,
4645                                SuppressUserConversions,
4646                                /*AllowExplicit=*/false,
4647                                InOverloadResolution,
4648                                /*CStyle=*/false,
4649                                AllowObjCWritebackConversion);
4650 }
4651 
TryCopyInitialization(const CanQualType FromQTy,const CanQualType ToQTy,Sema & S,SourceLocation Loc,ExprValueKind FromVK)4652 static bool TryCopyInitialization(const CanQualType FromQTy,
4653                                   const CanQualType ToQTy,
4654                                   Sema &S,
4655                                   SourceLocation Loc,
4656                                   ExprValueKind FromVK) {
4657   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4658   ImplicitConversionSequence ICS =
4659     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4660 
4661   return !ICS.isBad();
4662 }
4663 
4664 /// TryObjectArgumentInitialization - Try to initialize the object
4665 /// parameter of the given member function (@c Method) from the
4666 /// expression @p From.
4667 static ImplicitConversionSequence
TryObjectArgumentInitialization(Sema & S,QualType FromType,Expr::Classification FromClassification,CXXMethodDecl * Method,CXXRecordDecl * ActingContext)4668 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4669                                 Expr::Classification FromClassification,
4670                                 CXXMethodDecl *Method,
4671                                 CXXRecordDecl *ActingContext) {
4672   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4673   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4674   //                 const volatile object.
4675   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4676     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4677   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4678 
4679   // Set up the conversion sequence as a "bad" conversion, to allow us
4680   // to exit early.
4681   ImplicitConversionSequence ICS;
4682 
4683   // We need to have an object of class type.
4684   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4685     FromType = PT->getPointeeType();
4686 
4687     // When we had a pointer, it's implicitly dereferenced, so we
4688     // better have an lvalue.
4689     assert(FromClassification.isLValue());
4690   }
4691 
4692   assert(FromType->isRecordType());
4693 
4694   // C++0x [over.match.funcs]p4:
4695   //   For non-static member functions, the type of the implicit object
4696   //   parameter is
4697   //
4698   //     - "lvalue reference to cv X" for functions declared without a
4699   //        ref-qualifier or with the & ref-qualifier
4700   //     - "rvalue reference to cv X" for functions declared with the &&
4701   //        ref-qualifier
4702   //
4703   // where X is the class of which the function is a member and cv is the
4704   // cv-qualification on the member function declaration.
4705   //
4706   // However, when finding an implicit conversion sequence for the argument, we
4707   // are not allowed to create temporaries or perform user-defined conversions
4708   // (C++ [over.match.funcs]p5). We perform a simplified version of
4709   // reference binding here, that allows class rvalues to bind to
4710   // non-constant references.
4711 
4712   // First check the qualifiers.
4713   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4714   if (ImplicitParamType.getCVRQualifiers()
4715                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4716       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4717     ICS.setBad(BadConversionSequence::bad_qualifiers,
4718                FromType, ImplicitParamType);
4719     return ICS;
4720   }
4721 
4722   // Check that we have either the same type or a derived type. It
4723   // affects the conversion rank.
4724   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4725   ImplicitConversionKind SecondKind;
4726   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4727     SecondKind = ICK_Identity;
4728   } else if (S.IsDerivedFrom(FromType, ClassType))
4729     SecondKind = ICK_Derived_To_Base;
4730   else {
4731     ICS.setBad(BadConversionSequence::unrelated_class,
4732                FromType, ImplicitParamType);
4733     return ICS;
4734   }
4735 
4736   // Check the ref-qualifier.
4737   switch (Method->getRefQualifier()) {
4738   case RQ_None:
4739     // Do nothing; we don't care about lvalueness or rvalueness.
4740     break;
4741 
4742   case RQ_LValue:
4743     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4744       // non-const lvalue reference cannot bind to an rvalue
4745       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4746                  ImplicitParamType);
4747       return ICS;
4748     }
4749     break;
4750 
4751   case RQ_RValue:
4752     if (!FromClassification.isRValue()) {
4753       // rvalue reference cannot bind to an lvalue
4754       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4755                  ImplicitParamType);
4756       return ICS;
4757     }
4758     break;
4759   }
4760 
4761   // Success. Mark this as a reference binding.
4762   ICS.setStandard();
4763   ICS.Standard.setAsIdentityConversion();
4764   ICS.Standard.Second = SecondKind;
4765   ICS.Standard.setFromType(FromType);
4766   ICS.Standard.setAllToTypes(ImplicitParamType);
4767   ICS.Standard.ReferenceBinding = true;
4768   ICS.Standard.DirectBinding = true;
4769   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4770   ICS.Standard.BindsToFunctionLvalue = false;
4771   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4772   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4773     = (Method->getRefQualifier() == RQ_None);
4774   return ICS;
4775 }
4776 
4777 /// PerformObjectArgumentInitialization - Perform initialization of
4778 /// the implicit object parameter for the given Method with the given
4779 /// expression.
4780 ExprResult
PerformObjectArgumentInitialization(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,CXXMethodDecl * Method)4781 Sema::PerformObjectArgumentInitialization(Expr *From,
4782                                           NestedNameSpecifier *Qualifier,
4783                                           NamedDecl *FoundDecl,
4784                                           CXXMethodDecl *Method) {
4785   QualType FromRecordType, DestType;
4786   QualType ImplicitParamRecordType  =
4787     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4788 
4789   Expr::Classification FromClassification;
4790   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4791     FromRecordType = PT->getPointeeType();
4792     DestType = Method->getThisType(Context);
4793     FromClassification = Expr::Classification::makeSimpleLValue();
4794   } else {
4795     FromRecordType = From->getType();
4796     DestType = ImplicitParamRecordType;
4797     FromClassification = From->Classify(Context);
4798   }
4799 
4800   // Note that we always use the true parent context when performing
4801   // the actual argument initialization.
4802   ImplicitConversionSequence ICS
4803     = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4804                                       Method, Method->getParent());
4805   if (ICS.isBad()) {
4806     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4807       Qualifiers FromQs = FromRecordType.getQualifiers();
4808       Qualifiers ToQs = DestType.getQualifiers();
4809       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4810       if (CVR) {
4811         Diag(From->getLocStart(),
4812              diag::err_member_function_call_bad_cvr)
4813           << Method->getDeclName() << FromRecordType << (CVR - 1)
4814           << From->getSourceRange();
4815         Diag(Method->getLocation(), diag::note_previous_decl)
4816           << Method->getDeclName();
4817         return ExprError();
4818       }
4819     }
4820 
4821     return Diag(From->getLocStart(),
4822                 diag::err_implicit_object_parameter_init)
4823        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4824   }
4825 
4826   if (ICS.Standard.Second == ICK_Derived_To_Base) {
4827     ExprResult FromRes =
4828       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4829     if (FromRes.isInvalid())
4830       return ExprError();
4831     From = FromRes.take();
4832   }
4833 
4834   if (!Context.hasSameType(From->getType(), DestType))
4835     From = ImpCastExprToType(From, DestType, CK_NoOp,
4836                              From->getValueKind()).take();
4837   return Owned(From);
4838 }
4839 
4840 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4841 /// expression From to bool (C++0x [conv]p3).
4842 static ImplicitConversionSequence
TryContextuallyConvertToBool(Sema & S,Expr * From)4843 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4844   // FIXME: This is pretty broken.
4845   return TryImplicitConversion(S, From, S.Context.BoolTy,
4846                                // FIXME: Are these flags correct?
4847                                /*SuppressUserConversions=*/false,
4848                                /*AllowExplicit=*/true,
4849                                /*InOverloadResolution=*/false,
4850                                /*CStyle=*/false,
4851                                /*AllowObjCWritebackConversion=*/false);
4852 }
4853 
4854 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4855 /// of the expression From to bool (C++0x [conv]p3).
PerformContextuallyConvertToBool(Expr * From)4856 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4857   if (checkPlaceholderForOverload(*this, From))
4858     return ExprError();
4859 
4860   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4861   if (!ICS.isBad())
4862     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4863 
4864   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4865     return Diag(From->getLocStart(),
4866                 diag::err_typecheck_bool_condition)
4867                   << From->getType() << From->getSourceRange();
4868   return ExprError();
4869 }
4870 
4871 /// Check that the specified conversion is permitted in a converted constant
4872 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4873 /// is acceptable.
CheckConvertedConstantConversions(Sema & S,StandardConversionSequence & SCS)4874 static bool CheckConvertedConstantConversions(Sema &S,
4875                                               StandardConversionSequence &SCS) {
4876   // Since we know that the target type is an integral or unscoped enumeration
4877   // type, most conversion kinds are impossible. All possible First and Third
4878   // conversions are fine.
4879   switch (SCS.Second) {
4880   case ICK_Identity:
4881   case ICK_Integral_Promotion:
4882   case ICK_Integral_Conversion:
4883   case ICK_Zero_Event_Conversion:
4884     return true;
4885 
4886   case ICK_Boolean_Conversion:
4887     // Conversion from an integral or unscoped enumeration type to bool is
4888     // classified as ICK_Boolean_Conversion, but it's also an integral
4889     // conversion, so it's permitted in a converted constant expression.
4890     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4891            SCS.getToType(2)->isBooleanType();
4892 
4893   case ICK_Floating_Integral:
4894   case ICK_Complex_Real:
4895     return false;
4896 
4897   case ICK_Lvalue_To_Rvalue:
4898   case ICK_Array_To_Pointer:
4899   case ICK_Function_To_Pointer:
4900   case ICK_NoReturn_Adjustment:
4901   case ICK_Qualification:
4902   case ICK_Compatible_Conversion:
4903   case ICK_Vector_Conversion:
4904   case ICK_Vector_Splat:
4905   case ICK_Derived_To_Base:
4906   case ICK_Pointer_Conversion:
4907   case ICK_Pointer_Member:
4908   case ICK_Block_Pointer_Conversion:
4909   case ICK_Writeback_Conversion:
4910   case ICK_Floating_Promotion:
4911   case ICK_Complex_Promotion:
4912   case ICK_Complex_Conversion:
4913   case ICK_Floating_Conversion:
4914   case ICK_TransparentUnionConversion:
4915     llvm_unreachable("unexpected second conversion kind");
4916 
4917   case ICK_Num_Conversion_Kinds:
4918     break;
4919   }
4920 
4921   llvm_unreachable("unknown conversion kind");
4922 }
4923 
4924 /// CheckConvertedConstantExpression - Check that the expression From is a
4925 /// converted constant expression of type T, perform the conversion and produce
4926 /// the converted expression, per C++11 [expr.const]p3.
CheckConvertedConstantExpression(Expr * From,QualType T,llvm::APSInt & Value,CCEKind CCE)4927 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4928                                                   llvm::APSInt &Value,
4929                                                   CCEKind CCE) {
4930   assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4931   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4932 
4933   if (checkPlaceholderForOverload(*this, From))
4934     return ExprError();
4935 
4936   // C++11 [expr.const]p3 with proposed wording fixes:
4937   //  A converted constant expression of type T is a core constant expression,
4938   //  implicitly converted to a prvalue of type T, where the converted
4939   //  expression is a literal constant expression and the implicit conversion
4940   //  sequence contains only user-defined conversions, lvalue-to-rvalue
4941   //  conversions, integral promotions, and integral conversions other than
4942   //  narrowing conversions.
4943   ImplicitConversionSequence ICS =
4944     TryImplicitConversion(From, T,
4945                           /*SuppressUserConversions=*/false,
4946                           /*AllowExplicit=*/false,
4947                           /*InOverloadResolution=*/false,
4948                           /*CStyle=*/false,
4949                           /*AllowObjcWritebackConversion=*/false);
4950   StandardConversionSequence *SCS = 0;
4951   switch (ICS.getKind()) {
4952   case ImplicitConversionSequence::StandardConversion:
4953     if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4954       return Diag(From->getLocStart(),
4955                   diag::err_typecheck_converted_constant_expression_disallowed)
4956                << From->getType() << From->getSourceRange() << T;
4957     SCS = &ICS.Standard;
4958     break;
4959   case ImplicitConversionSequence::UserDefinedConversion:
4960     // We are converting from class type to an integral or enumeration type, so
4961     // the Before sequence must be trivial.
4962     if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4963       return Diag(From->getLocStart(),
4964                   diag::err_typecheck_converted_constant_expression_disallowed)
4965                << From->getType() << From->getSourceRange() << T;
4966     SCS = &ICS.UserDefined.After;
4967     break;
4968   case ImplicitConversionSequence::AmbiguousConversion:
4969   case ImplicitConversionSequence::BadConversion:
4970     if (!DiagnoseMultipleUserDefinedConversion(From, T))
4971       return Diag(From->getLocStart(),
4972                   diag::err_typecheck_converted_constant_expression)
4973                     << From->getType() << From->getSourceRange() << T;
4974     return ExprError();
4975 
4976   case ImplicitConversionSequence::EllipsisConversion:
4977     llvm_unreachable("ellipsis conversion in converted constant expression");
4978   }
4979 
4980   ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4981   if (Result.isInvalid())
4982     return Result;
4983 
4984   // Check for a narrowing implicit conversion.
4985   APValue PreNarrowingValue;
4986   QualType PreNarrowingType;
4987   switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4988                                 PreNarrowingType)) {
4989   case NK_Variable_Narrowing:
4990     // Implicit conversion to a narrower type, and the value is not a constant
4991     // expression. We'll diagnose this in a moment.
4992   case NK_Not_Narrowing:
4993     break;
4994 
4995   case NK_Constant_Narrowing:
4996     Diag(From->getLocStart(),
4997          isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4998                              diag::err_cce_narrowing)
4999       << CCE << /*Constant*/1
5000       << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
5001     break;
5002 
5003   case NK_Type_Narrowing:
5004     Diag(From->getLocStart(),
5005          isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5006                              diag::err_cce_narrowing)
5007       << CCE << /*Constant*/0 << From->getType() << T;
5008     break;
5009   }
5010 
5011   // Check the expression is a constant expression.
5012   SmallVector<PartialDiagnosticAt, 8> Notes;
5013   Expr::EvalResult Eval;
5014   Eval.Diag = &Notes;
5015 
5016   if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
5017     // The expression can't be folded, so we can't keep it at this position in
5018     // the AST.
5019     Result = ExprError();
5020   } else {
5021     Value = Eval.Val.getInt();
5022 
5023     if (Notes.empty()) {
5024       // It's a constant expression.
5025       return Result;
5026     }
5027   }
5028 
5029   // It's not a constant expression. Produce an appropriate diagnostic.
5030   if (Notes.size() == 1 &&
5031       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5032     Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5033   else {
5034     Diag(From->getLocStart(), diag::err_expr_not_cce)
5035       << CCE << From->getSourceRange();
5036     for (unsigned I = 0; I < Notes.size(); ++I)
5037       Diag(Notes[I].first, Notes[I].second);
5038   }
5039   return Result;
5040 }
5041 
5042 /// dropPointerConversions - If the given standard conversion sequence
5043 /// involves any pointer conversions, remove them.  This may change
5044 /// the result type of the conversion sequence.
dropPointerConversion(StandardConversionSequence & SCS)5045 static void dropPointerConversion(StandardConversionSequence &SCS) {
5046   if (SCS.Second == ICK_Pointer_Conversion) {
5047     SCS.Second = ICK_Identity;
5048     SCS.Third = ICK_Identity;
5049     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5050   }
5051 }
5052 
5053 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5054 /// convert the expression From to an Objective-C pointer type.
5055 static ImplicitConversionSequence
TryContextuallyConvertToObjCPointer(Sema & S,Expr * From)5056 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5057   // Do an implicit conversion to 'id'.
5058   QualType Ty = S.Context.getObjCIdType();
5059   ImplicitConversionSequence ICS
5060     = TryImplicitConversion(S, From, Ty,
5061                             // FIXME: Are these flags correct?
5062                             /*SuppressUserConversions=*/false,
5063                             /*AllowExplicit=*/true,
5064                             /*InOverloadResolution=*/false,
5065                             /*CStyle=*/false,
5066                             /*AllowObjCWritebackConversion=*/false);
5067 
5068   // Strip off any final conversions to 'id'.
5069   switch (ICS.getKind()) {
5070   case ImplicitConversionSequence::BadConversion:
5071   case ImplicitConversionSequence::AmbiguousConversion:
5072   case ImplicitConversionSequence::EllipsisConversion:
5073     break;
5074 
5075   case ImplicitConversionSequence::UserDefinedConversion:
5076     dropPointerConversion(ICS.UserDefined.After);
5077     break;
5078 
5079   case ImplicitConversionSequence::StandardConversion:
5080     dropPointerConversion(ICS.Standard);
5081     break;
5082   }
5083 
5084   return ICS;
5085 }
5086 
5087 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5088 /// conversion of the expression From to an Objective-C pointer type.
PerformContextuallyConvertToObjCPointer(Expr * From)5089 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5090   if (checkPlaceholderForOverload(*this, From))
5091     return ExprError();
5092 
5093   QualType Ty = Context.getObjCIdType();
5094   ImplicitConversionSequence ICS =
5095     TryContextuallyConvertToObjCPointer(*this, From);
5096   if (!ICS.isBad())
5097     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5098   return ExprError();
5099 }
5100 
5101 /// Determine whether the provided type is an integral type, or an enumeration
5102 /// type of a permitted flavor.
isIntegralOrEnumerationType(QualType T,bool AllowScopedEnum)5103 static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5104   return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5105                          : T->isIntegralOrUnscopedEnumerationType();
5106 }
5107 
5108 /// \brief Attempt to convert the given expression to an integral or
5109 /// enumeration type.
5110 ///
5111 /// This routine will attempt to convert an expression of class type to an
5112 /// integral or enumeration type, if that class type only has a single
5113 /// conversion to an integral or enumeration type.
5114 ///
5115 /// \param Loc The source location of the construct that requires the
5116 /// conversion.
5117 ///
5118 /// \param From The expression we're converting from.
5119 ///
5120 /// \param Diagnoser Used to output any diagnostics.
5121 ///
5122 /// \param AllowScopedEnumerations Specifies whether conversions to scoped
5123 /// enumerations should be considered.
5124 ///
5125 /// \returns The expression, converted to an integral or enumeration type if
5126 /// successful.
5127 ExprResult
ConvertToIntegralOrEnumerationType(SourceLocation Loc,Expr * From,ICEConvertDiagnoser & Diagnoser,bool AllowScopedEnumerations)5128 Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
5129                                          ICEConvertDiagnoser &Diagnoser,
5130                                          bool AllowScopedEnumerations) {
5131   // We can't perform any more checking for type-dependent expressions.
5132   if (From->isTypeDependent())
5133     return Owned(From);
5134 
5135   // Process placeholders immediately.
5136   if (From->hasPlaceholderType()) {
5137     ExprResult result = CheckPlaceholderExpr(From);
5138     if (result.isInvalid()) return result;
5139     From = result.take();
5140   }
5141 
5142   // If the expression already has integral or enumeration type, we're golden.
5143   QualType T = From->getType();
5144   if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
5145     return DefaultLvalueConversion(From);
5146 
5147   // FIXME: Check for missing '()' if T is a function type?
5148 
5149   // If we don't have a class type in C++, there's no way we can get an
5150   // expression of integral or enumeration type.
5151   const RecordType *RecordTy = T->getAs<RecordType>();
5152   if (!RecordTy || !getLangOpts().CPlusPlus) {
5153     if (!Diagnoser.Suppress)
5154       Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
5155     return Owned(From);
5156   }
5157 
5158   // We must have a complete class type.
5159   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5160     ICEConvertDiagnoser &Diagnoser;
5161     Expr *From;
5162 
5163     TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5164       : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
5165 
5166     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5167       Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5168     }
5169   } IncompleteDiagnoser(Diagnoser, From);
5170 
5171   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5172     return Owned(From);
5173 
5174   // Look for a conversion to an integral or enumeration type.
5175   UnresolvedSet<4> ViableConversions;
5176   UnresolvedSet<4> ExplicitConversions;
5177   std::pair<CXXRecordDecl::conversion_iterator,
5178             CXXRecordDecl::conversion_iterator> Conversions
5179     = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5180 
5181   bool HadMultipleCandidates
5182     = (std::distance(Conversions.first, Conversions.second) > 1);
5183 
5184   for (CXXRecordDecl::conversion_iterator
5185          I = Conversions.first, E = Conversions.second; I != E; ++I) {
5186     if (CXXConversionDecl *Conversion
5187           = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5188       if (isIntegralOrEnumerationType(
5189             Conversion->getConversionType().getNonReferenceType(),
5190             AllowScopedEnumerations)) {
5191         if (Conversion->isExplicit())
5192           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5193         else
5194           ViableConversions.addDecl(I.getDecl(), I.getAccess());
5195       }
5196     }
5197   }
5198 
5199   switch (ViableConversions.size()) {
5200   case 0:
5201     if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
5202       DeclAccessPair Found = ExplicitConversions[0];
5203       CXXConversionDecl *Conversion
5204         = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5205 
5206       // The user probably meant to invoke the given explicit
5207       // conversion; use it.
5208       QualType ConvTy
5209         = Conversion->getConversionType().getNonReferenceType();
5210       std::string TypeStr;
5211       ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
5212 
5213       Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
5214         << FixItHint::CreateInsertion(From->getLocStart(),
5215                                       "static_cast<" + TypeStr + ">(")
5216         << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5217                                       ")");
5218       Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
5219 
5220       // If we aren't in a SFINAE context, build a call to the
5221       // explicit conversion function.
5222       if (isSFINAEContext())
5223         return ExprError();
5224 
5225       CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5226       ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5227                                                  HadMultipleCandidates);
5228       if (Result.isInvalid())
5229         return ExprError();
5230       // Record usage of conversion in an implicit cast.
5231       From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5232                                       CK_UserDefinedConversion,
5233                                       Result.get(), 0,
5234                                       Result.get()->getValueKind());
5235     }
5236 
5237     // We'll complain below about a non-integral condition type.
5238     break;
5239 
5240   case 1: {
5241     // Apply this conversion.
5242     DeclAccessPair Found = ViableConversions[0];
5243     CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5244 
5245     CXXConversionDecl *Conversion
5246       = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5247     QualType ConvTy
5248       = Conversion->getConversionType().getNonReferenceType();
5249     if (!Diagnoser.SuppressConversion) {
5250       if (isSFINAEContext())
5251         return ExprError();
5252 
5253       Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5254         << From->getSourceRange();
5255     }
5256 
5257     ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5258                                                HadMultipleCandidates);
5259     if (Result.isInvalid())
5260       return ExprError();
5261     // Record usage of conversion in an implicit cast.
5262     From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5263                                     CK_UserDefinedConversion,
5264                                     Result.get(), 0,
5265                                     Result.get()->getValueKind());
5266     break;
5267   }
5268 
5269   default:
5270     if (Diagnoser.Suppress)
5271       return ExprError();
5272 
5273     Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
5274     for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5275       CXXConversionDecl *Conv
5276         = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5277       QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5278       Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
5279     }
5280     return Owned(From);
5281   }
5282 
5283   if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5284       !Diagnoser.Suppress) {
5285     Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5286       << From->getSourceRange();
5287   }
5288 
5289   return DefaultLvalueConversion(From);
5290 }
5291 
5292 /// AddOverloadCandidate - Adds the given function to the set of
5293 /// candidate functions, using the given function call arguments.  If
5294 /// @p SuppressUserConversions, then don't allow user-defined
5295 /// conversions via constructors or conversion operators.
5296 ///
5297 /// \param PartialOverloading true if we are performing "partial" overloading
5298 /// based on an incomplete set of function arguments. This feature is used by
5299 /// code completion.
5300 void
AddOverloadCandidate(FunctionDecl * Function,DeclAccessPair FoundDecl,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading,bool AllowExplicit)5301 Sema::AddOverloadCandidate(FunctionDecl *Function,
5302                            DeclAccessPair FoundDecl,
5303                            ArrayRef<Expr *> Args,
5304                            OverloadCandidateSet& CandidateSet,
5305                            bool SuppressUserConversions,
5306                            bool PartialOverloading,
5307                            bool AllowExplicit) {
5308   const FunctionProtoType* Proto
5309     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5310   assert(Proto && "Functions without a prototype cannot be overloaded");
5311   assert(!Function->getDescribedFunctionTemplate() &&
5312          "Use AddTemplateOverloadCandidate for function templates");
5313 
5314   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5315     if (!isa<CXXConstructorDecl>(Method)) {
5316       // If we get here, it's because we're calling a member function
5317       // that is named without a member access expression (e.g.,
5318       // "this->f") that was either written explicitly or created
5319       // implicitly. This can happen with a qualified call to a member
5320       // function, e.g., X::f(). We use an empty type for the implied
5321       // object argument (C++ [over.call.func]p3), and the acting context
5322       // is irrelevant.
5323       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5324                          QualType(), Expr::Classification::makeSimpleLValue(),
5325                          Args, CandidateSet, SuppressUserConversions);
5326       return;
5327     }
5328     // We treat a constructor like a non-member function, since its object
5329     // argument doesn't participate in overload resolution.
5330   }
5331 
5332   if (!CandidateSet.isNewCandidate(Function))
5333     return;
5334 
5335   // Overload resolution is always an unevaluated context.
5336   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5337 
5338   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5339     // C++ [class.copy]p3:
5340     //   A member function template is never instantiated to perform the copy
5341     //   of a class object to an object of its class type.
5342     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5343     if (Args.size() == 1 &&
5344         Constructor->isSpecializationCopyingObject() &&
5345         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5346          IsDerivedFrom(Args[0]->getType(), ClassType)))
5347       return;
5348   }
5349 
5350   // Add this candidate
5351   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5352   Candidate.FoundDecl = FoundDecl;
5353   Candidate.Function = Function;
5354   Candidate.Viable = true;
5355   Candidate.IsSurrogate = false;
5356   Candidate.IgnoreObjectArgument = false;
5357   Candidate.ExplicitCallArguments = Args.size();
5358 
5359   unsigned NumArgsInProto = Proto->getNumArgs();
5360 
5361   // (C++ 13.3.2p2): A candidate function having fewer than m
5362   // parameters is viable only if it has an ellipsis in its parameter
5363   // list (8.3.5).
5364   if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5365       !Proto->isVariadic()) {
5366     Candidate.Viable = false;
5367     Candidate.FailureKind = ovl_fail_too_many_arguments;
5368     return;
5369   }
5370 
5371   // (C++ 13.3.2p2): A candidate function having more than m parameters
5372   // is viable only if the (m+1)st parameter has a default argument
5373   // (8.3.6). For the purposes of overload resolution, the
5374   // parameter list is truncated on the right, so that there are
5375   // exactly m parameters.
5376   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5377   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5378     // Not enough arguments.
5379     Candidate.Viable = false;
5380     Candidate.FailureKind = ovl_fail_too_few_arguments;
5381     return;
5382   }
5383 
5384   // (CUDA B.1): Check for invalid calls between targets.
5385   if (getLangOpts().CUDA)
5386     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5387       if (CheckCUDATarget(Caller, Function)) {
5388         Candidate.Viable = false;
5389         Candidate.FailureKind = ovl_fail_bad_target;
5390         return;
5391       }
5392 
5393   // Determine the implicit conversion sequences for each of the
5394   // arguments.
5395   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5396     if (ArgIdx < NumArgsInProto) {
5397       // (C++ 13.3.2p3): for F to be a viable function, there shall
5398       // exist for each argument an implicit conversion sequence
5399       // (13.3.3.1) that converts that argument to the corresponding
5400       // parameter of F.
5401       QualType ParamType = Proto->getArgType(ArgIdx);
5402       Candidate.Conversions[ArgIdx]
5403         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5404                                 SuppressUserConversions,
5405                                 /*InOverloadResolution=*/true,
5406                                 /*AllowObjCWritebackConversion=*/
5407                                   getLangOpts().ObjCAutoRefCount,
5408                                 AllowExplicit);
5409       if (Candidate.Conversions[ArgIdx].isBad()) {
5410         Candidate.Viable = false;
5411         Candidate.FailureKind = ovl_fail_bad_conversion;
5412         break;
5413       }
5414     } else {
5415       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5416       // argument for which there is no corresponding parameter is
5417       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5418       Candidate.Conversions[ArgIdx].setEllipsis();
5419     }
5420   }
5421 }
5422 
5423 /// \brief Add all of the function declarations in the given function set to
5424 /// the overload canddiate set.
AddFunctionCandidates(const UnresolvedSetImpl & Fns,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,TemplateArgumentListInfo * ExplicitTemplateArgs)5425 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5426                                  ArrayRef<Expr *> Args,
5427                                  OverloadCandidateSet& CandidateSet,
5428                                  bool SuppressUserConversions,
5429                                TemplateArgumentListInfo *ExplicitTemplateArgs) {
5430   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5431     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5432     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5433       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5434         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5435                            cast<CXXMethodDecl>(FD)->getParent(),
5436                            Args[0]->getType(), Args[0]->Classify(Context),
5437                            Args.slice(1), CandidateSet,
5438                            SuppressUserConversions);
5439       else
5440         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5441                              SuppressUserConversions);
5442     } else {
5443       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5444       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5445           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5446         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5447                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5448                                    ExplicitTemplateArgs,
5449                                    Args[0]->getType(),
5450                                    Args[0]->Classify(Context), Args.slice(1),
5451                                    CandidateSet, SuppressUserConversions);
5452       else
5453         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5454                                      ExplicitTemplateArgs, Args,
5455                                      CandidateSet, SuppressUserConversions);
5456     }
5457   }
5458 }
5459 
5460 /// AddMethodCandidate - Adds a named decl (which is some kind of
5461 /// method) as a method candidate to the given overload set.
AddMethodCandidate(DeclAccessPair FoundDecl,QualType ObjectType,Expr::Classification ObjectClassification,Expr ** Args,unsigned NumArgs,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions)5462 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5463                               QualType ObjectType,
5464                               Expr::Classification ObjectClassification,
5465                               Expr **Args, unsigned NumArgs,
5466                               OverloadCandidateSet& CandidateSet,
5467                               bool SuppressUserConversions) {
5468   NamedDecl *Decl = FoundDecl.getDecl();
5469   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5470 
5471   if (isa<UsingShadowDecl>(Decl))
5472     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5473 
5474   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5475     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5476            "Expected a member function template");
5477     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5478                                /*ExplicitArgs*/ 0,
5479                                ObjectType, ObjectClassification,
5480                                llvm::makeArrayRef(Args, NumArgs), CandidateSet,
5481                                SuppressUserConversions);
5482   } else {
5483     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5484                        ObjectType, ObjectClassification,
5485                        llvm::makeArrayRef(Args, NumArgs),
5486                        CandidateSet, SuppressUserConversions);
5487   }
5488 }
5489 
5490 /// AddMethodCandidate - Adds the given C++ member function to the set
5491 /// of candidate functions, using the given function call arguments
5492 /// and the object argument (@c Object). For example, in a call
5493 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5494 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5495 /// allow user-defined conversions via constructors or conversion
5496 /// operators.
5497 void
AddMethodCandidate(CXXMethodDecl * Method,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions)5498 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5499                          CXXRecordDecl *ActingContext, QualType ObjectType,
5500                          Expr::Classification ObjectClassification,
5501                          ArrayRef<Expr *> Args,
5502                          OverloadCandidateSet& CandidateSet,
5503                          bool SuppressUserConversions) {
5504   const FunctionProtoType* Proto
5505     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5506   assert(Proto && "Methods without a prototype cannot be overloaded");
5507   assert(!isa<CXXConstructorDecl>(Method) &&
5508          "Use AddOverloadCandidate for constructors");
5509 
5510   if (!CandidateSet.isNewCandidate(Method))
5511     return;
5512 
5513   // Overload resolution is always an unevaluated context.
5514   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5515 
5516   // Add this candidate
5517   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5518   Candidate.FoundDecl = FoundDecl;
5519   Candidate.Function = Method;
5520   Candidate.IsSurrogate = false;
5521   Candidate.IgnoreObjectArgument = false;
5522   Candidate.ExplicitCallArguments = Args.size();
5523 
5524   unsigned NumArgsInProto = Proto->getNumArgs();
5525 
5526   // (C++ 13.3.2p2): A candidate function having fewer than m
5527   // parameters is viable only if it has an ellipsis in its parameter
5528   // list (8.3.5).
5529   if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5530     Candidate.Viable = false;
5531     Candidate.FailureKind = ovl_fail_too_many_arguments;
5532     return;
5533   }
5534 
5535   // (C++ 13.3.2p2): A candidate function having more than m parameters
5536   // is viable only if the (m+1)st parameter has a default argument
5537   // (8.3.6). For the purposes of overload resolution, the
5538   // parameter list is truncated on the right, so that there are
5539   // exactly m parameters.
5540   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5541   if (Args.size() < MinRequiredArgs) {
5542     // Not enough arguments.
5543     Candidate.Viable = false;
5544     Candidate.FailureKind = ovl_fail_too_few_arguments;
5545     return;
5546   }
5547 
5548   Candidate.Viable = true;
5549 
5550   if (Method->isStatic() || ObjectType.isNull())
5551     // The implicit object argument is ignored.
5552     Candidate.IgnoreObjectArgument = true;
5553   else {
5554     // Determine the implicit conversion sequence for the object
5555     // parameter.
5556     Candidate.Conversions[0]
5557       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5558                                         Method, ActingContext);
5559     if (Candidate.Conversions[0].isBad()) {
5560       Candidate.Viable = false;
5561       Candidate.FailureKind = ovl_fail_bad_conversion;
5562       return;
5563     }
5564   }
5565 
5566   // Determine the implicit conversion sequences for each of the
5567   // arguments.
5568   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5569     if (ArgIdx < NumArgsInProto) {
5570       // (C++ 13.3.2p3): for F to be a viable function, there shall
5571       // exist for each argument an implicit conversion sequence
5572       // (13.3.3.1) that converts that argument to the corresponding
5573       // parameter of F.
5574       QualType ParamType = Proto->getArgType(ArgIdx);
5575       Candidate.Conversions[ArgIdx + 1]
5576         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5577                                 SuppressUserConversions,
5578                                 /*InOverloadResolution=*/true,
5579                                 /*AllowObjCWritebackConversion=*/
5580                                   getLangOpts().ObjCAutoRefCount);
5581       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5582         Candidate.Viable = false;
5583         Candidate.FailureKind = ovl_fail_bad_conversion;
5584         break;
5585       }
5586     } else {
5587       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5588       // argument for which there is no corresponding parameter is
5589       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5590       Candidate.Conversions[ArgIdx + 1].setEllipsis();
5591     }
5592   }
5593 }
5594 
5595 /// \brief Add a C++ member function template as a candidate to the candidate
5596 /// set, using template argument deduction to produce an appropriate member
5597 /// function template specialization.
5598 void
AddMethodTemplateCandidate(FunctionTemplateDecl * MethodTmpl,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,TemplateArgumentListInfo * ExplicitTemplateArgs,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions)5599 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5600                                  DeclAccessPair FoundDecl,
5601                                  CXXRecordDecl *ActingContext,
5602                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5603                                  QualType ObjectType,
5604                                  Expr::Classification ObjectClassification,
5605                                  ArrayRef<Expr *> Args,
5606                                  OverloadCandidateSet& CandidateSet,
5607                                  bool SuppressUserConversions) {
5608   if (!CandidateSet.isNewCandidate(MethodTmpl))
5609     return;
5610 
5611   // C++ [over.match.funcs]p7:
5612   //   In each case where a candidate is a function template, candidate
5613   //   function template specializations are generated using template argument
5614   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5615   //   candidate functions in the usual way.113) A given name can refer to one
5616   //   or more function templates and also to a set of overloaded non-template
5617   //   functions. In such a case, the candidate functions generated from each
5618   //   function template are combined with the set of non-template candidate
5619   //   functions.
5620   TemplateDeductionInfo Info(CandidateSet.getLocation());
5621   FunctionDecl *Specialization = 0;
5622   if (TemplateDeductionResult Result
5623       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5624                                 Specialization, Info)) {
5625     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5626     Candidate.FoundDecl = FoundDecl;
5627     Candidate.Function = MethodTmpl->getTemplatedDecl();
5628     Candidate.Viable = false;
5629     Candidate.FailureKind = ovl_fail_bad_deduction;
5630     Candidate.IsSurrogate = false;
5631     Candidate.IgnoreObjectArgument = false;
5632     Candidate.ExplicitCallArguments = Args.size();
5633     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5634                                                           Info);
5635     return;
5636   }
5637 
5638   // Add the function template specialization produced by template argument
5639   // deduction as a candidate.
5640   assert(Specialization && "Missing member function template specialization?");
5641   assert(isa<CXXMethodDecl>(Specialization) &&
5642          "Specialization is not a member function?");
5643   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5644                      ActingContext, ObjectType, ObjectClassification, Args,
5645                      CandidateSet, SuppressUserConversions);
5646 }
5647 
5648 /// \brief Add a C++ function template specialization as a candidate
5649 /// in the candidate set, using template argument deduction to produce
5650 /// an appropriate function template specialization.
5651 void
AddTemplateOverloadCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions)5652 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5653                                    DeclAccessPair FoundDecl,
5654                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5655                                    ArrayRef<Expr *> Args,
5656                                    OverloadCandidateSet& CandidateSet,
5657                                    bool SuppressUserConversions) {
5658   if (!CandidateSet.isNewCandidate(FunctionTemplate))
5659     return;
5660 
5661   // C++ [over.match.funcs]p7:
5662   //   In each case where a candidate is a function template, candidate
5663   //   function template specializations are generated using template argument
5664   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5665   //   candidate functions in the usual way.113) A given name can refer to one
5666   //   or more function templates and also to a set of overloaded non-template
5667   //   functions. In such a case, the candidate functions generated from each
5668   //   function template are combined with the set of non-template candidate
5669   //   functions.
5670   TemplateDeductionInfo Info(CandidateSet.getLocation());
5671   FunctionDecl *Specialization = 0;
5672   if (TemplateDeductionResult Result
5673         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5674                                   Specialization, Info)) {
5675     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5676     Candidate.FoundDecl = FoundDecl;
5677     Candidate.Function = FunctionTemplate->getTemplatedDecl();
5678     Candidate.Viable = false;
5679     Candidate.FailureKind = ovl_fail_bad_deduction;
5680     Candidate.IsSurrogate = false;
5681     Candidate.IgnoreObjectArgument = false;
5682     Candidate.ExplicitCallArguments = Args.size();
5683     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5684                                                           Info);
5685     return;
5686   }
5687 
5688   // Add the function template specialization produced by template argument
5689   // deduction as a candidate.
5690   assert(Specialization && "Missing function template specialization?");
5691   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5692                        SuppressUserConversions);
5693 }
5694 
5695 /// AddConversionCandidate - Add a C++ conversion function as a
5696 /// candidate in the candidate set (C++ [over.match.conv],
5697 /// C++ [over.match.copy]). From is the expression we're converting from,
5698 /// and ToType is the type that we're eventually trying to convert to
5699 /// (which may or may not be the same type as the type that the
5700 /// conversion function produces).
5701 void
AddConversionCandidate(CXXConversionDecl * Conversion,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet)5702 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5703                              DeclAccessPair FoundDecl,
5704                              CXXRecordDecl *ActingContext,
5705                              Expr *From, QualType ToType,
5706                              OverloadCandidateSet& CandidateSet) {
5707   assert(!Conversion->getDescribedFunctionTemplate() &&
5708          "Conversion function templates use AddTemplateConversionCandidate");
5709   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5710   if (!CandidateSet.isNewCandidate(Conversion))
5711     return;
5712 
5713   // Overload resolution is always an unevaluated context.
5714   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5715 
5716   // Add this candidate
5717   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5718   Candidate.FoundDecl = FoundDecl;
5719   Candidate.Function = Conversion;
5720   Candidate.IsSurrogate = false;
5721   Candidate.IgnoreObjectArgument = false;
5722   Candidate.FinalConversion.setAsIdentityConversion();
5723   Candidate.FinalConversion.setFromType(ConvType);
5724   Candidate.FinalConversion.setAllToTypes(ToType);
5725   Candidate.Viable = true;
5726   Candidate.ExplicitCallArguments = 1;
5727 
5728   // C++ [over.match.funcs]p4:
5729   //   For conversion functions, the function is considered to be a member of
5730   //   the class of the implicit implied object argument for the purpose of
5731   //   defining the type of the implicit object parameter.
5732   //
5733   // Determine the implicit conversion sequence for the implicit
5734   // object parameter.
5735   QualType ImplicitParamType = From->getType();
5736   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5737     ImplicitParamType = FromPtrType->getPointeeType();
5738   CXXRecordDecl *ConversionContext
5739     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5740 
5741   Candidate.Conversions[0]
5742     = TryObjectArgumentInitialization(*this, From->getType(),
5743                                       From->Classify(Context),
5744                                       Conversion, ConversionContext);
5745 
5746   if (Candidate.Conversions[0].isBad()) {
5747     Candidate.Viable = false;
5748     Candidate.FailureKind = ovl_fail_bad_conversion;
5749     return;
5750   }
5751 
5752   // We won't go through a user-define type conversion function to convert a
5753   // derived to base as such conversions are given Conversion Rank. They only
5754   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5755   QualType FromCanon
5756     = Context.getCanonicalType(From->getType().getUnqualifiedType());
5757   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5758   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5759     Candidate.Viable = false;
5760     Candidate.FailureKind = ovl_fail_trivial_conversion;
5761     return;
5762   }
5763 
5764   // To determine what the conversion from the result of calling the
5765   // conversion function to the type we're eventually trying to
5766   // convert to (ToType), we need to synthesize a call to the
5767   // conversion function and attempt copy initialization from it. This
5768   // makes sure that we get the right semantics with respect to
5769   // lvalues/rvalues and the type. Fortunately, we can allocate this
5770   // call on the stack and we don't need its arguments to be
5771   // well-formed.
5772   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5773                             VK_LValue, From->getLocStart());
5774   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5775                                 Context.getPointerType(Conversion->getType()),
5776                                 CK_FunctionToPointerDecay,
5777                                 &ConversionRef, VK_RValue);
5778 
5779   QualType ConversionType = Conversion->getConversionType();
5780   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5781     Candidate.Viable = false;
5782     Candidate.FailureKind = ovl_fail_bad_final_conversion;
5783     return;
5784   }
5785 
5786   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5787 
5788   // Note that it is safe to allocate CallExpr on the stack here because
5789   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5790   // allocator).
5791   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5792   CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
5793                 From->getLocStart());
5794   ImplicitConversionSequence ICS =
5795     TryCopyInitialization(*this, &Call, ToType,
5796                           /*SuppressUserConversions=*/true,
5797                           /*InOverloadResolution=*/false,
5798                           /*AllowObjCWritebackConversion=*/false);
5799 
5800   switch (ICS.getKind()) {
5801   case ImplicitConversionSequence::StandardConversion:
5802     Candidate.FinalConversion = ICS.Standard;
5803 
5804     // C++ [over.ics.user]p3:
5805     //   If the user-defined conversion is specified by a specialization of a
5806     //   conversion function template, the second standard conversion sequence
5807     //   shall have exact match rank.
5808     if (Conversion->getPrimaryTemplate() &&
5809         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5810       Candidate.Viable = false;
5811       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5812     }
5813 
5814     // C++0x [dcl.init.ref]p5:
5815     //    In the second case, if the reference is an rvalue reference and
5816     //    the second standard conversion sequence of the user-defined
5817     //    conversion sequence includes an lvalue-to-rvalue conversion, the
5818     //    program is ill-formed.
5819     if (ToType->isRValueReferenceType() &&
5820         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5821       Candidate.Viable = false;
5822       Candidate.FailureKind = ovl_fail_bad_final_conversion;
5823     }
5824     break;
5825 
5826   case ImplicitConversionSequence::BadConversion:
5827     Candidate.Viable = false;
5828     Candidate.FailureKind = ovl_fail_bad_final_conversion;
5829     break;
5830 
5831   default:
5832     llvm_unreachable(
5833            "Can only end up with a standard conversion sequence or failure");
5834   }
5835 }
5836 
5837 /// \brief Adds a conversion function template specialization
5838 /// candidate to the overload set, using template argument deduction
5839 /// to deduce the template arguments of the conversion function
5840 /// template from the type that we are converting to (C++
5841 /// [temp.deduct.conv]).
5842 void
AddTemplateConversionCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,CXXRecordDecl * ActingDC,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet)5843 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
5844                                      DeclAccessPair FoundDecl,
5845                                      CXXRecordDecl *ActingDC,
5846                                      Expr *From, QualType ToType,
5847                                      OverloadCandidateSet &CandidateSet) {
5848   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5849          "Only conversion function templates permitted here");
5850 
5851   if (!CandidateSet.isNewCandidate(FunctionTemplate))
5852     return;
5853 
5854   TemplateDeductionInfo Info(CandidateSet.getLocation());
5855   CXXConversionDecl *Specialization = 0;
5856   if (TemplateDeductionResult Result
5857         = DeduceTemplateArguments(FunctionTemplate, ToType,
5858                                   Specialization, Info)) {
5859     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5860     Candidate.FoundDecl = FoundDecl;
5861     Candidate.Function = FunctionTemplate->getTemplatedDecl();
5862     Candidate.Viable = false;
5863     Candidate.FailureKind = ovl_fail_bad_deduction;
5864     Candidate.IsSurrogate = false;
5865     Candidate.IgnoreObjectArgument = false;
5866     Candidate.ExplicitCallArguments = 1;
5867     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5868                                                           Info);
5869     return;
5870   }
5871 
5872   // Add the conversion function template specialization produced by
5873   // template argument deduction as a candidate.
5874   assert(Specialization && "Missing function template specialization?");
5875   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
5876                          CandidateSet);
5877 }
5878 
5879 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5880 /// converts the given @c Object to a function pointer via the
5881 /// conversion function @c Conversion, and then attempts to call it
5882 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
5883 /// 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)5884 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
5885                                  DeclAccessPair FoundDecl,
5886                                  CXXRecordDecl *ActingContext,
5887                                  const FunctionProtoType *Proto,
5888                                  Expr *Object,
5889                                  ArrayRef<Expr *> Args,
5890                                  OverloadCandidateSet& CandidateSet) {
5891   if (!CandidateSet.isNewCandidate(Conversion))
5892     return;
5893 
5894   // Overload resolution is always an unevaluated context.
5895   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5896 
5897   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5898   Candidate.FoundDecl = FoundDecl;
5899   Candidate.Function = 0;
5900   Candidate.Surrogate = Conversion;
5901   Candidate.Viable = true;
5902   Candidate.IsSurrogate = true;
5903   Candidate.IgnoreObjectArgument = false;
5904   Candidate.ExplicitCallArguments = Args.size();
5905 
5906   // Determine the implicit conversion sequence for the implicit
5907   // object parameter.
5908   ImplicitConversionSequence ObjectInit
5909     = TryObjectArgumentInitialization(*this, Object->getType(),
5910                                       Object->Classify(Context),
5911                                       Conversion, ActingContext);
5912   if (ObjectInit.isBad()) {
5913     Candidate.Viable = false;
5914     Candidate.FailureKind = ovl_fail_bad_conversion;
5915     Candidate.Conversions[0] = ObjectInit;
5916     return;
5917   }
5918 
5919   // The first conversion is actually a user-defined conversion whose
5920   // first conversion is ObjectInit's standard conversion (which is
5921   // effectively a reference binding). Record it as such.
5922   Candidate.Conversions[0].setUserDefined();
5923   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
5924   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
5925   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
5926   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
5927   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
5928   Candidate.Conversions[0].UserDefined.After
5929     = Candidate.Conversions[0].UserDefined.Before;
5930   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5931 
5932   // Find the
5933   unsigned NumArgsInProto = Proto->getNumArgs();
5934 
5935   // (C++ 13.3.2p2): A candidate function having fewer than m
5936   // parameters is viable only if it has an ellipsis in its parameter
5937   // list (8.3.5).
5938   if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5939     Candidate.Viable = false;
5940     Candidate.FailureKind = ovl_fail_too_many_arguments;
5941     return;
5942   }
5943 
5944   // Function types don't have any default arguments, so just check if
5945   // we have enough arguments.
5946   if (Args.size() < NumArgsInProto) {
5947     // Not enough arguments.
5948     Candidate.Viable = false;
5949     Candidate.FailureKind = ovl_fail_too_few_arguments;
5950     return;
5951   }
5952 
5953   // Determine the implicit conversion sequences for each of the
5954   // arguments.
5955   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5956     if (ArgIdx < NumArgsInProto) {
5957       // (C++ 13.3.2p3): for F to be a viable function, there shall
5958       // exist for each argument an implicit conversion sequence
5959       // (13.3.3.1) that converts that argument to the corresponding
5960       // parameter of F.
5961       QualType ParamType = Proto->getArgType(ArgIdx);
5962       Candidate.Conversions[ArgIdx + 1]
5963         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5964                                 /*SuppressUserConversions=*/false,
5965                                 /*InOverloadResolution=*/false,
5966                                 /*AllowObjCWritebackConversion=*/
5967                                   getLangOpts().ObjCAutoRefCount);
5968       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5969         Candidate.Viable = false;
5970         Candidate.FailureKind = ovl_fail_bad_conversion;
5971         break;
5972       }
5973     } else {
5974       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5975       // argument for which there is no corresponding parameter is
5976       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5977       Candidate.Conversions[ArgIdx + 1].setEllipsis();
5978     }
5979   }
5980 }
5981 
5982 /// \brief Add overload candidates for overloaded operators that are
5983 /// member functions.
5984 ///
5985 /// Add the overloaded operator candidates that are member functions
5986 /// for the operator Op that was used in an operator expression such
5987 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
5988 /// CandidateSet will store the added overload candidates. (C++
5989 /// [over.match.oper]).
AddMemberOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,Expr ** Args,unsigned NumArgs,OverloadCandidateSet & CandidateSet,SourceRange OpRange)5990 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5991                                        SourceLocation OpLoc,
5992                                        Expr **Args, unsigned NumArgs,
5993                                        OverloadCandidateSet& CandidateSet,
5994                                        SourceRange OpRange) {
5995   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5996 
5997   // C++ [over.match.oper]p3:
5998   //   For a unary operator @ with an operand of a type whose
5999   //   cv-unqualified version is T1, and for a binary operator @ with
6000   //   a left operand of a type whose cv-unqualified version is T1 and
6001   //   a right operand of a type whose cv-unqualified version is T2,
6002   //   three sets of candidate functions, designated member
6003   //   candidates, non-member candidates and built-in candidates, are
6004   //   constructed as follows:
6005   QualType T1 = Args[0]->getType();
6006 
6007   //     -- If T1 is a class type, the set of member candidates is the
6008   //        result of the qualified lookup of T1::operator@
6009   //        (13.3.1.1.1); otherwise, the set of member candidates is
6010   //        empty.
6011   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6012     // Complete the type if it can be completed. Otherwise, we're done.
6013     if (RequireCompleteType(OpLoc, T1, 0))
6014       return;
6015 
6016     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6017     LookupQualifiedName(Operators, T1Rec->getDecl());
6018     Operators.suppressDiagnostics();
6019 
6020     for (LookupResult::iterator Oper = Operators.begin(),
6021                              OperEnd = Operators.end();
6022          Oper != OperEnd;
6023          ++Oper)
6024       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6025                          Args[0]->Classify(Context), Args + 1, NumArgs - 1,
6026                          CandidateSet,
6027                          /* SuppressUserConversions = */ false);
6028   }
6029 }
6030 
6031 /// AddBuiltinCandidate - Add a candidate for a built-in
6032 /// operator. ResultTy and ParamTys are the result and parameter types
6033 /// of the built-in candidate, respectively. Args and NumArgs are the
6034 /// arguments being passed to the candidate. IsAssignmentOperator
6035 /// should be true when this built-in candidate is an assignment
6036 /// operator. NumContextualBoolArguments is the number of arguments
6037 /// (at the beginning of the argument list) that will be contextually
6038 /// converted to bool.
AddBuiltinCandidate(QualType ResultTy,QualType * ParamTys,Expr ** Args,unsigned NumArgs,OverloadCandidateSet & CandidateSet,bool IsAssignmentOperator,unsigned NumContextualBoolArguments)6039 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6040                                Expr **Args, unsigned NumArgs,
6041                                OverloadCandidateSet& CandidateSet,
6042                                bool IsAssignmentOperator,
6043                                unsigned NumContextualBoolArguments) {
6044   // Overload resolution is always an unevaluated context.
6045   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6046 
6047   // Add this candidate
6048   OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
6049   Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
6050   Candidate.Function = 0;
6051   Candidate.IsSurrogate = false;
6052   Candidate.IgnoreObjectArgument = false;
6053   Candidate.BuiltinTypes.ResultTy = ResultTy;
6054   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6055     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6056 
6057   // Determine the implicit conversion sequences for each of the
6058   // arguments.
6059   Candidate.Viable = true;
6060   Candidate.ExplicitCallArguments = NumArgs;
6061   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6062     // C++ [over.match.oper]p4:
6063     //   For the built-in assignment operators, conversions of the
6064     //   left operand are restricted as follows:
6065     //     -- no temporaries are introduced to hold the left operand, and
6066     //     -- no user-defined conversions are applied to the left
6067     //        operand to achieve a type match with the left-most
6068     //        parameter of a built-in candidate.
6069     //
6070     // We block these conversions by turning off user-defined
6071     // conversions, since that is the only way that initialization of
6072     // a reference to a non-class type can occur from something that
6073     // is not of the same type.
6074     if (ArgIdx < NumContextualBoolArguments) {
6075       assert(ParamTys[ArgIdx] == Context.BoolTy &&
6076              "Contextual conversion to bool requires bool type");
6077       Candidate.Conversions[ArgIdx]
6078         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6079     } else {
6080       Candidate.Conversions[ArgIdx]
6081         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6082                                 ArgIdx == 0 && IsAssignmentOperator,
6083                                 /*InOverloadResolution=*/false,
6084                                 /*AllowObjCWritebackConversion=*/
6085                                   getLangOpts().ObjCAutoRefCount);
6086     }
6087     if (Candidate.Conversions[ArgIdx].isBad()) {
6088       Candidate.Viable = false;
6089       Candidate.FailureKind = ovl_fail_bad_conversion;
6090       break;
6091     }
6092   }
6093 }
6094 
6095 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6096 /// candidate operator functions for built-in operators (C++
6097 /// [over.built]). The types are separated into pointer types and
6098 /// enumeration types.
6099 class BuiltinCandidateTypeSet  {
6100   /// TypeSet - A set of types.
6101   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6102 
6103   /// PointerTypes - The set of pointer types that will be used in the
6104   /// built-in candidates.
6105   TypeSet PointerTypes;
6106 
6107   /// MemberPointerTypes - The set of member pointer types that will be
6108   /// used in the built-in candidates.
6109   TypeSet MemberPointerTypes;
6110 
6111   /// EnumerationTypes - The set of enumeration types that will be
6112   /// used in the built-in candidates.
6113   TypeSet EnumerationTypes;
6114 
6115   /// \brief The set of vector types that will be used in the built-in
6116   /// candidates.
6117   TypeSet VectorTypes;
6118 
6119   /// \brief A flag indicating non-record types are viable candidates
6120   bool HasNonRecordTypes;
6121 
6122   /// \brief A flag indicating whether either arithmetic or enumeration types
6123   /// were present in the candidate set.
6124   bool HasArithmeticOrEnumeralTypes;
6125 
6126   /// \brief A flag indicating whether the nullptr type was present in the
6127   /// candidate set.
6128   bool HasNullPtrType;
6129 
6130   /// Sema - The semantic analysis instance where we are building the
6131   /// candidate type set.
6132   Sema &SemaRef;
6133 
6134   /// Context - The AST context in which we will build the type sets.
6135   ASTContext &Context;
6136 
6137   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6138                                                const Qualifiers &VisibleQuals);
6139   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6140 
6141 public:
6142   /// iterator - Iterates through the types that are part of the set.
6143   typedef TypeSet::iterator iterator;
6144 
BuiltinCandidateTypeSet(Sema & SemaRef)6145   BuiltinCandidateTypeSet(Sema &SemaRef)
6146     : HasNonRecordTypes(false),
6147       HasArithmeticOrEnumeralTypes(false),
6148       HasNullPtrType(false),
6149       SemaRef(SemaRef),
6150       Context(SemaRef.Context) { }
6151 
6152   void AddTypesConvertedFrom(QualType Ty,
6153                              SourceLocation Loc,
6154                              bool AllowUserConversions,
6155                              bool AllowExplicitConversions,
6156                              const Qualifiers &VisibleTypeConversionsQuals);
6157 
6158   /// pointer_begin - First pointer type found;
pointer_begin()6159   iterator pointer_begin() { return PointerTypes.begin(); }
6160 
6161   /// pointer_end - Past the last pointer type found;
pointer_end()6162   iterator pointer_end() { return PointerTypes.end(); }
6163 
6164   /// member_pointer_begin - First member pointer type found;
member_pointer_begin()6165   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6166 
6167   /// member_pointer_end - Past the last member pointer type found;
member_pointer_end()6168   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6169 
6170   /// enumeration_begin - First enumeration type found;
enumeration_begin()6171   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6172 
6173   /// enumeration_end - Past the last enumeration type found;
enumeration_end()6174   iterator enumeration_end() { return EnumerationTypes.end(); }
6175 
vector_begin()6176   iterator vector_begin() { return VectorTypes.begin(); }
vector_end()6177   iterator vector_end() { return VectorTypes.end(); }
6178 
hasNonRecordTypes()6179   bool hasNonRecordTypes() { return HasNonRecordTypes; }
hasArithmeticOrEnumeralTypes()6180   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
hasNullPtrType() const6181   bool hasNullPtrType() const { return HasNullPtrType; }
6182 };
6183 
6184 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6185 /// the set of pointer types along with any more-qualified variants of
6186 /// that type. For example, if @p Ty is "int const *", this routine
6187 /// will add "int const *", "int const volatile *", "int const
6188 /// restrict *", and "int const volatile restrict *" to the set of
6189 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6190 /// false otherwise.
6191 ///
6192 /// FIXME: what to do about extended qualifiers?
6193 bool
AddPointerWithMoreQualifiedTypeVariants(QualType Ty,const Qualifiers & VisibleQuals)6194 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6195                                              const Qualifiers &VisibleQuals) {
6196 
6197   // Insert this type.
6198   if (!PointerTypes.insert(Ty))
6199     return false;
6200 
6201   QualType PointeeTy;
6202   const PointerType *PointerTy = Ty->getAs<PointerType>();
6203   bool buildObjCPtr = false;
6204   if (!PointerTy) {
6205     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6206     PointeeTy = PTy->getPointeeType();
6207     buildObjCPtr = true;
6208   } else {
6209     PointeeTy = PointerTy->getPointeeType();
6210   }
6211 
6212   // Don't add qualified variants of arrays. For one, they're not allowed
6213   // (the qualifier would sink to the element type), and for another, the
6214   // only overload situation where it matters is subscript or pointer +- int,
6215   // and those shouldn't have qualifier variants anyway.
6216   if (PointeeTy->isArrayType())
6217     return true;
6218 
6219   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6220   bool hasVolatile = VisibleQuals.hasVolatile();
6221   bool hasRestrict = VisibleQuals.hasRestrict();
6222 
6223   // Iterate through all strict supersets of BaseCVR.
6224   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6225     if ((CVR | BaseCVR) != CVR) continue;
6226     // Skip over volatile if no volatile found anywhere in the types.
6227     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6228 
6229     // Skip over restrict if no restrict found anywhere in the types, or if
6230     // the type cannot be restrict-qualified.
6231     if ((CVR & Qualifiers::Restrict) &&
6232         (!hasRestrict ||
6233          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6234       continue;
6235 
6236     // Build qualified pointee type.
6237     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6238 
6239     // Build qualified pointer type.
6240     QualType QPointerTy;
6241     if (!buildObjCPtr)
6242       QPointerTy = Context.getPointerType(QPointeeTy);
6243     else
6244       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6245 
6246     // Insert qualified pointer type.
6247     PointerTypes.insert(QPointerTy);
6248   }
6249 
6250   return true;
6251 }
6252 
6253 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6254 /// to the set of pointer types along with any more-qualified variants of
6255 /// that type. For example, if @p Ty is "int const *", this routine
6256 /// will add "int const *", "int const volatile *", "int const
6257 /// restrict *", and "int const volatile restrict *" to the set of
6258 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6259 /// false otherwise.
6260 ///
6261 /// FIXME: what to do about extended qualifiers?
6262 bool
AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty)6263 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6264     QualType Ty) {
6265   // Insert this type.
6266   if (!MemberPointerTypes.insert(Ty))
6267     return false;
6268 
6269   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6270   assert(PointerTy && "type was not a member pointer type!");
6271 
6272   QualType PointeeTy = PointerTy->getPointeeType();
6273   // Don't add qualified variants of arrays. For one, they're not allowed
6274   // (the qualifier would sink to the element type), and for another, the
6275   // only overload situation where it matters is subscript or pointer +- int,
6276   // and those shouldn't have qualifier variants anyway.
6277   if (PointeeTy->isArrayType())
6278     return true;
6279   const Type *ClassTy = PointerTy->getClass();
6280 
6281   // Iterate through all strict supersets of the pointee type's CVR
6282   // qualifiers.
6283   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6284   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6285     if ((CVR | BaseCVR) != CVR) continue;
6286 
6287     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6288     MemberPointerTypes.insert(
6289       Context.getMemberPointerType(QPointeeTy, ClassTy));
6290   }
6291 
6292   return true;
6293 }
6294 
6295 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6296 /// Ty can be implicit converted to the given set of @p Types. We're
6297 /// primarily interested in pointer types and enumeration types. We also
6298 /// take member pointer types, for the conditional operator.
6299 /// AllowUserConversions is true if we should look at the conversion
6300 /// functions of a class type, and AllowExplicitConversions if we
6301 /// should also include the explicit conversion functions of a class
6302 /// type.
6303 void
AddTypesConvertedFrom(QualType Ty,SourceLocation Loc,bool AllowUserConversions,bool AllowExplicitConversions,const Qualifiers & VisibleQuals)6304 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6305                                                SourceLocation Loc,
6306                                                bool AllowUserConversions,
6307                                                bool AllowExplicitConversions,
6308                                                const Qualifiers &VisibleQuals) {
6309   // Only deal with canonical types.
6310   Ty = Context.getCanonicalType(Ty);
6311 
6312   // Look through reference types; they aren't part of the type of an
6313   // expression for the purposes of conversions.
6314   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6315     Ty = RefTy->getPointeeType();
6316 
6317   // If we're dealing with an array type, decay to the pointer.
6318   if (Ty->isArrayType())
6319     Ty = SemaRef.Context.getArrayDecayedType(Ty);
6320 
6321   // Otherwise, we don't care about qualifiers on the type.
6322   Ty = Ty.getLocalUnqualifiedType();
6323 
6324   // Flag if we ever add a non-record type.
6325   const RecordType *TyRec = Ty->getAs<RecordType>();
6326   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6327 
6328   // Flag if we encounter an arithmetic type.
6329   HasArithmeticOrEnumeralTypes =
6330     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6331 
6332   if (Ty->isObjCIdType() || Ty->isObjCClassType())
6333     PointerTypes.insert(Ty);
6334   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6335     // Insert our type, and its more-qualified variants, into the set
6336     // of types.
6337     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6338       return;
6339   } else if (Ty->isMemberPointerType()) {
6340     // Member pointers are far easier, since the pointee can't be converted.
6341     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6342       return;
6343   } else if (Ty->isEnumeralType()) {
6344     HasArithmeticOrEnumeralTypes = true;
6345     EnumerationTypes.insert(Ty);
6346   } else if (Ty->isVectorType()) {
6347     // We treat vector types as arithmetic types in many contexts as an
6348     // extension.
6349     HasArithmeticOrEnumeralTypes = true;
6350     VectorTypes.insert(Ty);
6351   } else if (Ty->isNullPtrType()) {
6352     HasNullPtrType = true;
6353   } else if (AllowUserConversions && TyRec) {
6354     // No conversion functions in incomplete types.
6355     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6356       return;
6357 
6358     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6359     std::pair<CXXRecordDecl::conversion_iterator,
6360               CXXRecordDecl::conversion_iterator>
6361       Conversions = ClassDecl->getVisibleConversionFunctions();
6362     for (CXXRecordDecl::conversion_iterator
6363            I = Conversions.first, E = Conversions.second; I != E; ++I) {
6364       NamedDecl *D = I.getDecl();
6365       if (isa<UsingShadowDecl>(D))
6366         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6367 
6368       // Skip conversion function templates; they don't tell us anything
6369       // about which builtin types we can convert to.
6370       if (isa<FunctionTemplateDecl>(D))
6371         continue;
6372 
6373       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6374       if (AllowExplicitConversions || !Conv->isExplicit()) {
6375         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6376                               VisibleQuals);
6377       }
6378     }
6379   }
6380 }
6381 
6382 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6383 /// the volatile- and non-volatile-qualified assignment operators for the
6384 /// given type to the candidate set.
AddBuiltinAssignmentOperatorCandidates(Sema & S,QualType T,Expr ** Args,unsigned NumArgs,OverloadCandidateSet & CandidateSet)6385 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6386                                                    QualType T,
6387                                                    Expr **Args,
6388                                                    unsigned NumArgs,
6389                                     OverloadCandidateSet &CandidateSet) {
6390   QualType ParamTypes[2];
6391 
6392   // T& operator=(T&, T)
6393   ParamTypes[0] = S.Context.getLValueReferenceType(T);
6394   ParamTypes[1] = T;
6395   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6396                         /*IsAssignmentOperator=*/true);
6397 
6398   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6399     // volatile T& operator=(volatile T&, T)
6400     ParamTypes[0]
6401       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6402     ParamTypes[1] = T;
6403     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6404                           /*IsAssignmentOperator=*/true);
6405   }
6406 }
6407 
6408 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6409 /// if any, found in visible type conversion functions found in ArgExpr's type.
CollectVRQualifiers(ASTContext & Context,Expr * ArgExpr)6410 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6411     Qualifiers VRQuals;
6412     const RecordType *TyRec;
6413     if (const MemberPointerType *RHSMPType =
6414         ArgExpr->getType()->getAs<MemberPointerType>())
6415       TyRec = RHSMPType->getClass()->getAs<RecordType>();
6416     else
6417       TyRec = ArgExpr->getType()->getAs<RecordType>();
6418     if (!TyRec) {
6419       // Just to be safe, assume the worst case.
6420       VRQuals.addVolatile();
6421       VRQuals.addRestrict();
6422       return VRQuals;
6423     }
6424 
6425     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6426     if (!ClassDecl->hasDefinition())
6427       return VRQuals;
6428 
6429     std::pair<CXXRecordDecl::conversion_iterator,
6430               CXXRecordDecl::conversion_iterator>
6431       Conversions = ClassDecl->getVisibleConversionFunctions();
6432 
6433     for (CXXRecordDecl::conversion_iterator
6434            I = Conversions.first, E = Conversions.second; I != E; ++I) {
6435       NamedDecl *D = I.getDecl();
6436       if (isa<UsingShadowDecl>(D))
6437         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6438       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6439         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6440         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6441           CanTy = ResTypeRef->getPointeeType();
6442         // Need to go down the pointer/mempointer chain and add qualifiers
6443         // as see them.
6444         bool done = false;
6445         while (!done) {
6446           if (CanTy.isRestrictQualified())
6447             VRQuals.addRestrict();
6448           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6449             CanTy = ResTypePtr->getPointeeType();
6450           else if (const MemberPointerType *ResTypeMPtr =
6451                 CanTy->getAs<MemberPointerType>())
6452             CanTy = ResTypeMPtr->getPointeeType();
6453           else
6454             done = true;
6455           if (CanTy.isVolatileQualified())
6456             VRQuals.addVolatile();
6457           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6458             return VRQuals;
6459         }
6460       }
6461     }
6462     return VRQuals;
6463 }
6464 
6465 namespace {
6466 
6467 /// \brief Helper class to manage the addition of builtin operator overload
6468 /// candidates. It provides shared state and utility methods used throughout
6469 /// the process, as well as a helper method to add each group of builtin
6470 /// operator overloads from the standard to a candidate set.
6471 class BuiltinOperatorOverloadBuilder {
6472   // Common instance state available to all overload candidate addition methods.
6473   Sema &S;
6474   Expr **Args;
6475   unsigned NumArgs;
6476   Qualifiers VisibleTypeConversionsQuals;
6477   bool HasArithmeticOrEnumeralCandidateType;
6478   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6479   OverloadCandidateSet &CandidateSet;
6480 
6481   // Define some constants used to index and iterate over the arithemetic types
6482   // provided via the getArithmeticType() method below.
6483   // The "promoted arithmetic types" are the arithmetic
6484   // types are that preserved by promotion (C++ [over.built]p2).
6485   static const unsigned FirstIntegralType = 3;
6486   static const unsigned LastIntegralType = 20;
6487   static const unsigned FirstPromotedIntegralType = 3,
6488                         LastPromotedIntegralType = 11;
6489   static const unsigned FirstPromotedArithmeticType = 0,
6490                         LastPromotedArithmeticType = 11;
6491   static const unsigned NumArithmeticTypes = 20;
6492 
6493   /// \brief Get the canonical type for a given arithmetic type index.
getArithmeticType(unsigned index)6494   CanQualType getArithmeticType(unsigned index) {
6495     assert(index < NumArithmeticTypes);
6496     static CanQualType ASTContext::* const
6497       ArithmeticTypes[NumArithmeticTypes] = {
6498       // Start of promoted types.
6499       &ASTContext::FloatTy,
6500       &ASTContext::DoubleTy,
6501       &ASTContext::LongDoubleTy,
6502 
6503       // Start of integral types.
6504       &ASTContext::IntTy,
6505       &ASTContext::LongTy,
6506       &ASTContext::LongLongTy,
6507       &ASTContext::Int128Ty,
6508       &ASTContext::UnsignedIntTy,
6509       &ASTContext::UnsignedLongTy,
6510       &ASTContext::UnsignedLongLongTy,
6511       &ASTContext::UnsignedInt128Ty,
6512       // End of promoted types.
6513 
6514       &ASTContext::BoolTy,
6515       &ASTContext::CharTy,
6516       &ASTContext::WCharTy,
6517       &ASTContext::Char16Ty,
6518       &ASTContext::Char32Ty,
6519       &ASTContext::SignedCharTy,
6520       &ASTContext::ShortTy,
6521       &ASTContext::UnsignedCharTy,
6522       &ASTContext::UnsignedShortTy,
6523       // End of integral types.
6524       // FIXME: What about complex? What about half?
6525     };
6526     return S.Context.*ArithmeticTypes[index];
6527   }
6528 
6529   /// \brief Gets the canonical type resulting from the usual arithemetic
6530   /// converions for the given arithmetic types.
getUsualArithmeticConversions(unsigned L,unsigned R)6531   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6532     // Accelerator table for performing the usual arithmetic conversions.
6533     // The rules are basically:
6534     //   - if either is floating-point, use the wider floating-point
6535     //   - if same signedness, use the higher rank
6536     //   - if same size, use unsigned of the higher rank
6537     //   - use the larger type
6538     // These rules, together with the axiom that higher ranks are
6539     // never smaller, are sufficient to precompute all of these results
6540     // *except* when dealing with signed types of higher rank.
6541     // (we could precompute SLL x UI for all known platforms, but it's
6542     // better not to make any assumptions).
6543     // We assume that int128 has a higher rank than long long on all platforms.
6544     enum PromotedType {
6545             Dep=-1,
6546             Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128
6547     };
6548     static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6549                                         [LastPromotedArithmeticType] = {
6550 /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6551 /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6552 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6553 /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL, S128,   UI,   UL,  ULL, U128 },
6554 /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL, S128,  Dep,   UL,  ULL, U128 },
6555 /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL, S128,  Dep,  Dep,  ULL, U128 },
6556 /*S128*/ {  Flt,  Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6557 /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep, S128,   UI,   UL,  ULL, U128 },
6558 /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep, S128,   UL,   UL,  ULL, U128 },
6559 /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL, S128,  ULL,  ULL,  ULL, U128 },
6560 /*U128*/ {  Flt,  Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6561     };
6562 
6563     assert(L < LastPromotedArithmeticType);
6564     assert(R < LastPromotedArithmeticType);
6565     int Idx = ConversionsTable[L][R];
6566 
6567     // Fast path: the table gives us a concrete answer.
6568     if (Idx != Dep) return getArithmeticType(Idx);
6569 
6570     // Slow path: we need to compare widths.
6571     // An invariant is that the signed type has higher rank.
6572     CanQualType LT = getArithmeticType(L),
6573                 RT = getArithmeticType(R);
6574     unsigned LW = S.Context.getIntWidth(LT),
6575              RW = S.Context.getIntWidth(RT);
6576 
6577     // If they're different widths, use the signed type.
6578     if (LW > RW) return LT;
6579     else if (LW < RW) return RT;
6580 
6581     // Otherwise, use the unsigned type of the signed type's rank.
6582     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6583     assert(L == SLL || R == SLL);
6584     return S.Context.UnsignedLongLongTy;
6585   }
6586 
6587   /// \brief Helper method to factor out the common pattern of adding overloads
6588   /// for '++' and '--' builtin operators.
addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,bool HasVolatile,bool HasRestrict)6589   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6590                                            bool HasVolatile,
6591                                            bool HasRestrict) {
6592     QualType ParamTypes[2] = {
6593       S.Context.getLValueReferenceType(CandidateTy),
6594       S.Context.IntTy
6595     };
6596 
6597     // Non-volatile version.
6598     if (NumArgs == 1)
6599       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6600     else
6601       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6602 
6603     // Use a heuristic to reduce number of builtin candidates in the set:
6604     // add volatile version only if there are conversions to a volatile type.
6605     if (HasVolatile) {
6606       ParamTypes[0] =
6607         S.Context.getLValueReferenceType(
6608           S.Context.getVolatileType(CandidateTy));
6609       if (NumArgs == 1)
6610         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6611       else
6612         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6613     }
6614 
6615     // Add restrict version only if there are conversions to a restrict type
6616     // and our candidate type is a non-restrict-qualified pointer.
6617     if (HasRestrict && CandidateTy->isAnyPointerType() &&
6618         !CandidateTy.isRestrictQualified()) {
6619       ParamTypes[0]
6620         = S.Context.getLValueReferenceType(
6621             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6622       if (NumArgs == 1)
6623         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6624       else
6625         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6626 
6627       if (HasVolatile) {
6628         ParamTypes[0]
6629           = S.Context.getLValueReferenceType(
6630               S.Context.getCVRQualifiedType(CandidateTy,
6631                                             (Qualifiers::Volatile |
6632                                              Qualifiers::Restrict)));
6633         if (NumArgs == 1)
6634           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6635                                 CandidateSet);
6636         else
6637           S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6638       }
6639     }
6640 
6641   }
6642 
6643 public:
BuiltinOperatorOverloadBuilder(Sema & S,Expr ** Args,unsigned NumArgs,Qualifiers VisibleTypeConversionsQuals,bool HasArithmeticOrEnumeralCandidateType,SmallVectorImpl<BuiltinCandidateTypeSet> & CandidateTypes,OverloadCandidateSet & CandidateSet)6644   BuiltinOperatorOverloadBuilder(
6645     Sema &S, Expr **Args, unsigned NumArgs,
6646     Qualifiers VisibleTypeConversionsQuals,
6647     bool HasArithmeticOrEnumeralCandidateType,
6648     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6649     OverloadCandidateSet &CandidateSet)
6650     : S(S), Args(Args), NumArgs(NumArgs),
6651       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6652       HasArithmeticOrEnumeralCandidateType(
6653         HasArithmeticOrEnumeralCandidateType),
6654       CandidateTypes(CandidateTypes),
6655       CandidateSet(CandidateSet) {
6656     // Validate some of our static helper constants in debug builds.
6657     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6658            "Invalid first promoted integral type");
6659     assert(getArithmeticType(LastPromotedIntegralType - 1)
6660              == S.Context.UnsignedInt128Ty &&
6661            "Invalid last promoted integral type");
6662     assert(getArithmeticType(FirstPromotedArithmeticType)
6663              == S.Context.FloatTy &&
6664            "Invalid first promoted arithmetic type");
6665     assert(getArithmeticType(LastPromotedArithmeticType - 1)
6666              == S.Context.UnsignedInt128Ty &&
6667            "Invalid last promoted arithmetic type");
6668   }
6669 
6670   // C++ [over.built]p3:
6671   //
6672   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6673   //   is either volatile or empty, there exist candidate operator
6674   //   functions of the form
6675   //
6676   //       VQ T&      operator++(VQ T&);
6677   //       T          operator++(VQ T&, int);
6678   //
6679   // C++ [over.built]p4:
6680   //
6681   //   For every pair (T, VQ), where T is an arithmetic type other
6682   //   than bool, and VQ is either volatile or empty, there exist
6683   //   candidate operator functions of the form
6684   //
6685   //       VQ T&      operator--(VQ T&);
6686   //       T          operator--(VQ T&, int);
addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op)6687   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6688     if (!HasArithmeticOrEnumeralCandidateType)
6689       return;
6690 
6691     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6692          Arith < NumArithmeticTypes; ++Arith) {
6693       addPlusPlusMinusMinusStyleOverloads(
6694         getArithmeticType(Arith),
6695         VisibleTypeConversionsQuals.hasVolatile(),
6696         VisibleTypeConversionsQuals.hasRestrict());
6697     }
6698   }
6699 
6700   // C++ [over.built]p5:
6701   //
6702   //   For every pair (T, VQ), where T is a cv-qualified or
6703   //   cv-unqualified object type, and VQ is either volatile or
6704   //   empty, there exist candidate operator functions of the form
6705   //
6706   //       T*VQ&      operator++(T*VQ&);
6707   //       T*VQ&      operator--(T*VQ&);
6708   //       T*         operator++(T*VQ&, int);
6709   //       T*         operator--(T*VQ&, int);
addPlusPlusMinusMinusPointerOverloads()6710   void addPlusPlusMinusMinusPointerOverloads() {
6711     for (BuiltinCandidateTypeSet::iterator
6712               Ptr = CandidateTypes[0].pointer_begin(),
6713            PtrEnd = CandidateTypes[0].pointer_end();
6714          Ptr != PtrEnd; ++Ptr) {
6715       // Skip pointer types that aren't pointers to object types.
6716       if (!(*Ptr)->getPointeeType()->isObjectType())
6717         continue;
6718 
6719       addPlusPlusMinusMinusStyleOverloads(*Ptr,
6720         (!(*Ptr).isVolatileQualified() &&
6721          VisibleTypeConversionsQuals.hasVolatile()),
6722         (!(*Ptr).isRestrictQualified() &&
6723          VisibleTypeConversionsQuals.hasRestrict()));
6724     }
6725   }
6726 
6727   // C++ [over.built]p6:
6728   //   For every cv-qualified or cv-unqualified object type T, there
6729   //   exist candidate operator functions of the form
6730   //
6731   //       T&         operator*(T*);
6732   //
6733   // C++ [over.built]p7:
6734   //   For every function type T that does not have cv-qualifiers or a
6735   //   ref-qualifier, there exist candidate operator functions of the form
6736   //       T&         operator*(T*);
addUnaryStarPointerOverloads()6737   void addUnaryStarPointerOverloads() {
6738     for (BuiltinCandidateTypeSet::iterator
6739               Ptr = CandidateTypes[0].pointer_begin(),
6740            PtrEnd = CandidateTypes[0].pointer_end();
6741          Ptr != PtrEnd; ++Ptr) {
6742       QualType ParamTy = *Ptr;
6743       QualType PointeeTy = ParamTy->getPointeeType();
6744       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6745         continue;
6746 
6747       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6748         if (Proto->getTypeQuals() || Proto->getRefQualifier())
6749           continue;
6750 
6751       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6752                             &ParamTy, Args, 1, CandidateSet);
6753     }
6754   }
6755 
6756   // C++ [over.built]p9:
6757   //  For every promoted arithmetic type T, there exist candidate
6758   //  operator functions of the form
6759   //
6760   //       T         operator+(T);
6761   //       T         operator-(T);
addUnaryPlusOrMinusArithmeticOverloads()6762   void addUnaryPlusOrMinusArithmeticOverloads() {
6763     if (!HasArithmeticOrEnumeralCandidateType)
6764       return;
6765 
6766     for (unsigned Arith = FirstPromotedArithmeticType;
6767          Arith < LastPromotedArithmeticType; ++Arith) {
6768       QualType ArithTy = getArithmeticType(Arith);
6769       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6770     }
6771 
6772     // Extension: We also add these operators for vector types.
6773     for (BuiltinCandidateTypeSet::iterator
6774               Vec = CandidateTypes[0].vector_begin(),
6775            VecEnd = CandidateTypes[0].vector_end();
6776          Vec != VecEnd; ++Vec) {
6777       QualType VecTy = *Vec;
6778       S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6779     }
6780   }
6781 
6782   // C++ [over.built]p8:
6783   //   For every type T, there exist candidate operator functions of
6784   //   the form
6785   //
6786   //       T*         operator+(T*);
addUnaryPlusPointerOverloads()6787   void addUnaryPlusPointerOverloads() {
6788     for (BuiltinCandidateTypeSet::iterator
6789               Ptr = CandidateTypes[0].pointer_begin(),
6790            PtrEnd = CandidateTypes[0].pointer_end();
6791          Ptr != PtrEnd; ++Ptr) {
6792       QualType ParamTy = *Ptr;
6793       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6794     }
6795   }
6796 
6797   // C++ [over.built]p10:
6798   //   For every promoted integral type T, there exist candidate
6799   //   operator functions of the form
6800   //
6801   //        T         operator~(T);
addUnaryTildePromotedIntegralOverloads()6802   void addUnaryTildePromotedIntegralOverloads() {
6803     if (!HasArithmeticOrEnumeralCandidateType)
6804       return;
6805 
6806     for (unsigned Int = FirstPromotedIntegralType;
6807          Int < LastPromotedIntegralType; ++Int) {
6808       QualType IntTy = getArithmeticType(Int);
6809       S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6810     }
6811 
6812     // Extension: We also add this operator for vector types.
6813     for (BuiltinCandidateTypeSet::iterator
6814               Vec = CandidateTypes[0].vector_begin(),
6815            VecEnd = CandidateTypes[0].vector_end();
6816          Vec != VecEnd; ++Vec) {
6817       QualType VecTy = *Vec;
6818       S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6819     }
6820   }
6821 
6822   // C++ [over.match.oper]p16:
6823   //   For every pointer to member type T, there exist candidate operator
6824   //   functions of the form
6825   //
6826   //        bool operator==(T,T);
6827   //        bool operator!=(T,T);
addEqualEqualOrNotEqualMemberPointerOverloads()6828   void addEqualEqualOrNotEqualMemberPointerOverloads() {
6829     /// Set of (canonical) types that we've already handled.
6830     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6831 
6832     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6833       for (BuiltinCandidateTypeSet::iterator
6834                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6835              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6836            MemPtr != MemPtrEnd;
6837            ++MemPtr) {
6838         // Don't add the same builtin candidate twice.
6839         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6840           continue;
6841 
6842         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6843         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6844                               CandidateSet);
6845       }
6846     }
6847   }
6848 
6849   // C++ [over.built]p15:
6850   //
6851   //   For every T, where T is an enumeration type, a pointer type, or
6852   //   std::nullptr_t, there exist candidate operator functions of the form
6853   //
6854   //        bool       operator<(T, T);
6855   //        bool       operator>(T, T);
6856   //        bool       operator<=(T, T);
6857   //        bool       operator>=(T, T);
6858   //        bool       operator==(T, T);
6859   //        bool       operator!=(T, T);
addRelationalPointerOrEnumeralOverloads()6860   void addRelationalPointerOrEnumeralOverloads() {
6861     // C++ [over.match.oper]p3:
6862     //   [...]the built-in candidates include all of the candidate operator
6863     //   functions defined in 13.6 that, compared to the given operator, [...]
6864     //   do not have the same parameter-type-list as any non-template non-member
6865     //   candidate.
6866     //
6867     // Note that in practice, this only affects enumeration types because there
6868     // aren't any built-in candidates of record type, and a user-defined operator
6869     // must have an operand of record or enumeration type. Also, the only other
6870     // overloaded operator with enumeration arguments, operator=,
6871     // cannot be overloaded for enumeration types, so this is the only place
6872     // where we must suppress candidates like this.
6873     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6874       UserDefinedBinaryOperators;
6875 
6876     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6877       if (CandidateTypes[ArgIdx].enumeration_begin() !=
6878           CandidateTypes[ArgIdx].enumeration_end()) {
6879         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6880                                          CEnd = CandidateSet.end();
6881              C != CEnd; ++C) {
6882           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6883             continue;
6884 
6885           if (C->Function->isFunctionTemplateSpecialization())
6886             continue;
6887 
6888           QualType FirstParamType =
6889             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6890           QualType SecondParamType =
6891             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6892 
6893           // Skip if either parameter isn't of enumeral type.
6894           if (!FirstParamType->isEnumeralType() ||
6895               !SecondParamType->isEnumeralType())
6896             continue;
6897 
6898           // Add this operator to the set of known user-defined operators.
6899           UserDefinedBinaryOperators.insert(
6900             std::make_pair(S.Context.getCanonicalType(FirstParamType),
6901                            S.Context.getCanonicalType(SecondParamType)));
6902         }
6903       }
6904     }
6905 
6906     /// Set of (canonical) types that we've already handled.
6907     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6908 
6909     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6910       for (BuiltinCandidateTypeSet::iterator
6911                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6912              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6913            Ptr != PtrEnd; ++Ptr) {
6914         // Don't add the same builtin candidate twice.
6915         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6916           continue;
6917 
6918         QualType ParamTypes[2] = { *Ptr, *Ptr };
6919         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6920                               CandidateSet);
6921       }
6922       for (BuiltinCandidateTypeSet::iterator
6923                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6924              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6925            Enum != EnumEnd; ++Enum) {
6926         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6927 
6928         // Don't add the same builtin candidate twice, or if a user defined
6929         // candidate exists.
6930         if (!AddedTypes.insert(CanonType) ||
6931             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6932                                                             CanonType)))
6933           continue;
6934 
6935         QualType ParamTypes[2] = { *Enum, *Enum };
6936         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6937                               CandidateSet);
6938       }
6939 
6940       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6941         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6942         if (AddedTypes.insert(NullPtrTy) &&
6943             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6944                                                              NullPtrTy))) {
6945           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6946           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6947                                 CandidateSet);
6948         }
6949       }
6950     }
6951   }
6952 
6953   // C++ [over.built]p13:
6954   //
6955   //   For every cv-qualified or cv-unqualified object type T
6956   //   there exist candidate operator functions of the form
6957   //
6958   //      T*         operator+(T*, ptrdiff_t);
6959   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
6960   //      T*         operator-(T*, ptrdiff_t);
6961   //      T*         operator+(ptrdiff_t, T*);
6962   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
6963   //
6964   // C++ [over.built]p14:
6965   //
6966   //   For every T, where T is a pointer to object type, there
6967   //   exist candidate operator functions of the form
6968   //
6969   //      ptrdiff_t  operator-(T, T);
addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op)6970   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6971     /// Set of (canonical) types that we've already handled.
6972     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6973 
6974     for (int Arg = 0; Arg < 2; ++Arg) {
6975       QualType AsymetricParamTypes[2] = {
6976         S.Context.getPointerDiffType(),
6977         S.Context.getPointerDiffType(),
6978       };
6979       for (BuiltinCandidateTypeSet::iterator
6980                 Ptr = CandidateTypes[Arg].pointer_begin(),
6981              PtrEnd = CandidateTypes[Arg].pointer_end();
6982            Ptr != PtrEnd; ++Ptr) {
6983         QualType PointeeTy = (*Ptr)->getPointeeType();
6984         if (!PointeeTy->isObjectType())
6985           continue;
6986 
6987         AsymetricParamTypes[Arg] = *Ptr;
6988         if (Arg == 0 || Op == OO_Plus) {
6989           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6990           // T* operator+(ptrdiff_t, T*);
6991           S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6992                                 CandidateSet);
6993         }
6994         if (Op == OO_Minus) {
6995           // ptrdiff_t operator-(T, T);
6996           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6997             continue;
6998 
6999           QualType ParamTypes[2] = { *Ptr, *Ptr };
7000           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7001                                 Args, 2, CandidateSet);
7002         }
7003       }
7004     }
7005   }
7006 
7007   // C++ [over.built]p12:
7008   //
7009   //   For every pair of promoted arithmetic types L and R, there
7010   //   exist candidate operator functions of the form
7011   //
7012   //        LR         operator*(L, R);
7013   //        LR         operator/(L, R);
7014   //        LR         operator+(L, R);
7015   //        LR         operator-(L, R);
7016   //        bool       operator<(L, R);
7017   //        bool       operator>(L, R);
7018   //        bool       operator<=(L, R);
7019   //        bool       operator>=(L, R);
7020   //        bool       operator==(L, R);
7021   //        bool       operator!=(L, R);
7022   //
7023   //   where LR is the result of the usual arithmetic conversions
7024   //   between types L and R.
7025   //
7026   // C++ [over.built]p24:
7027   //
7028   //   For every pair of promoted arithmetic types L and R, there exist
7029   //   candidate operator functions of the form
7030   //
7031   //        LR       operator?(bool, L, R);
7032   //
7033   //   where LR is the result of the usual arithmetic conversions
7034   //   between types L and R.
7035   // Our candidates ignore the first parameter.
addGenericBinaryArithmeticOverloads(bool isComparison)7036   void addGenericBinaryArithmeticOverloads(bool isComparison) {
7037     if (!HasArithmeticOrEnumeralCandidateType)
7038       return;
7039 
7040     for (unsigned Left = FirstPromotedArithmeticType;
7041          Left < LastPromotedArithmeticType; ++Left) {
7042       for (unsigned Right = FirstPromotedArithmeticType;
7043            Right < LastPromotedArithmeticType; ++Right) {
7044         QualType LandR[2] = { getArithmeticType(Left),
7045                               getArithmeticType(Right) };
7046         QualType Result =
7047           isComparison ? S.Context.BoolTy
7048                        : getUsualArithmeticConversions(Left, Right);
7049         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7050       }
7051     }
7052 
7053     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7054     // conditional operator for vector types.
7055     for (BuiltinCandidateTypeSet::iterator
7056               Vec1 = CandidateTypes[0].vector_begin(),
7057            Vec1End = CandidateTypes[0].vector_end();
7058          Vec1 != Vec1End; ++Vec1) {
7059       for (BuiltinCandidateTypeSet::iterator
7060                 Vec2 = CandidateTypes[1].vector_begin(),
7061              Vec2End = CandidateTypes[1].vector_end();
7062            Vec2 != Vec2End; ++Vec2) {
7063         QualType LandR[2] = { *Vec1, *Vec2 };
7064         QualType Result = S.Context.BoolTy;
7065         if (!isComparison) {
7066           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7067             Result = *Vec1;
7068           else
7069             Result = *Vec2;
7070         }
7071 
7072         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7073       }
7074     }
7075   }
7076 
7077   // C++ [over.built]p17:
7078   //
7079   //   For every pair of promoted integral types L and R, there
7080   //   exist candidate operator functions of the form
7081   //
7082   //      LR         operator%(L, R);
7083   //      LR         operator&(L, R);
7084   //      LR         operator^(L, R);
7085   //      LR         operator|(L, R);
7086   //      L          operator<<(L, R);
7087   //      L          operator>>(L, R);
7088   //
7089   //   where LR is the result of the usual arithmetic conversions
7090   //   between types L and R.
addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op)7091   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7092     if (!HasArithmeticOrEnumeralCandidateType)
7093       return;
7094 
7095     for (unsigned Left = FirstPromotedIntegralType;
7096          Left < LastPromotedIntegralType; ++Left) {
7097       for (unsigned Right = FirstPromotedIntegralType;
7098            Right < LastPromotedIntegralType; ++Right) {
7099         QualType LandR[2] = { getArithmeticType(Left),
7100                               getArithmeticType(Right) };
7101         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7102             ? LandR[0]
7103             : getUsualArithmeticConversions(Left, Right);
7104         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7105       }
7106     }
7107   }
7108 
7109   // C++ [over.built]p20:
7110   //
7111   //   For every pair (T, VQ), where T is an enumeration or
7112   //   pointer to member type and VQ is either volatile or
7113   //   empty, there exist candidate operator functions of the form
7114   //
7115   //        VQ T&      operator=(VQ T&, T);
addAssignmentMemberPointerOrEnumeralOverloads()7116   void addAssignmentMemberPointerOrEnumeralOverloads() {
7117     /// Set of (canonical) types that we've already handled.
7118     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7119 
7120     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7121       for (BuiltinCandidateTypeSet::iterator
7122                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7123              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7124            Enum != EnumEnd; ++Enum) {
7125         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7126           continue;
7127 
7128         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7129                                                CandidateSet);
7130       }
7131 
7132       for (BuiltinCandidateTypeSet::iterator
7133                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7134              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7135            MemPtr != MemPtrEnd; ++MemPtr) {
7136         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7137           continue;
7138 
7139         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7140                                                CandidateSet);
7141       }
7142     }
7143   }
7144 
7145   // C++ [over.built]p19:
7146   //
7147   //   For every pair (T, VQ), where T is any type and VQ is either
7148   //   volatile or empty, there exist candidate operator functions
7149   //   of the form
7150   //
7151   //        T*VQ&      operator=(T*VQ&, T*);
7152   //
7153   // C++ [over.built]p21:
7154   //
7155   //   For every pair (T, VQ), where T is a cv-qualified or
7156   //   cv-unqualified object type and VQ is either volatile or
7157   //   empty, there exist candidate operator functions of the form
7158   //
7159   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7160   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
addAssignmentPointerOverloads(bool isEqualOp)7161   void addAssignmentPointerOverloads(bool isEqualOp) {
7162     /// Set of (canonical) types that we've already handled.
7163     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7164 
7165     for (BuiltinCandidateTypeSet::iterator
7166               Ptr = CandidateTypes[0].pointer_begin(),
7167            PtrEnd = CandidateTypes[0].pointer_end();
7168          Ptr != PtrEnd; ++Ptr) {
7169       // If this is operator=, keep track of the builtin candidates we added.
7170       if (isEqualOp)
7171         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7172       else if (!(*Ptr)->getPointeeType()->isObjectType())
7173         continue;
7174 
7175       // non-volatile version
7176       QualType ParamTypes[2] = {
7177         S.Context.getLValueReferenceType(*Ptr),
7178         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7179       };
7180       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7181                             /*IsAssigmentOperator=*/ isEqualOp);
7182 
7183       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7184                           VisibleTypeConversionsQuals.hasVolatile();
7185       if (NeedVolatile) {
7186         // volatile version
7187         ParamTypes[0] =
7188           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7189         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7190                               /*IsAssigmentOperator=*/isEqualOp);
7191       }
7192 
7193       if (!(*Ptr).isRestrictQualified() &&
7194           VisibleTypeConversionsQuals.hasRestrict()) {
7195         // restrict version
7196         ParamTypes[0]
7197           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7198         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7199                               /*IsAssigmentOperator=*/isEqualOp);
7200 
7201         if (NeedVolatile) {
7202           // volatile restrict version
7203           ParamTypes[0]
7204             = S.Context.getLValueReferenceType(
7205                 S.Context.getCVRQualifiedType(*Ptr,
7206                                               (Qualifiers::Volatile |
7207                                                Qualifiers::Restrict)));
7208           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7209                                 CandidateSet,
7210                                 /*IsAssigmentOperator=*/isEqualOp);
7211         }
7212       }
7213     }
7214 
7215     if (isEqualOp) {
7216       for (BuiltinCandidateTypeSet::iterator
7217                 Ptr = CandidateTypes[1].pointer_begin(),
7218              PtrEnd = CandidateTypes[1].pointer_end();
7219            Ptr != PtrEnd; ++Ptr) {
7220         // Make sure we don't add the same candidate twice.
7221         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7222           continue;
7223 
7224         QualType ParamTypes[2] = {
7225           S.Context.getLValueReferenceType(*Ptr),
7226           *Ptr,
7227         };
7228 
7229         // non-volatile version
7230         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7231                               /*IsAssigmentOperator=*/true);
7232 
7233         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7234                            VisibleTypeConversionsQuals.hasVolatile();
7235         if (NeedVolatile) {
7236           // volatile version
7237           ParamTypes[0] =
7238             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7239           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7240                                 CandidateSet, /*IsAssigmentOperator=*/true);
7241         }
7242 
7243         if (!(*Ptr).isRestrictQualified() &&
7244             VisibleTypeConversionsQuals.hasRestrict()) {
7245           // restrict version
7246           ParamTypes[0]
7247             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7248           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7249                                 CandidateSet, /*IsAssigmentOperator=*/true);
7250 
7251           if (NeedVolatile) {
7252             // volatile restrict version
7253             ParamTypes[0]
7254               = S.Context.getLValueReferenceType(
7255                   S.Context.getCVRQualifiedType(*Ptr,
7256                                                 (Qualifiers::Volatile |
7257                                                  Qualifiers::Restrict)));
7258             S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7259                                   CandidateSet, /*IsAssigmentOperator=*/true);
7260 
7261           }
7262         }
7263       }
7264     }
7265   }
7266 
7267   // C++ [over.built]p18:
7268   //
7269   //   For every triple (L, VQ, R), where L is an arithmetic type,
7270   //   VQ is either volatile or empty, and R is a promoted
7271   //   arithmetic type, there exist candidate operator functions of
7272   //   the form
7273   //
7274   //        VQ L&      operator=(VQ L&, R);
7275   //        VQ L&      operator*=(VQ L&, R);
7276   //        VQ L&      operator/=(VQ L&, R);
7277   //        VQ L&      operator+=(VQ L&, R);
7278   //        VQ L&      operator-=(VQ L&, R);
addAssignmentArithmeticOverloads(bool isEqualOp)7279   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7280     if (!HasArithmeticOrEnumeralCandidateType)
7281       return;
7282 
7283     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7284       for (unsigned Right = FirstPromotedArithmeticType;
7285            Right < LastPromotedArithmeticType; ++Right) {
7286         QualType ParamTypes[2];
7287         ParamTypes[1] = getArithmeticType(Right);
7288 
7289         // Add this built-in operator as a candidate (VQ is empty).
7290         ParamTypes[0] =
7291           S.Context.getLValueReferenceType(getArithmeticType(Left));
7292         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7293                               /*IsAssigmentOperator=*/isEqualOp);
7294 
7295         // Add this built-in operator as a candidate (VQ is 'volatile').
7296         if (VisibleTypeConversionsQuals.hasVolatile()) {
7297           ParamTypes[0] =
7298             S.Context.getVolatileType(getArithmeticType(Left));
7299           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7300           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7301                                 CandidateSet,
7302                                 /*IsAssigmentOperator=*/isEqualOp);
7303         }
7304       }
7305     }
7306 
7307     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7308     for (BuiltinCandidateTypeSet::iterator
7309               Vec1 = CandidateTypes[0].vector_begin(),
7310            Vec1End = CandidateTypes[0].vector_end();
7311          Vec1 != Vec1End; ++Vec1) {
7312       for (BuiltinCandidateTypeSet::iterator
7313                 Vec2 = CandidateTypes[1].vector_begin(),
7314              Vec2End = CandidateTypes[1].vector_end();
7315            Vec2 != Vec2End; ++Vec2) {
7316         QualType ParamTypes[2];
7317         ParamTypes[1] = *Vec2;
7318         // Add this built-in operator as a candidate (VQ is empty).
7319         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7320         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7321                               /*IsAssigmentOperator=*/isEqualOp);
7322 
7323         // Add this built-in operator as a candidate (VQ is 'volatile').
7324         if (VisibleTypeConversionsQuals.hasVolatile()) {
7325           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7326           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7327           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7328                                 CandidateSet,
7329                                 /*IsAssigmentOperator=*/isEqualOp);
7330         }
7331       }
7332     }
7333   }
7334 
7335   // C++ [over.built]p22:
7336   //
7337   //   For every triple (L, VQ, R), where L is an integral type, VQ
7338   //   is either volatile or empty, and R is a promoted integral
7339   //   type, there exist candidate operator functions of the form
7340   //
7341   //        VQ L&       operator%=(VQ L&, R);
7342   //        VQ L&       operator<<=(VQ L&, R);
7343   //        VQ L&       operator>>=(VQ L&, R);
7344   //        VQ L&       operator&=(VQ L&, R);
7345   //        VQ L&       operator^=(VQ L&, R);
7346   //        VQ L&       operator|=(VQ L&, R);
addAssignmentIntegralOverloads()7347   void addAssignmentIntegralOverloads() {
7348     if (!HasArithmeticOrEnumeralCandidateType)
7349       return;
7350 
7351     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7352       for (unsigned Right = FirstPromotedIntegralType;
7353            Right < LastPromotedIntegralType; ++Right) {
7354         QualType ParamTypes[2];
7355         ParamTypes[1] = getArithmeticType(Right);
7356 
7357         // Add this built-in operator as a candidate (VQ is empty).
7358         ParamTypes[0] =
7359           S.Context.getLValueReferenceType(getArithmeticType(Left));
7360         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7361         if (VisibleTypeConversionsQuals.hasVolatile()) {
7362           // Add this built-in operator as a candidate (VQ is 'volatile').
7363           ParamTypes[0] = getArithmeticType(Left);
7364           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7365           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7366           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7367                                 CandidateSet);
7368         }
7369       }
7370     }
7371   }
7372 
7373   // C++ [over.operator]p23:
7374   //
7375   //   There also exist candidate operator functions of the form
7376   //
7377   //        bool        operator!(bool);
7378   //        bool        operator&&(bool, bool);
7379   //        bool        operator||(bool, bool);
addExclaimOverload()7380   void addExclaimOverload() {
7381     QualType ParamTy = S.Context.BoolTy;
7382     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7383                           /*IsAssignmentOperator=*/false,
7384                           /*NumContextualBoolArguments=*/1);
7385   }
addAmpAmpOrPipePipeOverload()7386   void addAmpAmpOrPipePipeOverload() {
7387     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7388     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7389                           /*IsAssignmentOperator=*/false,
7390                           /*NumContextualBoolArguments=*/2);
7391   }
7392 
7393   // C++ [over.built]p13:
7394   //
7395   //   For every cv-qualified or cv-unqualified object type T there
7396   //   exist candidate operator functions of the form
7397   //
7398   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7399   //        T&         operator[](T*, ptrdiff_t);
7400   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7401   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7402   //        T&         operator[](ptrdiff_t, T*);
addSubscriptOverloads()7403   void addSubscriptOverloads() {
7404     for (BuiltinCandidateTypeSet::iterator
7405               Ptr = CandidateTypes[0].pointer_begin(),
7406            PtrEnd = CandidateTypes[0].pointer_end();
7407          Ptr != PtrEnd; ++Ptr) {
7408       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7409       QualType PointeeType = (*Ptr)->getPointeeType();
7410       if (!PointeeType->isObjectType())
7411         continue;
7412 
7413       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7414 
7415       // T& operator[](T*, ptrdiff_t)
7416       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7417     }
7418 
7419     for (BuiltinCandidateTypeSet::iterator
7420               Ptr = CandidateTypes[1].pointer_begin(),
7421            PtrEnd = CandidateTypes[1].pointer_end();
7422          Ptr != PtrEnd; ++Ptr) {
7423       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7424       QualType PointeeType = (*Ptr)->getPointeeType();
7425       if (!PointeeType->isObjectType())
7426         continue;
7427 
7428       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7429 
7430       // T& operator[](ptrdiff_t, T*)
7431       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7432     }
7433   }
7434 
7435   // C++ [over.built]p11:
7436   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7437   //    C1 is the same type as C2 or is a derived class of C2, T is an object
7438   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7439   //    there exist candidate operator functions of the form
7440   //
7441   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7442   //
7443   //    where CV12 is the union of CV1 and CV2.
addArrowStarOverloads()7444   void addArrowStarOverloads() {
7445     for (BuiltinCandidateTypeSet::iterator
7446              Ptr = CandidateTypes[0].pointer_begin(),
7447            PtrEnd = CandidateTypes[0].pointer_end();
7448          Ptr != PtrEnd; ++Ptr) {
7449       QualType C1Ty = (*Ptr);
7450       QualType C1;
7451       QualifierCollector Q1;
7452       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7453       if (!isa<RecordType>(C1))
7454         continue;
7455       // heuristic to reduce number of builtin candidates in the set.
7456       // Add volatile/restrict version only if there are conversions to a
7457       // volatile/restrict type.
7458       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7459         continue;
7460       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7461         continue;
7462       for (BuiltinCandidateTypeSet::iterator
7463                 MemPtr = CandidateTypes[1].member_pointer_begin(),
7464              MemPtrEnd = CandidateTypes[1].member_pointer_end();
7465            MemPtr != MemPtrEnd; ++MemPtr) {
7466         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7467         QualType C2 = QualType(mptr->getClass(), 0);
7468         C2 = C2.getUnqualifiedType();
7469         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7470           break;
7471         QualType ParamTypes[2] = { *Ptr, *MemPtr };
7472         // build CV12 T&
7473         QualType T = mptr->getPointeeType();
7474         if (!VisibleTypeConversionsQuals.hasVolatile() &&
7475             T.isVolatileQualified())
7476           continue;
7477         if (!VisibleTypeConversionsQuals.hasRestrict() &&
7478             T.isRestrictQualified())
7479           continue;
7480         T = Q1.apply(S.Context, T);
7481         QualType ResultTy = S.Context.getLValueReferenceType(T);
7482         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7483       }
7484     }
7485   }
7486 
7487   // Note that we don't consider the first argument, since it has been
7488   // contextually converted to bool long ago. The candidates below are
7489   // therefore added as binary.
7490   //
7491   // C++ [over.built]p25:
7492   //   For every type T, where T is a pointer, pointer-to-member, or scoped
7493   //   enumeration type, there exist candidate operator functions of the form
7494   //
7495   //        T        operator?(bool, T, T);
7496   //
addConditionalOperatorOverloads()7497   void addConditionalOperatorOverloads() {
7498     /// Set of (canonical) types that we've already handled.
7499     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7500 
7501     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7502       for (BuiltinCandidateTypeSet::iterator
7503                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7504              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7505            Ptr != PtrEnd; ++Ptr) {
7506         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7507           continue;
7508 
7509         QualType ParamTypes[2] = { *Ptr, *Ptr };
7510         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7511       }
7512 
7513       for (BuiltinCandidateTypeSet::iterator
7514                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7515              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7516            MemPtr != MemPtrEnd; ++MemPtr) {
7517         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7518           continue;
7519 
7520         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7521         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7522       }
7523 
7524       if (S.getLangOpts().CPlusPlus11) {
7525         for (BuiltinCandidateTypeSet::iterator
7526                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7527                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7528              Enum != EnumEnd; ++Enum) {
7529           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7530             continue;
7531 
7532           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7533             continue;
7534 
7535           QualType ParamTypes[2] = { *Enum, *Enum };
7536           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7537         }
7538       }
7539     }
7540   }
7541 };
7542 
7543 } // end anonymous namespace
7544 
7545 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
7546 /// operator overloads to the candidate set (C++ [over.built]), based
7547 /// on the operator @p Op and the arguments given. For example, if the
7548 /// operator is a binary '+', this routine might add "int
7549 /// operator+(int, int)" to cover integer addition.
7550 void
AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,Expr ** Args,unsigned NumArgs,OverloadCandidateSet & CandidateSet)7551 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7552                                    SourceLocation OpLoc,
7553                                    Expr **Args, unsigned NumArgs,
7554                                    OverloadCandidateSet& CandidateSet) {
7555   // Find all of the types that the arguments can convert to, but only
7556   // if the operator we're looking at has built-in operator candidates
7557   // that make use of these types. Also record whether we encounter non-record
7558   // candidate types or either arithmetic or enumeral candidate types.
7559   Qualifiers VisibleTypeConversionsQuals;
7560   VisibleTypeConversionsQuals.addConst();
7561   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7562     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7563 
7564   bool HasNonRecordCandidateType = false;
7565   bool HasArithmeticOrEnumeralCandidateType = false;
7566   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7567   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7568     CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7569     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7570                                                  OpLoc,
7571                                                  true,
7572                                                  (Op == OO_Exclaim ||
7573                                                   Op == OO_AmpAmp ||
7574                                                   Op == OO_PipePipe),
7575                                                  VisibleTypeConversionsQuals);
7576     HasNonRecordCandidateType = HasNonRecordCandidateType ||
7577         CandidateTypes[ArgIdx].hasNonRecordTypes();
7578     HasArithmeticOrEnumeralCandidateType =
7579         HasArithmeticOrEnumeralCandidateType ||
7580         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7581   }
7582 
7583   // Exit early when no non-record types have been added to the candidate set
7584   // for any of the arguments to the operator.
7585   //
7586   // We can't exit early for !, ||, or &&, since there we have always have
7587   // 'bool' overloads.
7588   if (!HasNonRecordCandidateType &&
7589       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7590     return;
7591 
7592   // Setup an object to manage the common state for building overloads.
7593   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7594                                            VisibleTypeConversionsQuals,
7595                                            HasArithmeticOrEnumeralCandidateType,
7596                                            CandidateTypes, CandidateSet);
7597 
7598   // Dispatch over the operation to add in only those overloads which apply.
7599   switch (Op) {
7600   case OO_None:
7601   case NUM_OVERLOADED_OPERATORS:
7602     llvm_unreachable("Expected an overloaded operator");
7603 
7604   case OO_New:
7605   case OO_Delete:
7606   case OO_Array_New:
7607   case OO_Array_Delete:
7608   case OO_Call:
7609     llvm_unreachable(
7610                     "Special operators don't use AddBuiltinOperatorCandidates");
7611 
7612   case OO_Comma:
7613   case OO_Arrow:
7614     // C++ [over.match.oper]p3:
7615     //   -- For the operator ',', the unary operator '&', or the
7616     //      operator '->', the built-in candidates set is empty.
7617     break;
7618 
7619   case OO_Plus: // '+' is either unary or binary
7620     if (NumArgs == 1)
7621       OpBuilder.addUnaryPlusPointerOverloads();
7622     // Fall through.
7623 
7624   case OO_Minus: // '-' is either unary or binary
7625     if (NumArgs == 1) {
7626       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7627     } else {
7628       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7629       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7630     }
7631     break;
7632 
7633   case OO_Star: // '*' is either unary or binary
7634     if (NumArgs == 1)
7635       OpBuilder.addUnaryStarPointerOverloads();
7636     else
7637       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7638     break;
7639 
7640   case OO_Slash:
7641     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7642     break;
7643 
7644   case OO_PlusPlus:
7645   case OO_MinusMinus:
7646     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7647     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7648     break;
7649 
7650   case OO_EqualEqual:
7651   case OO_ExclaimEqual:
7652     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7653     // Fall through.
7654 
7655   case OO_Less:
7656   case OO_Greater:
7657   case OO_LessEqual:
7658   case OO_GreaterEqual:
7659     OpBuilder.addRelationalPointerOrEnumeralOverloads();
7660     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7661     break;
7662 
7663   case OO_Percent:
7664   case OO_Caret:
7665   case OO_Pipe:
7666   case OO_LessLess:
7667   case OO_GreaterGreater:
7668     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7669     break;
7670 
7671   case OO_Amp: // '&' is either unary or binary
7672     if (NumArgs == 1)
7673       // C++ [over.match.oper]p3:
7674       //   -- For the operator ',', the unary operator '&', or the
7675       //      operator '->', the built-in candidates set is empty.
7676       break;
7677 
7678     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7679     break;
7680 
7681   case OO_Tilde:
7682     OpBuilder.addUnaryTildePromotedIntegralOverloads();
7683     break;
7684 
7685   case OO_Equal:
7686     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7687     // Fall through.
7688 
7689   case OO_PlusEqual:
7690   case OO_MinusEqual:
7691     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7692     // Fall through.
7693 
7694   case OO_StarEqual:
7695   case OO_SlashEqual:
7696     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7697     break;
7698 
7699   case OO_PercentEqual:
7700   case OO_LessLessEqual:
7701   case OO_GreaterGreaterEqual:
7702   case OO_AmpEqual:
7703   case OO_CaretEqual:
7704   case OO_PipeEqual:
7705     OpBuilder.addAssignmentIntegralOverloads();
7706     break;
7707 
7708   case OO_Exclaim:
7709     OpBuilder.addExclaimOverload();
7710     break;
7711 
7712   case OO_AmpAmp:
7713   case OO_PipePipe:
7714     OpBuilder.addAmpAmpOrPipePipeOverload();
7715     break;
7716 
7717   case OO_Subscript:
7718     OpBuilder.addSubscriptOverloads();
7719     break;
7720 
7721   case OO_ArrowStar:
7722     OpBuilder.addArrowStarOverloads();
7723     break;
7724 
7725   case OO_Conditional:
7726     OpBuilder.addConditionalOperatorOverloads();
7727     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7728     break;
7729   }
7730 }
7731 
7732 /// \brief Add function candidates found via argument-dependent lookup
7733 /// to the set of overloading candidates.
7734 ///
7735 /// This routine performs argument-dependent name lookup based on the
7736 /// given function name (which may also be an operator name) and adds
7737 /// all of the overload candidates found by ADL to the overload
7738 /// candidate set (C++ [basic.lookup.argdep]).
7739 void
AddArgumentDependentLookupCandidates(DeclarationName Name,bool Operator,SourceLocation Loc,ArrayRef<Expr * > Args,TemplateArgumentListInfo * ExplicitTemplateArgs,OverloadCandidateSet & CandidateSet,bool PartialOverloading)7740 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7741                                            bool Operator, SourceLocation Loc,
7742                                            ArrayRef<Expr *> Args,
7743                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
7744                                            OverloadCandidateSet& CandidateSet,
7745                                            bool PartialOverloading) {
7746   ADLResult Fns;
7747 
7748   // FIXME: This approach for uniquing ADL results (and removing
7749   // redundant candidates from the set) relies on pointer-equality,
7750   // which means we need to key off the canonical decl.  However,
7751   // always going back to the canonical decl might not get us the
7752   // right set of default arguments.  What default arguments are
7753   // we supposed to consider on ADL candidates, anyway?
7754 
7755   // FIXME: Pass in the explicit template arguments?
7756   ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
7757 
7758   // Erase all of the candidates we already knew about.
7759   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7760                                    CandEnd = CandidateSet.end();
7761        Cand != CandEnd; ++Cand)
7762     if (Cand->Function) {
7763       Fns.erase(Cand->Function);
7764       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7765         Fns.erase(FunTmpl);
7766     }
7767 
7768   // For each of the ADL candidates we found, add it to the overload
7769   // set.
7770   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7771     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7772     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7773       if (ExplicitTemplateArgs)
7774         continue;
7775 
7776       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7777                            PartialOverloading);
7778     } else
7779       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7780                                    FoundDecl, ExplicitTemplateArgs,
7781                                    Args, CandidateSet);
7782   }
7783 }
7784 
7785 /// isBetterOverloadCandidate - Determines whether the first overload
7786 /// candidate is a better candidate than the second (C++ 13.3.3p1).
7787 bool
isBetterOverloadCandidate(Sema & S,const OverloadCandidate & Cand1,const OverloadCandidate & Cand2,SourceLocation Loc,bool UserDefinedConversion)7788 isBetterOverloadCandidate(Sema &S,
7789                           const OverloadCandidate &Cand1,
7790                           const OverloadCandidate &Cand2,
7791                           SourceLocation Loc,
7792                           bool UserDefinedConversion) {
7793   // Define viable functions to be better candidates than non-viable
7794   // functions.
7795   if (!Cand2.Viable)
7796     return Cand1.Viable;
7797   else if (!Cand1.Viable)
7798     return false;
7799 
7800   // C++ [over.match.best]p1:
7801   //
7802   //   -- if F is a static member function, ICS1(F) is defined such
7803   //      that ICS1(F) is neither better nor worse than ICS1(G) for
7804   //      any function G, and, symmetrically, ICS1(G) is neither
7805   //      better nor worse than ICS1(F).
7806   unsigned StartArg = 0;
7807   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7808     StartArg = 1;
7809 
7810   // C++ [over.match.best]p1:
7811   //   A viable function F1 is defined to be a better function than another
7812   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
7813   //   conversion sequence than ICSi(F2), and then...
7814   unsigned NumArgs = Cand1.NumConversions;
7815   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7816   bool HasBetterConversion = false;
7817   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7818     switch (CompareImplicitConversionSequences(S,
7819                                                Cand1.Conversions[ArgIdx],
7820                                                Cand2.Conversions[ArgIdx])) {
7821     case ImplicitConversionSequence::Better:
7822       // Cand1 has a better conversion sequence.
7823       HasBetterConversion = true;
7824       break;
7825 
7826     case ImplicitConversionSequence::Worse:
7827       // Cand1 can't be better than Cand2.
7828       return false;
7829 
7830     case ImplicitConversionSequence::Indistinguishable:
7831       // Do nothing.
7832       break;
7833     }
7834   }
7835 
7836   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
7837   //       ICSj(F2), or, if not that,
7838   if (HasBetterConversion)
7839     return true;
7840 
7841   //     - F1 is a non-template function and F2 is a function template
7842   //       specialization, or, if not that,
7843   if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
7844       Cand2.Function && Cand2.Function->getPrimaryTemplate())
7845     return true;
7846 
7847   //   -- F1 and F2 are function template specializations, and the function
7848   //      template for F1 is more specialized than the template for F2
7849   //      according to the partial ordering rules described in 14.5.5.2, or,
7850   //      if not that,
7851   if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
7852       Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
7853     if (FunctionTemplateDecl *BetterTemplate
7854           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7855                                          Cand2.Function->getPrimaryTemplate(),
7856                                          Loc,
7857                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
7858                                                              : TPOC_Call,
7859                                          Cand1.ExplicitCallArguments))
7860       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
7861   }
7862 
7863   //   -- the context is an initialization by user-defined conversion
7864   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
7865   //      from the return type of F1 to the destination type (i.e.,
7866   //      the type of the entity being initialized) is a better
7867   //      conversion sequence than the standard conversion sequence
7868   //      from the return type of F2 to the destination type.
7869   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
7870       isa<CXXConversionDecl>(Cand1.Function) &&
7871       isa<CXXConversionDecl>(Cand2.Function)) {
7872     // First check whether we prefer one of the conversion functions over the
7873     // other. This only distinguishes the results in non-standard, extension
7874     // cases such as the conversion from a lambda closure type to a function
7875     // pointer or block.
7876     ImplicitConversionSequence::CompareKind FuncResult
7877       = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7878     if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7879       return FuncResult;
7880 
7881     switch (CompareStandardConversionSequences(S,
7882                                                Cand1.FinalConversion,
7883                                                Cand2.FinalConversion)) {
7884     case ImplicitConversionSequence::Better:
7885       // Cand1 has a better conversion sequence.
7886       return true;
7887 
7888     case ImplicitConversionSequence::Worse:
7889       // Cand1 can't be better than Cand2.
7890       return false;
7891 
7892     case ImplicitConversionSequence::Indistinguishable:
7893       // Do nothing
7894       break;
7895     }
7896   }
7897 
7898   return false;
7899 }
7900 
7901 /// \brief Computes the best viable function (C++ 13.3.3)
7902 /// within an overload candidate set.
7903 ///
7904 /// \param Loc The location of the function name (or operator symbol) for
7905 /// which overload resolution occurs.
7906 ///
7907 /// \param Best If overload resolution was successful or found a deleted
7908 /// function, \p Best points to the candidate function found.
7909 ///
7910 /// \returns The result of overload resolution.
7911 OverloadingResult
BestViableFunction(Sema & S,SourceLocation Loc,iterator & Best,bool UserDefinedConversion)7912 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
7913                                          iterator &Best,
7914                                          bool UserDefinedConversion) {
7915   // Find the best viable function.
7916   Best = end();
7917   for (iterator Cand = begin(); Cand != end(); ++Cand) {
7918     if (Cand->Viable)
7919       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
7920                                                      UserDefinedConversion))
7921         Best = Cand;
7922   }
7923 
7924   // If we didn't find any viable functions, abort.
7925   if (Best == end())
7926     return OR_No_Viable_Function;
7927 
7928   // Make sure that this function is better than every other viable
7929   // function. If not, we have an ambiguity.
7930   for (iterator Cand = begin(); Cand != end(); ++Cand) {
7931     if (Cand->Viable &&
7932         Cand != Best &&
7933         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
7934                                    UserDefinedConversion)) {
7935       Best = end();
7936       return OR_Ambiguous;
7937     }
7938   }
7939 
7940   // Best is the best viable function.
7941   if (Best->Function &&
7942       (Best->Function->isDeleted() ||
7943        S.isFunctionConsideredUnavailable(Best->Function)))
7944     return OR_Deleted;
7945 
7946   return OR_Success;
7947 }
7948 
7949 namespace {
7950 
7951 enum OverloadCandidateKind {
7952   oc_function,
7953   oc_method,
7954   oc_constructor,
7955   oc_function_template,
7956   oc_method_template,
7957   oc_constructor_template,
7958   oc_implicit_default_constructor,
7959   oc_implicit_copy_constructor,
7960   oc_implicit_move_constructor,
7961   oc_implicit_copy_assignment,
7962   oc_implicit_move_assignment,
7963   oc_implicit_inherited_constructor
7964 };
7965 
ClassifyOverloadCandidate(Sema & S,FunctionDecl * Fn,std::string & Description)7966 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7967                                                 FunctionDecl *Fn,
7968                                                 std::string &Description) {
7969   bool isTemplate = false;
7970 
7971   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7972     isTemplate = true;
7973     Description = S.getTemplateArgumentBindingsText(
7974       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7975   }
7976 
7977   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
7978     if (!Ctor->isImplicit())
7979       return isTemplate ? oc_constructor_template : oc_constructor;
7980 
7981     if (Ctor->getInheritedConstructor())
7982       return oc_implicit_inherited_constructor;
7983 
7984     if (Ctor->isDefaultConstructor())
7985       return oc_implicit_default_constructor;
7986 
7987     if (Ctor->isMoveConstructor())
7988       return oc_implicit_move_constructor;
7989 
7990     assert(Ctor->isCopyConstructor() &&
7991            "unexpected sort of implicit constructor");
7992     return oc_implicit_copy_constructor;
7993   }
7994 
7995   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7996     // This actually gets spelled 'candidate function' for now, but
7997     // it doesn't hurt to split it out.
7998     if (!Meth->isImplicit())
7999       return isTemplate ? oc_method_template : oc_method;
8000 
8001     if (Meth->isMoveAssignmentOperator())
8002       return oc_implicit_move_assignment;
8003 
8004     if (Meth->isCopyAssignmentOperator())
8005       return oc_implicit_copy_assignment;
8006 
8007     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8008     return oc_method;
8009   }
8010 
8011   return isTemplate ? oc_function_template : oc_function;
8012 }
8013 
MaybeEmitInheritedConstructorNote(Sema & S,FunctionDecl * Fn)8014 void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
8015   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8016   if (!Ctor) return;
8017 
8018   Ctor = Ctor->getInheritedConstructor();
8019   if (!Ctor) return;
8020 
8021   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8022 }
8023 
8024 } // end anonymous namespace
8025 
8026 // Notes the location of an overload candidate.
NoteOverloadCandidate(FunctionDecl * Fn,QualType DestType)8027 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8028   std::string FnDesc;
8029   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8030   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8031                              << (unsigned) K << FnDesc;
8032   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8033   Diag(Fn->getLocation(), PD);
8034   MaybeEmitInheritedConstructorNote(*this, Fn);
8035 }
8036 
8037 //Notes the location of all overload candidates designated through
8038 // OverloadedExpr
NoteAllOverloadCandidates(Expr * OverloadedExpr,QualType DestType)8039 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8040   assert(OverloadedExpr->getType() == Context.OverloadTy);
8041 
8042   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8043   OverloadExpr *OvlExpr = Ovl.Expression;
8044 
8045   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8046                             IEnd = OvlExpr->decls_end();
8047        I != IEnd; ++I) {
8048     if (FunctionTemplateDecl *FunTmpl =
8049                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8050       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8051     } else if (FunctionDecl *Fun
8052                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8053       NoteOverloadCandidate(Fun, DestType);
8054     }
8055   }
8056 }
8057 
8058 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
8059 /// "lead" diagnostic; it will be given two arguments, the source and
8060 /// target types of the conversion.
DiagnoseAmbiguousConversion(Sema & S,SourceLocation CaretLoc,const PartialDiagnostic & PDiag) const8061 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8062                                  Sema &S,
8063                                  SourceLocation CaretLoc,
8064                                  const PartialDiagnostic &PDiag) const {
8065   S.Diag(CaretLoc, PDiag)
8066     << Ambiguous.getFromType() << Ambiguous.getToType();
8067   // FIXME: The note limiting machinery is borrowed from
8068   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8069   // refactoring here.
8070   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8071   unsigned CandsShown = 0;
8072   AmbiguousConversionSequence::const_iterator I, E;
8073   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8074     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8075       break;
8076     ++CandsShown;
8077     S.NoteOverloadCandidate(*I);
8078   }
8079   if (I != E)
8080     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8081 }
8082 
8083 namespace {
8084 
DiagnoseBadConversion(Sema & S,OverloadCandidate * Cand,unsigned I)8085 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8086   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8087   assert(Conv.isBad());
8088   assert(Cand->Function && "for now, candidate must be a function");
8089   FunctionDecl *Fn = Cand->Function;
8090 
8091   // There's a conversion slot for the object argument if this is a
8092   // non-constructor method.  Note that 'I' corresponds the
8093   // conversion-slot index.
8094   bool isObjectArgument = false;
8095   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8096     if (I == 0)
8097       isObjectArgument = true;
8098     else
8099       I--;
8100   }
8101 
8102   std::string FnDesc;
8103   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8104 
8105   Expr *FromExpr = Conv.Bad.FromExpr;
8106   QualType FromTy = Conv.Bad.getFromType();
8107   QualType ToTy = Conv.Bad.getToType();
8108 
8109   if (FromTy == S.Context.OverloadTy) {
8110     assert(FromExpr && "overload set argument came from implicit argument?");
8111     Expr *E = FromExpr->IgnoreParens();
8112     if (isa<UnaryOperator>(E))
8113       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8114     DeclarationName Name = cast<OverloadExpr>(E)->getName();
8115 
8116     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8117       << (unsigned) FnKind << FnDesc
8118       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8119       << ToTy << Name << I+1;
8120     MaybeEmitInheritedConstructorNote(S, Fn);
8121     return;
8122   }
8123 
8124   // Do some hand-waving analysis to see if the non-viability is due
8125   // to a qualifier mismatch.
8126   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8127   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8128   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8129     CToTy = RT->getPointeeType();
8130   else {
8131     // TODO: detect and diagnose the full richness of const mismatches.
8132     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8133       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8134         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8135   }
8136 
8137   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8138       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8139     Qualifiers FromQs = CFromTy.getQualifiers();
8140     Qualifiers ToQs = CToTy.getQualifiers();
8141 
8142     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8143       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8144         << (unsigned) FnKind << FnDesc
8145         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8146         << FromTy
8147         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8148         << (unsigned) isObjectArgument << I+1;
8149       MaybeEmitInheritedConstructorNote(S, Fn);
8150       return;
8151     }
8152 
8153     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8154       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8155         << (unsigned) FnKind << FnDesc
8156         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8157         << FromTy
8158         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8159         << (unsigned) isObjectArgument << I+1;
8160       MaybeEmitInheritedConstructorNote(S, Fn);
8161       return;
8162     }
8163 
8164     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8165       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8166       << (unsigned) FnKind << FnDesc
8167       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8168       << FromTy
8169       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8170       << (unsigned) isObjectArgument << I+1;
8171       MaybeEmitInheritedConstructorNote(S, Fn);
8172       return;
8173     }
8174 
8175     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8176     assert(CVR && "unexpected qualifiers mismatch");
8177 
8178     if (isObjectArgument) {
8179       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8180         << (unsigned) FnKind << FnDesc
8181         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8182         << FromTy << (CVR - 1);
8183     } else {
8184       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8185         << (unsigned) FnKind << FnDesc
8186         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8187         << FromTy << (CVR - 1) << I+1;
8188     }
8189     MaybeEmitInheritedConstructorNote(S, Fn);
8190     return;
8191   }
8192 
8193   // Special diagnostic for failure to convert an initializer list, since
8194   // telling the user that it has type void is not useful.
8195   if (FromExpr && isa<InitListExpr>(FromExpr)) {
8196     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8197       << (unsigned) FnKind << FnDesc
8198       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8199       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8200     MaybeEmitInheritedConstructorNote(S, Fn);
8201     return;
8202   }
8203 
8204   // Diagnose references or pointers to incomplete types differently,
8205   // since it's far from impossible that the incompleteness triggered
8206   // the failure.
8207   QualType TempFromTy = FromTy.getNonReferenceType();
8208   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8209     TempFromTy = PTy->getPointeeType();
8210   if (TempFromTy->isIncompleteType()) {
8211     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8212       << (unsigned) FnKind << FnDesc
8213       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8214       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8215     MaybeEmitInheritedConstructorNote(S, Fn);
8216     return;
8217   }
8218 
8219   // Diagnose base -> derived pointer conversions.
8220   unsigned BaseToDerivedConversion = 0;
8221   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8222     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8223       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8224                                                FromPtrTy->getPointeeType()) &&
8225           !FromPtrTy->getPointeeType()->isIncompleteType() &&
8226           !ToPtrTy->getPointeeType()->isIncompleteType() &&
8227           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8228                           FromPtrTy->getPointeeType()))
8229         BaseToDerivedConversion = 1;
8230     }
8231   } else if (const ObjCObjectPointerType *FromPtrTy
8232                                     = FromTy->getAs<ObjCObjectPointerType>()) {
8233     if (const ObjCObjectPointerType *ToPtrTy
8234                                         = ToTy->getAs<ObjCObjectPointerType>())
8235       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8236         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8237           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8238                                                 FromPtrTy->getPointeeType()) &&
8239               FromIface->isSuperClassOf(ToIface))
8240             BaseToDerivedConversion = 2;
8241   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8242     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8243         !FromTy->isIncompleteType() &&
8244         !ToRefTy->getPointeeType()->isIncompleteType() &&
8245         S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8246       BaseToDerivedConversion = 3;
8247     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8248                ToTy.getNonReferenceType().getCanonicalType() ==
8249                FromTy.getNonReferenceType().getCanonicalType()) {
8250       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8251         << (unsigned) FnKind << FnDesc
8252         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8253         << (unsigned) isObjectArgument << I + 1;
8254       MaybeEmitInheritedConstructorNote(S, Fn);
8255       return;
8256     }
8257   }
8258 
8259   if (BaseToDerivedConversion) {
8260     S.Diag(Fn->getLocation(),
8261            diag::note_ovl_candidate_bad_base_to_derived_conv)
8262       << (unsigned) FnKind << FnDesc
8263       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8264       << (BaseToDerivedConversion - 1)
8265       << FromTy << ToTy << I+1;
8266     MaybeEmitInheritedConstructorNote(S, Fn);
8267     return;
8268   }
8269 
8270   if (isa<ObjCObjectPointerType>(CFromTy) &&
8271       isa<PointerType>(CToTy)) {
8272       Qualifiers FromQs = CFromTy.getQualifiers();
8273       Qualifiers ToQs = CToTy.getQualifiers();
8274       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8275         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8276         << (unsigned) FnKind << FnDesc
8277         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8278         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8279         MaybeEmitInheritedConstructorNote(S, Fn);
8280         return;
8281       }
8282   }
8283 
8284   // Emit the generic diagnostic and, optionally, add the hints to it.
8285   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8286   FDiag << (unsigned) FnKind << FnDesc
8287     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8288     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8289     << (unsigned) (Cand->Fix.Kind);
8290 
8291   // If we can fix the conversion, suggest the FixIts.
8292   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8293        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8294     FDiag << *HI;
8295   S.Diag(Fn->getLocation(), FDiag);
8296 
8297   MaybeEmitInheritedConstructorNote(S, Fn);
8298 }
8299 
DiagnoseArityMismatch(Sema & S,OverloadCandidate * Cand,unsigned NumFormalArgs)8300 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8301                            unsigned NumFormalArgs) {
8302   // TODO: treat calls to a missing default constructor as a special case
8303 
8304   FunctionDecl *Fn = Cand->Function;
8305   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8306 
8307   unsigned MinParams = Fn->getMinRequiredArguments();
8308 
8309   // With invalid overloaded operators, it's possible that we think we
8310   // have an arity mismatch when it fact it looks like we have the
8311   // right number of arguments, because only overloaded operators have
8312   // the weird behavior of overloading member and non-member functions.
8313   // Just don't report anything.
8314   if (Fn->isInvalidDecl() &&
8315       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8316     return;
8317 
8318   // at least / at most / exactly
8319   unsigned mode, modeCount;
8320   if (NumFormalArgs < MinParams) {
8321     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8322            (Cand->FailureKind == ovl_fail_bad_deduction &&
8323             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8324     if (MinParams != FnTy->getNumArgs() ||
8325         FnTy->isVariadic() || FnTy->isTemplateVariadic())
8326       mode = 0; // "at least"
8327     else
8328       mode = 2; // "exactly"
8329     modeCount = MinParams;
8330   } else {
8331     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8332            (Cand->FailureKind == ovl_fail_bad_deduction &&
8333             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8334     if (MinParams != FnTy->getNumArgs())
8335       mode = 1; // "at most"
8336     else
8337       mode = 2; // "exactly"
8338     modeCount = FnTy->getNumArgs();
8339   }
8340 
8341   std::string Description;
8342   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8343 
8344   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8345     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8346       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8347       << Fn->getParamDecl(0) << NumFormalArgs;
8348   else
8349     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8350       << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8351       << modeCount << NumFormalArgs;
8352   MaybeEmitInheritedConstructorNote(S, Fn);
8353 }
8354 
8355 /// Diagnose a failed template-argument deduction.
DiagnoseBadDeduction(Sema & S,OverloadCandidate * Cand,unsigned NumArgs)8356 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
8357                           unsigned NumArgs) {
8358   FunctionDecl *Fn = Cand->Function; // pattern
8359 
8360   TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
8361   NamedDecl *ParamD;
8362   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8363   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8364   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8365   switch (Cand->DeductionFailure.Result) {
8366   case Sema::TDK_Success:
8367     llvm_unreachable("TDK_success while diagnosing bad deduction");
8368 
8369   case Sema::TDK_Incomplete: {
8370     assert(ParamD && "no parameter found for incomplete deduction result");
8371     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8372       << ParamD->getDeclName();
8373     MaybeEmitInheritedConstructorNote(S, Fn);
8374     return;
8375   }
8376 
8377   case Sema::TDK_Underqualified: {
8378     assert(ParamD && "no parameter found for bad qualifiers deduction result");
8379     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8380 
8381     QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8382 
8383     // Param will have been canonicalized, but it should just be a
8384     // qualified version of ParamD, so move the qualifiers to that.
8385     QualifierCollector Qs;
8386     Qs.strip(Param);
8387     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8388     assert(S.Context.hasSameType(Param, NonCanonParam));
8389 
8390     // Arg has also been canonicalized, but there's nothing we can do
8391     // about that.  It also doesn't matter as much, because it won't
8392     // have any template parameters in it (because deduction isn't
8393     // done on dependent types).
8394     QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8395 
8396     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8397       << ParamD->getDeclName() << Arg << NonCanonParam;
8398     MaybeEmitInheritedConstructorNote(S, Fn);
8399     return;
8400   }
8401 
8402   case Sema::TDK_Inconsistent: {
8403     assert(ParamD && "no parameter found for inconsistent deduction result");
8404     int which = 0;
8405     if (isa<TemplateTypeParmDecl>(ParamD))
8406       which = 0;
8407     else if (isa<NonTypeTemplateParmDecl>(ParamD))
8408       which = 1;
8409     else {
8410       which = 2;
8411     }
8412 
8413     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
8414       << which << ParamD->getDeclName()
8415       << *Cand->DeductionFailure.getFirstArg()
8416       << *Cand->DeductionFailure.getSecondArg();
8417     MaybeEmitInheritedConstructorNote(S, Fn);
8418     return;
8419   }
8420 
8421   case Sema::TDK_InvalidExplicitArguments:
8422     assert(ParamD && "no parameter found for invalid explicit arguments");
8423     if (ParamD->getDeclName())
8424       S.Diag(Fn->getLocation(),
8425              diag::note_ovl_candidate_explicit_arg_mismatch_named)
8426         << ParamD->getDeclName();
8427     else {
8428       int index = 0;
8429       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8430         index = TTP->getIndex();
8431       else if (NonTypeTemplateParmDecl *NTTP
8432                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8433         index = NTTP->getIndex();
8434       else
8435         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8436       S.Diag(Fn->getLocation(),
8437              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8438         << (index + 1);
8439     }
8440     MaybeEmitInheritedConstructorNote(S, Fn);
8441     return;
8442 
8443   case Sema::TDK_TooManyArguments:
8444   case Sema::TDK_TooFewArguments:
8445     DiagnoseArityMismatch(S, Cand, NumArgs);
8446     return;
8447 
8448   case Sema::TDK_InstantiationDepth:
8449     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
8450     MaybeEmitInheritedConstructorNote(S, Fn);
8451     return;
8452 
8453   case Sema::TDK_SubstitutionFailure: {
8454     // Format the template argument list into the argument string.
8455     SmallString<128> TemplateArgString;
8456     if (TemplateArgumentList *Args =
8457           Cand->DeductionFailure.getTemplateArgumentList()) {
8458       TemplateArgString = " ";
8459       TemplateArgString += S.getTemplateArgumentBindingsText(
8460           Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8461     }
8462 
8463     // If this candidate was disabled by enable_if, say so.
8464     PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8465     if (PDiag && PDiag->second.getDiagID() ==
8466           diag::err_typename_nested_not_found_enable_if) {
8467       // FIXME: Use the source range of the condition, and the fully-qualified
8468       //        name of the enable_if template. These are both present in PDiag.
8469       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8470         << "'enable_if'" << TemplateArgString;
8471       return;
8472     }
8473 
8474     // Format the SFINAE diagnostic into the argument string.
8475     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8476     //        formatted message in another diagnostic.
8477     SmallString<128> SFINAEArgString;
8478     SourceRange R;
8479     if (PDiag) {
8480       SFINAEArgString = ": ";
8481       R = SourceRange(PDiag->first, PDiag->first);
8482       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8483     }
8484 
8485     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8486       << TemplateArgString << SFINAEArgString << R;
8487     MaybeEmitInheritedConstructorNote(S, Fn);
8488     return;
8489   }
8490 
8491   case Sema::TDK_FailedOverloadResolution: {
8492     OverloadExpr::FindResult R =
8493         OverloadExpr::find(Cand->DeductionFailure.getExpr());
8494     S.Diag(Fn->getLocation(),
8495            diag::note_ovl_candidate_failed_overload_resolution)
8496       << R.Expression->getName();
8497     return;
8498   }
8499 
8500   case Sema::TDK_NonDeducedMismatch:
8501     // FIXME: Provide a source location to indicate what we couldn't match.
8502     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
8503       << *Cand->DeductionFailure.getFirstArg()
8504       << *Cand->DeductionFailure.getSecondArg();
8505     return;
8506 
8507   // TODO: diagnose these individually, then kill off
8508   // note_ovl_candidate_bad_deduction, which is uselessly vague.
8509   case Sema::TDK_MiscellaneousDeductionFailure:
8510     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
8511     MaybeEmitInheritedConstructorNote(S, Fn);
8512     return;
8513   }
8514 }
8515 
8516 /// CUDA: diagnose an invalid call across targets.
DiagnoseBadTarget(Sema & S,OverloadCandidate * Cand)8517 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8518   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8519   FunctionDecl *Callee = Cand->Function;
8520 
8521   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8522                            CalleeTarget = S.IdentifyCUDATarget(Callee);
8523 
8524   std::string FnDesc;
8525   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8526 
8527   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8528       << (unsigned) FnKind << CalleeTarget << CallerTarget;
8529 }
8530 
8531 /// Generates a 'note' diagnostic for an overload candidate.  We've
8532 /// already generated a primary error at the call site.
8533 ///
8534 /// It really does need to be a single diagnostic with its caret
8535 /// pointed at the candidate declaration.  Yes, this creates some
8536 /// major challenges of technical writing.  Yes, this makes pointing
8537 /// out problems with specific arguments quite awkward.  It's still
8538 /// better than generating twenty screens of text for every failed
8539 /// overload.
8540 ///
8541 /// It would be great to be able to express per-candidate problems
8542 /// more richly for those diagnostic clients that cared, but we'd
8543 /// still have to be just as careful with the default diagnostics.
NoteFunctionCandidate(Sema & S,OverloadCandidate * Cand,unsigned NumArgs)8544 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8545                            unsigned NumArgs) {
8546   FunctionDecl *Fn = Cand->Function;
8547 
8548   // Note deleted candidates, but only if they're viable.
8549   if (Cand->Viable && (Fn->isDeleted() ||
8550       S.isFunctionConsideredUnavailable(Fn))) {
8551     std::string FnDesc;
8552     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8553 
8554     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8555       << FnKind << FnDesc
8556       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8557     MaybeEmitInheritedConstructorNote(S, Fn);
8558     return;
8559   }
8560 
8561   // We don't really have anything else to say about viable candidates.
8562   if (Cand->Viable) {
8563     S.NoteOverloadCandidate(Fn);
8564     return;
8565   }
8566 
8567   switch (Cand->FailureKind) {
8568   case ovl_fail_too_many_arguments:
8569   case ovl_fail_too_few_arguments:
8570     return DiagnoseArityMismatch(S, Cand, NumArgs);
8571 
8572   case ovl_fail_bad_deduction:
8573     return DiagnoseBadDeduction(S, Cand, NumArgs);
8574 
8575   case ovl_fail_trivial_conversion:
8576   case ovl_fail_bad_final_conversion:
8577   case ovl_fail_final_conversion_not_exact:
8578     return S.NoteOverloadCandidate(Fn);
8579 
8580   case ovl_fail_bad_conversion: {
8581     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8582     for (unsigned N = Cand->NumConversions; I != N; ++I)
8583       if (Cand->Conversions[I].isBad())
8584         return DiagnoseBadConversion(S, Cand, I);
8585 
8586     // FIXME: this currently happens when we're called from SemaInit
8587     // when user-conversion overload fails.  Figure out how to handle
8588     // those conditions and diagnose them well.
8589     return S.NoteOverloadCandidate(Fn);
8590   }
8591 
8592   case ovl_fail_bad_target:
8593     return DiagnoseBadTarget(S, Cand);
8594   }
8595 }
8596 
NoteSurrogateCandidate(Sema & S,OverloadCandidate * Cand)8597 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8598   // Desugar the type of the surrogate down to a function type,
8599   // retaining as many typedefs as possible while still showing
8600   // the function type (and, therefore, its parameter types).
8601   QualType FnType = Cand->Surrogate->getConversionType();
8602   bool isLValueReference = false;
8603   bool isRValueReference = false;
8604   bool isPointer = false;
8605   if (const LValueReferenceType *FnTypeRef =
8606         FnType->getAs<LValueReferenceType>()) {
8607     FnType = FnTypeRef->getPointeeType();
8608     isLValueReference = true;
8609   } else if (const RValueReferenceType *FnTypeRef =
8610                FnType->getAs<RValueReferenceType>()) {
8611     FnType = FnTypeRef->getPointeeType();
8612     isRValueReference = true;
8613   }
8614   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8615     FnType = FnTypePtr->getPointeeType();
8616     isPointer = true;
8617   }
8618   // Desugar down to a function type.
8619   FnType = QualType(FnType->getAs<FunctionType>(), 0);
8620   // Reconstruct the pointer/reference as appropriate.
8621   if (isPointer) FnType = S.Context.getPointerType(FnType);
8622   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8623   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8624 
8625   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8626     << FnType;
8627   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8628 }
8629 
NoteBuiltinOperatorCandidate(Sema & S,StringRef Opc,SourceLocation OpLoc,OverloadCandidate * Cand)8630 void NoteBuiltinOperatorCandidate(Sema &S,
8631                                   StringRef Opc,
8632                                   SourceLocation OpLoc,
8633                                   OverloadCandidate *Cand) {
8634   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8635   std::string TypeStr("operator");
8636   TypeStr += Opc;
8637   TypeStr += "(";
8638   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8639   if (Cand->NumConversions == 1) {
8640     TypeStr += ")";
8641     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8642   } else {
8643     TypeStr += ", ";
8644     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8645     TypeStr += ")";
8646     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8647   }
8648 }
8649 
NoteAmbiguousUserConversions(Sema & S,SourceLocation OpLoc,OverloadCandidate * Cand)8650 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8651                                   OverloadCandidate *Cand) {
8652   unsigned NoOperands = Cand->NumConversions;
8653   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8654     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8655     if (ICS.isBad()) break; // all meaningless after first invalid
8656     if (!ICS.isAmbiguous()) continue;
8657 
8658     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8659                               S.PDiag(diag::note_ambiguous_type_conversion));
8660   }
8661 }
8662 
GetLocationForCandidate(const OverloadCandidate * Cand)8663 SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8664   if (Cand->Function)
8665     return Cand->Function->getLocation();
8666   if (Cand->IsSurrogate)
8667     return Cand->Surrogate->getLocation();
8668   return SourceLocation();
8669 }
8670 
8671 static unsigned
RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo & DFI)8672 RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
8673   switch ((Sema::TemplateDeductionResult)DFI.Result) {
8674   case Sema::TDK_Success:
8675     llvm_unreachable("TDK_success while diagnosing bad deduction");
8676 
8677   case Sema::TDK_Invalid:
8678   case Sema::TDK_Incomplete:
8679     return 1;
8680 
8681   case Sema::TDK_Underqualified:
8682   case Sema::TDK_Inconsistent:
8683     return 2;
8684 
8685   case Sema::TDK_SubstitutionFailure:
8686   case Sema::TDK_NonDeducedMismatch:
8687   case Sema::TDK_MiscellaneousDeductionFailure:
8688     return 3;
8689 
8690   case Sema::TDK_InstantiationDepth:
8691   case Sema::TDK_FailedOverloadResolution:
8692     return 4;
8693 
8694   case Sema::TDK_InvalidExplicitArguments:
8695     return 5;
8696 
8697   case Sema::TDK_TooManyArguments:
8698   case Sema::TDK_TooFewArguments:
8699     return 6;
8700   }
8701   llvm_unreachable("Unhandled deduction result");
8702 }
8703 
8704 struct CompareOverloadCandidatesForDisplay {
8705   Sema &S;
CompareOverloadCandidatesForDisplayclang::__anon5e4855d90611::CompareOverloadCandidatesForDisplay8706   CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8707 
operator ()clang::__anon5e4855d90611::CompareOverloadCandidatesForDisplay8708   bool operator()(const OverloadCandidate *L,
8709                   const OverloadCandidate *R) {
8710     // Fast-path this check.
8711     if (L == R) return false;
8712 
8713     // Order first by viability.
8714     if (L->Viable) {
8715       if (!R->Viable) return true;
8716 
8717       // TODO: introduce a tri-valued comparison for overload
8718       // candidates.  Would be more worthwhile if we had a sort
8719       // that could exploit it.
8720       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8721       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8722     } else if (R->Viable)
8723       return false;
8724 
8725     assert(L->Viable == R->Viable);
8726 
8727     // Criteria by which we can sort non-viable candidates:
8728     if (!L->Viable) {
8729       // 1. Arity mismatches come after other candidates.
8730       if (L->FailureKind == ovl_fail_too_many_arguments ||
8731           L->FailureKind == ovl_fail_too_few_arguments)
8732         return false;
8733       if (R->FailureKind == ovl_fail_too_many_arguments ||
8734           R->FailureKind == ovl_fail_too_few_arguments)
8735         return true;
8736 
8737       // 2. Bad conversions come first and are ordered by the number
8738       // of bad conversions and quality of good conversions.
8739       if (L->FailureKind == ovl_fail_bad_conversion) {
8740         if (R->FailureKind != ovl_fail_bad_conversion)
8741           return true;
8742 
8743         // The conversion that can be fixed with a smaller number of changes,
8744         // comes first.
8745         unsigned numLFixes = L->Fix.NumConversionsFixed;
8746         unsigned numRFixes = R->Fix.NumConversionsFixed;
8747         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8748         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8749         if (numLFixes != numRFixes) {
8750           if (numLFixes < numRFixes)
8751             return true;
8752           else
8753             return false;
8754         }
8755 
8756         // If there's any ordering between the defined conversions...
8757         // FIXME: this might not be transitive.
8758         assert(L->NumConversions == R->NumConversions);
8759 
8760         int leftBetter = 0;
8761         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8762         for (unsigned E = L->NumConversions; I != E; ++I) {
8763           switch (CompareImplicitConversionSequences(S,
8764                                                      L->Conversions[I],
8765                                                      R->Conversions[I])) {
8766           case ImplicitConversionSequence::Better:
8767             leftBetter++;
8768             break;
8769 
8770           case ImplicitConversionSequence::Worse:
8771             leftBetter--;
8772             break;
8773 
8774           case ImplicitConversionSequence::Indistinguishable:
8775             break;
8776           }
8777         }
8778         if (leftBetter > 0) return true;
8779         if (leftBetter < 0) return false;
8780 
8781       } else if (R->FailureKind == ovl_fail_bad_conversion)
8782         return false;
8783 
8784       if (L->FailureKind == ovl_fail_bad_deduction) {
8785         if (R->FailureKind != ovl_fail_bad_deduction)
8786           return true;
8787 
8788         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8789           return RankDeductionFailure(L->DeductionFailure)
8790                < RankDeductionFailure(R->DeductionFailure);
8791       } else if (R->FailureKind == ovl_fail_bad_deduction)
8792         return false;
8793 
8794       // TODO: others?
8795     }
8796 
8797     // Sort everything else by location.
8798     SourceLocation LLoc = GetLocationForCandidate(L);
8799     SourceLocation RLoc = GetLocationForCandidate(R);
8800 
8801     // Put candidates without locations (e.g. builtins) at the end.
8802     if (LLoc.isInvalid()) return false;
8803     if (RLoc.isInvalid()) return true;
8804 
8805     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8806   }
8807 };
8808 
8809 /// CompleteNonViableCandidate - Normally, overload resolution only
8810 /// computes up to the first. Produces the FixIt set if possible.
CompleteNonViableCandidate(Sema & S,OverloadCandidate * Cand,ArrayRef<Expr * > Args)8811 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8812                                 ArrayRef<Expr *> Args) {
8813   assert(!Cand->Viable);
8814 
8815   // Don't do anything on failures other than bad conversion.
8816   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8817 
8818   // We only want the FixIts if all the arguments can be corrected.
8819   bool Unfixable = false;
8820   // Use a implicit copy initialization to check conversion fixes.
8821   Cand->Fix.setConversionChecker(TryCopyInitialization);
8822 
8823   // Skip forward to the first bad conversion.
8824   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
8825   unsigned ConvCount = Cand->NumConversions;
8826   while (true) {
8827     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8828     ConvIdx++;
8829     if (Cand->Conversions[ConvIdx - 1].isBad()) {
8830       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
8831       break;
8832     }
8833   }
8834 
8835   if (ConvIdx == ConvCount)
8836     return;
8837 
8838   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8839          "remaining conversion is initialized?");
8840 
8841   // FIXME: this should probably be preserved from the overload
8842   // operation somehow.
8843   bool SuppressUserConversions = false;
8844 
8845   const FunctionProtoType* Proto;
8846   unsigned ArgIdx = ConvIdx;
8847 
8848   if (Cand->IsSurrogate) {
8849     QualType ConvType
8850       = Cand->Surrogate->getConversionType().getNonReferenceType();
8851     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8852       ConvType = ConvPtrType->getPointeeType();
8853     Proto = ConvType->getAs<FunctionProtoType>();
8854     ArgIdx--;
8855   } else if (Cand->Function) {
8856     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8857     if (isa<CXXMethodDecl>(Cand->Function) &&
8858         !isa<CXXConstructorDecl>(Cand->Function))
8859       ArgIdx--;
8860   } else {
8861     // Builtin binary operator with a bad first conversion.
8862     assert(ConvCount <= 3);
8863     for (; ConvIdx != ConvCount; ++ConvIdx)
8864       Cand->Conversions[ConvIdx]
8865         = TryCopyInitialization(S, Args[ConvIdx],
8866                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
8867                                 SuppressUserConversions,
8868                                 /*InOverloadResolution*/ true,
8869                                 /*AllowObjCWritebackConversion=*/
8870                                   S.getLangOpts().ObjCAutoRefCount);
8871     return;
8872   }
8873 
8874   // Fill in the rest of the conversions.
8875   unsigned NumArgsInProto = Proto->getNumArgs();
8876   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
8877     if (ArgIdx < NumArgsInProto) {
8878       Cand->Conversions[ConvIdx]
8879         = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
8880                                 SuppressUserConversions,
8881                                 /*InOverloadResolution=*/true,
8882                                 /*AllowObjCWritebackConversion=*/
8883                                   S.getLangOpts().ObjCAutoRefCount);
8884       // Store the FixIt in the candidate if it exists.
8885       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
8886         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
8887     }
8888     else
8889       Cand->Conversions[ConvIdx].setEllipsis();
8890   }
8891 }
8892 
8893 } // end anonymous namespace
8894 
8895 /// PrintOverloadCandidates - When overload resolution fails, prints
8896 /// diagnostic messages containing the candidates in the candidate
8897 /// set.
NoteCandidates(Sema & S,OverloadCandidateDisplayKind OCD,ArrayRef<Expr * > Args,StringRef Opc,SourceLocation OpLoc)8898 void OverloadCandidateSet::NoteCandidates(Sema &S,
8899                                           OverloadCandidateDisplayKind OCD,
8900                                           ArrayRef<Expr *> Args,
8901                                           StringRef Opc,
8902                                           SourceLocation OpLoc) {
8903   // Sort the candidates by viability and position.  Sorting directly would
8904   // be prohibitive, so we make a set of pointers and sort those.
8905   SmallVector<OverloadCandidate*, 32> Cands;
8906   if (OCD == OCD_AllCandidates) Cands.reserve(size());
8907   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
8908     if (Cand->Viable)
8909       Cands.push_back(Cand);
8910     else if (OCD == OCD_AllCandidates) {
8911       CompleteNonViableCandidate(S, Cand, Args);
8912       if (Cand->Function || Cand->IsSurrogate)
8913         Cands.push_back(Cand);
8914       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
8915       // want to list every possible builtin candidate.
8916     }
8917   }
8918 
8919   std::sort(Cands.begin(), Cands.end(),
8920             CompareOverloadCandidatesForDisplay(S));
8921 
8922   bool ReportedAmbiguousConversions = false;
8923 
8924   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
8925   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8926   unsigned CandsShown = 0;
8927   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8928     OverloadCandidate *Cand = *I;
8929 
8930     // Set an arbitrary limit on the number of candidate functions we'll spam
8931     // the user with.  FIXME: This limit should depend on details of the
8932     // candidate list.
8933     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
8934       break;
8935     }
8936     ++CandsShown;
8937 
8938     if (Cand->Function)
8939       NoteFunctionCandidate(S, Cand, Args.size());
8940     else if (Cand->IsSurrogate)
8941       NoteSurrogateCandidate(S, Cand);
8942     else {
8943       assert(Cand->Viable &&
8944              "Non-viable built-in candidates are not added to Cands.");
8945       // Generally we only see ambiguities including viable builtin
8946       // operators if overload resolution got screwed up by an
8947       // ambiguous user-defined conversion.
8948       //
8949       // FIXME: It's quite possible for different conversions to see
8950       // different ambiguities, though.
8951       if (!ReportedAmbiguousConversions) {
8952         NoteAmbiguousUserConversions(S, OpLoc, Cand);
8953         ReportedAmbiguousConversions = true;
8954       }
8955 
8956       // If this is a viable builtin, print it.
8957       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
8958     }
8959   }
8960 
8961   if (I != E)
8962     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
8963 }
8964 
8965 // [PossiblyAFunctionType]  -->   [Return]
8966 // NonFunctionType --> NonFunctionType
8967 // R (A) --> R(A)
8968 // R (*)(A) --> R (A)
8969 // R (&)(A) --> R (A)
8970 // R (S::*)(A) --> R (A)
ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)8971 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8972   QualType Ret = PossiblyAFunctionType;
8973   if (const PointerType *ToTypePtr =
8974     PossiblyAFunctionType->getAs<PointerType>())
8975     Ret = ToTypePtr->getPointeeType();
8976   else if (const ReferenceType *ToTypeRef =
8977     PossiblyAFunctionType->getAs<ReferenceType>())
8978     Ret = ToTypeRef->getPointeeType();
8979   else if (const MemberPointerType *MemTypePtr =
8980     PossiblyAFunctionType->getAs<MemberPointerType>())
8981     Ret = MemTypePtr->getPointeeType();
8982   Ret =
8983     Context.getCanonicalType(Ret).getUnqualifiedType();
8984   return Ret;
8985 }
8986 
8987 // A helper class to help with address of function resolution
8988 // - allows us to avoid passing around all those ugly parameters
8989 class AddressOfFunctionResolver
8990 {
8991   Sema& S;
8992   Expr* SourceExpr;
8993   const QualType& TargetType;
8994   QualType TargetFunctionType; // Extracted function type from target type
8995 
8996   bool Complain;
8997   //DeclAccessPair& ResultFunctionAccessPair;
8998   ASTContext& Context;
8999 
9000   bool TargetTypeIsNonStaticMemberFunction;
9001   bool FoundNonTemplateFunction;
9002 
9003   OverloadExpr::FindResult OvlExprInfo;
9004   OverloadExpr *OvlExpr;
9005   TemplateArgumentListInfo OvlExplicitTemplateArgs;
9006   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9007 
9008 public:
AddressOfFunctionResolver(Sema & S,Expr * SourceExpr,const QualType & TargetType,bool Complain)9009   AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
9010                             const QualType& TargetType, bool Complain)
9011     : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9012       Complain(Complain), Context(S.getASTContext()),
9013       TargetTypeIsNonStaticMemberFunction(
9014                                     !!TargetType->getAs<MemberPointerType>()),
9015       FoundNonTemplateFunction(false),
9016       OvlExprInfo(OverloadExpr::find(SourceExpr)),
9017       OvlExpr(OvlExprInfo.Expression)
9018   {
9019     ExtractUnqualifiedFunctionTypeFromTargetType();
9020 
9021     if (!TargetFunctionType->isFunctionType()) {
9022       if (OvlExpr->hasExplicitTemplateArgs()) {
9023         DeclAccessPair dap;
9024         if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
9025                                             OvlExpr, false, &dap) ) {
9026 
9027           if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9028             if (!Method->isStatic()) {
9029               // If the target type is a non-function type and the function
9030               // found is a non-static member function, pretend as if that was
9031               // the target, it's the only possible type to end up with.
9032               TargetTypeIsNonStaticMemberFunction = true;
9033 
9034               // And skip adding the function if its not in the proper form.
9035               // We'll diagnose this due to an empty set of functions.
9036               if (!OvlExprInfo.HasFormOfMemberPointer)
9037                 return;
9038             }
9039           }
9040 
9041           Matches.push_back(std::make_pair(dap,Fn));
9042         }
9043       }
9044       return;
9045     }
9046 
9047     if (OvlExpr->hasExplicitTemplateArgs())
9048       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9049 
9050     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9051       // C++ [over.over]p4:
9052       //   If more than one function is selected, [...]
9053       if (Matches.size() > 1) {
9054         if (FoundNonTemplateFunction)
9055           EliminateAllTemplateMatches();
9056         else
9057           EliminateAllExceptMostSpecializedTemplate();
9058       }
9059     }
9060   }
9061 
9062 private:
isTargetTypeAFunction() const9063   bool isTargetTypeAFunction() const {
9064     return TargetFunctionType->isFunctionType();
9065   }
9066 
9067   // [ToType]     [Return]
9068 
9069   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9070   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9071   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
ExtractUnqualifiedFunctionTypeFromTargetType()9072   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9073     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9074   }
9075 
9076   // return true if any matching specializations were found
AddMatchingTemplateFunction(FunctionTemplateDecl * FunctionTemplate,const DeclAccessPair & CurAccessFunPair)9077   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9078                                    const DeclAccessPair& CurAccessFunPair) {
9079     if (CXXMethodDecl *Method
9080               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9081       // Skip non-static function templates when converting to pointer, and
9082       // static when converting to member pointer.
9083       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9084         return false;
9085     }
9086     else if (TargetTypeIsNonStaticMemberFunction)
9087       return false;
9088 
9089     // C++ [over.over]p2:
9090     //   If the name is a function template, template argument deduction is
9091     //   done (14.8.2.2), and if the argument deduction succeeds, the
9092     //   resulting template argument list is used to generate a single
9093     //   function template specialization, which is added to the set of
9094     //   overloaded functions considered.
9095     FunctionDecl *Specialization = 0;
9096     TemplateDeductionInfo Info(OvlExpr->getNameLoc());
9097     if (Sema::TemplateDeductionResult Result
9098           = S.DeduceTemplateArguments(FunctionTemplate,
9099                                       &OvlExplicitTemplateArgs,
9100                                       TargetFunctionType, Specialization,
9101                                       Info)) {
9102       // FIXME: make a note of the failed deduction for diagnostics.
9103       (void)Result;
9104       return false;
9105     }
9106 
9107     // Template argument deduction ensures that we have an exact match.
9108     // This function template specicalization works.
9109     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9110     assert(TargetFunctionType
9111                       == Context.getCanonicalType(Specialization->getType()));
9112     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9113     return true;
9114   }
9115 
AddMatchingNonTemplateFunction(NamedDecl * Fn,const DeclAccessPair & CurAccessFunPair)9116   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9117                                       const DeclAccessPair& CurAccessFunPair) {
9118     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9119       // Skip non-static functions when converting to pointer, and static
9120       // when converting to member pointer.
9121       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9122         return false;
9123     }
9124     else if (TargetTypeIsNonStaticMemberFunction)
9125       return false;
9126 
9127     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9128       if (S.getLangOpts().CUDA)
9129         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9130           if (S.CheckCUDATarget(Caller, FunDecl))
9131             return false;
9132 
9133       QualType ResultTy;
9134       if (Context.hasSameUnqualifiedType(TargetFunctionType,
9135                                          FunDecl->getType()) ||
9136           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9137                                  ResultTy)) {
9138         Matches.push_back(std::make_pair(CurAccessFunPair,
9139           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9140         FoundNonTemplateFunction = true;
9141         return true;
9142       }
9143     }
9144 
9145     return false;
9146   }
9147 
FindAllFunctionsThatMatchTargetTypeExactly()9148   bool FindAllFunctionsThatMatchTargetTypeExactly() {
9149     bool Ret = false;
9150 
9151     // If the overload expression doesn't have the form of a pointer to
9152     // member, don't try to convert it to a pointer-to-member type.
9153     if (IsInvalidFormOfPointerToMemberFunction())
9154       return false;
9155 
9156     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9157                                E = OvlExpr->decls_end();
9158          I != E; ++I) {
9159       // Look through any using declarations to find the underlying function.
9160       NamedDecl *Fn = (*I)->getUnderlyingDecl();
9161 
9162       // C++ [over.over]p3:
9163       //   Non-member functions and static member functions match
9164       //   targets of type "pointer-to-function" or "reference-to-function."
9165       //   Nonstatic member functions match targets of
9166       //   type "pointer-to-member-function."
9167       // Note that according to DR 247, the containing class does not matter.
9168       if (FunctionTemplateDecl *FunctionTemplate
9169                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
9170         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9171           Ret = true;
9172       }
9173       // If we have explicit template arguments supplied, skip non-templates.
9174       else if (!OvlExpr->hasExplicitTemplateArgs() &&
9175                AddMatchingNonTemplateFunction(Fn, I.getPair()))
9176         Ret = true;
9177     }
9178     assert(Ret || Matches.empty());
9179     return Ret;
9180   }
9181 
EliminateAllExceptMostSpecializedTemplate()9182   void EliminateAllExceptMostSpecializedTemplate() {
9183     //   [...] and any given function template specialization F1 is
9184     //   eliminated if the set contains a second function template
9185     //   specialization whose function template is more specialized
9186     //   than the function template of F1 according to the partial
9187     //   ordering rules of 14.5.5.2.
9188 
9189     // The algorithm specified above is quadratic. We instead use a
9190     // two-pass algorithm (similar to the one used to identify the
9191     // best viable function in an overload set) that identifies the
9192     // best function template (if it exists).
9193 
9194     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9195     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9196       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9197 
9198     UnresolvedSetIterator Result =
9199       S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9200                            TPOC_Other, 0, SourceExpr->getLocStart(),
9201                            S.PDiag(),
9202                            S.PDiag(diag::err_addr_ovl_ambiguous)
9203                              << Matches[0].second->getDeclName(),
9204                            S.PDiag(diag::note_ovl_candidate)
9205                              << (unsigned) oc_function_template,
9206                            Complain, TargetFunctionType);
9207 
9208     if (Result != MatchesCopy.end()) {
9209       // Make it the first and only element
9210       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9211       Matches[0].second = cast<FunctionDecl>(*Result);
9212       Matches.resize(1);
9213     }
9214   }
9215 
EliminateAllTemplateMatches()9216   void EliminateAllTemplateMatches() {
9217     //   [...] any function template specializations in the set are
9218     //   eliminated if the set also contains a non-template function, [...]
9219     for (unsigned I = 0, N = Matches.size(); I != N; ) {
9220       if (Matches[I].second->getPrimaryTemplate() == 0)
9221         ++I;
9222       else {
9223         Matches[I] = Matches[--N];
9224         Matches.set_size(N);
9225       }
9226     }
9227   }
9228 
9229 public:
ComplainNoMatchesFound() const9230   void ComplainNoMatchesFound() const {
9231     assert(Matches.empty());
9232     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9233         << OvlExpr->getName() << TargetFunctionType
9234         << OvlExpr->getSourceRange();
9235     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9236   }
9237 
IsInvalidFormOfPointerToMemberFunction() const9238   bool IsInvalidFormOfPointerToMemberFunction() const {
9239     return TargetTypeIsNonStaticMemberFunction &&
9240       !OvlExprInfo.HasFormOfMemberPointer;
9241   }
9242 
ComplainIsInvalidFormOfPointerToMemberFunction() const9243   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9244       // TODO: Should we condition this on whether any functions might
9245       // have matched, or is it more appropriate to do that in callers?
9246       // TODO: a fixit wouldn't hurt.
9247       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9248         << TargetType << OvlExpr->getSourceRange();
9249   }
9250 
ComplainOfInvalidConversion() const9251   void ComplainOfInvalidConversion() const {
9252     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9253       << OvlExpr->getName() << TargetType;
9254   }
9255 
ComplainMultipleMatchesFound() const9256   void ComplainMultipleMatchesFound() const {
9257     assert(Matches.size() > 1);
9258     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9259       << OvlExpr->getName()
9260       << OvlExpr->getSourceRange();
9261     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9262   }
9263 
hadMultipleCandidates() const9264   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9265 
getNumMatches() const9266   int getNumMatches() const { return Matches.size(); }
9267 
getMatchingFunctionDecl() const9268   FunctionDecl* getMatchingFunctionDecl() const {
9269     if (Matches.size() != 1) return 0;
9270     return Matches[0].second;
9271   }
9272 
getMatchingFunctionAccessPair() const9273   const DeclAccessPair* getMatchingFunctionAccessPair() const {
9274     if (Matches.size() != 1) return 0;
9275     return &Matches[0].first;
9276   }
9277 };
9278 
9279 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9280 /// an overloaded function (C++ [over.over]), where @p From is an
9281 /// expression with overloaded function type and @p ToType is the type
9282 /// we're trying to resolve to. For example:
9283 ///
9284 /// @code
9285 /// int f(double);
9286 /// int f(int);
9287 ///
9288 /// int (*pfd)(double) = f; // selects f(double)
9289 /// @endcode
9290 ///
9291 /// This routine returns the resulting FunctionDecl if it could be
9292 /// resolved, and NULL otherwise. When @p Complain is true, this
9293 /// routine will emit diagnostics if there is an error.
9294 FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr * AddressOfExpr,QualType TargetType,bool Complain,DeclAccessPair & FoundResult,bool * pHadMultipleCandidates)9295 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9296                                          QualType TargetType,
9297                                          bool Complain,
9298                                          DeclAccessPair &FoundResult,
9299                                          bool *pHadMultipleCandidates) {
9300   assert(AddressOfExpr->getType() == Context.OverloadTy);
9301 
9302   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9303                                      Complain);
9304   int NumMatches = Resolver.getNumMatches();
9305   FunctionDecl* Fn = 0;
9306   if (NumMatches == 0 && Complain) {
9307     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9308       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9309     else
9310       Resolver.ComplainNoMatchesFound();
9311   }
9312   else if (NumMatches > 1 && Complain)
9313     Resolver.ComplainMultipleMatchesFound();
9314   else if (NumMatches == 1) {
9315     Fn = Resolver.getMatchingFunctionDecl();
9316     assert(Fn);
9317     FoundResult = *Resolver.getMatchingFunctionAccessPair();
9318     if (Complain)
9319       CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9320   }
9321 
9322   if (pHadMultipleCandidates)
9323     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9324   return Fn;
9325 }
9326 
9327 /// \brief Given an expression that refers to an overloaded function, try to
9328 /// resolve that overloaded function expression down to a single function.
9329 ///
9330 /// This routine can only resolve template-ids that refer to a single function
9331 /// template, where that template-id refers to a single template whose template
9332 /// arguments are either provided by the template-id or have defaults,
9333 /// as described in C++0x [temp.arg.explicit]p3.
9334 FunctionDecl *
ResolveSingleFunctionTemplateSpecialization(OverloadExpr * ovl,bool Complain,DeclAccessPair * FoundResult)9335 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9336                                                   bool Complain,
9337                                                   DeclAccessPair *FoundResult) {
9338   // C++ [over.over]p1:
9339   //   [...] [Note: any redundant set of parentheses surrounding the
9340   //   overloaded function name is ignored (5.1). ]
9341   // C++ [over.over]p1:
9342   //   [...] The overloaded function name can be preceded by the &
9343   //   operator.
9344 
9345   // If we didn't actually find any template-ids, we're done.
9346   if (!ovl->hasExplicitTemplateArgs())
9347     return 0;
9348 
9349   TemplateArgumentListInfo ExplicitTemplateArgs;
9350   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9351 
9352   // Look through all of the overloaded functions, searching for one
9353   // whose type matches exactly.
9354   FunctionDecl *Matched = 0;
9355   for (UnresolvedSetIterator I = ovl->decls_begin(),
9356          E = ovl->decls_end(); I != E; ++I) {
9357     // C++0x [temp.arg.explicit]p3:
9358     //   [...] In contexts where deduction is done and fails, or in contexts
9359     //   where deduction is not done, if a template argument list is
9360     //   specified and it, along with any default template arguments,
9361     //   identifies a single function template specialization, then the
9362     //   template-id is an lvalue for the function template specialization.
9363     FunctionTemplateDecl *FunctionTemplate
9364       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9365 
9366     // C++ [over.over]p2:
9367     //   If the name is a function template, template argument deduction is
9368     //   done (14.8.2.2), and if the argument deduction succeeds, the
9369     //   resulting template argument list is used to generate a single
9370     //   function template specialization, which is added to the set of
9371     //   overloaded functions considered.
9372     FunctionDecl *Specialization = 0;
9373     TemplateDeductionInfo Info(ovl->getNameLoc());
9374     if (TemplateDeductionResult Result
9375           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9376                                     Specialization, Info)) {
9377       // FIXME: make a note of the failed deduction for diagnostics.
9378       (void)Result;
9379       continue;
9380     }
9381 
9382     assert(Specialization && "no specialization and no error?");
9383 
9384     // Multiple matches; we can't resolve to a single declaration.
9385     if (Matched) {
9386       if (Complain) {
9387         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9388           << ovl->getName();
9389         NoteAllOverloadCandidates(ovl);
9390       }
9391       return 0;
9392     }
9393 
9394     Matched = Specialization;
9395     if (FoundResult) *FoundResult = I.getPair();
9396   }
9397 
9398   return Matched;
9399 }
9400 
9401 
9402 
9403 
9404 // Resolve and fix an overloaded expression that can be resolved
9405 // because it identifies a single function template specialization.
9406 //
9407 // Last three arguments should only be supplied if Complain = true
9408 //
9409 // Return true if it was logically possible to so resolve the
9410 // expression, regardless of whether or not it succeeded.  Always
9411 // returns true if 'complain' is set.
ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult & SrcExpr,bool doFunctionPointerConverion,bool complain,const SourceRange & OpRangeForComplaining,QualType DestTypeForComplaining,unsigned DiagIDForComplaining)9412 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9413                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
9414                    bool complain, const SourceRange& OpRangeForComplaining,
9415                                            QualType DestTypeForComplaining,
9416                                             unsigned DiagIDForComplaining) {
9417   assert(SrcExpr.get()->getType() == Context.OverloadTy);
9418 
9419   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9420 
9421   DeclAccessPair found;
9422   ExprResult SingleFunctionExpression;
9423   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9424                            ovl.Expression, /*complain*/ false, &found)) {
9425     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9426       SrcExpr = ExprError();
9427       return true;
9428     }
9429 
9430     // It is only correct to resolve to an instance method if we're
9431     // resolving a form that's permitted to be a pointer to member.
9432     // Otherwise we'll end up making a bound member expression, which
9433     // is illegal in all the contexts we resolve like this.
9434     if (!ovl.HasFormOfMemberPointer &&
9435         isa<CXXMethodDecl>(fn) &&
9436         cast<CXXMethodDecl>(fn)->isInstance()) {
9437       if (!complain) return false;
9438 
9439       Diag(ovl.Expression->getExprLoc(),
9440            diag::err_bound_member_function)
9441         << 0 << ovl.Expression->getSourceRange();
9442 
9443       // TODO: I believe we only end up here if there's a mix of
9444       // static and non-static candidates (otherwise the expression
9445       // would have 'bound member' type, not 'overload' type).
9446       // Ideally we would note which candidate was chosen and why
9447       // the static candidates were rejected.
9448       SrcExpr = ExprError();
9449       return true;
9450     }
9451 
9452     // Fix the expression to refer to 'fn'.
9453     SingleFunctionExpression =
9454       Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9455 
9456     // If desired, do function-to-pointer decay.
9457     if (doFunctionPointerConverion) {
9458       SingleFunctionExpression =
9459         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9460       if (SingleFunctionExpression.isInvalid()) {
9461         SrcExpr = ExprError();
9462         return true;
9463       }
9464     }
9465   }
9466 
9467   if (!SingleFunctionExpression.isUsable()) {
9468     if (complain) {
9469       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9470         << ovl.Expression->getName()
9471         << DestTypeForComplaining
9472         << OpRangeForComplaining
9473         << ovl.Expression->getQualifierLoc().getSourceRange();
9474       NoteAllOverloadCandidates(SrcExpr.get());
9475 
9476       SrcExpr = ExprError();
9477       return true;
9478     }
9479 
9480     return false;
9481   }
9482 
9483   SrcExpr = SingleFunctionExpression;
9484   return true;
9485 }
9486 
9487 /// \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)9488 static void AddOverloadedCallCandidate(Sema &S,
9489                                        DeclAccessPair FoundDecl,
9490                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9491                                        ArrayRef<Expr *> Args,
9492                                        OverloadCandidateSet &CandidateSet,
9493                                        bool PartialOverloading,
9494                                        bool KnownValid) {
9495   NamedDecl *Callee = FoundDecl.getDecl();
9496   if (isa<UsingShadowDecl>(Callee))
9497     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9498 
9499   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9500     if (ExplicitTemplateArgs) {
9501       assert(!KnownValid && "Explicit template arguments?");
9502       return;
9503     }
9504     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9505                            PartialOverloading);
9506     return;
9507   }
9508 
9509   if (FunctionTemplateDecl *FuncTemplate
9510       = dyn_cast<FunctionTemplateDecl>(Callee)) {
9511     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9512                                    ExplicitTemplateArgs, Args, CandidateSet);
9513     return;
9514   }
9515 
9516   assert(!KnownValid && "unhandled case in overloaded call candidate");
9517 }
9518 
9519 /// \brief Add the overload candidates named by callee and/or found by argument
9520 /// dependent lookup to the given overload set.
AddOverloadedCallCandidates(UnresolvedLookupExpr * ULE,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading)9521 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9522                                        ArrayRef<Expr *> Args,
9523                                        OverloadCandidateSet &CandidateSet,
9524                                        bool PartialOverloading) {
9525 
9526 #ifndef NDEBUG
9527   // Verify that ArgumentDependentLookup is consistent with the rules
9528   // in C++0x [basic.lookup.argdep]p3:
9529   //
9530   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9531   //   and let Y be the lookup set produced by argument dependent
9532   //   lookup (defined as follows). If X contains
9533   //
9534   //     -- a declaration of a class member, or
9535   //
9536   //     -- a block-scope function declaration that is not a
9537   //        using-declaration, or
9538   //
9539   //     -- a declaration that is neither a function or a function
9540   //        template
9541   //
9542   //   then Y is empty.
9543 
9544   if (ULE->requiresADL()) {
9545     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9546            E = ULE->decls_end(); I != E; ++I) {
9547       assert(!(*I)->getDeclContext()->isRecord());
9548       assert(isa<UsingShadowDecl>(*I) ||
9549              !(*I)->getDeclContext()->isFunctionOrMethod());
9550       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9551     }
9552   }
9553 #endif
9554 
9555   // It would be nice to avoid this copy.
9556   TemplateArgumentListInfo TABuffer;
9557   TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9558   if (ULE->hasExplicitTemplateArgs()) {
9559     ULE->copyTemplateArgumentsInto(TABuffer);
9560     ExplicitTemplateArgs = &TABuffer;
9561   }
9562 
9563   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9564          E = ULE->decls_end(); I != E; ++I)
9565     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9566                                CandidateSet, PartialOverloading,
9567                                /*KnownValid*/ true);
9568 
9569   if (ULE->requiresADL())
9570     AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9571                                          ULE->getExprLoc(),
9572                                          Args, ExplicitTemplateArgs,
9573                                          CandidateSet, PartialOverloading);
9574 }
9575 
9576 /// Attempt to recover from an ill-formed use of a non-dependent name in a
9577 /// template, where the non-dependent name was declared after the template
9578 /// was defined. This is common in code written for a compilers which do not
9579 /// correctly implement two-stage name lookup.
9580 ///
9581 /// Returns true if a viable candidate was found and a diagnostic was issued.
9582 static bool
DiagnoseTwoPhaseLookup(Sema & SemaRef,SourceLocation FnLoc,const CXXScopeSpec & SS,LookupResult & R,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args)9583 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9584                        const CXXScopeSpec &SS, LookupResult &R,
9585                        TemplateArgumentListInfo *ExplicitTemplateArgs,
9586                        ArrayRef<Expr *> Args) {
9587   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9588     return false;
9589 
9590   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9591     if (DC->isTransparentContext())
9592       continue;
9593 
9594     SemaRef.LookupQualifiedName(R, DC);
9595 
9596     if (!R.empty()) {
9597       R.suppressDiagnostics();
9598 
9599       if (isa<CXXRecordDecl>(DC)) {
9600         // Don't diagnose names we find in classes; we get much better
9601         // diagnostics for these from DiagnoseEmptyLookup.
9602         R.clear();
9603         return false;
9604       }
9605 
9606       OverloadCandidateSet Candidates(FnLoc);
9607       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9608         AddOverloadedCallCandidate(SemaRef, I.getPair(),
9609                                    ExplicitTemplateArgs, Args,
9610                                    Candidates, false, /*KnownValid*/ false);
9611 
9612       OverloadCandidateSet::iterator Best;
9613       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9614         // No viable functions. Don't bother the user with notes for functions
9615         // which don't work and shouldn't be found anyway.
9616         R.clear();
9617         return false;
9618       }
9619 
9620       // Find the namespaces where ADL would have looked, and suggest
9621       // declaring the function there instead.
9622       Sema::AssociatedNamespaceSet AssociatedNamespaces;
9623       Sema::AssociatedClassSet AssociatedClasses;
9624       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
9625                                                  AssociatedNamespaces,
9626                                                  AssociatedClasses);
9627       Sema::AssociatedNamespaceSet SuggestedNamespaces;
9628       DeclContext *Std = SemaRef.getStdNamespace();
9629       for (Sema::AssociatedNamespaceSet::iterator
9630              it = AssociatedNamespaces.begin(),
9631              end = AssociatedNamespaces.end(); it != end; ++it) {
9632         // Never suggest declaring a function within namespace 'std'.
9633         if (Std && Std->Encloses(*it))
9634           continue;
9635 
9636         // Never suggest declaring a function within a namespace with a reserved
9637         // name, like __gnu_cxx.
9638         NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9639         if (NS &&
9640             NS->getQualifiedNameAsString().find("__") != std::string::npos)
9641           continue;
9642 
9643         SuggestedNamespaces.insert(*it);
9644       }
9645 
9646       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9647         << R.getLookupName();
9648       if (SuggestedNamespaces.empty()) {
9649         SemaRef.Diag(Best->Function->getLocation(),
9650                      diag::note_not_found_by_two_phase_lookup)
9651           << R.getLookupName() << 0;
9652       } else if (SuggestedNamespaces.size() == 1) {
9653         SemaRef.Diag(Best->Function->getLocation(),
9654                      diag::note_not_found_by_two_phase_lookup)
9655           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
9656       } else {
9657         // FIXME: It would be useful to list the associated namespaces here,
9658         // but the diagnostics infrastructure doesn't provide a way to produce
9659         // a localized representation of a list of items.
9660         SemaRef.Diag(Best->Function->getLocation(),
9661                      diag::note_not_found_by_two_phase_lookup)
9662           << R.getLookupName() << 2;
9663       }
9664 
9665       // Try to recover by calling this function.
9666       return true;
9667     }
9668 
9669     R.clear();
9670   }
9671 
9672   return false;
9673 }
9674 
9675 /// Attempt to recover from ill-formed use of a non-dependent operator in a
9676 /// template, where the non-dependent operator was declared after the template
9677 /// was defined.
9678 ///
9679 /// Returns true if a viable candidate was found and a diagnostic was issued.
9680 static bool
DiagnoseTwoPhaseOperatorLookup(Sema & SemaRef,OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args)9681 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9682                                SourceLocation OpLoc,
9683                                ArrayRef<Expr *> Args) {
9684   DeclarationName OpName =
9685     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9686   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9687   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9688                                 /*ExplicitTemplateArgs=*/0, Args);
9689 }
9690 
9691 namespace {
9692 // Callback to limit the allowed keywords and to only accept typo corrections
9693 // that are keywords or whose decls refer to functions (or template functions)
9694 // that accept the given number of arguments.
9695 class RecoveryCallCCC : public CorrectionCandidateCallback {
9696  public:
RecoveryCallCCC(Sema & SemaRef,unsigned NumArgs,bool HasExplicitTemplateArgs)9697   RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9698       : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9699     WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
9700     WantRemainingKeywords = false;
9701   }
9702 
ValidateCandidate(const TypoCorrection & candidate)9703   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9704     if (!candidate.getCorrectionDecl())
9705       return candidate.isKeyword();
9706 
9707     for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9708            DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9709       FunctionDecl *FD = 0;
9710       NamedDecl *ND = (*DI)->getUnderlyingDecl();
9711       if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9712         FD = FTD->getTemplatedDecl();
9713       if (!HasExplicitTemplateArgs && !FD) {
9714         if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9715           // If the Decl is neither a function nor a template function,
9716           // determine if it is a pointer or reference to a function. If so,
9717           // check against the number of arguments expected for the pointee.
9718           QualType ValType = cast<ValueDecl>(ND)->getType();
9719           if (ValType->isAnyPointerType() || ValType->isReferenceType())
9720             ValType = ValType->getPointeeType();
9721           if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9722             if (FPT->getNumArgs() == NumArgs)
9723               return true;
9724         }
9725       }
9726       if (FD && FD->getNumParams() >= NumArgs &&
9727           FD->getMinRequiredArguments() <= NumArgs)
9728         return true;
9729     }
9730     return false;
9731   }
9732 
9733  private:
9734   unsigned NumArgs;
9735   bool HasExplicitTemplateArgs;
9736 };
9737 
9738 // Callback that effectively disabled typo correction
9739 class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9740  public:
NoTypoCorrectionCCC()9741   NoTypoCorrectionCCC() {
9742     WantTypeSpecifiers = false;
9743     WantExpressionKeywords = false;
9744     WantCXXNamedCasts = false;
9745     WantRemainingKeywords = false;
9746   }
9747 
ValidateCandidate(const TypoCorrection & candidate)9748   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9749     return false;
9750   }
9751 };
9752 
9753 class BuildRecoveryCallExprRAII {
9754   Sema &SemaRef;
9755 public:
BuildRecoveryCallExprRAII(Sema & S)9756   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9757     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9758     SemaRef.IsBuildingRecoveryCallExpr = true;
9759   }
9760 
~BuildRecoveryCallExprRAII()9761   ~BuildRecoveryCallExprRAII() {
9762     SemaRef.IsBuildingRecoveryCallExpr = false;
9763   }
9764 };
9765 
9766 }
9767 
9768 /// Attempts to recover from a call where no functions were found.
9769 ///
9770 /// Returns true if new candidates were found.
9771 static ExprResult
BuildRecoveryCallExpr(Sema & SemaRef,Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,llvm::MutableArrayRef<Expr * > Args,SourceLocation RParenLoc,bool EmptyLookup,bool AllowTypoCorrection)9772 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9773                       UnresolvedLookupExpr *ULE,
9774                       SourceLocation LParenLoc,
9775                       llvm::MutableArrayRef<Expr *> Args,
9776                       SourceLocation RParenLoc,
9777                       bool EmptyLookup, bool AllowTypoCorrection) {
9778   // Do not try to recover if it is already building a recovery call.
9779   // This stops infinite loops for template instantiations like
9780   //
9781   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9782   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9783   //
9784   if (SemaRef.IsBuildingRecoveryCallExpr)
9785     return ExprError();
9786   BuildRecoveryCallExprRAII RCE(SemaRef);
9787 
9788   CXXScopeSpec SS;
9789   SS.Adopt(ULE->getQualifierLoc());
9790   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
9791 
9792   TemplateArgumentListInfo TABuffer;
9793   TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9794   if (ULE->hasExplicitTemplateArgs()) {
9795     ULE->copyTemplateArgumentsInto(TABuffer);
9796     ExplicitTemplateArgs = &TABuffer;
9797   }
9798 
9799   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9800                  Sema::LookupOrdinaryName);
9801   RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
9802   NoTypoCorrectionCCC RejectAll;
9803   CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9804       (CorrectionCandidateCallback*)&Validator :
9805       (CorrectionCandidateCallback*)&RejectAll;
9806   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9807                               ExplicitTemplateArgs, Args) &&
9808       (!EmptyLookup ||
9809        SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
9810                                    ExplicitTemplateArgs, Args)))
9811     return ExprError();
9812 
9813   assert(!R.empty() && "lookup results empty despite recovery");
9814 
9815   // Build an implicit member call if appropriate.  Just drop the
9816   // casts and such from the call, we don't really care.
9817   ExprResult NewFn = ExprError();
9818   if ((*R.begin())->isCXXClassMember())
9819     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9820                                                     R, ExplicitTemplateArgs);
9821   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
9822     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
9823                                         ExplicitTemplateArgs);
9824   else
9825     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9826 
9827   if (NewFn.isInvalid())
9828     return ExprError();
9829 
9830   // This shouldn't cause an infinite loop because we're giving it
9831   // an expression with viable lookup results, which should never
9832   // end up here.
9833   return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
9834                                MultiExprArg(Args.data(), Args.size()),
9835                                RParenLoc);
9836 }
9837 
9838 /// \brief Constructs and populates an OverloadedCandidateSet from
9839 /// the given function.
9840 /// \returns true when an the ExprResult output parameter has been set.
buildOverloadedCallSet(Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,Expr ** Args,unsigned NumArgs,SourceLocation RParenLoc,OverloadCandidateSet * CandidateSet,ExprResult * Result)9841 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9842                                   UnresolvedLookupExpr *ULE,
9843                                   Expr **Args, unsigned NumArgs,
9844                                   SourceLocation RParenLoc,
9845                                   OverloadCandidateSet *CandidateSet,
9846                                   ExprResult *Result) {
9847 #ifndef NDEBUG
9848   if (ULE->requiresADL()) {
9849     // To do ADL, we must have found an unqualified name.
9850     assert(!ULE->getQualifier() && "qualified name with ADL");
9851 
9852     // We don't perform ADL for implicit declarations of builtins.
9853     // Verify that this was correctly set up.
9854     FunctionDecl *F;
9855     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9856         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9857         F->getBuiltinID() && F->isImplicit())
9858       llvm_unreachable("performing ADL for builtin");
9859 
9860     // We don't perform ADL in C.
9861     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
9862   }
9863 #endif
9864 
9865   UnbridgedCastsSet UnbridgedCasts;
9866   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9867     *Result = ExprError();
9868     return true;
9869   }
9870 
9871   // Add the functions denoted by the callee to the set of candidate
9872   // functions, including those from argument-dependent lookup.
9873   AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9874                               *CandidateSet);
9875 
9876   // If we found nothing, try to recover.
9877   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9878   // out if it fails.
9879   if (CandidateSet->empty()) {
9880     // In Microsoft mode, if we are inside a template class member function then
9881     // create a type dependent CallExpr. The goal is to postpone name lookup
9882     // to instantiation time to be able to search into type dependent base
9883     // classes.
9884     if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
9885         (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
9886       CallExpr *CE = new (Context) CallExpr(Context, Fn,
9887                                             llvm::makeArrayRef(Args, NumArgs),
9888                                             Context.DependentTy, VK_RValue,
9889                                             RParenLoc);
9890       CE->setTypeDependent(true);
9891       *Result = Owned(CE);
9892       return true;
9893     }
9894     return false;
9895   }
9896 
9897   UnbridgedCasts.restore();
9898   return false;
9899 }
9900 
9901 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9902 /// the completed call expression. If overload resolution fails, emits
9903 /// diagnostics and returns ExprError()
FinishOverloadedCallExpr(Sema & SemaRef,Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,Expr ** Args,unsigned NumArgs,SourceLocation RParenLoc,Expr * ExecConfig,OverloadCandidateSet * CandidateSet,OverloadCandidateSet::iterator * Best,OverloadingResult OverloadResult,bool AllowTypoCorrection)9904 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9905                                            UnresolvedLookupExpr *ULE,
9906                                            SourceLocation LParenLoc,
9907                                            Expr **Args, unsigned NumArgs,
9908                                            SourceLocation RParenLoc,
9909                                            Expr *ExecConfig,
9910                                            OverloadCandidateSet *CandidateSet,
9911                                            OverloadCandidateSet::iterator *Best,
9912                                            OverloadingResult OverloadResult,
9913                                            bool AllowTypoCorrection) {
9914   if (CandidateSet->empty())
9915     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9916                                  llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9917                                  RParenLoc, /*EmptyLookup=*/true,
9918                                  AllowTypoCorrection);
9919 
9920   switch (OverloadResult) {
9921   case OR_Success: {
9922     FunctionDecl *FDecl = (*Best)->Function;
9923     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9924     SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9925     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9926     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9927                                          RParenLoc, ExecConfig);
9928   }
9929 
9930   case OR_No_Viable_Function: {
9931     // Try to recover by looking for viable functions which the user might
9932     // have meant to call.
9933     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9934                                   llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9935                                                 RParenLoc,
9936                                                 /*EmptyLookup=*/false,
9937                                                 AllowTypoCorrection);
9938     if (!Recovery.isInvalid())
9939       return Recovery;
9940 
9941     SemaRef.Diag(Fn->getLocStart(),
9942          diag::err_ovl_no_viable_function_in_call)
9943       << ULE->getName() << Fn->getSourceRange();
9944     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9945                                  llvm::makeArrayRef(Args, NumArgs));
9946     break;
9947   }
9948 
9949   case OR_Ambiguous:
9950     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
9951       << ULE->getName() << Fn->getSourceRange();
9952     CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9953                                  llvm::makeArrayRef(Args, NumArgs));
9954     break;
9955 
9956   case OR_Deleted: {
9957     SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9958       << (*Best)->Function->isDeleted()
9959       << ULE->getName()
9960       << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9961       << Fn->getSourceRange();
9962     CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9963                                  llvm::makeArrayRef(Args, NumArgs));
9964 
9965     // We emitted an error for the unvailable/deleted function call but keep
9966     // the call in the AST.
9967     FunctionDecl *FDecl = (*Best)->Function;
9968     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9969     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9970                                  RParenLoc, ExecConfig);
9971   }
9972   }
9973 
9974   // Overload resolution failed.
9975   return ExprError();
9976 }
9977 
9978 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
9979 /// (which eventually refers to the declaration Func) and the call
9980 /// arguments Args/NumArgs, attempt to resolve the function call down
9981 /// to a specific function. If overload resolution succeeds, returns
9982 /// the call expression produced by overload resolution.
9983 /// Otherwise, emits diagnostics and returns ExprError.
BuildOverloadedCallExpr(Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,Expr ** Args,unsigned NumArgs,SourceLocation RParenLoc,Expr * ExecConfig,bool AllowTypoCorrection)9984 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9985                                          UnresolvedLookupExpr *ULE,
9986                                          SourceLocation LParenLoc,
9987                                          Expr **Args, unsigned NumArgs,
9988                                          SourceLocation RParenLoc,
9989                                          Expr *ExecConfig,
9990                                          bool AllowTypoCorrection) {
9991   OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9992   ExprResult result;
9993 
9994   if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9995                              &CandidateSet, &result))
9996     return result;
9997 
9998   OverloadCandidateSet::iterator Best;
9999   OverloadingResult OverloadResult =
10000       CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10001 
10002   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
10003                                   RParenLoc, ExecConfig, &CandidateSet,
10004                                   &Best, OverloadResult,
10005                                   AllowTypoCorrection);
10006 }
10007 
IsOverloaded(const UnresolvedSetImpl & Functions)10008 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10009   return Functions.size() > 1 ||
10010     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10011 }
10012 
10013 /// \brief Create a unary operation that may resolve to an overloaded
10014 /// operator.
10015 ///
10016 /// \param OpLoc The location of the operator itself (e.g., '*').
10017 ///
10018 /// \param OpcIn The UnaryOperator::Opcode that describes this
10019 /// operator.
10020 ///
10021 /// \param Fns The set of non-member functions that will be
10022 /// considered by overload resolution. The caller needs to build this
10023 /// set based on the context using, e.g.,
10024 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10025 /// set should not contain any member functions; those will be added
10026 /// by CreateOverloadedUnaryOp().
10027 ///
10028 /// \param Input The input argument.
10029 ExprResult
CreateOverloadedUnaryOp(SourceLocation OpLoc,unsigned OpcIn,const UnresolvedSetImpl & Fns,Expr * Input)10030 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10031                               const UnresolvedSetImpl &Fns,
10032                               Expr *Input) {
10033   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10034 
10035   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10036   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10037   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10038   // TODO: provide better source location info.
10039   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10040 
10041   if (checkPlaceholderForOverload(*this, Input))
10042     return ExprError();
10043 
10044   Expr *Args[2] = { Input, 0 };
10045   unsigned NumArgs = 1;
10046 
10047   // For post-increment and post-decrement, add the implicit '0' as
10048   // the second argument, so that we know this is a post-increment or
10049   // post-decrement.
10050   if (Opc == UO_PostInc || Opc == UO_PostDec) {
10051     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10052     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10053                                      SourceLocation());
10054     NumArgs = 2;
10055   }
10056 
10057   if (Input->isTypeDependent()) {
10058     if (Fns.empty())
10059       return Owned(new (Context) UnaryOperator(Input,
10060                                                Opc,
10061                                                Context.DependentTy,
10062                                                VK_RValue, OK_Ordinary,
10063                                                OpLoc));
10064 
10065     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10066     UnresolvedLookupExpr *Fn
10067       = UnresolvedLookupExpr::Create(Context, NamingClass,
10068                                      NestedNameSpecifierLoc(), OpNameInfo,
10069                                      /*ADL*/ true, IsOverloaded(Fns),
10070                                      Fns.begin(), Fns.end());
10071     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
10072                                               llvm::makeArrayRef(Args, NumArgs),
10073                                                    Context.DependentTy,
10074                                                    VK_RValue,
10075                                                    OpLoc, false));
10076   }
10077 
10078   // Build an empty overload set.
10079   OverloadCandidateSet CandidateSet(OpLoc);
10080 
10081   // Add the candidates from the given function set.
10082   AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10083                         false);
10084 
10085   // Add operator candidates that are member functions.
10086   AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10087 
10088   // Add candidates from ADL.
10089   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10090                                        OpLoc, llvm::makeArrayRef(Args, NumArgs),
10091                                        /*ExplicitTemplateArgs*/ 0,
10092                                        CandidateSet);
10093 
10094   // Add builtin operator candidates.
10095   AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10096 
10097   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10098 
10099   // Perform overload resolution.
10100   OverloadCandidateSet::iterator Best;
10101   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10102   case OR_Success: {
10103     // We found a built-in operator or an overloaded operator.
10104     FunctionDecl *FnDecl = Best->Function;
10105 
10106     if (FnDecl) {
10107       // We matched an overloaded operator. Build a call to that
10108       // operator.
10109 
10110       // Convert the arguments.
10111       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10112         CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
10113 
10114         ExprResult InputRes =
10115           PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10116                                               Best->FoundDecl, Method);
10117         if (InputRes.isInvalid())
10118           return ExprError();
10119         Input = InputRes.take();
10120       } else {
10121         // Convert the arguments.
10122         ExprResult InputInit
10123           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10124                                                       Context,
10125                                                       FnDecl->getParamDecl(0)),
10126                                       SourceLocation(),
10127                                       Input);
10128         if (InputInit.isInvalid())
10129           return ExprError();
10130         Input = InputInit.take();
10131       }
10132 
10133       // Determine the result type.
10134       QualType ResultTy = FnDecl->getResultType();
10135       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10136       ResultTy = ResultTy.getNonLValueExprType(Context);
10137 
10138       // Build the actual expression node.
10139       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10140                                                 HadMultipleCandidates, OpLoc);
10141       if (FnExpr.isInvalid())
10142         return ExprError();
10143 
10144       Args[0] = Input;
10145       CallExpr *TheCall =
10146         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10147                                           llvm::makeArrayRef(Args, NumArgs),
10148                                           ResultTy, VK, OpLoc, false);
10149 
10150       if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10151                               FnDecl))
10152         return ExprError();
10153 
10154       return MaybeBindToTemporary(TheCall);
10155     } else {
10156       // We matched a built-in operator. Convert the arguments, then
10157       // break out so that we will build the appropriate built-in
10158       // operator node.
10159       ExprResult InputRes =
10160         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10161                                   Best->Conversions[0], AA_Passing);
10162       if (InputRes.isInvalid())
10163         return ExprError();
10164       Input = InputRes.take();
10165       break;
10166     }
10167   }
10168 
10169   case OR_No_Viable_Function:
10170     // This is an erroneous use of an operator which can be overloaded by
10171     // a non-member function. Check for non-member operators which were
10172     // defined too late to be candidates.
10173     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10174                                        llvm::makeArrayRef(Args, NumArgs)))
10175       // FIXME: Recover by calling the found function.
10176       return ExprError();
10177 
10178     // No viable function; fall through to handling this as a
10179     // built-in operator, which will produce an error message for us.
10180     break;
10181 
10182   case OR_Ambiguous:
10183     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10184         << UnaryOperator::getOpcodeStr(Opc)
10185         << Input->getType()
10186         << Input->getSourceRange();
10187     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10188                                 llvm::makeArrayRef(Args, NumArgs),
10189                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10190     return ExprError();
10191 
10192   case OR_Deleted:
10193     Diag(OpLoc, diag::err_ovl_deleted_oper)
10194       << Best->Function->isDeleted()
10195       << UnaryOperator::getOpcodeStr(Opc)
10196       << getDeletedOrUnavailableSuffix(Best->Function)
10197       << Input->getSourceRange();
10198     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10199                                 llvm::makeArrayRef(Args, NumArgs),
10200                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10201     return ExprError();
10202   }
10203 
10204   // Either we found no viable overloaded operator or we matched a
10205   // built-in operator. In either case, fall through to trying to
10206   // build a built-in operation.
10207   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10208 }
10209 
10210 /// \brief Create a binary operation that may resolve to an overloaded
10211 /// operator.
10212 ///
10213 /// \param OpLoc The location of the operator itself (e.g., '+').
10214 ///
10215 /// \param OpcIn The BinaryOperator::Opcode that describes this
10216 /// operator.
10217 ///
10218 /// \param Fns The set of non-member functions that will be
10219 /// considered by overload resolution. The caller needs to build this
10220 /// set based on the context using, e.g.,
10221 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10222 /// set should not contain any member functions; those will be added
10223 /// by CreateOverloadedBinOp().
10224 ///
10225 /// \param LHS Left-hand argument.
10226 /// \param RHS Right-hand argument.
10227 ExprResult
CreateOverloadedBinOp(SourceLocation OpLoc,unsigned OpcIn,const UnresolvedSetImpl & Fns,Expr * LHS,Expr * RHS)10228 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10229                             unsigned OpcIn,
10230                             const UnresolvedSetImpl &Fns,
10231                             Expr *LHS, Expr *RHS) {
10232   Expr *Args[2] = { LHS, RHS };
10233   LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
10234 
10235   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10236   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10237   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10238 
10239   // If either side is type-dependent, create an appropriate dependent
10240   // expression.
10241   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10242     if (Fns.empty()) {
10243       // If there are no functions to store, just build a dependent
10244       // BinaryOperator or CompoundAssignment.
10245       if (Opc <= BO_Assign || Opc > BO_OrAssign)
10246         return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
10247                                                   Context.DependentTy,
10248                                                   VK_RValue, OK_Ordinary,
10249                                                   OpLoc,
10250                                                   FPFeatures.fp_contract));
10251 
10252       return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10253                                                         Context.DependentTy,
10254                                                         VK_LValue,
10255                                                         OK_Ordinary,
10256                                                         Context.DependentTy,
10257                                                         Context.DependentTy,
10258                                                         OpLoc,
10259                                                         FPFeatures.fp_contract));
10260     }
10261 
10262     // FIXME: save results of ADL from here?
10263     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10264     // TODO: provide better source location info in DNLoc component.
10265     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10266     UnresolvedLookupExpr *Fn
10267       = UnresolvedLookupExpr::Create(Context, NamingClass,
10268                                      NestedNameSpecifierLoc(), OpNameInfo,
10269                                      /*ADL*/ true, IsOverloaded(Fns),
10270                                      Fns.begin(), Fns.end());
10271     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10272                                                 Context.DependentTy, VK_RValue,
10273                                                 OpLoc, FPFeatures.fp_contract));
10274   }
10275 
10276   // Always do placeholder-like conversions on the RHS.
10277   if (checkPlaceholderForOverload(*this, Args[1]))
10278     return ExprError();
10279 
10280   // Do placeholder-like conversion on the LHS; note that we should
10281   // not get here with a PseudoObject LHS.
10282   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10283   if (checkPlaceholderForOverload(*this, Args[0]))
10284     return ExprError();
10285 
10286   // If this is the assignment operator, we only perform overload resolution
10287   // if the left-hand side is a class or enumeration type. This is actually
10288   // a hack. The standard requires that we do overload resolution between the
10289   // various built-in candidates, but as DR507 points out, this can lead to
10290   // problems. So we do it this way, which pretty much follows what GCC does.
10291   // Note that we go the traditional code path for compound assignment forms.
10292   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10293     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10294 
10295   // If this is the .* operator, which is not overloadable, just
10296   // create a built-in binary operator.
10297   if (Opc == BO_PtrMemD)
10298     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10299 
10300   // Build an empty overload set.
10301   OverloadCandidateSet CandidateSet(OpLoc);
10302 
10303   // Add the candidates from the given function set.
10304   AddFunctionCandidates(Fns, Args, CandidateSet, false);
10305 
10306   // Add operator candidates that are member functions.
10307   AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10308 
10309   // Add candidates from ADL.
10310   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
10311                                        OpLoc, Args,
10312                                        /*ExplicitTemplateArgs*/ 0,
10313                                        CandidateSet);
10314 
10315   // Add builtin operator candidates.
10316   AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10317 
10318   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10319 
10320   // Perform overload resolution.
10321   OverloadCandidateSet::iterator Best;
10322   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10323     case OR_Success: {
10324       // We found a built-in operator or an overloaded operator.
10325       FunctionDecl *FnDecl = Best->Function;
10326 
10327       if (FnDecl) {
10328         // We matched an overloaded operator. Build a call to that
10329         // operator.
10330 
10331         // Convert the arguments.
10332         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10333           // Best->Access is only meaningful for class members.
10334           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10335 
10336           ExprResult Arg1 =
10337             PerformCopyInitialization(
10338               InitializedEntity::InitializeParameter(Context,
10339                                                      FnDecl->getParamDecl(0)),
10340               SourceLocation(), Owned(Args[1]));
10341           if (Arg1.isInvalid())
10342             return ExprError();
10343 
10344           ExprResult Arg0 =
10345             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10346                                                 Best->FoundDecl, Method);
10347           if (Arg0.isInvalid())
10348             return ExprError();
10349           Args[0] = Arg0.takeAs<Expr>();
10350           Args[1] = RHS = Arg1.takeAs<Expr>();
10351         } else {
10352           // Convert the arguments.
10353           ExprResult Arg0 = PerformCopyInitialization(
10354             InitializedEntity::InitializeParameter(Context,
10355                                                    FnDecl->getParamDecl(0)),
10356             SourceLocation(), Owned(Args[0]));
10357           if (Arg0.isInvalid())
10358             return ExprError();
10359 
10360           ExprResult Arg1 =
10361             PerformCopyInitialization(
10362               InitializedEntity::InitializeParameter(Context,
10363                                                      FnDecl->getParamDecl(1)),
10364               SourceLocation(), Owned(Args[1]));
10365           if (Arg1.isInvalid())
10366             return ExprError();
10367           Args[0] = LHS = Arg0.takeAs<Expr>();
10368           Args[1] = RHS = Arg1.takeAs<Expr>();
10369         }
10370 
10371         // Determine the result type.
10372         QualType ResultTy = FnDecl->getResultType();
10373         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10374         ResultTy = ResultTy.getNonLValueExprType(Context);
10375 
10376         // Build the actual expression node.
10377         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10378                                                   Best->FoundDecl,
10379                                                   HadMultipleCandidates, OpLoc);
10380         if (FnExpr.isInvalid())
10381           return ExprError();
10382 
10383         CXXOperatorCallExpr *TheCall =
10384           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10385                                             Args, ResultTy, VK, OpLoc,
10386                                             FPFeatures.fp_contract);
10387 
10388         if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10389                                 FnDecl))
10390           return ExprError();
10391 
10392         ArrayRef<const Expr *> ArgsArray(Args, 2);
10393         // Cut off the implicit 'this'.
10394         if (isa<CXXMethodDecl>(FnDecl))
10395           ArgsArray = ArgsArray.slice(1);
10396         checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10397                   TheCall->getSourceRange(), VariadicDoesNotApply);
10398 
10399         return MaybeBindToTemporary(TheCall);
10400       } else {
10401         // We matched a built-in operator. Convert the arguments, then
10402         // break out so that we will build the appropriate built-in
10403         // operator node.
10404         ExprResult ArgsRes0 =
10405           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10406                                     Best->Conversions[0], AA_Passing);
10407         if (ArgsRes0.isInvalid())
10408           return ExprError();
10409         Args[0] = ArgsRes0.take();
10410 
10411         ExprResult ArgsRes1 =
10412           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10413                                     Best->Conversions[1], AA_Passing);
10414         if (ArgsRes1.isInvalid())
10415           return ExprError();
10416         Args[1] = ArgsRes1.take();
10417         break;
10418       }
10419     }
10420 
10421     case OR_No_Viable_Function: {
10422       // C++ [over.match.oper]p9:
10423       //   If the operator is the operator , [...] and there are no
10424       //   viable functions, then the operator is assumed to be the
10425       //   built-in operator and interpreted according to clause 5.
10426       if (Opc == BO_Comma)
10427         break;
10428 
10429       // For class as left operand for assignment or compound assigment
10430       // operator do not fall through to handling in built-in, but report that
10431       // no overloaded assignment operator found
10432       ExprResult Result = ExprError();
10433       if (Args[0]->getType()->isRecordType() &&
10434           Opc >= BO_Assign && Opc <= BO_OrAssign) {
10435         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10436              << BinaryOperator::getOpcodeStr(Opc)
10437              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10438       } else {
10439         // This is an erroneous use of an operator which can be overloaded by
10440         // a non-member function. Check for non-member operators which were
10441         // defined too late to be candidates.
10442         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10443           // FIXME: Recover by calling the found function.
10444           return ExprError();
10445 
10446         // No viable function; try to create a built-in operation, which will
10447         // produce an error. Then, show the non-viable candidates.
10448         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10449       }
10450       assert(Result.isInvalid() &&
10451              "C++ binary operator overloading is missing candidates!");
10452       if (Result.isInvalid())
10453         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10454                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
10455       return Result;
10456     }
10457 
10458     case OR_Ambiguous:
10459       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10460           << BinaryOperator::getOpcodeStr(Opc)
10461           << Args[0]->getType() << Args[1]->getType()
10462           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10463       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10464                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
10465       return ExprError();
10466 
10467     case OR_Deleted:
10468       if (isImplicitlyDeleted(Best->Function)) {
10469         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10470         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10471           << Context.getRecordType(Method->getParent())
10472           << getSpecialMember(Method);
10473 
10474         // The user probably meant to call this special member. Just
10475         // explain why it's deleted.
10476         NoteDeletedFunction(Method);
10477         return ExprError();
10478       } else {
10479         Diag(OpLoc, diag::err_ovl_deleted_oper)
10480           << Best->Function->isDeleted()
10481           << BinaryOperator::getOpcodeStr(Opc)
10482           << getDeletedOrUnavailableSuffix(Best->Function)
10483           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10484       }
10485       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10486                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
10487       return ExprError();
10488   }
10489 
10490   // We matched a built-in operator; build it.
10491   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10492 }
10493 
10494 ExprResult
CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,SourceLocation RLoc,Expr * Base,Expr * Idx)10495 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10496                                          SourceLocation RLoc,
10497                                          Expr *Base, Expr *Idx) {
10498   Expr *Args[2] = { Base, Idx };
10499   DeclarationName OpName =
10500       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10501 
10502   // If either side is type-dependent, create an appropriate dependent
10503   // expression.
10504   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10505 
10506     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10507     // CHECKME: no 'operator' keyword?
10508     DeclarationNameInfo OpNameInfo(OpName, LLoc);
10509     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10510     UnresolvedLookupExpr *Fn
10511       = UnresolvedLookupExpr::Create(Context, NamingClass,
10512                                      NestedNameSpecifierLoc(), OpNameInfo,
10513                                      /*ADL*/ true, /*Overloaded*/ false,
10514                                      UnresolvedSetIterator(),
10515                                      UnresolvedSetIterator());
10516     // Can't add any actual overloads yet
10517 
10518     return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10519                                                    Args,
10520                                                    Context.DependentTy,
10521                                                    VK_RValue,
10522                                                    RLoc, false));
10523   }
10524 
10525   // Handle placeholders on both operands.
10526   if (checkPlaceholderForOverload(*this, Args[0]))
10527     return ExprError();
10528   if (checkPlaceholderForOverload(*this, Args[1]))
10529     return ExprError();
10530 
10531   // Build an empty overload set.
10532   OverloadCandidateSet CandidateSet(LLoc);
10533 
10534   // Subscript can only be overloaded as a member function.
10535 
10536   // Add operator candidates that are member functions.
10537   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10538 
10539   // Add builtin operator candidates.
10540   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10541 
10542   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10543 
10544   // Perform overload resolution.
10545   OverloadCandidateSet::iterator Best;
10546   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10547     case OR_Success: {
10548       // We found a built-in operator or an overloaded operator.
10549       FunctionDecl *FnDecl = Best->Function;
10550 
10551       if (FnDecl) {
10552         // We matched an overloaded operator. Build a call to that
10553         // operator.
10554 
10555         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10556 
10557         // Convert the arguments.
10558         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10559         ExprResult Arg0 =
10560           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10561                                               Best->FoundDecl, Method);
10562         if (Arg0.isInvalid())
10563           return ExprError();
10564         Args[0] = Arg0.take();
10565 
10566         // Convert the arguments.
10567         ExprResult InputInit
10568           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10569                                                       Context,
10570                                                       FnDecl->getParamDecl(0)),
10571                                       SourceLocation(),
10572                                       Owned(Args[1]));
10573         if (InputInit.isInvalid())
10574           return ExprError();
10575 
10576         Args[1] = InputInit.takeAs<Expr>();
10577 
10578         // Determine the result type
10579         QualType ResultTy = FnDecl->getResultType();
10580         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10581         ResultTy = ResultTy.getNonLValueExprType(Context);
10582 
10583         // Build the actual expression node.
10584         DeclarationNameInfo OpLocInfo(OpName, LLoc);
10585         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10586         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10587                                                   Best->FoundDecl,
10588                                                   HadMultipleCandidates,
10589                                                   OpLocInfo.getLoc(),
10590                                                   OpLocInfo.getInfo());
10591         if (FnExpr.isInvalid())
10592           return ExprError();
10593 
10594         CXXOperatorCallExpr *TheCall =
10595           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10596                                             FnExpr.take(), Args,
10597                                             ResultTy, VK, RLoc,
10598                                             false);
10599 
10600         if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10601                                 FnDecl))
10602           return ExprError();
10603 
10604         return MaybeBindToTemporary(TheCall);
10605       } else {
10606         // We matched a built-in operator. Convert the arguments, then
10607         // break out so that we will build the appropriate built-in
10608         // operator node.
10609         ExprResult ArgsRes0 =
10610           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10611                                     Best->Conversions[0], AA_Passing);
10612         if (ArgsRes0.isInvalid())
10613           return ExprError();
10614         Args[0] = ArgsRes0.take();
10615 
10616         ExprResult ArgsRes1 =
10617           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10618                                     Best->Conversions[1], AA_Passing);
10619         if (ArgsRes1.isInvalid())
10620           return ExprError();
10621         Args[1] = ArgsRes1.take();
10622 
10623         break;
10624       }
10625     }
10626 
10627     case OR_No_Viable_Function: {
10628       if (CandidateSet.empty())
10629         Diag(LLoc, diag::err_ovl_no_oper)
10630           << Args[0]->getType() << /*subscript*/ 0
10631           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10632       else
10633         Diag(LLoc, diag::err_ovl_no_viable_subscript)
10634           << Args[0]->getType()
10635           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10636       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10637                                   "[]", LLoc);
10638       return ExprError();
10639     }
10640 
10641     case OR_Ambiguous:
10642       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10643           << "[]"
10644           << Args[0]->getType() << Args[1]->getType()
10645           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10646       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10647                                   "[]", LLoc);
10648       return ExprError();
10649 
10650     case OR_Deleted:
10651       Diag(LLoc, diag::err_ovl_deleted_oper)
10652         << Best->Function->isDeleted() << "[]"
10653         << getDeletedOrUnavailableSuffix(Best->Function)
10654         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10655       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10656                                   "[]", LLoc);
10657       return ExprError();
10658     }
10659 
10660   // We matched a built-in operator; build it.
10661   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10662 }
10663 
10664 /// BuildCallToMemberFunction - Build a call to a member
10665 /// function. MemExpr is the expression that refers to the member
10666 /// function (and includes the object parameter), Args/NumArgs are the
10667 /// arguments to the function call (not including the object
10668 /// parameter). The caller needs to validate that the member
10669 /// expression refers to a non-static member function or an overloaded
10670 /// member function.
10671 ExprResult
BuildCallToMemberFunction(Scope * S,Expr * MemExprE,SourceLocation LParenLoc,Expr ** Args,unsigned NumArgs,SourceLocation RParenLoc)10672 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10673                                 SourceLocation LParenLoc, Expr **Args,
10674                                 unsigned NumArgs, SourceLocation RParenLoc) {
10675   assert(MemExprE->getType() == Context.BoundMemberTy ||
10676          MemExprE->getType() == Context.OverloadTy);
10677 
10678   // Dig out the member expression. This holds both the object
10679   // argument and the member function we're referring to.
10680   Expr *NakedMemExpr = MemExprE->IgnoreParens();
10681 
10682   // Determine whether this is a call to a pointer-to-member function.
10683   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10684     assert(op->getType() == Context.BoundMemberTy);
10685     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10686 
10687     QualType fnType =
10688       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10689 
10690     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10691     QualType resultType = proto->getCallResultType(Context);
10692     ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10693 
10694     // Check that the object type isn't more qualified than the
10695     // member function we're calling.
10696     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10697 
10698     QualType objectType = op->getLHS()->getType();
10699     if (op->getOpcode() == BO_PtrMemI)
10700       objectType = objectType->castAs<PointerType>()->getPointeeType();
10701     Qualifiers objectQuals = objectType.getQualifiers();
10702 
10703     Qualifiers difference = objectQuals - funcQuals;
10704     difference.removeObjCGCAttr();
10705     difference.removeAddressSpace();
10706     if (difference) {
10707       std::string qualsString = difference.getAsString();
10708       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10709         << fnType.getUnqualifiedType()
10710         << qualsString
10711         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10712     }
10713 
10714     CXXMemberCallExpr *call
10715       = new (Context) CXXMemberCallExpr(Context, MemExprE,
10716                                         llvm::makeArrayRef(Args, NumArgs),
10717                                         resultType, valueKind, RParenLoc);
10718 
10719     if (CheckCallReturnType(proto->getResultType(),
10720                             op->getRHS()->getLocStart(),
10721                             call, 0))
10722       return ExprError();
10723 
10724     if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10725       return ExprError();
10726 
10727     return MaybeBindToTemporary(call);
10728   }
10729 
10730   UnbridgedCastsSet UnbridgedCasts;
10731   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10732     return ExprError();
10733 
10734   MemberExpr *MemExpr;
10735   CXXMethodDecl *Method = 0;
10736   DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
10737   NestedNameSpecifier *Qualifier = 0;
10738   if (isa<MemberExpr>(NakedMemExpr)) {
10739     MemExpr = cast<MemberExpr>(NakedMemExpr);
10740     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
10741     FoundDecl = MemExpr->getFoundDecl();
10742     Qualifier = MemExpr->getQualifier();
10743     UnbridgedCasts.restore();
10744   } else {
10745     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
10746     Qualifier = UnresExpr->getQualifier();
10747 
10748     QualType ObjectType = UnresExpr->getBaseType();
10749     Expr::Classification ObjectClassification
10750       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10751                             : UnresExpr->getBase()->Classify(Context);
10752 
10753     // Add overload candidates
10754     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
10755 
10756     // FIXME: avoid copy.
10757     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10758     if (UnresExpr->hasExplicitTemplateArgs()) {
10759       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10760       TemplateArgs = &TemplateArgsBuffer;
10761     }
10762 
10763     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10764            E = UnresExpr->decls_end(); I != E; ++I) {
10765 
10766       NamedDecl *Func = *I;
10767       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10768       if (isa<UsingShadowDecl>(Func))
10769         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10770 
10771 
10772       // Microsoft supports direct constructor calls.
10773       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
10774         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10775                              llvm::makeArrayRef(Args, NumArgs), CandidateSet);
10776       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
10777         // If explicit template arguments were provided, we can't call a
10778         // non-template member function.
10779         if (TemplateArgs)
10780           continue;
10781 
10782         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
10783                            ObjectClassification,
10784                            llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10785                            /*SuppressUserConversions=*/false);
10786       } else {
10787         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
10788                                    I.getPair(), ActingDC, TemplateArgs,
10789                                    ObjectType,  ObjectClassification,
10790                                    llvm::makeArrayRef(Args, NumArgs),
10791                                    CandidateSet,
10792                                    /*SuppressUsedConversions=*/false);
10793       }
10794     }
10795 
10796     DeclarationName DeclName = UnresExpr->getMemberName();
10797 
10798     UnbridgedCasts.restore();
10799 
10800     OverloadCandidateSet::iterator Best;
10801     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
10802                                             Best)) {
10803     case OR_Success:
10804       Method = cast<CXXMethodDecl>(Best->Function);
10805       FoundDecl = Best->FoundDecl;
10806       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
10807       DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
10808       break;
10809 
10810     case OR_No_Viable_Function:
10811       Diag(UnresExpr->getMemberLoc(),
10812            diag::err_ovl_no_viable_member_function_in_call)
10813         << DeclName << MemExprE->getSourceRange();
10814       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10815                                   llvm::makeArrayRef(Args, NumArgs));
10816       // FIXME: Leaking incoming expressions!
10817       return ExprError();
10818 
10819     case OR_Ambiguous:
10820       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
10821         << DeclName << MemExprE->getSourceRange();
10822       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10823                                   llvm::makeArrayRef(Args, NumArgs));
10824       // FIXME: Leaking incoming expressions!
10825       return ExprError();
10826 
10827     case OR_Deleted:
10828       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
10829         << Best->Function->isDeleted()
10830         << DeclName
10831         << getDeletedOrUnavailableSuffix(Best->Function)
10832         << MemExprE->getSourceRange();
10833       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10834                                   llvm::makeArrayRef(Args, NumArgs));
10835       // FIXME: Leaking incoming expressions!
10836       return ExprError();
10837     }
10838 
10839     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
10840 
10841     // If overload resolution picked a static member, build a
10842     // non-member call based on that function.
10843     if (Method->isStatic()) {
10844       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10845                                    Args, NumArgs, RParenLoc);
10846     }
10847 
10848     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
10849   }
10850 
10851   QualType ResultType = Method->getResultType();
10852   ExprValueKind VK = Expr::getValueKindForType(ResultType);
10853   ResultType = ResultType.getNonLValueExprType(Context);
10854 
10855   assert(Method && "Member call to something that isn't a method?");
10856   CXXMemberCallExpr *TheCall =
10857     new (Context) CXXMemberCallExpr(Context, MemExprE,
10858                                     llvm::makeArrayRef(Args, NumArgs),
10859                                     ResultType, VK, RParenLoc);
10860 
10861   // Check for a valid return type.
10862   if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
10863                           TheCall, Method))
10864     return ExprError();
10865 
10866   // Convert the object argument (for a non-static member function call).
10867   // We only need to do this if there was actually an overload; otherwise
10868   // it was done at lookup.
10869   if (!Method->isStatic()) {
10870     ExprResult ObjectArg =
10871       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10872                                           FoundDecl, Method);
10873     if (ObjectArg.isInvalid())
10874       return ExprError();
10875     MemExpr->setBase(ObjectArg.take());
10876   }
10877 
10878   // Convert the rest of the arguments
10879   const FunctionProtoType *Proto =
10880     Method->getType()->getAs<FunctionProtoType>();
10881   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
10882                               RParenLoc))
10883     return ExprError();
10884 
10885   DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10886 
10887   if (CheckFunctionCall(Method, TheCall, Proto))
10888     return ExprError();
10889 
10890   if ((isa<CXXConstructorDecl>(CurContext) ||
10891        isa<CXXDestructorDecl>(CurContext)) &&
10892       TheCall->getMethodDecl()->isPure()) {
10893     const CXXMethodDecl *MD = TheCall->getMethodDecl();
10894 
10895     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
10896       Diag(MemExpr->getLocStart(),
10897            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10898         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10899         << MD->getParent()->getDeclName();
10900 
10901       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
10902     }
10903   }
10904   return MaybeBindToTemporary(TheCall);
10905 }
10906 
10907 /// BuildCallToObjectOfClassType - Build a call to an object of class
10908 /// type (C++ [over.call.object]), which can end up invoking an
10909 /// overloaded function call operator (@c operator()) or performing a
10910 /// user-defined conversion on the object argument.
10911 ExprResult
BuildCallToObjectOfClassType(Scope * S,Expr * Obj,SourceLocation LParenLoc,Expr ** Args,unsigned NumArgs,SourceLocation RParenLoc)10912 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
10913                                    SourceLocation LParenLoc,
10914                                    Expr **Args, unsigned NumArgs,
10915                                    SourceLocation RParenLoc) {
10916   if (checkPlaceholderForOverload(*this, Obj))
10917     return ExprError();
10918   ExprResult Object = Owned(Obj);
10919 
10920   UnbridgedCastsSet UnbridgedCasts;
10921   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10922     return ExprError();
10923 
10924   assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10925   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
10926 
10927   // C++ [over.call.object]p1:
10928   //  If the primary-expression E in the function call syntax
10929   //  evaluates to a class object of type "cv T", then the set of
10930   //  candidate functions includes at least the function call
10931   //  operators of T. The function call operators of T are obtained by
10932   //  ordinary lookup of the name operator() in the context of
10933   //  (E).operator().
10934   OverloadCandidateSet CandidateSet(LParenLoc);
10935   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
10936 
10937   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
10938                           diag::err_incomplete_object_call, Object.get()))
10939     return true;
10940 
10941   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10942   LookupQualifiedName(R, Record->getDecl());
10943   R.suppressDiagnostics();
10944 
10945   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10946        Oper != OperEnd; ++Oper) {
10947     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10948                        Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
10949                        /*SuppressUserConversions=*/ false);
10950   }
10951 
10952   // C++ [over.call.object]p2:
10953   //   In addition, for each (non-explicit in C++0x) conversion function
10954   //   declared in T of the form
10955   //
10956   //        operator conversion-type-id () cv-qualifier;
10957   //
10958   //   where cv-qualifier is the same cv-qualification as, or a
10959   //   greater cv-qualification than, cv, and where conversion-type-id
10960   //   denotes the type "pointer to function of (P1,...,Pn) returning
10961   //   R", or the type "reference to pointer to function of
10962   //   (P1,...,Pn) returning R", or the type "reference to function
10963   //   of (P1,...,Pn) returning R", a surrogate call function [...]
10964   //   is also considered as a candidate function. Similarly,
10965   //   surrogate call functions are added to the set of candidate
10966   //   functions for each conversion function declared in an
10967   //   accessible base class provided the function is not hidden
10968   //   within T by another intervening declaration.
10969   std::pair<CXXRecordDecl::conversion_iterator,
10970             CXXRecordDecl::conversion_iterator> Conversions
10971     = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
10972   for (CXXRecordDecl::conversion_iterator
10973          I = Conversions.first, E = Conversions.second; I != E; ++I) {
10974     NamedDecl *D = *I;
10975     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10976     if (isa<UsingShadowDecl>(D))
10977       D = cast<UsingShadowDecl>(D)->getTargetDecl();
10978 
10979     // Skip over templated conversion functions; they aren't
10980     // surrogates.
10981     if (isa<FunctionTemplateDecl>(D))
10982       continue;
10983 
10984     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
10985     if (!Conv->isExplicit()) {
10986       // Strip the reference type (if any) and then the pointer type (if
10987       // any) to get down to what might be a function type.
10988       QualType ConvType = Conv->getConversionType().getNonReferenceType();
10989       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10990         ConvType = ConvPtrType->getPointeeType();
10991 
10992       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10993       {
10994         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10995                               Object.get(), llvm::makeArrayRef(Args, NumArgs),
10996                               CandidateSet);
10997       }
10998     }
10999   }
11000 
11001   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11002 
11003   // Perform overload resolution.
11004   OverloadCandidateSet::iterator Best;
11005   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11006                              Best)) {
11007   case OR_Success:
11008     // Overload resolution succeeded; we'll build the appropriate call
11009     // below.
11010     break;
11011 
11012   case OR_No_Viable_Function:
11013     if (CandidateSet.empty())
11014       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11015         << Object.get()->getType() << /*call*/ 1
11016         << Object.get()->getSourceRange();
11017     else
11018       Diag(Object.get()->getLocStart(),
11019            diag::err_ovl_no_viable_object_call)
11020         << Object.get()->getType() << Object.get()->getSourceRange();
11021     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11022                                 llvm::makeArrayRef(Args, NumArgs));
11023     break;
11024 
11025   case OR_Ambiguous:
11026     Diag(Object.get()->getLocStart(),
11027          diag::err_ovl_ambiguous_object_call)
11028       << Object.get()->getType() << Object.get()->getSourceRange();
11029     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
11030                                 llvm::makeArrayRef(Args, NumArgs));
11031     break;
11032 
11033   case OR_Deleted:
11034     Diag(Object.get()->getLocStart(),
11035          diag::err_ovl_deleted_object_call)
11036       << Best->Function->isDeleted()
11037       << Object.get()->getType()
11038       << getDeletedOrUnavailableSuffix(Best->Function)
11039       << Object.get()->getSourceRange();
11040     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11041                                 llvm::makeArrayRef(Args, NumArgs));
11042     break;
11043   }
11044 
11045   if (Best == CandidateSet.end())
11046     return true;
11047 
11048   UnbridgedCasts.restore();
11049 
11050   if (Best->Function == 0) {
11051     // Since there is no function declaration, this is one of the
11052     // surrogate candidates. Dig out the conversion function.
11053     CXXConversionDecl *Conv
11054       = cast<CXXConversionDecl>(
11055                          Best->Conversions[0].UserDefined.ConversionFunction);
11056 
11057     CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11058     DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
11059 
11060     // We selected one of the surrogate functions that converts the
11061     // object parameter to a function pointer. Perform the conversion
11062     // on the object argument, then let ActOnCallExpr finish the job.
11063 
11064     // Create an implicit member expr to refer to the conversion operator.
11065     // and then call it.
11066     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11067                                              Conv, HadMultipleCandidates);
11068     if (Call.isInvalid())
11069       return ExprError();
11070     // Record usage of conversion in an implicit cast.
11071     Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11072                                           CK_UserDefinedConversion,
11073                                           Call.get(), 0, VK_RValue));
11074 
11075     return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
11076                          RParenLoc);
11077   }
11078 
11079   CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
11080 
11081   // We found an overloaded operator(). Build a CXXOperatorCallExpr
11082   // that calls this method, using Object for the implicit object
11083   // parameter and passing along the remaining arguments.
11084   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11085 
11086   // An error diagnostic has already been printed when parsing the declaration.
11087   if (Method->isInvalidDecl())
11088     return ExprError();
11089 
11090   const FunctionProtoType *Proto =
11091     Method->getType()->getAs<FunctionProtoType>();
11092 
11093   unsigned NumArgsInProto = Proto->getNumArgs();
11094   unsigned NumArgsToCheck = NumArgs;
11095 
11096   // Build the full argument list for the method call (the
11097   // implicit object parameter is placed at the beginning of the
11098   // list).
11099   Expr **MethodArgs;
11100   if (NumArgs < NumArgsInProto) {
11101     NumArgsToCheck = NumArgsInProto;
11102     MethodArgs = new Expr*[NumArgsInProto + 1];
11103   } else {
11104     MethodArgs = new Expr*[NumArgs + 1];
11105   }
11106   MethodArgs[0] = Object.get();
11107   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11108     MethodArgs[ArgIdx + 1] = Args[ArgIdx];
11109 
11110   DeclarationNameInfo OpLocInfo(
11111                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11112   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11113   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11114                                            HadMultipleCandidates,
11115                                            OpLocInfo.getLoc(),
11116                                            OpLocInfo.getInfo());
11117   if (NewFn.isInvalid())
11118     return true;
11119 
11120   // Once we've built TheCall, all of the expressions are properly
11121   // owned.
11122   QualType ResultTy = Method->getResultType();
11123   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11124   ResultTy = ResultTy.getNonLValueExprType(Context);
11125 
11126   CXXOperatorCallExpr *TheCall =
11127     new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11128                                       llvm::makeArrayRef(MethodArgs, NumArgs+1),
11129                                       ResultTy, VK, RParenLoc, false);
11130   delete [] MethodArgs;
11131 
11132   if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
11133                           Method))
11134     return true;
11135 
11136   // We may have default arguments. If so, we need to allocate more
11137   // slots in the call for them.
11138   if (NumArgs < NumArgsInProto)
11139     TheCall->setNumArgs(Context, NumArgsInProto + 1);
11140   else if (NumArgs > NumArgsInProto)
11141     NumArgsToCheck = NumArgsInProto;
11142 
11143   bool IsError = false;
11144 
11145   // Initialize the implicit object parameter.
11146   ExprResult ObjRes =
11147     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11148                                         Best->FoundDecl, Method);
11149   if (ObjRes.isInvalid())
11150     IsError = true;
11151   else
11152     Object = ObjRes;
11153   TheCall->setArg(0, Object.take());
11154 
11155   // Check the argument types.
11156   for (unsigned i = 0; i != NumArgsToCheck; i++) {
11157     Expr *Arg;
11158     if (i < NumArgs) {
11159       Arg = Args[i];
11160 
11161       // Pass the argument.
11162 
11163       ExprResult InputInit
11164         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11165                                                     Context,
11166                                                     Method->getParamDecl(i)),
11167                                     SourceLocation(), Arg);
11168 
11169       IsError |= InputInit.isInvalid();
11170       Arg = InputInit.takeAs<Expr>();
11171     } else {
11172       ExprResult DefArg
11173         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11174       if (DefArg.isInvalid()) {
11175         IsError = true;
11176         break;
11177       }
11178 
11179       Arg = DefArg.takeAs<Expr>();
11180     }
11181 
11182     TheCall->setArg(i + 1, Arg);
11183   }
11184 
11185   // If this is a variadic call, handle args passed through "...".
11186   if (Proto->isVariadic()) {
11187     // Promote the arguments (C99 6.5.2.2p7).
11188     for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
11189       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11190       IsError |= Arg.isInvalid();
11191       TheCall->setArg(i + 1, Arg.take());
11192     }
11193   }
11194 
11195   if (IsError) return true;
11196 
11197   DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11198 
11199   if (CheckFunctionCall(Method, TheCall, Proto))
11200     return true;
11201 
11202   return MaybeBindToTemporary(TheCall);
11203 }
11204 
11205 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11206 ///  (if one exists), where @c Base is an expression of class type and
11207 /// @c Member is the name of the member we're trying to find.
11208 ExprResult
BuildOverloadedArrowExpr(Scope * S,Expr * Base,SourceLocation OpLoc)11209 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
11210   assert(Base->getType()->isRecordType() &&
11211          "left-hand side must have class type");
11212 
11213   if (checkPlaceholderForOverload(*this, Base))
11214     return ExprError();
11215 
11216   SourceLocation Loc = Base->getExprLoc();
11217 
11218   // C++ [over.ref]p1:
11219   //
11220   //   [...] An expression x->m is interpreted as (x.operator->())->m
11221   //   for a class object x of type T if T::operator->() exists and if
11222   //   the operator is selected as the best match function by the
11223   //   overload resolution mechanism (13.3).
11224   DeclarationName OpName =
11225     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11226   OverloadCandidateSet CandidateSet(Loc);
11227   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11228 
11229   if (RequireCompleteType(Loc, Base->getType(),
11230                           diag::err_typecheck_incomplete_tag, Base))
11231     return ExprError();
11232 
11233   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11234   LookupQualifiedName(R, BaseRecord->getDecl());
11235   R.suppressDiagnostics();
11236 
11237   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11238        Oper != OperEnd; ++Oper) {
11239     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11240                        0, 0, CandidateSet, /*SuppressUserConversions=*/false);
11241   }
11242 
11243   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11244 
11245   // Perform overload resolution.
11246   OverloadCandidateSet::iterator Best;
11247   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11248   case OR_Success:
11249     // Overload resolution succeeded; we'll build the call below.
11250     break;
11251 
11252   case OR_No_Viable_Function:
11253     if (CandidateSet.empty())
11254       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11255         << Base->getType() << Base->getSourceRange();
11256     else
11257       Diag(OpLoc, diag::err_ovl_no_viable_oper)
11258         << "operator->" << Base->getSourceRange();
11259     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11260     return ExprError();
11261 
11262   case OR_Ambiguous:
11263     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
11264       << "->" << Base->getType() << Base->getSourceRange();
11265     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11266     return ExprError();
11267 
11268   case OR_Deleted:
11269     Diag(OpLoc,  diag::err_ovl_deleted_oper)
11270       << Best->Function->isDeleted()
11271       << "->"
11272       << getDeletedOrUnavailableSuffix(Best->Function)
11273       << Base->getSourceRange();
11274     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11275     return ExprError();
11276   }
11277 
11278   CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11279 
11280   // Convert the object parameter.
11281   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11282   ExprResult BaseResult =
11283     PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11284                                         Best->FoundDecl, Method);
11285   if (BaseResult.isInvalid())
11286     return ExprError();
11287   Base = BaseResult.take();
11288 
11289   // Build the operator call.
11290   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11291                                             HadMultipleCandidates, OpLoc);
11292   if (FnExpr.isInvalid())
11293     return ExprError();
11294 
11295   QualType ResultTy = Method->getResultType();
11296   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11297   ResultTy = ResultTy.getNonLValueExprType(Context);
11298   CXXOperatorCallExpr *TheCall =
11299     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
11300                                       Base, ResultTy, VK, OpLoc, false);
11301 
11302   if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
11303                           Method))
11304           return ExprError();
11305 
11306   return MaybeBindToTemporary(TheCall);
11307 }
11308 
11309 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11310 /// a literal operator described by the provided lookup results.
BuildLiteralOperatorCall(LookupResult & R,DeclarationNameInfo & SuffixInfo,ArrayRef<Expr * > Args,SourceLocation LitEndLoc,TemplateArgumentListInfo * TemplateArgs)11311 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11312                                           DeclarationNameInfo &SuffixInfo,
11313                                           ArrayRef<Expr*> Args,
11314                                           SourceLocation LitEndLoc,
11315                                        TemplateArgumentListInfo *TemplateArgs) {
11316   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11317 
11318   OverloadCandidateSet CandidateSet(UDSuffixLoc);
11319   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11320                         TemplateArgs);
11321 
11322   bool HadMultipleCandidates = (CandidateSet.size() > 1);
11323 
11324   // Perform overload resolution. This will usually be trivial, but might need
11325   // to perform substitutions for a literal operator template.
11326   OverloadCandidateSet::iterator Best;
11327   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11328   case OR_Success:
11329   case OR_Deleted:
11330     break;
11331 
11332   case OR_No_Viable_Function:
11333     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11334       << R.getLookupName();
11335     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11336     return ExprError();
11337 
11338   case OR_Ambiguous:
11339     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11340     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11341     return ExprError();
11342   }
11343 
11344   FunctionDecl *FD = Best->Function;
11345   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11346                                         HadMultipleCandidates,
11347                                         SuffixInfo.getLoc(),
11348                                         SuffixInfo.getInfo());
11349   if (Fn.isInvalid())
11350     return true;
11351 
11352   // Check the argument types. This should almost always be a no-op, except
11353   // that array-to-pointer decay is applied to string literals.
11354   Expr *ConvArgs[2];
11355   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11356     ExprResult InputInit = PerformCopyInitialization(
11357       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11358       SourceLocation(), Args[ArgIdx]);
11359     if (InputInit.isInvalid())
11360       return true;
11361     ConvArgs[ArgIdx] = InputInit.take();
11362   }
11363 
11364   QualType ResultTy = FD->getResultType();
11365   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11366   ResultTy = ResultTy.getNonLValueExprType(Context);
11367 
11368   UserDefinedLiteral *UDL =
11369     new (Context) UserDefinedLiteral(Context, Fn.take(),
11370                                      llvm::makeArrayRef(ConvArgs, Args.size()),
11371                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
11372 
11373   if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11374     return ExprError();
11375 
11376   if (CheckFunctionCall(FD, UDL, NULL))
11377     return ExprError();
11378 
11379   return MaybeBindToTemporary(UDL);
11380 }
11381 
11382 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11383 /// given LookupResult is non-empty, it is assumed to describe a member which
11384 /// will be invoked. Otherwise, the function will be found via argument
11385 /// dependent lookup.
11386 /// CallExpr is set to a valid expression and FRS_Success returned on success,
11387 /// otherwise CallExpr is set to ExprError() and some non-success value
11388 /// is returned.
11389 Sema::ForRangeStatus
BuildForRangeBeginEndCall(Scope * S,SourceLocation Loc,SourceLocation RangeLoc,VarDecl * Decl,BeginEndFunction BEF,const DeclarationNameInfo & NameInfo,LookupResult & MemberLookup,OverloadCandidateSet * CandidateSet,Expr * Range,ExprResult * CallExpr)11390 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11391                                 SourceLocation RangeLoc, VarDecl *Decl,
11392                                 BeginEndFunction BEF,
11393                                 const DeclarationNameInfo &NameInfo,
11394                                 LookupResult &MemberLookup,
11395                                 OverloadCandidateSet *CandidateSet,
11396                                 Expr *Range, ExprResult *CallExpr) {
11397   CandidateSet->clear();
11398   if (!MemberLookup.empty()) {
11399     ExprResult MemberRef =
11400         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11401                                  /*IsPtr=*/false, CXXScopeSpec(),
11402                                  /*TemplateKWLoc=*/SourceLocation(),
11403                                  /*FirstQualifierInScope=*/0,
11404                                  MemberLookup,
11405                                  /*TemplateArgs=*/0);
11406     if (MemberRef.isInvalid()) {
11407       *CallExpr = ExprError();
11408       Diag(Range->getLocStart(), diag::note_in_for_range)
11409           << RangeLoc << BEF << Range->getType();
11410       return FRS_DiagnosticIssued;
11411     }
11412     *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11413     if (CallExpr->isInvalid()) {
11414       *CallExpr = ExprError();
11415       Diag(Range->getLocStart(), diag::note_in_for_range)
11416           << RangeLoc << BEF << Range->getType();
11417       return FRS_DiagnosticIssued;
11418     }
11419   } else {
11420     UnresolvedSet<0> FoundNames;
11421     UnresolvedLookupExpr *Fn =
11422       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11423                                    NestedNameSpecifierLoc(), NameInfo,
11424                                    /*NeedsADL=*/true, /*Overloaded=*/false,
11425                                    FoundNames.begin(), FoundNames.end());
11426 
11427     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11428                                                     CandidateSet, CallExpr);
11429     if (CandidateSet->empty() || CandidateSetError) {
11430       *CallExpr = ExprError();
11431       return FRS_NoViableFunction;
11432     }
11433     OverloadCandidateSet::iterator Best;
11434     OverloadingResult OverloadResult =
11435         CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11436 
11437     if (OverloadResult == OR_No_Viable_Function) {
11438       *CallExpr = ExprError();
11439       return FRS_NoViableFunction;
11440     }
11441     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11442                                          Loc, 0, CandidateSet, &Best,
11443                                          OverloadResult,
11444                                          /*AllowTypoCorrection=*/false);
11445     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11446       *CallExpr = ExprError();
11447       Diag(Range->getLocStart(), diag::note_in_for_range)
11448           << RangeLoc << BEF << Range->getType();
11449       return FRS_DiagnosticIssued;
11450     }
11451   }
11452   return FRS_Success;
11453 }
11454 
11455 
11456 /// FixOverloadedFunctionReference - E is an expression that refers to
11457 /// a C++ overloaded function (possibly with some parentheses and
11458 /// perhaps a '&' around it). We have resolved the overloaded function
11459 /// to the function declaration Fn, so patch up the expression E to
11460 /// refer (possibly indirectly) to Fn. Returns the new expr.
FixOverloadedFunctionReference(Expr * E,DeclAccessPair Found,FunctionDecl * Fn)11461 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11462                                            FunctionDecl *Fn) {
11463   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11464     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11465                                                    Found, Fn);
11466     if (SubExpr == PE->getSubExpr())
11467       return PE;
11468 
11469     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11470   }
11471 
11472   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11473     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11474                                                    Found, Fn);
11475     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11476                                SubExpr->getType()) &&
11477            "Implicit cast type cannot be determined from overload");
11478     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11479     if (SubExpr == ICE->getSubExpr())
11480       return ICE;
11481 
11482     return ImplicitCastExpr::Create(Context, ICE->getType(),
11483                                     ICE->getCastKind(),
11484                                     SubExpr, 0,
11485                                     ICE->getValueKind());
11486   }
11487 
11488   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11489     assert(UnOp->getOpcode() == UO_AddrOf &&
11490            "Can only take the address of an overloaded function");
11491     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11492       if (Method->isStatic()) {
11493         // Do nothing: static member functions aren't any different
11494         // from non-member functions.
11495       } else {
11496         // Fix the sub expression, which really has to be an
11497         // UnresolvedLookupExpr holding an overloaded member function
11498         // or template.
11499         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11500                                                        Found, Fn);
11501         if (SubExpr == UnOp->getSubExpr())
11502           return UnOp;
11503 
11504         assert(isa<DeclRefExpr>(SubExpr)
11505                && "fixed to something other than a decl ref");
11506         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11507                && "fixed to a member ref with no nested name qualifier");
11508 
11509         // We have taken the address of a pointer to member
11510         // function. Perform the computation here so that we get the
11511         // appropriate pointer to member type.
11512         QualType ClassType
11513           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11514         QualType MemPtrType
11515           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11516 
11517         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11518                                            VK_RValue, OK_Ordinary,
11519                                            UnOp->getOperatorLoc());
11520       }
11521     }
11522     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11523                                                    Found, Fn);
11524     if (SubExpr == UnOp->getSubExpr())
11525       return UnOp;
11526 
11527     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11528                                      Context.getPointerType(SubExpr->getType()),
11529                                        VK_RValue, OK_Ordinary,
11530                                        UnOp->getOperatorLoc());
11531   }
11532 
11533   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11534     // FIXME: avoid copy.
11535     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11536     if (ULE->hasExplicitTemplateArgs()) {
11537       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11538       TemplateArgs = &TemplateArgsBuffer;
11539     }
11540 
11541     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11542                                            ULE->getQualifierLoc(),
11543                                            ULE->getTemplateKeywordLoc(),
11544                                            Fn,
11545                                            /*enclosing*/ false, // FIXME?
11546                                            ULE->getNameLoc(),
11547                                            Fn->getType(),
11548                                            VK_LValue,
11549                                            Found.getDecl(),
11550                                            TemplateArgs);
11551     MarkDeclRefReferenced(DRE);
11552     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11553     return DRE;
11554   }
11555 
11556   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11557     // FIXME: avoid copy.
11558     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11559     if (MemExpr->hasExplicitTemplateArgs()) {
11560       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11561       TemplateArgs = &TemplateArgsBuffer;
11562     }
11563 
11564     Expr *Base;
11565 
11566     // If we're filling in a static method where we used to have an
11567     // implicit member access, rewrite to a simple decl ref.
11568     if (MemExpr->isImplicitAccess()) {
11569       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11570         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11571                                                MemExpr->getQualifierLoc(),
11572                                                MemExpr->getTemplateKeywordLoc(),
11573                                                Fn,
11574                                                /*enclosing*/ false,
11575                                                MemExpr->getMemberLoc(),
11576                                                Fn->getType(),
11577                                                VK_LValue,
11578                                                Found.getDecl(),
11579                                                TemplateArgs);
11580         MarkDeclRefReferenced(DRE);
11581         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11582         return DRE;
11583       } else {
11584         SourceLocation Loc = MemExpr->getMemberLoc();
11585         if (MemExpr->getQualifier())
11586           Loc = MemExpr->getQualifierLoc().getBeginLoc();
11587         CheckCXXThisCapture(Loc);
11588         Base = new (Context) CXXThisExpr(Loc,
11589                                          MemExpr->getBaseType(),
11590                                          /*isImplicit=*/true);
11591       }
11592     } else
11593       Base = MemExpr->getBase();
11594 
11595     ExprValueKind valueKind;
11596     QualType type;
11597     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11598       valueKind = VK_LValue;
11599       type = Fn->getType();
11600     } else {
11601       valueKind = VK_RValue;
11602       type = Context.BoundMemberTy;
11603     }
11604 
11605     MemberExpr *ME = MemberExpr::Create(Context, Base,
11606                                         MemExpr->isArrow(),
11607                                         MemExpr->getQualifierLoc(),
11608                                         MemExpr->getTemplateKeywordLoc(),
11609                                         Fn,
11610                                         Found,
11611                                         MemExpr->getMemberNameInfo(),
11612                                         TemplateArgs,
11613                                         type, valueKind, OK_Ordinary);
11614     ME->setHadMultipleCandidates(true);
11615     MarkMemberReferenced(ME);
11616     return ME;
11617   }
11618 
11619   llvm_unreachable("Invalid reference to overloaded function");
11620 }
11621 
FixOverloadedFunctionReference(ExprResult E,DeclAccessPair Found,FunctionDecl * Fn)11622 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11623                                                 DeclAccessPair Found,
11624                                                 FunctionDecl *Fn) {
11625   return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11626 }
11627 
11628 } // end namespace clang
11629